1
|
|
|
<?php |
2
|
|
|
namespace Wandu\Annotation; |
3
|
|
|
|
4
|
|
|
use Doctrine\Common\Annotations\AnnotationReader; |
5
|
|
|
use Doctrine\Common\Annotations\Reader; |
6
|
|
|
use Psr\SimpleCache\CacheInterface; |
7
|
|
|
use ReflectionClass; |
8
|
|
|
|
9
|
|
|
class AnnotationManager |
10
|
|
|
{ |
11
|
|
|
/** @var \Doctrine\Common\Annotations\Reader */ |
12
|
|
|
protected $reader; |
13
|
|
|
|
14
|
|
|
/** @var \Psr\SimpleCache\CacheInterface */ |
15
|
|
|
protected $cache; |
16
|
|
|
|
17
|
|
|
/** @var string */ |
18
|
|
|
protected $cachePrefix; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param \Doctrine\Common\Annotations\Reader $reader |
22
|
|
|
* @param \Psr\SimpleCache\CacheInterface $cache |
23
|
|
|
* @param string $cachePrefix |
24
|
|
|
*/ |
25
|
1 |
|
public function __construct(Reader $reader = null, CacheInterface $cache = null, string $cachePrefix = 'annotation.') |
26
|
|
|
{ |
27
|
1 |
|
$this->reader = $reader ?? new AnnotationReader(); |
28
|
1 |
|
$this->cache = $cache; |
29
|
1 |
|
$this->cachePrefix = $cachePrefix; |
30
|
1 |
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param string $className |
34
|
|
|
* @return \Wandu\Annotation\AnnotationBag |
35
|
|
|
*/ |
36
|
1 |
|
public function read(string $className): AnnotationBag |
37
|
|
|
{ |
38
|
1 |
|
if ($this->cache && $this->cache->has($className)) { |
39
|
|
|
return $this->cache->get($this->cachePrefix . $className); |
40
|
|
|
} |
41
|
1 |
|
$reflClass = new ReflectionClass($className); |
42
|
1 |
|
$classAnnotations = []; |
43
|
1 |
|
foreach ($this->reader->getClassAnnotations($reflClass) as $classAnnotation) { |
44
|
1 |
|
$classAnnotations[] = $classAnnotation; |
45
|
|
|
} |
46
|
1 |
|
$propsAnnotations = []; |
47
|
1 |
|
foreach ($reflClass->getProperties() as $reflProperty) { |
48
|
1 |
|
$propsAnnotations[$reflProperty->getName()] = []; |
49
|
1 |
|
foreach ($this->reader->getPropertyAnnotations($reflProperty) as $propertyAnnotation) { |
50
|
1 |
|
$propsAnnotations[$reflProperty->getName()][] = $propertyAnnotation; |
51
|
|
|
} |
52
|
|
|
} |
53
|
1 |
|
$methodsAnnotations = []; |
54
|
1 |
|
foreach ($reflClass->getMethods() as $reflMethod) { |
55
|
1 |
|
$methodsAnnotations[$reflMethod->getName()] = []; |
|
|
|
|
56
|
1 |
|
foreach ($this->reader->getMethodAnnotations($reflMethod) as $methodAnnotation) { |
57
|
1 |
|
$methodsAnnotations[$reflMethod->getName()][] = $methodAnnotation; |
|
|
|
|
58
|
|
|
} |
59
|
|
|
} |
60
|
1 |
|
$result = new AnnotationBag($classAnnotations, $propsAnnotations, $methodsAnnotations); |
61
|
1 |
|
if ($this->cache) { |
62
|
|
|
$this->cache->set($this->cachePrefix . $className, $result); |
63
|
|
|
} |
64
|
1 |
|
return $result; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|