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

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