MaxDistinctGenerator   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 51
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __get() 0 3 1
A __call() 0 16 4
1
<?php
2
3
namespace Kaliop\eZLoremIpsumBundle\Faker;
4
5
use Faker\Generator;
6
7
/**
8
 * Proxy for other generators, to return only a limited amount of distinct values. Works with
9
 * Faker\Generator\Base->unique()
10
 */
11
class MaxDistinctGenerator
12
{
13
    protected $generator;
14
    protected $maxElements;
15
    protected $maxTries = 10000;
16
    protected $uniques = array();
17
18
    /**
19
     * @param Generator $generator
20
     * @param integer $maxElements
21
     */
22
    public function __construct(Generator $generator, $maxElements = 100)
23
    {
24
        $this->generator = $generator;
25
        $this->maxElements = $maxElements;
26
    }
27
28
    /**
29
     * Catch and proxy all generator calls but return only unique values
30
     * @param string $attribute
31
     * @return mixed
32
     */
33
    public function __get($attribute)
34
    {
35
        return $this->__call($attribute, array());
36
    }
37
38
    /**
39
     * Catch and proxy all generator calls with arguments and return only up to maxElements unique values.
40
     * NB: does *not* guarantee that all returned values are unique - combine it with a `unique()` modifier for that.
41
     *
42
     * @param string $name
43
     * @param array $arguments
44
     * @return mixed
45
     */
46
    public function __call($name, $arguments)
47
    {
48
        if (!isset($this->uniques[$name])) {
49
            $this->uniques[$name] = array();
50
        }
51
52
        if (count($this->uniques[$name]) >= $this->maxElements) {
53
            return unserialize($this->uniques[$name][mt_rand(0, count($this->uniques[$name]) - 1)]);
54
        }
55
56
        $res = call_user_func_array(array($this->generator, $name), $arguments);
57
        $sres = serialize($res);
58
        if (!in_array($sres, $this->uniques[$name])) {
59
            $this->uniques[$name][] = $sres;
60
        }
61
        return $res;
62
    }
63
}
64