1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace JDecool\Bundle\TwigConstantAccessorBundle\Accessor; |
4
|
|
|
|
5
|
|
|
class ConstantAccessor extends \ReflectionClass |
6
|
|
|
{ |
7
|
|
|
/** @var array */ |
8
|
|
|
private $options; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Constructor |
12
|
|
|
* |
13
|
|
|
* @param array $options |
14
|
|
|
*/ |
15
|
|
|
public function __construct(array $options = []) |
16
|
|
|
{ |
17
|
|
|
if (empty($options['class'])) { |
18
|
|
|
throw new \InvalidArgumentException(sprintf('Missing "class" name.')); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
$this->options = $options; |
22
|
|
|
|
23
|
|
|
parent::__construct($options['class']); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Get constant access key |
28
|
|
|
* |
29
|
|
|
* @return string |
30
|
|
|
*/ |
31
|
|
|
public function getKey() |
32
|
|
|
{ |
33
|
|
|
if (!empty($this->options['alias'])) { |
34
|
|
|
return $this->options['alias']; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return $this->getShortName(); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Get declared matches rules |
42
|
|
|
* |
43
|
|
|
* @return string |
44
|
|
|
*/ |
45
|
|
|
public function getMatches() |
46
|
|
|
{ |
47
|
|
|
if (empty($this->options['matches'])) { |
48
|
|
|
return null; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $this->options['matches']; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Extract class constants |
56
|
|
|
* |
57
|
|
|
* @return array |
58
|
|
|
*/ |
59
|
|
|
public function getConstants() |
60
|
|
|
{ |
61
|
|
|
if (empty($this->options['matches'])) { |
62
|
|
|
return parent::getConstants(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$constants = []; |
66
|
|
|
foreach (parent::getConstants() as $const => $value) { |
67
|
|
|
if (false === ($matches = preg_match($this->options['matches'], $const))) { |
68
|
|
|
throw new \InvalidArgumentException(sprintf('RegExp rule "%s" is not valid.', $this->options['matches'])); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
if ($matches) { |
72
|
|
|
$constants[$const] = $value; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $constants; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* Transform object to an array |
81
|
|
|
* |
82
|
|
|
* @return array |
83
|
|
|
*/ |
84
|
|
|
public function toArray() |
85
|
|
|
{ |
86
|
|
|
return [ |
87
|
|
|
'class' => $this->getName(), |
88
|
|
|
'alias' => $this->getKey(), |
89
|
|
|
'matches' => $this->getMatches(), |
90
|
|
|
'constants' => $this->getConstants(), |
91
|
|
|
]; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|