Completed
Pull Request — master (#50)
by Jonathan
04:13 queued 01:53
created

AbstractClassMetadataFactory   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 371
Duplicated Lines 0 %

Test Coverage

Coverage 72.64%

Importance

Changes 0
Metric Value
wmc 36
eloc 98
dl 0
loc 371
ccs 77
cts 106
cp 0.7264
rs 9.52
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A getCacheDriver() 0 3 1
A getLoadedMetadata() 0 3 1
A setCacheDriver() 0 3 1
A getAllMetadata() 0 13 3
A hasMetadataFor() 0 3 1
A getReflectionService() 0 7 2
A isTransient() 0 14 3
A getParentClasses() 0 17 3
A setMetadataFor() 0 3 1
A setReflectionService() 0 3 1
B getMetadataFor() 0 57 10
A onNotFoundMetadata() 0 3 1
B loadMetadata() 0 51 6
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 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(
101
        string $namespaceAlias,
102
        string $simpleClassName
103
    ) : string;
104
105
    /**
106
     * Returns the mapping driver implementation.
107
     */
108
    abstract protected function getDriver() : MappingDriver;
109
110
    /**
111
     * Wakes up reflection after ClassMetadata gets unserialized from cache.
112
     */
113
    abstract protected function wakeupReflection(
114
        ClassMetadata $class,
115
        ReflectionService $reflService
116
    ) : void;
117
118
    /**
119
     * Initializes Reflection after ClassMetadata was constructed.
120
     */
121
    abstract protected function initializeReflection(
122
        ClassMetadata $class,
123
        ReflectionService $reflService
124
    ) : void;
125
126
    /**
127
     * Checks whether the class metadata is an entity.
128
     *
129
     * This method should return false for mapped superclasses or embedded classes.
130
     */
131
    abstract protected function isEntity(ClassMetadata $class) : bool;
132
133
    /**
134
     * Gets the class metadata descriptor for a class.
135
     *
136
     * @param string $className The name of the class.
137
     *
138
     * @throws ReflectionException
139
     * @throws MappingException
140
     */
141 10
    public function getMetadataFor(string $className) : ClassMetadata
142
    {
143 10
        if (isset($this->loadedMetadata[$className])) {
144
            return $this->loadedMetadata[$className];
145
        }
146
147
        // Check for namespace alias
148 10
        if (strpos($className, ':') !== false) {
149 2
            [$namespaceAlias, $simpleClassName] = explode(':', $className, 2);
150
151 2
            $realClassName = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName);
152
        } else {
153 8
            $realClassName = $this->getRealClass($className);
154
        }
155
156 10
        if (isset($this->loadedMetadata[$realClassName])) {
157
            // We do not have the alias name in the map, include it
158
            return $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName];
159
        }
160
161 10
        $loadingException = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $loadingException is dead and can be removed.
Loading history...
162
163
        try {
164 10
            if ($this->cacheDriver) {
165 3
                $cached = $this->cacheDriver->fetch($realClassName . $this->cacheSalt);
166 3
                if ($cached instanceof ClassMetadata) {
167 1
                    $this->loadedMetadata[$realClassName] = $cached;
168
169 1
                    $this->wakeupReflection($cached, $this->getReflectionService());
170
                } else {
171 3
                    foreach ($this->loadMetadata($realClassName) as $loadedClassName) {
172 1
                        $this->cacheDriver->save(
173 1
                            $loadedClassName . $this->cacheSalt,
174 1
                            $this->loadedMetadata[$loadedClassName],
175
                            0
176
                        );
177
                    }
178
                }
179
            } else {
180 9
                $this->loadMetadata($realClassName);
181
            }
182 5
        } catch (MappingException $loadingException) {
183 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...
184
185 5
            if (! $fallbackMetadataResponse) {
0 ignored issues
show
introduced by
$fallbackMetadataResponse is of type null, thus it always evaluated to false.
Loading history...
186 3
                throw $loadingException;
187
            }
188
189 2
            $this->loadedMetadata[$realClassName] = $fallbackMetadataResponse;
190
        }
191
192 7
        if ($className !== $realClassName) {
193
            // We do not have the alias name in the map, include it
194 1
            $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName];
195
        }
196
197 7
        return $this->loadedMetadata[$className];
198
    }
199
200
    /**
201
     * Checks whether the factory has the metadata for a class loaded already.
202
     *
203
     * @return bool TRUE if the metadata of the class in question is already loaded, FALSE otherwise.
204
     */
205 3
    public function hasMetadataFor(string $className) : bool
206
    {
207 3
        return isset($this->loadedMetadata[$className]);
208
    }
209
210
    /**
211
     * Sets the metadata descriptor for a specific class.
212
     *
213
     * NOTE: This is only useful in very special cases, like when generating proxy classes.
214
     */
215
    public function setMetadataFor(string $className, ClassMetadata $class) : void
216
    {
217
        $this->loadedMetadata[$className] = $class;
218
    }
219
220
    /**
221
     * Gets an array of parent classes for the given entity class.
222
     *
223
     * @return string[]
224
     */
225 9
    protected function getParentClasses(string $name) : array
226
    {
227
        // Collect parent classes, ignoring transient (not-mapped) classes.
228 9
        $parentClasses = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $parentClasses is dead and can be removed.
Loading history...
229
230 9
        $parentClasses = $this->getReflectionService()
231 9
            ->getParentClasses($name);
232
233 4
        foreach (array_reverse($parentClasses) as $parentClass) {
234 3
            if ($this->getDriver()->isTransient($parentClass)) {
235
                continue;
236
            }
237
238 3
            $parentClasses[] = $parentClass;
239
        }
240
241 4
        return $parentClasses;
242
    }
243
244
    /**
245
     * Loads the metadata of the class in question and all it's ancestors whose metadata
246
     * is still not loaded.
247
     *
248
     * Important: The class $name does not necessarily exist at this point here.
249
     * Scenarios in a code-generation setup might have access to XML/YAML
250
     * Mapping files without the actual PHP code existing here. That is why the
251
     * {@see Doctrine\Persistence\Mapping\ReflectionService} interface
252
     * should be used for reflection.
253
     *
254
     * @param string $name The name of the class for which the metadata should get loaded.
255
     *
256
     * @return string[]
257
     */
258 9
    protected function loadMetadata(string $name) : array
259
    {
260 9
        if (! $this->initialized) {
261 9
            $this->initialize();
262
        }
263
264 9
        $loaded = [];
265
266 9
        $parentClasses   = $this->getParentClasses($name);
267 4
        $parentClasses[] = $name;
268
269
        // Move down the hierarchy of parent classes, starting from the topmost class
270 4
        $parent          = null;
271 4
        $rootEntityFound = false;
272 4
        $visited         = [];
273 4
        $reflService     = $this->getReflectionService();
274
275 4
        foreach ($parentClasses as $className) {
276 4
            if (isset($this->loadedMetadata[$className])) {
277 3
                $parent = $this->loadedMetadata[$className];
278
279 3
                if ($this->isEntity($parent)) {
280 3
                    $rootEntityFound = true;
281
282 3
                    array_unshift($visited, $className);
283
                }
284
285 3
                continue;
286
            }
287
288 4
            $class = $this->newClassMetadataInstance($className);
289 4
            $this->initializeReflection($class, $reflService);
290
291 4
            $this->doLoadMetadata($class, $parent, $rootEntityFound, $visited);
292
293 4
            $this->loadedMetadata[$className] = $class;
294
295 4
            $parent = $class;
296
297 4
            if ($this->isEntity($class)) {
298 4
                $rootEntityFound = true;
299
300 4
                array_unshift($visited, $className);
301
            }
302
303 4
            $this->wakeupReflection($class, $reflService);
304
305 4
            $loaded[] = $className;
306
        }
307
308 4
        return $loaded;
309
    }
310
311
    /**
312
     * Provides a fallback hook for loading metadata when loading failed due to reflection/mapping exceptions
313
     *
314
     * Override this method to implement a fallback strategy for failed metadata loading
315
     */
316
    protected function onNotFoundMetadata(string $className) : ?ClassMetadata
317
    {
318
        return null;
319
    }
320
321
    /**
322
     * Actually loads the metadata from the underlying metadata.
323
     *
324
     * @param string[] $nonSuperclassParents All parent class names
325
     *                                       that are not marked as mapped superclasses.
326
     *
327
     * @return void
328
     */
329
    abstract protected function doLoadMetadata(
330
        ClassMetadata $class,
331
        ?ClassMetadata $parent,
332
        bool $rootEntityFound,
333
        array $nonSuperclassParents
334
    );
335
336
    /**
337
     * Creates a new ClassMetadata instance for the given class name.
338
     */
339
    abstract protected function newClassMetadataInstance(string $className) : ClassMetadata;
340
341
    /**
342
     * {@inheritDoc}
343
     */
344
    public function isTransient(string $class) : bool
345
    {
346
        if (! $this->initialized) {
347
            $this->initialize();
348
        }
349
350
        // Check for namespace alias
351
        if (strpos($class, ':') !== false) {
352
            [$namespaceAlias, $simpleClassName] = explode(':', $class, 2);
353
354
            $class = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName);
355
        }
356
357
        return $this->getDriver()->isTransient($class);
358
    }
359
360
    /**
361
     * Sets the reflectionService.
362
     *
363
     * @return void
364
     */
365
    public function setReflectionService(ReflectionService $reflectionService)
366
    {
367
        $this->reflectionService = $reflectionService;
368
    }
369
370
    /**
371
     * Gets the reflection service associated with this metadata factory.
372
     */
373 10
    public function getReflectionService() : ReflectionService
374
    {
375 10
        if ($this->reflectionService === null) {
376 10
            $this->reflectionService = new RuntimeReflectionService();
377
        }
378
379 10
        return $this->reflectionService;
380
    }
381
382
    /**
383
     * Gets the real class name of a class name that could be a proxy.
384
     */
385 8
    private function getRealClass(string $class) : string
386
    {
387 8
        $pos = strrpos($class, '\\' . Proxy::MARKER . '\\');
388
389 8
        if ($pos === false) {
390 8
            return $class;
391
        }
392
393
        return substr($class, $pos + Proxy::MARKER_LENGTH + 2);
394
    }
395
}
396