Calculator
5 years ago
Guesser
5 years ago
ORM
5 years ago
Provider
5 years ago
DefaultGenerator.php
5 years ago
Documentor.php
5 years ago
Factory.php
5 years ago
Generator.php
5 years ago
UniqueGenerator.php
5 years ago
ValidGenerator.php
5 years ago
UniqueGenerator.php
59 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Faker; |
| 4 | |
| 5 | /** |
| 6 | * Proxy for other generators, to return only unique values. Works with |
| 7 | * Faker\Generator\Base->unique() |
| 8 | */ |
| 9 | class UniqueGenerator |
| 10 | { |
| 11 | protected $generator; |
| 12 | protected $maxRetries; |
| 13 | protected $uniques = array(); |
| 14 | |
| 15 | /** |
| 16 | * @param Generator $generator |
| 17 | * @param integer $maxRetries |
| 18 | */ |
| 19 | public function __construct(Generator $generator, $maxRetries = 10000) |
| 20 | { |
| 21 | $this->generator = $generator; |
| 22 | $this->maxRetries = $maxRetries; |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Catch and proxy all generator calls but return only unique values |
| 27 | * @param string $attribute |
| 28 | * @return mixed |
| 29 | */ |
| 30 | public function __get($attribute) |
| 31 | { |
| 32 | return $this->__call($attribute, array()); |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Catch and proxy all generator calls with arguments but return only unique values |
| 37 | * @param string $name |
| 38 | * @param array $arguments |
| 39 | * @return mixed |
| 40 | */ |
| 41 | public function __call($name, $arguments) |
| 42 | { |
| 43 | if (!isset($this->uniques[$name])) { |
| 44 | $this->uniques[$name] = array(); |
| 45 | } |
| 46 | $i = 0; |
| 47 | do { |
| 48 | $res = call_user_func_array(array($this->generator, $name), $arguments); |
| 49 | $i++; |
| 50 | if ($i > $this->maxRetries) { |
| 51 | throw new \OverflowException(sprintf('Maximum retries of %d reached without finding a unique value', $this->maxRetries)); |
| 52 | } |
| 53 | } while (array_key_exists(serialize($res), $this->uniques[$name])); |
| 54 | $this->uniques[$name][serialize($res)]= null; |
| 55 | |
| 56 | return $res; |
| 57 | } |
| 58 | } |
| 59 |