Test Failed
Pull Request — master (#21)
by
unknown
02:48
created

AbstractClassMetadataFactory::getRealClassName()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.074

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 21
ccs 5
cts 6
cp 0.8333
rs 9.7998
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 4.074
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 array */
0 ignored issues
show
introduced by
@var annotation of property \Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory::$aliasesMap does not specify type hint for its items.
Loading history...
39
    private $aliasesMap = [];
40
41
    /** @var bool */
42
    protected $initialized = false;
43
44
    /** @var ReflectionService|null */
45
    private $reflectionService = null;
46
47
    /**
48
     * Sets the cache driver used by the factory to cache ClassMetadata instances.
49 4
     *
50
     * @return void
51 4
     */
52 4
    public function setCacheDriver(?Cache $cacheDriver = null)
53
    {
54
        $this->cacheDriver = $cacheDriver;
55
    }
56
57
    /**
58
     * Gets the cache driver used by the factory to cache ClassMetadata instances.
59 1
     *
60
     * @return Cache|null
61 1
     */
62
    public function getCacheDriver()
63
    {
64
        return $this->cacheDriver;
65
    }
66
67
    /**
68
     * Returns an array of all the loaded metadata currently in memory.
69
     *
70
     * @return ClassMetadata[]
71
     */
72
    public function getLoadedMetadata()
73
    {
74
        return $this->loadedMetadata;
75
    }
76
77
    /**
78
     * Forces the factory to load the metadata of all classes known to the underlying
79
     * mapping driver.
80
     *
81
     * @return ClassMetadata[] The ClassMetadata instances of all mapped classes.
82
     */
83
    public function getAllMetadata()
84
    {
85
        if (! $this->initialized) {
86
            $this->initialize();
87
        }
88
89
        $driver   = $this->getDriver();
90
        $metadata = [];
91
        foreach ($driver->getAllClassNames() as $className) {
92
            $metadata[] = $this->getMetadataFor($className);
93
        }
94
95
        return $metadata;
96
    }
97
98
    /**
99
     * Lazy initialization of this stuff, especially the metadata driver,
100
     * since these are not needed at all when a metadata cache is active.
101
     *
102
     * @return void
103
     */
104
    abstract protected function initialize();
105
106
    /**
107
     * Gets the fully qualified class-name from the namespace alias.
108
     *
109
     * @param string $namespaceAlias
110
     * @param string $simpleClassName
111
     *
112
     * @return string
113
     */
114
    abstract protected function getFqcnFromAlias($namespaceAlias, $simpleClassName);
115
116
    /**
117
     * Returns the mapping driver implementation.
118
     *
119
     * @return MappingDriver
120
     */
121
    abstract protected function getDriver();
122
123
    /**
124
     * Wakes up reflection after ClassMetadata gets unserialized from cache.
125
     *
126
     * @return void
127
     */
128
    abstract protected function wakeupReflection(ClassMetadata $class, ReflectionService $reflService);
129
130
    /**
131
     * Initializes Reflection after ClassMetadata was constructed.
132
     *
133
     * @return void
134
     */
135
    abstract protected function initializeReflection(ClassMetadata $class, ReflectionService $reflService);
136
137
    /**
138
     * Checks whether the class metadata is an entity.
139
     *
140
     * This method should return false for mapped superclasses or embedded classes.
141
     *
142
     * @return bool
143
     */
144
    abstract protected function isEntity(ClassMetadata $class);
145
146
    /**
147
     * Gets the class metadata descriptor for a class.
148
     *
149
     * @param string $className The name of the class.
150
     *
151
     * @return ClassMetadata
152
     *
153 10
     * @throws ReflectionException
154
     * @throws MappingException
155 10
     */
156
    public function getMetadataFor($className)
157
    {
158
        $className = $this->getRealClassName($className);
159
160 10
        if (isset($this->loadedMetadata[$className])) {
161 2
            return $this->loadedMetadata[$className];
162
        }
163 2
164
        $loadingException = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $loadingException is dead and can be removed.
Loading history...
165 8
166
        try {
167
            if ($this->cacheDriver) {
168 10
                $cached = $this->cacheDriver->fetch($className . $this->cacheSalt);
169
                if ($cached instanceof ClassMetadata) {
170
                    $this->loadedMetadata[$className] = $cached;
171
172
                    $this->wakeupReflection($cached, $this->getReflectionService());
173 10
                } else {
174
                    $this->loadMetadata($className);
175
                }
176 10
            } else {
177 3
                $this->loadMetadata($className);
178 3
            }
179 1
        } catch (MappingException $loadingException) {
180
            $fallbackMetadataResponse = $this->onNotFoundMetadata($className);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $fallbackMetadataResponse is correct as $this->onNotFoundMetadata($className) 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...
181 1
182
            if (! $fallbackMetadataResponse) {
0 ignored issues
show
introduced by
$fallbackMetadataResponse is of type null, thus it always evaluated to false.
Loading history...
183 2
                throw $loadingException;
184 1
            }
185 1
186 1
            $this->setMetadataFor($className, $fallbackMetadataResponse);
187 2
        }
188
189
        return $this->loadedMetadata[$className];
190
    }
191
192 9
    /**
193
     * Checks whether the factory has the metadata for a class loaded already.
194 5
     *
195 5
     * @param string $className
196
     *
197 5
     * @return bool TRUE if the metadata of the class in question is already loaded, FALSE otherwise.
198 3
     */
199
    public function hasMetadataFor($className)
200
    {
201 2
        return isset($this->loadedMetadata[$className]);
202
    }
203
204 7
    /**
205
     * Sets the metadata descriptor for a specific class.
206 1
     *
207
     * NOTE: This is only useful in very special cases, like when generating proxy classes.
208
     *
209 7
     * @param string        $className
210
     * @param ClassMetadata $class
211
     *
212
     * @return void
213
     */
214
    public function setMetadataFor($className, $class)
215
    {
216
        $className = $this->getRealClassName($className);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 24 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
217
        $this->loadedMetadata[$className] = $class;
218
219 3
        if ($this->cacheDriver === null) {
220
            return;
221 3
        }
222
223
        $this->cacheDriver->save(
224
            $className . $this->cacheSalt,
225
            $this->loadedMetadata[$className],
226
            null
227
        );
228
    }
229
230
    /**
231
     * Gets an array of parent classes for the given entity class.
232
     *
233
     * @param string $name
234
     *
235
     * @return string[]
236
     */
237
    protected function getParentClasses($name)
238
    {
239
        // Collect parent classes, ignoring transient (not-mapped) classes.
240
        $parentClasses = [];
241
242
        foreach (array_reverse($this->getReflectionService()->getParentClasses($name)) as $parentClass) {
243
            if ($this->getDriver()->isTransient($parentClass)) {
244
                continue;
245
            }
246 9
247
            $parentClasses[] = $parentClass;
248
        }
249 9
250
        return $parentClasses;
251 9
    }
252 3
253
    /**
254
     * Loads the metadata of the class in question and all it's ancestors whose metadata
255
     * is still not loaded.
256 3
     *
257
     * Important: The class $name does not necessarily exist at this point here.
258
     * Scenarios in a code-generation setup might have access to XML/YAML
259 4
     * Mapping files without the actual PHP code existing here. That is why the
260
     * {@see Doctrine\Common\Persistence\Mapping\ReflectionService} interface
261
     * should be used for reflection.
262
     *
263
     * @param string $name The name of the class for which the metadata should get loaded.
264
     *
265
     * @return string[]
266
     */
267
    protected function loadMetadata($name)
268
    {
269
        if (! $this->initialized) {
270
            $this->initialize();
271
        }
272
273
        $loaded = [];
274
275
        $parentClasses   = $this->getParentClasses($name);
276 9
        $parentClasses[] = $name;
277
278 9
        // Move down the hierarchy of parent classes, starting from the topmost class
279 9
        $parent          = null;
280
        $rootEntityFound = false;
281
        $visited         = [];
282 9
        $reflService     = $this->getReflectionService();
283
        foreach ($parentClasses as $className) {
284 9
            if (isset($this->loadedMetadata[$className])) {
285 4
                $parent = $this->loadedMetadata[$className];
286
                if ($this->isEntity($parent)) {
287
                    $rootEntityFound = true;
288 4
                    array_unshift($visited, $className);
289 4
                }
290 4
                continue;
291 4
            }
292 4
293 4
            $class = $this->newClassMetadataInstance($className);
294
            $this->initializeReflection($class, $reflService);
295
296
            $this->doLoadMetadata($class, $parent, $rootEntityFound, $visited);
297
            $this->setMetadataFor($className, $class);
298
299
            $parent = $class;
300
301
            if ($this->isEntity($class)) {
302 4
                $rootEntityFound = true;
303 4
                array_unshift($visited, $className);
304
            }
305 4
306
            $this->wakeupReflection($class, $reflService);
307 4
308
            $loaded[] = $className;
309 4
        }
310
311 4
        return $loaded;
312 4
    }
313 4
314
    /**
315
     * Provides a fallback hook for loading metadata when loading failed due to reflection/mapping exceptions
316 4
     *
317
     * Override this method to implement a fallback strategy for failed metadata loading
318 4
     *
319
     * @param string $className
320
     *
321 4
     * @return ClassMetadata|null
322
     */
323
    protected function onNotFoundMetadata($className)
324
    {
325
        return null;
326
    }
327
328
    /**
329
     * Actually loads the metadata from the underlying metadata.
330
     *
331
     * @param ClassMetadata      $class
332
     * @param ClassMetadata|null $parent
333
     * @param bool               $rootEntityFound
334
     * @param string[]           $nonSuperclassParents All parent class names
335
     *                                                 that are not marked as mapped superclasses.
336
     *
337
     * @return void
338
     */
339
    abstract protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents);
340
341
    /**
342
     * Creates a new ClassMetadata instance for the given class name.
343
     *
344
     * @param string $className
345
     *
346
     * @return ClassMetadata
347
     */
348
    abstract protected function newClassMetadataInstance($className);
349
350
    /**
351
     * {@inheritDoc}
352
     */
353
    public function isTransient($class)
354
    {
355
        if (! $this->initialized) {
356
            $this->initialize();
357
        }
358
359
        // Check for namespace alias
360
        if (strpos($class, ':') !== false) {
361
            [$namespaceAlias, $simpleClassName] = explode(':', $class, 2);
362
            $class                              = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName);
363
        }
364
365
        return $this->getDriver()->isTransient($class);
366
    }
367
368
    /**
369
     * Sets the reflectionService.
370
     *
371
     * @return void
372
     */
373
    public function setReflectionService(ReflectionService $reflectionService)
374
    {
375
        $this->reflectionService = $reflectionService;
376
    }
377
378
    /**
379
     * Gets the reflection service associated with this metadata factory.
380
     *
381
     * @return ReflectionService
382
     */
383
    public function getReflectionService()
384
    {
385
        if ($this->reflectionService === null) {
386
            $this->reflectionService = new RuntimeReflectionService();
387
        }
388
        return $this->reflectionService;
389
    }
390
391
    /**
392
     * Gets the real class name of a class name that could be a proxy or alias.
393 10
     *
394
     * @param string $className
395 10
     *
396 10
     * @return string
397
     */
398 10
    private function getRealClassName($className)
399
    {
400
        if (isset($this->aliasesMap[$className])) {
401
            return $this->aliasesMap[$className];
402
        }
403
404 8
        switch (true) {
405
            case strpos($className, ':') !== false: // Check for namespace alias
406 8
                [$namespaceAlias, $simpleClassName] = explode(':', $className, 2);
407
                $realClassName = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 22 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
408 8
                break;
409 8
            case $pos = strrpos($className, '\\' . Proxy::MARKER . '\\') !== false: // Check for namespace proxy
410
                $realClassName = substr($className, $pos + Proxy::MARKER_LENGTH + 2);
411
                break;
412
            default:
413
                $realClassName = $className;
414
        }
415
416
        $this->aliasesMap[$className] = $realClassName;
417
418
        return $realClassName;
419
    }
420
}
421