Failed Conditions
Pull Request — master (#70)
by Alexander M.
02:45
created

AbstractClassMetadataFactory::setCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Persistence\Mapping;
6
7
use BadMethodCallException;
8
use Doctrine\Common\Cache\Cache;
9
use Doctrine\Persistence\Mapping\Driver\MappingDriver;
10
use Doctrine\Persistence\Proxy;
11
use Doctrine\Persistence\SimpleCacheAdapter;
12
use Psr\SimpleCache\CacheInterface;
13
use ReflectionException;
14
use const E_USER_DEPRECATED;
15
use function array_reverse;
16
use function array_unshift;
17
use function explode;
18
use function sprintf;
19
use function str_replace;
20
use function strpos;
21
use function strrpos;
22
use function substr;
23
use function trigger_error;
24
25
/**
26
 * The ClassMetadataFactory is used to create ClassMetadata objects that contain all the
27
 * metadata mapping informations of a class which describes how a class should be mapped
28
 * to a relational database.
29
 *
30
 * This class was abstracted from the ORM ClassMetadataFactory.
31
 */
32
abstract class AbstractClassMetadataFactory implements ClassMetadataFactory
33
{
34
    /**
35
     * Salt used by specific Object Manager implementation.
36
     *
37
     * @var string
38
     */
39
    protected $cacheSalt = '$CLASSMETADATA';
40
41
    /** @var CacheInterface|null */
42
    private $cache;
43
44
    /** @var array<string, ClassMetadata> */
45
    private $loadedMetadata = [];
46
47
    /** @var bool */
48
    protected $initialized = false;
49
50
    /** @var ReflectionService|null */
51
    private $reflectionService = null;
52
53
    /**
54
     * Sets the cache driver used by the factory to cache ClassMetadata instances.
55
     *
56
     * @deprecated
57
     */
58 4
    public function setCacheDriver(?Cache $cacheDriver = null) : void
59
    {
60 4
        @trigger_error(sprintf('%s is deprecated. Use setCache() with a PSR-16 cache instead.', __METHOD__), E_USER_DEPRECATED);
61
62 4
        $this->cache = new SimpleCacheAdapter($cacheDriver);
0 ignored issues
show
Bug introduced by
It seems like $cacheDriver can also be of type null; however, parameter $wrapped of Doctrine\Persistence\Sim...eAdapter::__construct() does only seem to accept Doctrine\Common\Cache\Cache, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

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