forked from fzaninotto/Faker
-
Notifications
You must be signed in to change notification settings - Fork 327
/
EntityPopulator.php
246 lines (201 loc) · 7.14 KB
/
EntityPopulator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<?php
namespace Faker\ORM\Doctrine;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Doctrine\Common\Persistence\ObjectManager;
/**
* Service class for populating a table through a Doctrine Entity class.
*/
class EntityPopulator
{
/**
* @var ClassMetadata
*/
protected $class;
/**
* @var array
*/
protected $columnFormatters = [];
/**
* @var array
*/
protected $modifiers = [];
public function __construct(ClassMetadata $class)
{
$this->class = $class;
}
/**
* @return string
*/
public function getClass()
{
return $this->class->getName();
}
public function setColumnFormatters($columnFormatters)
{
$this->columnFormatters = $columnFormatters;
}
/**
* @return array
*/
public function getColumnFormatters()
{
return $this->columnFormatters;
}
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}
public function setModifiers(array $modifiers)
{
$this->modifiers = $modifiers;
}
/**
* @return array
*/
public function getModifiers()
{
return $this->modifiers;
}
public function mergeModifiersWith(array $modifiers)
{
$this->modifiers = array_merge($this->modifiers, $modifiers);
}
/**
* @return array
*/
public function guessColumnFormatters(\Faker\Generator $generator)
{
$formatters = [];
$nameGuesser = new \Faker\Guesser\Name($generator);
$columnTypeGuesser = new ColumnTypeGuesser($generator);
foreach ($this->class->getFieldNames() as $fieldName) {
if ($this->class->isIdentifier($fieldName) || !$this->class->hasField($fieldName)) {
continue;
}
$size = $this->class->fieldMappings[$fieldName]['length'] ?? null;
if ($formatter = $nameGuesser->guessFormat($fieldName, $size)) {
$formatters[$fieldName] = $formatter;
continue;
}
if ($formatter = $columnTypeGuesser->guessFormat($fieldName, $this->class)) {
$formatters[$fieldName] = $formatter;
continue;
}
}
foreach ($this->class->getAssociationNames() as $assocName) {
if ($this->class->isCollectionValuedAssociation($assocName)) {
continue;
}
$relatedClass = $this->class->getAssociationTargetClass($assocName);
$unique = $optional = false;
if ($this->class instanceof \Doctrine\ORM\Mapping\ClassMetadata) {
$mappings = $this->class->getAssociationMappings();
foreach ($mappings as $mapping) {
if ($mapping['targetEntity'] == $relatedClass) {
if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadata::ONE_TO_ONE) {
$unique = true;
$optional = $mapping['joinColumns'][0]['nullable'] ?? false;
break;
}
}
}
} elseif ($this->class instanceof \Doctrine\ODM\MongoDB\Mapping\ClassMetadata) {
$mappings = $this->class->associationMappings;
foreach ($mappings as $mapping) {
if ($mapping['targetDocument'] == $relatedClass) {
if ($mapping['type'] == \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::ONE && $mapping['association'] == \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::REFERENCE_ONE) {
$unique = true;
$optional = $mapping['nullable'] ?? false;
break;
}
}
}
}
$index = 0;
$formatters[$assocName] = static function ($inserted) use ($relatedClass, &$index, $unique, $optional, $generator) {
if (isset($inserted[$relatedClass])) {
if ($unique) {
$related = null;
if (isset($inserted[$relatedClass][$index]) || !$optional) {
$related = $inserted[$relatedClass][$index];
}
++$index;
return $related;
}
return $generator->randomElement($inserted[$relatedClass]);
}
return null;
};
}
return $formatters;
}
/**
* Insert one new record using the Entity class.
*
* @param bool $generateId
*
* @return EntityPopulator
*/
public function execute(ObjectManager $manager, $insertedEntities, $generateId = false)
{
$obj = $this->class->newInstance();
$this->fillColumns($obj, $insertedEntities);
$this->callMethods($obj, $insertedEntities);
if ($generateId) {
$idsName = $this->class->getIdentifier();
foreach ($idsName as $idName) {
$id = $this->generateId($obj, $idName, $manager);
$this->class->reflFields[$idName]->setValue($obj, $id);
}
}
$manager->persist($obj);
return $obj;
}
private function fillColumns($obj, $insertedEntities)
{
foreach ($this->columnFormatters as $field => $format) {
if (null !== $format) {
// Add some extended debugging information to any errors thrown by the formatter
try {
$value = is_callable($format) ? $format($insertedEntities, $obj) : $format;
} catch (\InvalidArgumentException $ex) {
throw new \InvalidArgumentException(sprintf(
'Failed to generate a value for %s::%s: %s',
get_class($obj),
$field,
$ex->getMessage()
));
}
// Try a standard setter if it's available, otherwise fall back on reflection
$setter = sprintf('set%s', ucfirst($field));
if (is_callable([$obj, $setter])) {
$obj->$setter($value);
} else {
$this->class->reflFields[$field]->setValue($obj, $value);
}
}
}
}
private function callMethods($obj, $insertedEntities)
{
foreach ($this->getModifiers() as $modifier) {
$modifier($obj, $insertedEntities);
}
}
/**
* @return int
*/
private function generateId($obj, $column, ObjectManager $manager)
{
$repository = $manager->getRepository(get_class($obj));
$result = $repository->createQueryBuilder('e')
->select(sprintf('e.%s', $column))
->getQuery()
->execute();
$ids = array_map('current', $result->toArray());
do {
$id = mt_rand();
} while (in_array($id, $ids, false));
return $id;
}
}