Failed Conditions
Pull Request — 1.3.x (#71)
by Grégoire
02:19
created

AbstractClassMetadataFactory   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 390
Duplicated Lines 0 %

Test Coverage

Coverage 67.31%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 36
eloc 96
c 1
b 0
f 0
dl 0
loc 390
ccs 70
cts 104
cp 0.6731
rs 9.52

14 Methods

Rating   Name   Duplication   Size   Complexity  
A hasMetadataFor() 0 3 1
A isTransient() 0 13 3
A getCacheDriver() 0 3 1
A getParentClasses() 0 14 3
A setMetadataFor() 0 3 1
A setReflectionService() 0 3 1
A getLoadedMetadata() 0 3 1
A setCacheDriver() 0 3 1
A getAllMetadata() 0 13 3
B getMetadataFor() 0 56 10
A onNotFoundMetadata() 0 3 1
B loadMetadata() 0 46 6
A getReflectionService() 0 7 2
A getRealClass() 0 9 2
1
<?php
2
3
namespace Doctrine\Persistence\Mapping;
4
5
use Doctrine\Common\Cache\Cache;
6
use Doctrine\Persistence\Mapping\Driver\MappingDriver;
7
use Doctrine\Persistence\Proxy;
8
use ReflectionException;
9
use function array_reverse;
10
use function array_unshift;
11
use function class_exists;
12
use function explode;
13
use function strpos;
14
use function strrpos;
15
use function substr;
16
17
/**
18
 * The ClassMetadataFactory is used to create ClassMetadata objects that contain all the
19
 * metadata mapping informations of a class which describes how a class should be mapped
20
 * to a relational database.
21
 *
22
 * This class was abstracted from the ORM ClassMetadataFactory.
23
 */
24
abstract class AbstractClassMetadataFactory implements ClassMetadataFactory
0 ignored issues
show
introduced by
Superfluous prefix "Abstract".
Loading history...
25
{
26
    /**
27
     * Salt used by specific Object Manager implementation.
28
     *
29
     * @var string
30
     */
31
    protected $cacheSalt = '$CLASSMETADATA';
32
33
    /** @var Cache|null */
34
    private $cacheDriver;
35
36
    /** @var ClassMetadata[] */
37
    private $loadedMetadata = [];
38
39
    /** @var bool */
40
    protected $initialized = false;
41
42
    /** @var ReflectionService|null */
43
    private $reflectionService = null;
44
45
    /**
46
     * Sets the cache driver used by the factory to cache ClassMetadata instances.
47
     *
48
     * @return void
49
     */
50 4
    public function setCacheDriver(?Cache $cacheDriver = null)
51
    {
52 4
        $this->cacheDriver = $cacheDriver;
53 4
    }
54
55
    /**
56
     * Gets the cache driver used by the factory to cache ClassMetadata instances.
57
     *
58
     * @return Cache|null
59
     */
60 1
    public function getCacheDriver()
61
    {
62 1
        return $this->cacheDriver;
63
    }
64
65
    /**
66
     * Returns an array of all the loaded metadata currently in memory.
67
     *
68
     * @return ClassMetadata[]
69
     */
70
    public function getLoadedMetadata()
71
    {
72
        return $this->loadedMetadata;
73
    }
74
75
    /**
76
     * Forces the factory to load the metadata of all classes known to the underlying
77
     * mapping driver.
78
     *
79
     * @return ClassMetadata[] The ClassMetadata instances of all mapped classes.
80
     */
81
    public function getAllMetadata()
82
    {
83
        if (! $this->initialized) {
84
            $this->initialize();
85
        }
86
87
        $driver   = $this->getDriver();
88
        $metadata = [];
89
        foreach ($driver->getAllClassNames() as $className) {
90
            $metadata[] = $this->getMetadataFor($className);
91
        }
92
93
        return $metadata;
94
    }
95
96
    /**
97
     * Lazy initialization of this stuff, especially the metadata driver,
98
     * since these are not needed at all when a metadata cache is active.
99
     *
100
     * @return void
101
     */
102
    abstract protected function initialize();
103
104
    /**
105
     * Gets the fully qualified class-name from the namespace alias.
106
     *
107
     * @param string $namespaceAlias
108
     * @param string $simpleClassName
109
     *
110
     * @return string
111
     */
112
    abstract protected function getFqcnFromAlias($namespaceAlias, $simpleClassName);
113
114
    /**
115
     * Returns the mapping driver implementation.
116
     *
117
     * @return MappingDriver
118
     */
119
    abstract protected function getDriver();
120
121
    /**
122
     * Wakes up reflection after ClassMetadata gets unserialized from cache.
123
     *
124
     * @return void
125
     */
126
    abstract protected function wakeupReflection(ClassMetadata $class, ReflectionService $reflService);
127
128
    /**
129
     * Initializes Reflection after ClassMetadata was constructed.
130
     *
131
     * @return void
132
     */
133
    abstract protected function initializeReflection(ClassMetadata $class, ReflectionService $reflService);
134
135
    /**
136
     * Checks whether the class metadata is an entity.
137
     *
138
     * This method should return false for mapped superclasses or embedded classes.
139
     *
140
     * @return bool
141
     */
142
    abstract protected function isEntity(ClassMetadata $class);
143
144
    /**
145
     * Gets the class metadata descriptor for a class.
146
     *
147
     * @param string $className The name of the class.
148
     *
149
     * @return ClassMetadata
150
     *
151
     * @throws ReflectionException
152
     * @throws MappingException
153
     */
154 10
    public function getMetadataFor($className)
155
    {
156 10
        if (isset($this->loadedMetadata[$className])) {
157
            return $this->loadedMetadata[$className];
158
        }
159
160
        // Check for namespace alias
161 10
        if (strpos($className, ':') !== false) {
162 2
            [$namespaceAlias, $simpleClassName] = explode(':', $className, 2);
163
164 2
            $realClassName = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName);
165
        } else {
166 8
            $realClassName = $this->getRealClass($className);
167
        }
168
169 10
        if (isset($this->loadedMetadata[$realClassName])) {
170
            // We do not have the alias name in the map, include it
171
            return $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName];
172
        }
173
174 10
        $loadingException = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $loadingException is dead and can be removed.
Loading history...
175
176
        try {
177 10
            if ($this->cacheDriver) {
178 3
                $cached = $this->cacheDriver->fetch($realClassName . $this->cacheSalt);
179 3
                if ($cached instanceof ClassMetadata) {
180 1
                    $this->loadedMetadata[$realClassName] = $cached;
181
182 1
                    $this->wakeupReflection($cached, $this->getReflectionService());
183
                } else {
184 2
                    foreach ($this->loadMetadata($realClassName) as $loadedClassName) {
185 1
                        $this->cacheDriver->save(
186 1
                            $loadedClassName . $this->cacheSalt,
187 2
                            $this->loadedMetadata[$loadedClassName]
188
                        );
189
                    }
190
                }
191
            } else {
192 9
                $this->loadMetadata($realClassName);
193
            }
194 5
        } catch (MappingException $loadingException) {
195 5
            $fallbackMetadataResponse = $this->onNotFoundMetadata($realClassName);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $fallbackMetadataResponse is correct as $this->onNotFoundMetadata($realClassName) targeting Doctrine\Persistence\Map...y::onNotFoundMetadata() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
196
197 5
            if (! $fallbackMetadataResponse) {
0 ignored issues
show
introduced by
$fallbackMetadataResponse is of type null, thus it always evaluated to false.
Loading history...
198 3
                throw $loadingException;
199
            }
200
201 2
            $this->loadedMetadata[$realClassName] = $fallbackMetadataResponse;
202
        }
203
204 7
        if ($className !== $realClassName) {
205
            // We do not have the alias name in the map, include it
206 1
            $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName];
207
        }
208
209 7
        return $this->loadedMetadata[$className];
210
    }
211
212
    /**
213
     * Checks whether the factory has the metadata for a class loaded already.
214
     *
215
     * @param string $className
216
     *
217
     * @return bool TRUE if the metadata of the class in question is already loaded, FALSE otherwise.
218
     */
219 3
    public function hasMetadataFor($className)
220
    {
221 3
        return isset($this->loadedMetadata[$className]);
222
    }
223
224
    /**
225
     * Sets the metadata descriptor for a specific class.
226
     *
227
     * NOTE: This is only useful in very special cases, like when generating proxy classes.
228
     *
229
     * @param string        $className
230
     * @param ClassMetadata $class
231
     *
232
     * @return void
233
     */
234
    public function setMetadataFor($className, $class)
235
    {
236
        $this->loadedMetadata[$className] = $class;
237
    }
238
239
    /**
240
     * Gets an array of parent classes for the given entity class.
241
     *
242
     * @param string $name
243
     *
244
     * @return string[]
245
     */
246 9
    protected function getParentClasses($name)
247
    {
248
        // Collect parent classes, ignoring transient (not-mapped) classes.
249 9
        $parentClasses = [];
250
251 9
        foreach (array_reverse($this->getReflectionService()->getParentClasses($name)) as $parentClass) {
252 3
            if ($this->getDriver()->isTransient($parentClass)) {
253
                continue;
254
            }
255
256 3
            $parentClasses[] = $parentClass;
257
        }
258
259 4
        return $parentClasses;
260
    }
261
262
    /**
263
     * Loads the metadata of the class in question and all it's ancestors whose metadata
264
     * is still not loaded.
265
     *
266
     * Important: The class $name does not necessarily exist at this point here.
267
     * Scenarios in a code-generation setup might have access to XML/YAML
268
     * Mapping files without the actual PHP code existing here. That is why the
269
     * {@see Doctrine\Common\Persistence\Mapping\ReflectionService} interface
270
     * should be used for reflection.
271
     *
272
     * @param string $name The name of the class for which the metadata should get loaded.
273
     *
274
     * @return string[]
275
     */
276 9
    protected function loadMetadata($name)
277
    {
278 9
        if (! $this->initialized) {
279 9
            $this->initialize();
280
        }
281
282 9
        $loaded = [];
283
284 9
        $parentClasses   = $this->getParentClasses($name);
285 4
        $parentClasses[] = $name;
286
287
        // Move down the hierarchy of parent classes, starting from the topmost class
288 4
        $parent          = null;
289 4
        $rootEntityFound = false;
290 4
        $visited         = [];
291 4
        $reflService     = $this->getReflectionService();
292 4
        foreach ($parentClasses as $className) {
293 4
            if (isset($this->loadedMetadata[$className])) {
294
                $parent = $this->loadedMetadata[$className];
295
                if ($this->isEntity($parent)) {
296
                    $rootEntityFound = true;
297
                    array_unshift($visited, $className);
298
                }
299
                continue;
300
            }
301
302 4
            $class = $this->newClassMetadataInstance($className);
303 4
            $this->initializeReflection($class, $reflService);
304
305 4
            $this->doLoadMetadata($class, $parent, $rootEntityFound, $visited);
306
307 4
            $this->loadedMetadata[$className] = $class;
308
309 4
            $parent = $class;
310
311 4
            if ($this->isEntity($class)) {
312 4
                $rootEntityFound = true;
313 4
                array_unshift($visited, $className);
314
            }
315
316 4
            $this->wakeupReflection($class, $reflService);
317
318 4
            $loaded[] = $className;
319
        }
320
321 4
        return $loaded;
322
    }
323
324
    /**
325
     * Provides a fallback hook for loading metadata when loading failed due to reflection/mapping exceptions
326
     *
327
     * Override this method to implement a fallback strategy for failed metadata loading
328
     *
329
     * @param string $className
330
     *
331
     * @return ClassMetadata|null
332
     */
333
    protected function onNotFoundMetadata($className)
334
    {
335
        return null;
336
    }
337
338
    /**
339
     * Actually loads the metadata from the underlying metadata.
340
     *
341
     * @param ClassMetadata      $class
342
     * @param ClassMetadata|null $parent
343
     * @param bool               $rootEntityFound
344
     * @param string[]           $nonSuperclassParents All parent class names
345
     *                                                 that are not marked as mapped superclasses.
346
     *
347
     * @return void
348
     */
349
    abstract protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents);
350
351
    /**
352
     * Creates a new ClassMetadata instance for the given class name.
353
     *
354
     * @param string $className
355
     *
356
     * @return ClassMetadata
357
     */
358
    abstract protected function newClassMetadataInstance($className);
359
360
    /**
361
     * {@inheritDoc}
362
     */
363
    public function isTransient($class)
364
    {
365
        if (! $this->initialized) {
366
            $this->initialize();
367
        }
368
369
        // Check for namespace alias
370
        if (strpos($class, ':') !== false) {
371
            [$namespaceAlias, $simpleClassName] = explode(':', $class, 2);
372
            $class                              = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName);
373
        }
374
375
        return $this->getDriver()->isTransient($class);
376
    }
377
378
    /**
379
     * Sets the reflectionService.
380
     *
381
     * @return void
382
     */
383
    public function setReflectionService(ReflectionService $reflectionService)
384
    {
385
        $this->reflectionService = $reflectionService;
386
    }
387
388
    /**
389
     * Gets the reflection service associated with this metadata factory.
390
     *
391
     * @return ReflectionService
392
     */
393 10
    public function getReflectionService()
394
    {
395 10
        if ($this->reflectionService === null) {
396 10
            $this->reflectionService = new RuntimeReflectionService();
397
        }
398
399 10
        return $this->reflectionService;
400
    }
401
402
    /**
403
     * Gets the real class name of a class name that could be a proxy.
404
     */
405 8
    private function getRealClass(string $class) : string
406
    {
407 8
        $pos = strrpos($class, '\\' . Proxy::MARKER . '\\');
408
409 8
        if ($pos === false) {
410 8
            return $class;
411
        }
412
413
        return substr($class, $pos + Proxy::MARKER_LENGTH + 2);
414
    }
415
}
416
417
class_exists(\Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory::class);
418