-
-
Notifications
You must be signed in to change notification settings - Fork 505
/
Copy pathAttributeDriver.php
451 lines (380 loc) · 16.6 KB
/
AttributeDriver.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
<?php
declare(strict_types=1);
namespace Doctrine\ODM\MongoDB\Mapping\Driver;
use Doctrine\Common\Annotations\Reader;
use Doctrine\ODM\MongoDB\Events;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Mapping\Annotations\AbstractIndex;
use Doctrine\ODM\MongoDB\Mapping\Annotations\SearchIndex;
use Doctrine\ODM\MongoDB\Mapping\Annotations\ShardKey;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\Mapping\MappingException;
use Doctrine\Persistence\Mapping\ClassMetadata as PersistenceClassMetadata;
use Doctrine\Persistence\Mapping\Driver\ColocatedMappingDriver;
use Doctrine\Persistence\Mapping\Driver\MappingDriver;
use MongoDB\Driver\Exception\UnexpectedValueException;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use function array_merge;
use function array_replace;
use function assert;
use function class_exists;
use function constant;
use function count;
use function is_array;
use function MongoDB\BSON\fromJSON;
use function MongoDB\BSON\toPHP;
use function trigger_deprecation;
/**
* The AtttributeDriver reads the mapping metadata from attributes.
*/
class AttributeDriver implements MappingDriver
{
use ColocatedMappingDriver;
/**
* @internal this property will be private in 3.0
*
* @var Reader|AttributeReader
*/
protected $reader;
/** @param string|string[]|null $paths */
public function __construct($paths = null, ?Reader $reader = null)
{
if ($reader !== null) {
trigger_deprecation(
'doctrine/mongodb-odm',
'2.7',
'Passing a $reader parameter to %s is deprecated',
__METHOD__,
);
}
$this->reader = $reader ?? new AttributeReader();
$this->addPaths((array) $paths);
}
public function isTransient($className)
{
$classAttributes = $this->getClassAttributes(new ReflectionClass($className));
foreach ($classAttributes as $attribute) {
if ($attribute instanceof ODM\AbstractDocument) {
return false;
}
}
return true;
}
public function loadMetadataForClass($className, PersistenceClassMetadata $metadata): void
{
assert($metadata instanceof ClassMetadata);
$reflClass = $metadata->getReflectionClass();
$classAttributes = $this->getClassAttributes($reflClass);
$documentAttribute = null;
foreach ($classAttributes as $attribute) {
$classAttributes[$attribute::class] = $attribute;
if ($attribute instanceof ODM\AbstractDocument) {
if ($documentAttribute !== null) {
throw MappingException::classCanOnlyBeMappedByOneAbstractDocument($className, $documentAttribute, $attribute);
}
$documentAttribute = $attribute;
}
// non-document class attributes
if ($attribute instanceof ODM\AbstractIndex) {
$this->addIndex($metadata, $attribute);
}
if ($attribute instanceof ODM\SearchIndex) {
$this->addSearchIndex($metadata, $attribute);
}
if ($attribute instanceof ODM\Indexes) {
trigger_deprecation(
'doctrine/mongodb-odm',
'2.2',
'The "@Indexes" attribute used in class "%s" is deprecated. Specify all "@Index" and "@UniqueIndex" attributes on the class.',
$className,
);
$value = $attribute->value;
foreach (is_array($value) ? $value : [$value] as $index) {
$this->addIndex($metadata, $index);
}
} elseif ($attribute instanceof ODM\InheritanceType) {
$metadata->setInheritanceType(constant(ClassMetadata::class . '::INHERITANCE_TYPE_' . $attribute->value));
} elseif ($attribute instanceof ODM\DiscriminatorField) {
$metadata->setDiscriminatorField($attribute->value);
} elseif ($attribute instanceof ODM\DiscriminatorMap) {
$value = $attribute->value;
assert(is_array($value));
$metadata->setDiscriminatorMap($value);
} elseif ($attribute instanceof ODM\DiscriminatorValue) {
$metadata->setDiscriminatorValue($attribute->value);
} elseif ($attribute instanceof ODM\ChangeTrackingPolicy) {
$metadata->setChangeTrackingPolicy(constant(ClassMetadata::class . '::CHANGETRACKING_' . $attribute->value));
} elseif ($attribute instanceof ODM\DefaultDiscriminatorValue) {
$metadata->setDefaultDiscriminatorValue($attribute->value);
} elseif ($attribute instanceof ODM\ReadPreference) {
$metadata->setReadPreference($attribute->value, $attribute->tags ?? []);
} elseif ($attribute instanceof ODM\Validation) {
if (isset($attribute->validator)) {
try {
$validatorBson = fromJSON($attribute->validator);
} catch (UnexpectedValueException $e) {
throw MappingException::schemaValidationError($e->getCode(), $e->getMessage(), $className, 'validator');
}
$validator = toPHP($validatorBson, []);
$metadata->setValidator($validator);
}
if (isset($attribute->action)) {
$metadata->setValidationAction($attribute->action);
}
if (isset($attribute->level)) {
$metadata->setValidationLevel($attribute->level);
}
}
}
if ($documentAttribute === null) {
throw MappingException::classIsNotAValidDocument($className);
}
if ($documentAttribute instanceof ODM\MappedSuperclass) {
$metadata->isMappedSuperclass = true;
} elseif ($documentAttribute instanceof ODM\EmbeddedDocument) {
$metadata->isEmbeddedDocument = true;
} elseif ($documentAttribute instanceof ODM\QueryResultDocument) {
$metadata->isQueryResultDocument = true;
} elseif ($documentAttribute instanceof ODM\View) {
if (! $documentAttribute->rootClass) {
throw MappingException::viewWithoutRootClass($className);
}
if (! class_exists($documentAttribute->rootClass)) {
throw MappingException::viewRootClassNotFound($className, $documentAttribute->rootClass);
}
$metadata->markViewOf($documentAttribute->rootClass);
} elseif ($documentAttribute instanceof ODM\File) {
$metadata->isFile = true;
if ($documentAttribute->chunkSizeBytes !== null) {
$metadata->setChunkSizeBytes($documentAttribute->chunkSizeBytes);
}
}
if (isset($documentAttribute->db)) {
$metadata->setDatabase($documentAttribute->db);
}
if (isset($documentAttribute->collection)) {
$metadata->setCollection($documentAttribute->collection);
}
if (isset($documentAttribute->view)) {
$metadata->setCollection($documentAttribute->view);
}
// Store bucketName as collection name for GridFS files
if (isset($documentAttribute->bucketName)) {
$metadata->setBucketName($documentAttribute->bucketName);
}
if (isset($documentAttribute->repositoryClass)) {
$metadata->setCustomRepositoryClass($documentAttribute->repositoryClass);
}
if (isset($documentAttribute->writeConcern)) {
$metadata->setWriteConcern($documentAttribute->writeConcern);
}
if (isset($documentAttribute->indexes) && count($documentAttribute->indexes)) {
trigger_deprecation(
'doctrine/mongodb-odm',
'2.2',
'The "indexes" parameter in the "%s" attribute for class "%s" is deprecated. Specify all "@Index" and "@UniqueIndex" attributes on the class.',
$documentAttribute::class,
$className,
);
foreach ($documentAttribute->indexes as $index) {
$this->addIndex($metadata, $index);
}
}
if (! empty($documentAttribute->readOnly)) {
$metadata->markReadOnly();
}
foreach ($reflClass->getProperties() as $property) {
if (
($metadata->isMappedSuperclass && ! $property->isPrivate())
||
($metadata->isInheritedField($property->name) && $property->getDeclaringClass()->name !== $metadata->name)
) {
continue;
}
$indexes = [];
$mapping = ['fieldName' => $property->getName()];
$fieldAttribute = null;
foreach ($this->getPropertyAttributes($property) as $propertyAttribute) {
if ($propertyAttribute instanceof ODM\AbstractField) {
$fieldAttribute = $propertyAttribute;
}
if ($propertyAttribute instanceof ODM\AbstractIndex) {
$indexes[] = $propertyAttribute;
}
if ($propertyAttribute instanceof ODM\Indexes) {
trigger_deprecation(
'doctrine/mongodb-odm',
'2.2',
'The "@Indexes" attribute used in property "%s" of class "%s" is deprecated. Specify all "@Index" and "@UniqueIndex" attributes on the class.',
$property->getName(),
$className,
);
$value = $propertyAttribute->value;
foreach (is_array($value) ? $value : [$value] as $index) {
$indexes[] = $index;
}
} elseif ($propertyAttribute instanceof ODM\AlsoLoad) {
$mapping['alsoLoadFields'] = (array) $propertyAttribute->value;
} elseif ($propertyAttribute instanceof ODM\Version) {
$mapping['version'] = true;
} elseif ($propertyAttribute instanceof ODM\Lock) {
$mapping['lock'] = true;
}
}
if ($fieldAttribute) {
$mapping = array_replace($mapping, (array) $fieldAttribute);
$metadata->mapField($mapping);
}
if (! $indexes) {
continue;
}
foreach ($indexes as $index) {
$name = $mapping['name'] ?? $mapping['fieldName'];
$keys = [$name => $index->order ?: 'asc'];
$this->addIndex($metadata, $index, $keys);
}
}
// Set shard key after all fields to ensure we mapped all its keys
if (isset($classAttributes[ShardKey::class])) {
assert($classAttributes[ShardKey::class] instanceof ShardKey);
$this->setShardKey($metadata, $classAttributes[ShardKey::class]);
}
foreach ($reflClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
/* Filter for the declaring class only. Callbacks from parent
* classes will already be registered.
*/
if ($method->getDeclaringClass()->name !== $reflClass->name) {
continue;
}
foreach ($this->getMethodAttributes($method) as $methodAttribute) {
if ($methodAttribute instanceof ODM\AlsoLoad) {
$metadata->registerAlsoLoadMethod($method->getName(), $methodAttribute->value);
}
if (! isset($classAttributes[ODM\HasLifecycleCallbacks::class])) {
continue;
}
if ($methodAttribute instanceof ODM\PrePersist) {
$metadata->addLifecycleCallback($method->getName(), Events::prePersist);
} elseif ($methodAttribute instanceof ODM\PostPersist) {
$metadata->addLifecycleCallback($method->getName(), Events::postPersist);
} elseif ($methodAttribute instanceof ODM\PreUpdate) {
$metadata->addLifecycleCallback($method->getName(), Events::preUpdate);
} elseif ($methodAttribute instanceof ODM\PostUpdate) {
$metadata->addLifecycleCallback($method->getName(), Events::postUpdate);
} elseif ($methodAttribute instanceof ODM\PreRemove) {
$metadata->addLifecycleCallback($method->getName(), Events::preRemove);
} elseif ($methodAttribute instanceof ODM\PostRemove) {
$metadata->addLifecycleCallback($method->getName(), Events::postRemove);
} elseif ($methodAttribute instanceof ODM\PreLoad) {
$metadata->addLifecycleCallback($method->getName(), Events::preLoad);
} elseif ($methodAttribute instanceof ODM\PostLoad) {
$metadata->addLifecycleCallback($method->getName(), Events::postLoad);
} elseif ($methodAttribute instanceof ODM\PreFlush) {
$metadata->addLifecycleCallback($method->getName(), Events::preFlush);
}
}
}
}
/**
* @param ClassMetadata<object> $class
* @param array<string, int|string> $keys
*/
private function addIndex(ClassMetadata $class, AbstractIndex $index, array $keys = []): void
{
$keys = array_merge($keys, $index->keys);
$options = [];
$allowed = ['name', 'background', 'unique', 'sparse', 'expireAfterSeconds'];
foreach ($allowed as $name) {
if (! isset($index->$name)) {
continue;
}
$options[$name] = $index->$name;
}
if (! empty($index->partialFilterExpression)) {
$options['partialFilterExpression'] = $index->partialFilterExpression;
}
$options = array_merge($options, $index->options);
$class->addIndex($keys, $options);
}
/** @param ClassMetadata<object> $class */
private function addSearchIndex(ClassMetadata $class, SearchIndex $index): void
{
$definition = [];
foreach (['dynamic', 'fields'] as $key) {
if (isset($index->$key)) {
$definition['mappings'][$key] = $index->$key;
}
}
foreach (['analyzer', 'searchAnalyzer', 'analyzers', 'storedSource', 'synonyms'] as $key) {
if (isset($index->$key)) {
$definition[$key] = $index->$key;
}
}
$class->addSearchIndex($definition, $index->name ?? null);
}
/**
* @param ClassMetadata<object> $class
*
* @throws MappingException
*/
private function setShardKey(ClassMetadata $class, ODM\ShardKey $shardKey): void
{
$options = [];
$allowed = ['unique', 'numInitialChunks'];
foreach ($allowed as $name) {
if (! isset($shardKey->$name)) {
continue;
}
$options[$name] = $shardKey->$name;
}
$class->setShardKey($shardKey->keys, $options);
}
/** @return Reader|AttributeReader */
public function getReader()
{
trigger_deprecation(
'doctrine/mongodb-odm',
'2.4',
'%s is deprecated with no replacement',
__METHOD__,
);
return $this->reader;
}
/**
* Factory method for the Attribute Driver
*
* @param string[]|string $paths
*
* @return AttributeDriver
*/
public static function create($paths = [], ?Reader $reader = null)
{
return new self($paths, $reader);
}
/** @return object[] */
private function getClassAttributes(ReflectionClass $class): array
{
if ($this->reader instanceof AttributeReader) {
return $this->reader->getClassAttributes($class);
}
return $this->reader->getClassAnnotations($class);
}
/** @return object[] */
private function getMethodAttributes(ReflectionMethod $method): array
{
if ($this->reader instanceof AttributeReader) {
return $this->reader->getMethodAttributes($method);
}
return $this->reader->getMethodAnnotations($method);
}
/** @return object[] */
private function getPropertyAttributes(ReflectionProperty $property): array
{
if ($this->reader instanceof AttributeReader) {
return $this->reader->getPropertyAttributes($property);
}
return $this->reader->getPropertyAnnotations($property);
}
}