-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathValueListTrait
87 lines (76 loc) · 2.49 KB
/
ValueListTrait
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
namespace AlterPHP\Component\Behavior;
trait ValueListTrait
{
/**
* Returns entity translation prefix.
*
* @return string
*/
protected static function getLowerCaseClassName()
{
$refClass = new \ReflectionClass(get_called_class());
$className = $refClass->getShortName();
return strtolower($className);
}
/**
* Returns values list, with or without labels, for a given property.
*
* @param string $property
* @param bool $withLabelsAsIndexes
* @param array $filterValues
*
* @return array
*/
public static function getValuesList(string $property, bool $withLabelsAsIndexes = false, array $filterValues = null)
{
$propertyValues = array();
$refClass = new \ReflectionClass(get_called_class());
$classConstants = $refClass->getConstants();
$className = $refClass->getShortName();
$constantPrefix = strtoupper($property).'_';
foreach ($classConstants as $key => $val) {
if (substr($key, 0, strlen($constantPrefix)) === $constantPrefix) {
$propertyValues[$val] = static::getLowerCaseClassName().'.'.strtolower($property).'.'.$val;
}
}
// Filter on specified status list
if (isset($filterValues)) {
$propertyValues = array_filter($propertyValues, function ($key) use ($filterValues) {
return in_array($key, $filterValues);
}, ARRAY_FILTER_USE_KEY);
}
if ($withLabelsAsIndexes) {
return array_flip($propertyValues);
}
return array_keys($propertyValues);
}
/**
* Checks that a value is valid for a given property.
*
* @param string $property
* @param mixed $value
*
* @throws \InvalidArgumentException
*/
public static function checkAllowedValue(string $property, $value)
{
if (!in_array($value, static::getValuesList($property))) {
throw new \InvalidArgumentException(
sprintf('"%s" is not a valid value for "%s" property !', (string) $value, $property)
);
}
}
/**
* Get value label.
*
* @param string $property
*
* @return string
*/
public function getValueLabel(string $property)
{
$valueList = array_flip($this->getValuesList($property, true));
return isset($valueList[$this->{$property}]) ? $valueList[$this->{$property}] : $this->{$property};
}
}