Failed Conditions
Push — ProxyNamingInflector ( 293790 )
by Michael
03:54
created

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