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