Failed Conditions
Pull Request — master (#1)
by Jonathan
03:48
created

AbstractClassMetadataFactory::getLoadedMetadata()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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