1 | <?php |
||
26 | class LazyMetadataFactory implements MetadataFactoryInterface |
||
27 | { |
||
28 | /** |
||
29 | * @var LoaderInterface |
||
30 | */ |
||
31 | protected $loader; |
||
32 | |||
33 | /** |
||
34 | * @var CacheInterface |
||
35 | */ |
||
36 | protected $cache; |
||
37 | |||
38 | /** |
||
39 | * Loaded metadata indexed by class name |
||
40 | * |
||
41 | * @var GenericMetadataInterface[] |
||
42 | */ |
||
43 | protected $loadedClasses = []; |
||
44 | |||
45 | /** |
||
46 | * Constructor |
||
47 | * |
||
48 | * @param LoaderInterface $loader |
||
49 | * @param CacheInterface|null $cache |
||
50 | */ |
||
51 | 22 | public function __construct(LoaderInterface $loader, CacheInterface $cache = null) |
|
56 | |||
57 | /** |
||
58 | * @inheritdoc |
||
59 | */ |
||
60 | 11 | public function getMetadataFor($value) |
|
61 | { |
||
62 | 11 | if (!is_object($value) && !is_string($value)) { |
|
63 | 1 | throw new \InvalidArgumentException(sprintf( |
|
64 | 1 | "Cannot create metadata for non-objects. Got: %s", |
|
65 | 1 | gettype($value) |
|
66 | 1 | )); |
|
67 | } |
||
68 | |||
69 | 11 | $class = ltrim(((is_object($value)) ? get_class($value) : $value), '\\'); |
|
70 | |||
71 | 11 | if (array_key_exists($value, $this->loadedClasses)) { |
|
72 | 6 | return $this->loadedClasses[$class]; |
|
73 | } |
||
74 | |||
75 | 11 | if ((null !== $this->cache) && (false !== ($this->loadedClasses[$class] = $this->cache->read($class)))) { |
|
76 | return $this->loadedClasses[$class]; |
||
77 | } |
||
78 | |||
79 | 11 | if (!class_exists($class)) { |
|
80 | 1 | throw new \RuntimeException(sprintf( |
|
81 | 1 | "The class '%s' doesn't exist", |
|
82 | $class |
||
83 | 1 | )); |
|
84 | } |
||
85 | |||
86 | 10 | $reflection = new \ReflectionClass($class); |
|
87 | |||
88 | 10 | $metadata = $this->loader->loadClassMetadata($reflection); |
|
89 | 10 | if (($metadata instanceof ClassMetadataInterface) && (false !== ($parent = $reflection->getParentClass()))) { |
|
90 | 8 | $metadata->mergeMetadata($this->getMetadataFor($parent->getName())); |
|
91 | 8 | } |
|
92 | |||
93 | 10 | if (null !== $this->cache) { |
|
94 | 1 | $this->cache->write($metadata); |
|
95 | 1 | } |
|
96 | |||
97 | 10 | return $this->loadedClasses[$class] = $metadata; |
|
98 | } |
||
99 | |||
100 | /** |
||
101 | * @inheritdoc |
||
102 | */ |
||
103 | 2 | public function hasMetadataFor($value) |
|
117 | } |
||
118 |