Completed
Pull Request — master (#21)
by Michael
05:25
created

AbstractClassMetadataFactory::getMetadataFor()   B

Complexity

Conditions 9
Paths 45

Size

Total Lines 53
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 9.1244

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 53
ccs 23
cts 26
cp 0.8846
rs 8.0555
c 0
b 0
f 0
cc 9
nc 45
nop 1
crap 9.1244

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