Repository navigation
Expand file tree
/
Copy pathContextMenu.php
More file actions
98 lines (82 loc) · 2.66 KB
/
Copy pathContextMenu.php
File metadata and controls
98 lines (82 loc) · 2.66 KB
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
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace Phpactor\Extension\ContextMenu\Model;
use DTL\Invoke\Invoke;
use RuntimeException;
class ContextMenu
{
/**
* @var array
*/
private $actions = [];
/**
* @var array
*/
private $contexts = [];
public function __construct(array $actions, array $contexts)
{
foreach ($actions as $name => $action) {
$this->actions[$name] = Invoke::new(Action::class, $action);
}
$this->contexts = $contexts;
$this->validate();
}
public static function fromArray(array $array): self
{
return Invoke::new(self::class, $array);
}
public function hasContext(string $context): bool
{
return isset($this->contexts[$context]);
}
public function forContext(string $context): array
{
if (!isset($this->contexts[$context])) {
throw new RuntimeException(sprintf(
'Context "%s" does not exist',
$context
));
}
return array_combine($this->contexts[$context], array_map(function (string $action) {
return $this->getAction($action);
}, $this->contexts[$context]));
}
private function getAction(string $name): Action
{
if (!isset($this->actions[$name])) {
throw new RuntimeException(sprintf(
'Action "%s" does not exist, known actions: "%s"',
$name,
implode('", "', array_keys($this->actions))
));
}
return $this->actions[$name];
}
private function validate(): void
{
$missingActions = [];
foreach ($this->contexts as $name => $actions) {
$keys = [];
foreach ($actions as $actionName) {
if (!isset($this->actions[$actionName])) {
throw new RuntimeException(sprintf(
'Action "%s" used in context "%s" does not exist, known actions: "%s"',
$actionName,
$name,
implode('", "', array_keys($this->actions))
));
}
$action = $this->actions[$actionName];
if (isset($keys[$action->key()])) {
throw new RuntimeException(sprintf(
'Key "%s" in context "%s" mapped by action "%s" is already used by action "%s"',
$action->key(),
$name,
$actionName,
$keys[$action->key()]
));
}
$keys[$action->key()] = $actionName;
}
}
}
}