1
|
|
|
<?php |
2
|
|
|
namespace rtens\domin\delivery\web; |
3
|
|
|
|
4
|
|
|
use rtens\domin\Action; |
5
|
|
|
use rtens\domin\delivery\ParameterReader; |
6
|
|
|
|
7
|
|
|
class BreadCrumbsTrail { |
8
|
|
|
|
9
|
|
|
/** @var BreadCrumb[] */ |
10
|
|
|
private $crumbs; |
11
|
|
|
|
12
|
|
|
/** @var ParameterReader */ |
13
|
|
|
private $reader; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @param ParameterReader $reader |
17
|
|
|
* @param BreadCrumb[] $crumbs |
18
|
|
|
*/ |
19
|
|
|
public function __construct(ParameterReader $reader, array $crumbs) { |
20
|
|
|
$this->crumbs = $crumbs; |
21
|
|
|
$this->reader = $reader; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @return bool |
26
|
|
|
*/ |
27
|
|
|
public function hasCrumbs() { |
28
|
|
|
return !empty($this->crumbs); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @return array|BreadCrumb[] |
33
|
|
|
*/ |
34
|
|
|
public function getCrumbs() { |
35
|
|
|
return $this->crumbs; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @return BreadCrumb |
40
|
|
|
* @throws \Exception If there are no crumbs |
41
|
|
|
*/ |
42
|
|
|
public function getLastCrumb() { |
43
|
|
|
if (!$this->hasCrumbs()) { |
44
|
|
|
throw new \Exception("There are no crumbs"); |
45
|
|
|
} |
46
|
|
|
return $this->crumbs[count($this->crumbs) - 1]; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param Action $action |
51
|
|
|
* @param string $actionId |
52
|
|
|
* @return array|BreadCrumb[] |
53
|
|
|
*/ |
54
|
|
|
public function updateCrumbs(Action $action, $actionId) { |
55
|
|
|
$current = new BreadCrumb($action->caption(), (string)Url::relative($actionId, $this->readRawParameters($action))); |
56
|
|
|
|
57
|
|
|
$newCrumbs = []; |
58
|
|
|
foreach ($this->crumbs as $crumb) { |
59
|
|
|
if ($crumb == $current) { |
60
|
|
|
break; |
61
|
|
|
} |
62
|
|
|
$newCrumbs[] = $crumb; |
63
|
|
|
} |
64
|
|
|
$newCrumbs[] = $current; |
65
|
|
|
|
66
|
|
|
$this->crumbs = $newCrumbs; |
67
|
|
|
return $newCrumbs; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function reset() { |
71
|
|
|
$this->crumbs = []; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
private function readRawParameters(Action $action) { |
75
|
|
|
$values = []; |
76
|
|
|
|
77
|
|
|
foreach ($action->parameters() as $parameter) { |
78
|
|
|
if ($this->reader->has($parameter)) { |
79
|
|
|
$values[$parameter->getName()] = $this->reader->read($parameter); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
return $values; |
83
|
|
|
} |
84
|
|
|
} |