|
1
|
|
|
<?php |
|
2
|
|
|
namespace rtens\domin\delivery\cli\fields; |
|
3
|
|
|
|
|
4
|
|
|
use rtens\domin\delivery\cli\CliField; |
|
5
|
|
|
use rtens\domin\delivery\FieldRegistry; |
|
6
|
|
|
use rtens\domin\Parameter; |
|
7
|
|
|
use rtens\domin\reflection\types\EnumerationType; |
|
8
|
|
|
|
|
9
|
|
|
class EnumerationField implements CliField { |
|
10
|
|
|
|
|
11
|
|
|
/** @var FieldRegistry */ |
|
12
|
|
|
private $fields; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* EnumerationField constructor. |
|
16
|
|
|
* @param FieldRegistry $fields |
|
17
|
|
|
*/ |
|
18
|
|
|
public function __construct(FieldRegistry $fields) { |
|
19
|
|
|
$this->fields = $fields; |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param Parameter $parameter |
|
24
|
|
|
* @return bool |
|
25
|
|
|
*/ |
|
26
|
|
|
public function handles(Parameter $parameter) { |
|
27
|
|
|
return $parameter->getType() instanceof EnumerationType; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @param Parameter $parameter |
|
32
|
|
|
* @param string $serialized |
|
33
|
|
|
* @return mixed |
|
34
|
|
|
* @throws \Exception |
|
35
|
|
|
*/ |
|
36
|
|
|
public function inflate(Parameter $parameter, $serialized) { |
|
37
|
|
|
$param = new Parameter($parameter->getName(), $this->getType($parameter)->getOptionType()); |
|
38
|
|
|
$options = $this->getType($parameter)->getOptions(); |
|
39
|
|
|
if (!array_key_exists($serialized, $options)) { |
|
40
|
|
|
throw new \Exception("[$serialized] is not an option in [" . implode(',', array_keys($options)) . ']'); |
|
41
|
|
|
} |
|
42
|
|
|
return $this->fields->getField($param)->inflate($param, $options[$serialized]); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @param Parameter $parameter |
|
47
|
|
|
* @return EnumerationType |
|
48
|
|
|
*/ |
|
49
|
|
|
private function getType(Parameter $parameter) { |
|
50
|
|
|
$type = $parameter->getType(); |
|
51
|
|
|
if (!($type instanceof EnumerationType)) { |
|
52
|
|
|
throw new \InvalidArgumentException("[$type] must be an EnumerationType"); |
|
53
|
|
|
} |
|
54
|
|
|
return $type; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @param Parameter $parameter |
|
59
|
|
|
* @return string |
|
60
|
|
|
*/ |
|
61
|
|
View Code Duplication |
public function getDescription(Parameter $parameter) { |
|
|
|
|
|
|
62
|
|
|
$out = ['']; |
|
63
|
|
|
foreach ($this->getType($parameter)->getOptions() as $i => $option) { |
|
64
|
|
|
$out[] = ' ' . $i . ' - ' . $option; |
|
65
|
|
|
} |
|
66
|
|
|
$out[] = 'Selection'; |
|
67
|
|
|
return implode(PHP_EOL, $out); |
|
68
|
|
|
} |
|
69
|
|
|
} |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.