ValidGenerator.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Faker;
  3. /**
  4. * Proxy for other generators, to return only valid values. Works with
  5. * Faker\Generator\Base->valid()
  6. */
  7. class ValidGenerator
  8. {
  9. protected $generator;
  10. protected $validator;
  11. protected $maxRetries;
  12. /**
  13. * @param Generator $generator
  14. */
  15. public function __construct(Generator $generator, $validator = null, $maxRetries = 10000)
  16. {
  17. if (is_null($validator)) {
  18. $validator = function () {
  19. return true;
  20. };
  21. } elseif (!is_callable($validator)) {
  22. throw new \InvalidArgumentException('valid() only accepts callables as first argument');
  23. }
  24. $this->generator = $generator;
  25. $this->validator = $validator;
  26. $this->maxRetries = $maxRetries;
  27. }
  28. /**
  29. * Catch and proxy all generator calls but return only valid values
  30. * @param string $attribute
  31. */
  32. public function __get($attribute)
  33. {
  34. return $this->__call($attribute, array());
  35. }
  36. /**
  37. * Catch and proxy all generator calls with arguments but return only valid values
  38. * @param string $name
  39. * @param array $arguments
  40. */
  41. public function __call($name, $arguments)
  42. {
  43. $i = 0;
  44. do {
  45. $res = call_user_func_array(array($this->generator, $name), $arguments);
  46. $i++;
  47. if ($i > $this->maxRetries) {
  48. throw new \OverflowException(sprintf('Maximum retries of %d reached without finding a valid value', $this->maxRetries));
  49. }
  50. } while (!call_user_func($this->validator, $res));
  51. return $res;
  52. }
  53. }