Passed
Push — add_typed_no_default_reflectio... ( 26533b...1005a7 )
by Benjamin
04:11
created

AbstractClassMetadataFactory::getParentClasses()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 14
ccs 6
cts 7
cp 0.8571
rs 10
cc 3
nc 3
nop 1
crap 3.0261
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 interface_exists;
14
use function strpos;
15
use function strrpos;
16
use function substr;
17
18
/**
19
 * The ClassMetadataFactory is used to create ClassMetadata objects that contain all the
20
 * metadata mapping informations of a class which describes how a class should be mapped
21
 * to a relational database.
22
 *
23
 * This class was abstracted from the ORM ClassMetadataFactory.
24
 */
25
abstract class AbstractClassMetadataFactory implements ClassMetadataFactory
26
{
27
    /**
28
     * Salt used by specific Object Manager implementation.
29
     *
30
     * @var string
31
     */
32
    protected $cacheSalt = '$CLASSMETADATA';
33
34
    /** @var Cache|null */
35
    private $cacheDriver;
36
37
    /** @var ClassMetadata[] */
38
    private $loadedMetadata = [];
39
40
    /** @var bool */
41
    protected $initialized = false;
42
43
    /** @var ReflectionService|null */
44
    private $reflectionService = null;
45
46
    /**
47
     * Sets the cache driver used by the factory to cache ClassMetadata instances.
48
     *
49
     * @return void
50
     */
51 4
    public function setCacheDriver(?Cache $cacheDriver = null)
52
    {
53 4
        $this->cacheDriver = $cacheDriver;
54 4
    }
55
56
    /**
57
     * Gets the cache driver used by the factory to cache ClassMetadata instances.
58
     *
59
     * @return Cache|null
60
     */
61 1
    public function getCacheDriver()
62
    {
63 1
        return $this->cacheDriver;
64
    }
65
66
    /**
67
     * Returns an array of all the loaded metadata currently in memory.
68
     *
69
     * @return ClassMetadata[]
70
     */
71
    public function getLoadedMetadata()
72
    {
73
        return $this->loadedMetadata;
74
    }
75
76
    /**
77
     * Forces the factory to load the metadata of all classes known to the underlying
78
     * mapping driver.
79
     *
80
     * @return ClassMetadata[] The ClassMetadata instances of all mapped classes.
81
     */
82
    public function getAllMetadata()
83
    {
84
        if (! $this->initialized) {
85
            $this->initialize();
86
        }
87
88
        $driver   = $this->getDriver();
89
        $metadata = [];
90
        foreach ($driver->getAllClassNames() as $className) {
91
            $metadata[] = $this->getMetadataFor($className);
92
        }
93
94
        return $metadata;
95
    }
96
97
    /**
98
     * Lazy initialization of this stuff, especially the metadata driver,
99
     * since these are not needed at all when a metadata cache is active.
100
     *
101
     * @return void
102
     */
103
    abstract protected function initialize();
104
105
    /**
106
     * Gets the fully qualified class-name from the namespace alias.
107
     *
108
     * @param string $namespaceAlias
109
     * @param string $simpleClassName
110
     *
111
     * @return string
112
     */
113
    abstract protected function getFqcnFromAlias($namespaceAlias, $simpleClassName);
114
115
    /**
116
     * Returns the mapping driver implementation.
117
     *
118
     * @return MappingDriver
119
     */
120
    abstract protected function getDriver();
121
122
    /**
123
     * Wakes up reflection after ClassMetadata gets unserialized from cache.
124
     *
125
     * @return void
126
     */
127
    abstract protected function wakeupReflection(ClassMetadata $class, ReflectionService $reflService);
128
129
    /**
130
     * Initializes Reflection after ClassMetadata was constructed.
131
     *
132
     * @return void
133
     */
134
    abstract protected function initializeReflection(ClassMetadata $class, ReflectionService $reflService);
135
136
    /**
137
     * Checks whether the class metadata is an entity.
138
     *
139
     * This method should return false for mapped superclasses or embedded classes.
140
     *
141
     * @return bool
142
     */
143
    abstract protected function isEntity(ClassMetadata $class);
144
145
    /**
146
     * Gets the class metadata descriptor for a class.
147
     *
148
     * @param string $className The name of the class.
149
     *
150
     * @return ClassMetadata
151
     *
152
     * @throws ReflectionException
153
     * @throws MappingException
154
     */
155 10
    public function getMetadataFor($className)
156
    {
157 10
        if (isset($this->loadedMetadata[$className])) {
158
            return $this->loadedMetadata[$className];
159
        }
160
161
        // Check for namespace alias
162 10
        if (strpos($className, ':') !== false) {
163 2
            [$namespaceAlias, $simpleClassName] = explode(':', $className, 2);
164
165 2
            $realClassName = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName);
166
        } else {
167 8
            $realClassName = $this->getRealClass($className);
168
        }
169
170 10
        if (isset($this->loadedMetadata[$realClassName])) {
171
            // We do not have the alias name in the map, include it
172
            return $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName];
173
        }
174
175 10
        $loadingException = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $loadingException is dead and can be removed.
Loading history...
176
177
        try {
178 10
            if ($this->cacheDriver) {
179 3
                $cached = $this->cacheDriver->fetch($realClassName . $this->cacheSalt);
180 3
                if ($cached instanceof ClassMetadata) {
181 1
                    $this->loadedMetadata[$realClassName] = $cached;
182
183 1
                    $this->wakeupReflection($cached, $this->getReflectionService());
184
                } else {
185 2
                    foreach ($this->loadMetadata($realClassName) as $loadedClassName) {
186 1
                        $this->cacheDriver->save(
187 1
                            $loadedClassName . $this->cacheSalt,
188 2
                            $this->loadedMetadata[$loadedClassName]
189
                        );
190
                    }
191
                }
192
            } else {
193 9
                $this->loadMetadata($realClassName);
194
            }
195 5
        } catch (MappingException $loadingException) {
196 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...
197
198 5
            if (! $fallbackMetadataResponse) {
0 ignored issues
show
introduced by
$fallbackMetadataResponse is of type null, thus it always evaluated to false.
Loading history...
199 3
                throw $loadingException;
200
            }
201
202 2
            $this->loadedMetadata[$realClassName] = $fallbackMetadataResponse;
203
        }
204
205 7
        if ($className !== $realClassName) {
206
            // We do not have the alias name in the map, include it
207 1
            $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName];
208
        }
209
210 7
        return $this->loadedMetadata[$className];
211
    }
212
213
    /**
214
     * Checks whether the factory has the metadata for a class loaded already.
215
     *
216
     * @param string $className
217
     *
218
     * @return bool TRUE if the metadata of the class in question is already loaded, FALSE otherwise.
219
     */
220 3
    public function hasMetadataFor($className)
221
    {
222 3
        return isset($this->loadedMetadata[$className]);
223
    }
224
225
    /**
226
     * Sets the metadata descriptor for a specific class.
227
     *
228
     * NOTE: This is only useful in very special cases, like when generating proxy classes.
229
     *
230
     * @param string        $className
231
     * @param ClassMetadata $class
232
     *
233
     * @return void
234
     */
235
    public function setMetadataFor($className, $class)
236
    {
237
        $this->loadedMetadata[$className] = $class;
238
    }
239
240
    /**
241
     * Gets an array of parent classes for the given entity class.
242
     *
243
     * @param string $name
244
     *
245
     * @return string[]
246
     */
247 9
    protected function getParentClasses($name)
248
    {
249
        // Collect parent classes, ignoring transient (not-mapped) classes.
250 9
        $parentClasses = [];
251
252 9
        foreach (array_reverse($this->getReflectionService()->getParentClasses($name)) as $parentClass) {
253 3
            if ($this->getDriver()->isTransient($parentClass)) {
254
                continue;
255
            }
256
257 3
            $parentClasses[] = $parentClass;
258
        }
259
260 4
        return $parentClasses;
261
    }
262
263
    /**
264
     * Loads the metadata of the class in question and all it's ancestors whose metadata
265
     * is still not loaded.
266
     *
267
     * Important: The class $name does not necessarily exist at this point here.
268
     * Scenarios in a code-generation setup might have access to XML/YAML
269
     * Mapping files without the actual PHP code existing here. That is why the
270
     * {@see Doctrine\Common\Persistence\Mapping\ReflectionService} interface
271
     * should be used for reflection.
272
     *
273
     * @param string $name The name of the class for which the metadata should get loaded.
274
     *
275
     * @return string[]
276
     */
277 9
    protected function loadMetadata($name)
278
    {
279 9
        if (! $this->initialized) {
280 9
            $this->initialize();
281
        }
282
283 9
        $loaded = [];
284
285 9
        $parentClasses   = $this->getParentClasses($name);
286 4
        $parentClasses[] = $name;
287
288
        // Move down the hierarchy of parent classes, starting from the topmost class
289 4
        $parent          = null;
290 4
        $rootEntityFound = false;
291 4
        $visited         = [];
292 4
        $reflService     = $this->getReflectionService();
293 4
        foreach ($parentClasses as $className) {
294 4
            if (isset($this->loadedMetadata[$className])) {
295
                $parent = $this->loadedMetadata[$className];
296
                if ($this->isEntity($parent)) {
297
                    $rootEntityFound = true;
298
                    array_unshift($visited, $className);
299
                }
300
                continue;
301
            }
302
303 4
            $class = $this->newClassMetadataInstance($className);
304 4
            $this->initializeReflection($class, $reflService);
305
306 4
            $this->doLoadMetadata($class, $parent, $rootEntityFound, $visited);
307
308 4
            $this->loadedMetadata[$className] = $class;
309
310 4
            $parent = $class;
311
312 4
            if ($this->isEntity($class)) {
313 4
                $rootEntityFound = true;
314 4
                array_unshift($visited, $className);
315
            }
316
317 4
            $this->wakeupReflection($class, $reflService);
318
319 4
            $loaded[] = $className;
320
        }
321
322 4
        return $loaded;
323
    }
324
325
    /**
326
     * Provides a fallback hook for loading metadata when loading failed due to reflection/mapping exceptions
327
     *
328
     * Override this method to implement a fallback strategy for failed metadata loading
329
     *
330
     * @param string $className
331
     *
332
     * @return ClassMetadata|null
333
     */
334
    protected function onNotFoundMetadata($className)
335
    {
336
        return null;
337
    }
338
339
    /**
340
     * Actually loads the metadata from the underlying metadata.
341
     *
342
     * @param ClassMetadata      $class
343
     * @param ClassMetadata|null $parent
344
     * @param bool               $rootEntityFound
345
     * @param string[]           $nonSuperclassParents All parent class names
346
     *                                                 that are not marked as mapped superclasses.
347
     *
348
     * @return void
349
     */
350
    abstract protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents);
351
352
    /**
353
     * Creates a new ClassMetadata instance for the given class name.
354
     *
355
     * @param string $className
356
     *
357
     * @return ClassMetadata
358
     */
359
    abstract protected function newClassMetadataInstance($className);
360
361
    /**
362
     * {@inheritDoc}
363
     */
364
    public function isTransient($class)
365
    {
366
        if (! $this->initialized) {
367
            $this->initialize();
368
        }
369
370
        // Check for namespace alias
371
        if (strpos($class, ':') !== false) {
372
            [$namespaceAlias, $simpleClassName] = explode(':', $class, 2);
373
            $class                              = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName);
374
        }
375
376
        return $this->getDriver()->isTransient($class);
377
    }
378
379
    /**
380
     * Sets the reflectionService.
381
     *
382
     * @return void
383
     */
384
    public function setReflectionService(ReflectionService $reflectionService)
385
    {
386
        $this->reflectionService = $reflectionService;
387
    }
388
389
    /**
390
     * Gets the reflection service associated with this metadata factory.
391
     *
392
     * @return ReflectionService
393
     */
394 10
    public function getReflectionService()
395
    {
396 10
        if ($this->reflectionService === null) {
397 10
            $this->reflectionService = new RuntimeReflectionService();
398
        }
399
400 10
        return $this->reflectionService;
401
    }
402
403
    /**
404
     * Gets the real class name of a class name that could be a proxy.
405
     */
406 8
    private function getRealClass(string $class) : string
407
    {
408 8
        $pos = strrpos($class, '\\' . Proxy::MARKER . '\\');
409
410 8
        if ($pos === false) {
411 8
            return $class;
412
        }
413
414
        return substr($class, $pos + Proxy::MARKER_LENGTH + 2);
415
    }
416
}
417
418 1
class_exists(\Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory::class);
419 1
interface_exists(ClassMetadata::class);
420
interface_exists(ReflectionService::class);
421