Completed
Push — master ( 82cd1d...312098 )
by Nikolas
163:59 queued 138:22
created

CurirBreadCrumbsTrail::readCrumbs()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
namespace rtens\domin\delivery\web\adapters\curir;
3
4
use rtens\domin\Action;
5
use rtens\domin\delivery\ParameterReader;
6
use rtens\domin\delivery\web\BreadCrumb;
7
use rtens\domin\delivery\web\BreadCrumbsTrail;
8
use watoki\curir\cookie\Cookie;
9
use watoki\curir\cookie\CookieStore;
10
11
class CurirBreadCrumbsTrail extends BreadCrumbsTrail {
12
13
    const COOKIE_KEY = 'domin_trail';
14
15
    /** @var CookieStore */
16
    private $cookies;
17
18
    public function __construct(ParameterReader $reader, CookieStore $cookies) {
19
        parent::__construct($reader, $this->readCrumbs($cookies));
20
        $this->cookies = $cookies;
21
    }
22
23
    public function updateCrumbs(Action $action, $actionId) {
24
        return $this->saveCrumbs(parent::updateCrumbs($action, $actionId));
25
    }
26
27
    /**
28
     * @param CookieStore $cookies
29
     * @return BreadCrumb[]
30
     */
31
    private function readCrumbs(CookieStore $cookies) {
32
        if ($cookies->hasKey(self::COOKIE_KEY)) {
33
            return array_map(function ($array) {
34
                return new BreadCrumb($array['caption'], $array['target']);
35
            }, $cookies->read(self::COOKIE_KEY)->payload);
36
        }
37
        return [];
38
    }
39
40
    /**
41
     * @param BreadCrumb[] $crumbs
42
     * @return BreadCrumb[]
43
     */
44
    private function saveCrumbs($crumbs) {
45
        $this->cookies->create(new Cookie(array_map(function (BreadCrumb $crumb) {
46
            return [
47
                'caption' => $crumb->getCaption(),
48
                'target' => $crumb->getTarget()
49
            ];
50
        }, $crumbs)), self::COOKIE_KEY);
51
        return $crumbs;
52
    }
53
}