Passed
Pull Request — master (#21)
by
unknown
02:11
created

AbstractClassMetadataFactory::getRealClassName()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.0582

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 21
ccs 11
cts 13
cp 0.8462
rs 9.7998
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 4.0582
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 string[] */
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
     *
50
     * @return void
51
     */
52 6
    public function setCacheDriver(?Cache $cacheDriver = null)
53
    {
54 6
        $this->cacheDriver = $cacheDriver;
55 6
    }
56
57
    /**
58
     * Gets the cache driver used by the factory to cache ClassMetadata instances.
59
     *
60
     * @return Cache|null
61
     */
62 1
    public function getCacheDriver()
63
    {
64 1
        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
     * @throws ReflectionException
154
     * @throws MappingException
155
     */
156 11
    public function getMetadataFor($className)
157
    {
158 11
        $className = $this->getRealClassName($className);
159
160 11
        if (isset($this->loadedMetadata[$className])) {
161
            return $this->loadedMetadata[$className];
162
        }
163
164 11
        $loadingException = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $loadingException is dead and can be removed.
Loading history...
165
166
        try {
167 11
            if ($this->cacheDriver) {
168 4
                $cached = $this->cacheDriver->fetch($className . $this->cacheSalt);
169 4
                if ($cached instanceof ClassMetadata) {
170 1
                    $this->loadedMetadata[$className] = $cached;
171
172 1
                    $this->wakeupReflection($cached, $this->getReflectionService());
173
                } else {
174 4
                    $this->loadMetadata($className);
175
                }
176
            } else {
177 9
                $this->loadMetadata($className);
178
            }
179 6
        } catch (MappingException $loadingException) {
180 6
            $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
182 6
            if (! $fallbackMetadataResponse) {
0 ignored issues
show
introduced by
$fallbackMetadataResponse is of type null, thus it always evaluated to false.
Loading history...
183 3
                throw $loadingException;
184
            }
185
186 3
            $this->setMetadataFor($className, $fallbackMetadataResponse);
187
        }
188
189 8
        return $this->loadedMetadata[$className];
190
    }
191
192
    /**
193
     * Checks whether the factory has the metadata for a class loaded already.
194
     *
195
     * @param string $className
196
     *
197
     * @return bool TRUE if the metadata of the class in question is already loaded, FALSE otherwise.
198
     */
199 3
    public function hasMetadataFor($className)
200
    {
201 3
        $className = $this->getRealClassName($className);
202
203 3
        return isset($this->loadedMetadata[$className]);
204
    }
205
206
    /**
207
     * Sets the metadata descriptor for a specific class.
208
     *
209
     * NOTE: This is only useful in very special cases, like when generating proxy classes.
210
     *
211
     * @param string        $className
212
     * @param ClassMetadata $class
213
     *
214
     * @return void
215
     */
216 8
    public function setMetadataFor($className, $class)
217
    {
218 8
        $className                        = $this->getRealClassName($className);
219 8
        $this->loadedMetadata[$className] = $class;
220
221 8
        if ($this->cacheDriver === null) {
222 4
            return;
223
        }
224
225 4
        $this->cacheDriver->save(
226 4
            $className . $this->cacheSalt,
227 4
            $this->loadedMetadata[$className],
228 4
            null
229
        );
230 4
    }
231
232
    /**
233
     * Gets an array of parent classes for the given entity class.
234
     *
235
     * @param string $name
236
     *
237
     * @return string[]
238
     */
239 10
    protected function getParentClasses($name)
240
    {
241
        // Collect parent classes, ignoring transient (not-mapped) classes.
242 10
        $parentClasses = [];
243
244 10
        foreach (array_reverse($this->getReflectionService()->getParentClasses($name)) as $parentClass) {
245 3
            if ($this->getDriver()->isTransient($parentClass)) {
246
                continue;
247
            }
248
249 3
            $parentClasses[] = $parentClass;
250
        }
251
252 4
        return $parentClasses;
253
    }
254
255
    /**
256
     * Loads the metadata of the class in question and all it's ancestors whose metadata
257
     * is still not loaded.
258
     *
259
     * Important: The class $name does not necessarily exist at this point here.
260
     * Scenarios in a code-generation setup might have access to XML/YAML
261
     * Mapping files without the actual PHP code existing here. That is why the
262
     * {@see Doctrine\Common\Persistence\Mapping\ReflectionService} interface
263
     * should be used for reflection.
264
     *
265
     * @param string $name The name of the class for which the metadata should get loaded.
266
     *
267
     * @return string[]
268
     */
269 10
    protected function loadMetadata($name)
270
    {
271 10
        if (! $this->initialized) {
272 10
            $this->initialize();
273
        }
274
275 10
        $loaded = [];
276
277 10
        $parentClasses   = $this->getParentClasses($name);
278 4
        $parentClasses[] = $name;
279
280
        // Move down the hierarchy of parent classes, starting from the topmost class
281 4
        $parent          = null;
282 4
        $rootEntityFound = false;
283 4
        $visited         = [];
284 4
        $reflService     = $this->getReflectionService();
285 4
        foreach ($parentClasses as $className) {
286 4
            if (isset($this->loadedMetadata[$className])) {
287
                $parent = $this->loadedMetadata[$className];
288
                if ($this->isEntity($parent)) {
289
                    $rootEntityFound = true;
290
                    array_unshift($visited, $className);
291
                }
292
                continue;
293
            }
294
295 4
            $class = $this->newClassMetadataInstance($className);
296 4
            $this->initializeReflection($class, $reflService);
297
298 4
            $this->doLoadMetadata($class, $parent, $rootEntityFound, $visited);
299 4
            $this->setMetadataFor($className, $class);
300
301 4
            $parent = $class;
302
303 4
            if ($this->isEntity($class)) {
304 4
                $rootEntityFound = true;
305 4
                array_unshift($visited, $className);
306
            }
307
308 4
            $this->wakeupReflection($class, $reflService);
309
310 4
            $loaded[] = $className;
311
        }
312
313 4
        return $loaded;
314
    }
315
316
    /**
317
     * Provides a fallback hook for loading metadata when loading failed due to reflection/mapping exceptions
318
     *
319
     * Override this method to implement a fallback strategy for failed metadata loading
320
     *
321
     * @param string $className
322
     *
323
     * @return ClassMetadata|null
324
     */
325
    protected function onNotFoundMetadata($className)
326
    {
327
        return null;
328
    }
329
330
    /**
331
     * Actually loads the metadata from the underlying metadata.
332
     *
333
     * @param ClassMetadata      $class
334
     * @param ClassMetadata|null $parent
335
     * @param bool               $rootEntityFound
336
     * @param string[]           $nonSuperclassParents All parent class names
337
     *                                                 that are not marked as mapped superclasses.
338
     *
339
     * @return void
340
     */
341
    abstract protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents);
342
343
    /**
344
     * Creates a new ClassMetadata instance for the given class name.
345
     *
346
     * @param string $className
347
     *
348
     * @return ClassMetadata
349
     */
350
    abstract protected function newClassMetadataInstance($className);
351
352
    /**
353
     * {@inheritDoc}
354
     */
355
    public function isTransient($class)
356
    {
357
        if (! $this->initialized) {
358
            $this->initialize();
359
        }
360
361
        // Check for namespace alias
362
        if (strpos($class, ':') !== false) {
363
            [$namespaceAlias, $simpleClassName] = explode(':', $class, 2);
364
            $class                              = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName);
365
        }
366
367
        return $this->getDriver()->isTransient($class);
368
    }
369
370
    /**
371
     * Sets the reflectionService.
372
     *
373
     * @return void
374
     */
375
    public function setReflectionService(ReflectionService $reflectionService)
376
    {
377
        $this->reflectionService = $reflectionService;
378
    }
379
380
    /**
381
     * Gets the reflection service associated with this metadata factory.
382
     *
383
     * @return ReflectionService
384
     */
385 11
    public function getReflectionService()
386
    {
387 11
        if ($this->reflectionService === null) {
388 11
            $this->reflectionService = new RuntimeReflectionService();
389
        }
390 11
        return $this->reflectionService;
391
    }
392
393
    /**
394
     * Gets the real class name of a class name that could be a proxy or alias.
395
     *
396
     * @param string $className
397
     *
398
     * @return string
399
     */
400 12
    private function getRealClassName($className)
401
    {
402 12
        if (isset($this->aliasesMap[$className])) {
403 7
            return $this->aliasesMap[$className];
404
        }
405
406
        switch (true) {
407 12
            case strpos($className, ':') !== false: // Check for namespace alias
408 2
                [$namespaceAlias, $simpleClassName] = explode(':', $className, 2);
409 2
                $realClassName                      = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName);
410 2
                break;
411 11
            case $pos = strrpos($className, '\\' . Proxy::MARKER . '\\') !== false: // Check for namespace proxy
412
                $realClassName = substr($className, $pos + Proxy::MARKER_LENGTH + 2);
413
                break;
414
            default:
415 11
                $realClassName = $className;
416
        }
417
418 12
        $this->aliasesMap[$className] = $realClassName;
419
420 12
        return $realClassName;
421
    }
422
}
423