Failed Conditions
Pull Request — master (#2)
by Jonathan
03:52
created

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