-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathMappedEventSubscriber.php
More file actions
376 lines (329 loc) · 12.9 KB
/
MappedEventSubscriber.php
File metadata and controls
376 lines (329 loc) · 12.9 KB
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
<?php
/*
* This file is part of the Doctrine Behavioral Extensions package.
* (c) Gediminas Morkevicius <gediminas.morkevicius@gmail.com> http://www.gediminasm.org
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Gedmo\Mapping;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\PsrCachedReader;
use Doctrine\Common\Annotations\Reader;
use Doctrine\Common\EventArgs;
use Doctrine\Common\EventSubscriber;
use Doctrine\Deprecations\Deprecation;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata as DocumentClassMetadata;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata as EntityClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo as LegacyEntityClassMetadata;
use Doctrine\Persistence\Mapping\AbstractClassMetadataFactory;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\ObjectManager;
use Gedmo\Exception\InvalidArgumentException;
use Gedmo\Mapping\Driver\AttributeReader;
use Gedmo\Mapping\Event\AdapterInterface;
use Gedmo\Mapping\Event\ClockAwareAdapterInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Clock\ClockInterface;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
/**
* This is extension of event subscriber class and is
* used specifically for handling the extension metadata
* mapping for extensions.
*
* It dries up some reusable code which is common for
* all extensions who maps additional metadata through
* extended drivers
*
* @phpstan-template TConfig of array
* @phpstan-template TEventAdapter of AdapterInterface
*
* @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
*/
abstract class MappedEventSubscriber implements EventSubscriber
{
/**
* Static List of cached object configurations
* leaving it static for reasons to look into
* other listener configuration
*
* @var array<string, array<string, array<string, mixed>>>
*
* @phpstan-var array<string, array<class-string, array<string, mixed>>>
*/
protected static $configurations = [];
/**
* Listener name, etc: sluggable
*
* @var string
*/
protected $name;
/**
* ExtensionMetadataFactory used to read the extension
* metadata through the extension drivers
*
* @var array<int, ExtensionMetadataFactory>
*/
private array $extensionMetadataFactory = [];
/**
* List of event adapters used for this listener
*
* @var array<string, AdapterInterface>
*/
private array $adapters = [];
/**
* Custom annotation reader
*
* @var Reader|AttributeReader|object|false|null
*/
private $annotationReader = false;
/**
* @var Reader|AttributeReader|false|null
*/
private static $defaultAnnotationReader = false;
/**
* @var CacheItemPoolInterface|null
*/
private $cacheItemPool;
private ?ClockInterface $clock = null;
/**
* Ignore doctrine driver class and force use attribute reader for gedmo properties
* @var bool
*/
private $forceUseAttributeReader = false;
public function __construct()
{
$parts = explode('\\', $this->getNamespace());
$this->name = end($parts);
}
public function setForceUseAttributeReader(bool $forceUseAttributeReader) {
$this->forceUseAttributeReader = $forceUseAttributeReader;
}
/**
* Get the configuration for specific object class
* if cache driver is present it scans it also
*
* @param string $class
*
* @phpstan-param class-string $class
*
* @return array<string, mixed>
*
* @phpstan-return TConfig
*/
public function getConfiguration(ObjectManager $objectManager, $class)
{
if (isset(self::$configurations[$this->name][$class])) {
return self::$configurations[$this->name][$class];
}
$config = [];
$cacheItemPool = $this->getCacheItemPool($objectManager);
$cacheId = ExtensionMetadataFactory::getCacheId($class, $this->getNamespace());
$cacheItem = $cacheItemPool->getItem($cacheId);
if ($cacheItem->isHit()) {
$config = $cacheItem->get();
self::$configurations[$this->name][$class] = $config;
} else {
// re-generate metadata on cache miss
$this->loadMetadataForObjectClass($objectManager, $objectManager->getClassMetadata($class));
if (isset(self::$configurations[$this->name][$class])) {
$config = self::$configurations[$this->name][$class];
}
}
$objectClass = $config['useObjectClass'] ?? $class;
if ($objectClass !== $class) {
$this->getConfiguration($objectManager, $objectClass);
}
return $config;
}
/**
* Get extended metadata mapping reader
*
* @return ExtensionMetadataFactory
*/
public function getExtensionMetadataFactory(ObjectManager $objectManager)
{
$oid = spl_object_id($objectManager);
if (!isset($this->extensionMetadataFactory[$oid])) {
if (false === $this->annotationReader) {
// create default annotation/attribute reader for extensions
$this->annotationReader = $this->getDefaultAnnotationReader();
}
$this->extensionMetadataFactory[$oid] = new ExtensionMetadataFactory(
$objectManager,
$this->getNamespace(),
$this->annotationReader,
$this->getCacheItemPool($objectManager),
$this->forceUseAttributeReader
);
}
return $this->extensionMetadataFactory[$oid];
}
/**
* Set the annotation reader instance
*
* When originally implemented, `Doctrine\Common\Annotations\Reader` was not available,
* therefore this method may accept any object implementing these methods from the interface:
*
* getClassAnnotations([reflectionClass])
* getClassAnnotation([reflectionClass], [name])
* getPropertyAnnotations([reflectionProperty])
* getPropertyAnnotation([reflectionProperty], [name])
*
* @param Reader|AttributeReader|object $reader
*
* @return void
*
* @note Providing any object is deprecated, as of 4.0 an {@see AttributeReader} will be required
*/
public function setAnnotationReader($reader)
{
if ($reader instanceof Reader) {
Deprecation::trigger(
'gedmo/doctrine-extensions',
'https://github.com/doctrine-extensions/DoctrineExtensions/pull/2772',
'Annotations support is deprecated, migrate your application to use attributes and pass an instance of %s to the %s() method instead.',
AttributeReader::class,
__METHOD__
);
} elseif (!$reader instanceof AttributeReader) {
Deprecation::trigger(
'gedmo/doctrine-extensions',
'https://github.com/doctrine-extensions/DoctrineExtensions/pull/2558',
'Providing an annotation reader which does not implement %s or is not an instance of %s to %s() is deprecated.',
Reader::class,
AttributeReader::class,
__METHOD__
);
}
$this->annotationReader = $reader;
}
final public function setCacheItemPool(CacheItemPoolInterface $cacheItemPool): void
{
$this->cacheItemPool = $cacheItemPool;
}
final public function setClock(ClockInterface $clock): void
{
$this->clock = $clock;
}
/**
* Scans the objects for extended annotations
* event subscribers must subscribe to loadClassMetadata event
*
* @param ClassMetadata<object> $metadata
*
* @return void
*/
public function loadMetadataForObjectClass(ObjectManager $objectManager, $metadata)
{
assert($metadata instanceof DocumentClassMetadata || $metadata instanceof EntityClassMetadata || $metadata instanceof LegacyEntityClassMetadata);
$factory = $this->getExtensionMetadataFactory($objectManager);
try {
$config = $factory->getExtensionMetadata($metadata);
} catch (\ReflectionException $e) {
// entity\document generator is running
$config = []; // will not store a cached version, to remap later
}
if ([] !== $config) {
self::$configurations[$this->name][$metadata->getName()] = $config;
}
}
/**
* Get an event adapter to handle event specific
* methods
*
* @throws InvalidArgumentException if event is not recognized
*
* @return AdapterInterface
*
* @phpstan-return TEventAdapter
*/
protected function getEventAdapter(EventArgs $args)
{
$class = get_class($args);
if (preg_match('@Doctrine\\\([^\\\]+)@', $class, $m) && in_array($m[1], ['ODM', 'ORM'], true)) {
if (!isset($this->adapters[$m[1]])) {
$adapterClass = $this->getNamespace().'\\Mapping\\Event\\Adapter\\'.$m[1];
if (!\class_exists($adapterClass)) {
$adapterClass = 'Gedmo\\Mapping\\Event\\Adapter\\'.$m[1];
}
$this->adapters[$m[1]] = new $adapterClass();
if ($this->adapters[$m[1]] instanceof ClockAwareAdapterInterface && $this->clock instanceof ClockInterface) {
$this->adapters[$m[1]]->setClock($this->clock);
}
}
$this->adapters[$m[1]]->setEventArgs($args);
return $this->adapters[$m[1]];
}
throw new InvalidArgumentException('Event mapper does not support event arg class: '.$class);
}
/**
* Get the namespace of extension event subscriber.
* used for cache id of extensions also to know where
* to find Mapping drivers and event adapters
*
* @return string
*/
abstract protected function getNamespace();
/**
* Sets the value for a mapped field
*
* @param object $object
* @param string $field
* @param mixed $oldValue
* @param mixed $newValue
*
* @return void
*/
protected function setFieldValue(AdapterInterface $adapter, $object, $field, $oldValue, $newValue)
{
$manager = $adapter->getObjectManager();
$meta = $manager->getClassMetadata(get_class($object));
$uow = $manager->getUnitOfWork();
$meta->setFieldValue($object, $field, $newValue);
$uow->propertyChanged($object, $field, $oldValue, $newValue);
$adapter->recomputeSingleObjectChangeSet($uow, $meta, $object);
}
/**
* Get the default annotation or attribute reader for extensions, creating it if necessary.
*
* If a reader cannot be created due to missing requirements, no default will be set as the reader is only required for annotation or attribute metadata,
* and the {@see ExtensionMetadataFactory} can handle raising an error if it tries to create a mapping driver that requires this reader.
*
* @return Reader|AttributeReader|null
*/
private function getDefaultAnnotationReader()
{
if (false === self::$defaultAnnotationReader) {
if (class_exists(PsrCachedReader::class)) {
self::$defaultAnnotationReader = new PsrCachedReader(new AnnotationReader(), new ArrayAdapter());
} elseif (\PHP_VERSION_ID >= 80000) {
self::$defaultAnnotationReader = new AttributeReader();
} else {
self::$defaultAnnotationReader = null;
}
}
return self::$defaultAnnotationReader;
}
private function getCacheItemPool(ObjectManager $objectManager): CacheItemPoolInterface
{
if (null !== $this->cacheItemPool) {
return $this->cacheItemPool;
}
// TODO: The user should configure its own cache, we are using the one from Doctrine for BC. We should deprecate using
// the one from Doctrine when the bundle offers an easy way to configure this cache, otherwise users using the bundle
// will see lots of deprecations without an easy way to avoid them.
if ($objectManager instanceof EntityManagerInterface || $objectManager instanceof DocumentManager) {
$metadataFactory = $objectManager->getMetadataFactory();
$getCache = \Closure::bind(static fn (AbstractClassMetadataFactory $metadataFactory): ?CacheItemPoolInterface => $metadataFactory->getCache(), null, \get_class($metadataFactory));
$metadataCache = $getCache($metadataFactory);
if (null !== $metadataCache) {
$this->cacheItemPool = $metadataCache;
return $this->cacheItemPool;
}
}
$this->cacheItemPool = new ArrayAdapter();
return $this->cacheItemPool;
}
}