Passed
Push — types ( 30d5cd )
by Jonathan
04:47
created

AbstractClassMetadataFactory::getAllMetadata()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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