Completed
Pull Request — master (#50)
by Jonathan
04:19 queued 02:16
created

AbstractClassMetadataFactory::loadMetadata()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 51
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 51
ccs 28
cts 28
cp 1
rs 8.8657
c 0
b 0
f 0
cc 6
nc 10
nop 1
crap 6

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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