1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Povs\ListerBundle\Mapper; |
4
|
|
|
|
5
|
|
|
use Povs\ListerBundle\Exception\ListFieldException; |
6
|
|
|
use Povs\ListerBundle\Mixin\OptionsTrait; |
7
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver; |
8
|
|
|
use Throwable; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @author Povilas Margaiatis <[email protected]> |
12
|
|
|
*/ |
13
|
|
|
abstract class AbstractField |
14
|
|
|
{ |
15
|
|
|
use OptionsTrait; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var string |
19
|
|
|
*/ |
20
|
|
|
protected $id; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* AbstractField constructor. |
24
|
|
|
* |
25
|
|
|
* @param string $id |
26
|
|
|
* @param array $options |
27
|
|
|
*/ |
28
|
79 |
|
public function __construct(string $id, array $options) |
29
|
|
|
{ |
30
|
79 |
|
$this->id = str_replace('.', '_', $id); |
31
|
79 |
|
$resolver = new OptionsResolver(); |
32
|
79 |
|
$this->configureOptions($resolver); |
33
|
|
|
|
34
|
|
|
try { |
35
|
79 |
|
$options = $resolver->resolve($options); |
36
|
3 |
|
} catch (Throwable $e) { |
37
|
3 |
|
throw ListFieldException::invalidFieldConfiguration($id, $e->getMessage()); |
38
|
|
|
} |
39
|
|
|
|
40
|
76 |
|
$this->initOptions($options); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @return string |
45
|
|
|
*/ |
46
|
36 |
|
public function getId(): string |
47
|
|
|
{ |
48
|
36 |
|
return $this->id; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Normalizes paths by path and property options. If both are not set - default path is id. |
53
|
|
|
* |
54
|
|
|
* @param $id |
55
|
|
|
* |
56
|
|
|
* @return array paths |
57
|
|
|
*/ |
58
|
59 |
|
protected function normalizePaths(string $id): array |
59
|
|
|
{ |
60
|
59 |
|
$paths = (array) $this->getOption(ListField::OPTION_PATH); |
61
|
59 |
|
$properties = (array) $this->getOption(ListField::OPTION_PROPERTY); |
62
|
|
|
|
63
|
59 |
|
if (empty($paths)) { |
64
|
45 |
|
$paths = [$id]; |
65
|
|
|
} |
66
|
|
|
|
67
|
59 |
|
if (!empty($properties)) { |
68
|
18 |
|
if (count($paths) > 1) { |
69
|
2 |
|
throw ListFieldException::invalidPropertiesOption($id); |
70
|
|
|
} |
71
|
|
|
|
72
|
16 |
|
$path = reset($paths); |
73
|
16 |
|
$paths = []; |
74
|
|
|
|
75
|
16 |
|
foreach ($properties as $key => $property) { |
76
|
16 |
|
$paths[$key] = $path ? sprintf('%s.%s', $path, $property) : $property; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
57 |
|
return $paths; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @param OptionsResolver $resolver |
85
|
|
|
*/ |
86
|
|
|
abstract protected function configureOptions(OptionsResolver $resolver): void; |
87
|
|
|
} |
88
|
|
|
|