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, to return only valid values. Works with
9
 * Faker\Generator\Base->valid()
10
 *
11
 * @mixin Generator
12
 */
13
class ValidGenerator
14
{
15
    protected $generator;
16
    protected $validator;
17
    protected $maxRetries;
18
 
19
    /**
20
     * @param Extension|Generator $generator
21
     * @param callable|null       $validator
22
     * @param int                 $maxRetries
23
     */
24
    public function __construct($generator, $validator = null, $maxRetries = 10000)
25
    {
26
        if (null === $validator) {
27
            $validator = static function () {
28
                return true;
29
            };
30
        } elseif (!is_callable($validator)) {
31
            throw new \InvalidArgumentException('valid() only accepts callables as first argument');
32
        }
33
        $this->generator = $generator;
34
        $this->validator = $validator;
35
        $this->maxRetries = $maxRetries;
36
    }
37
 
38
    public function ext(string $id)
39
    {
40
        return new self($this->generator->ext($id), $this->validator, $this->maxRetries);
41
    }
42
 
43
    /**
44
     * Catch and proxy all generator calls but return only valid values
45
     *
46
     * @param string $attribute
47
     *
48
     * @deprecated Use a method instead.
49
     */
50
    public function __get($attribute)
51
    {
52
        trigger_deprecation('fakerphp/faker', '1.14', 'Accessing property "%s" is deprecated, use "%s()" instead.', $attribute, $attribute);
53
 
54
        return $this->__call($attribute, []);
55
    }
56
 
57
    /**
58
     * Catch and proxy all generator calls with arguments but return only valid values
59
     *
60
     * @param string $name
61
     * @param array  $arguments
62
     */
63
    public function __call($name, $arguments)
64
    {
65
        $i = 0;
66
 
67
        do {
68
            $res = call_user_func_array([$this->generator, $name], $arguments);
69
            ++$i;
70
 
71
            if ($i > $this->maxRetries) {
72
                throw new \OverflowException(sprintf('Maximum retries of %d reached without finding a valid value', $this->maxRetries));
73
            }
74
        } while (!call_user_func($this->validator, $res));
75
 
76
        return $res;
77
    }
78
}