1
|
|
|
<?php |
2
|
|
|
namespace DBFaker\Generators; |
3
|
|
|
|
4
|
|
|
use DBFaker\DBFaker; |
5
|
|
|
use DBFaker\Exceptions\MaxNbOfIterationsForUniqueValueException; |
6
|
|
|
use Doctrine\DBAL\Schema\Column; |
7
|
|
|
|
8
|
|
|
abstract class UniqueAbleGenerator implements FakeDataGeneratorInterface |
9
|
|
|
{ |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @var bool |
13
|
|
|
*/ |
14
|
|
|
private $generateUniqueValues; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var Column |
18
|
|
|
*/ |
19
|
|
|
private $column; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var mixed[]; |
23
|
|
|
*/ |
24
|
|
|
private $generatedValues = []; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* ComplexObjectGenerator constructor. |
28
|
|
|
* @param Column $column |
29
|
|
|
* @param bool $generateUniqueValues |
30
|
|
|
*/ |
31
|
|
|
public function __construct(Column $column, bool $generateUniqueValues = false) |
32
|
|
|
{ |
33
|
|
|
$this->generateUniqueValues = $generateUniqueValues; |
34
|
|
|
$this->column = $column; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @return mixed |
39
|
|
|
*/ |
40
|
|
|
public function __invoke() |
41
|
|
|
{ |
42
|
|
|
$object = $this->generateRandomValue($this->column); |
43
|
|
|
$iterations = 1; |
44
|
|
|
while (!$this->isUnique($object)) { |
45
|
|
|
$object = $this->generateRandomValue($this->column); |
46
|
|
|
$iterations++; |
47
|
|
|
if ($iterations > DBFaker::MAX_ITERATIONS_FOR_UNIQUE_VALUE) { |
48
|
|
|
throw new MaxNbOfIterationsForUniqueValueException('Unable to generate a unique value in less then maximumn allowed iterations.'); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
$this->storeObjectInGeneratedValues($object); |
52
|
|
|
|
53
|
|
|
return $object; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param Column $column |
58
|
|
|
* @return mixed |
59
|
|
|
*/ |
60
|
|
|
abstract protected function generateRandomValue(Column $column); |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param mixed $object |
64
|
|
|
*/ |
65
|
|
|
private function storeObjectInGeneratedValues($object) : void |
66
|
|
|
{ |
67
|
|
|
if ($this->generateUniqueValues) { |
68
|
|
|
$this->generatedValues[] = $object; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param mixed $object |
74
|
|
|
* @return bool |
75
|
|
|
*/ |
76
|
|
|
private function isUnique($object) : bool |
77
|
|
|
{ |
78
|
|
|
if (!$this->generateUniqueValues) { |
79
|
|
|
return true; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
$filtered = array_filter($this->generatedValues, function ($value) use ($object) { |
83
|
|
|
return $object === $value; |
84
|
|
|
}); |
85
|
|
|
return count($filtered) === 0; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|