Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
namespace Faker;
4
 
5
use Faker\Extension\Extension;
6
 
7
/**
8
 * Proxy for other generators that returns only unique values.
9
 *
10
 * Instantiated through @see Generator::unique().
11
 *
12
 * @mixin Generator
13
 */
14
class UniqueGenerator
15
{
16
    protected $generator;
17
    protected $maxRetries;
18
 
19
    /**
20
     * Maps from method names to a map with serialized result keys.
21
     *
22
     * @example [
23
     *   'phone' => ['0123' => null],
24
     *   'city' => ['London' => null, 'Tokyo' => null],
25
     * ]
26
     *
27
     * @var array<string, array<string, null>>
28
     */
29
    protected $uniques = [];
30
 
31
    /**
32
     * @param Extension|Generator                $generator
33
     * @param int                                $maxRetries
34
     * @param array<string, array<string, null>> $uniques
35
     */
36
    public function __construct($generator, $maxRetries = 10000, &$uniques = [])
37
    {
38
        $this->generator = $generator;
39
        $this->maxRetries = $maxRetries;
40
        $this->uniques = &$uniques;
41
    }
42
 
43
    public function ext(string $id)
44
    {
45
        return new self($this->generator->ext($id), $this->maxRetries, $this->uniques);
46
    }
47
 
48
    /**
49
     * Catch and proxy all generator calls but return only unique values
50
     *
51
     * @param string $attribute
52
     *
53
     * @deprecated Use a method instead.
54
     */
55
    public function __get($attribute)
56
    {
57
        trigger_deprecation('fakerphp/faker', '1.14', 'Accessing property "%s" is deprecated, use "%s()" instead.', $attribute, $attribute);
58
 
59
        return $this->__call($attribute, []);
60
    }
61
 
62
    /**
63
     * Catch and proxy all generator calls with arguments but return only unique values
64
     *
65
     * @param string $name
66
     * @param array  $arguments
67
     */
68
    public function __call($name, $arguments)
69
    {
70
        if (!isset($this->uniques[$name])) {
71
            $this->uniques[$name] = [];
72
        }
73
        $i = 0;
74
 
75
        do {
76
            $res = call_user_func_array([$this->generator, $name], $arguments);
77
            ++$i;
78
 
79
            if ($i > $this->maxRetries) {
80
                throw new \OverflowException(sprintf('Maximum retries of %d reached without finding a unique value', $this->maxRetries));
81
            }
82
        } while (array_key_exists(serialize($res), $this->uniques[$name]));
83
        $this->uniques[$name][serialize($res)] = null;
84
 
85
        return $res;
86
    }
87
}