Completed
Push — master ( ea86b0...eab576 )
by Hannes
01:36
created

Visitor::after()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of byrokrat\autogiro.
4
 *
5
 * byrokrat\autogiro is free software: you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License as published
7
 * by the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * byrokrat\autogiro is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with byrokrat\autogiro. If not, see <http://www.gnu.org/licenses/>.
17
 *
18
 * Copyright 2016-18 Hannes Forsgård
19
 */
20
21
declare(strict_types = 1);
22
23
namespace byrokrat\autogiro\Visitor;
24
25
use byrokrat\autogiro\Tree\Node;
26
27
/**
28
 * Visitor that dynamically calls method based on node name and type
29
 *
30
 * Will read the node name and type (eg. SomeNode) and dispatch a node specific
31
 * method if defined in visitor (eg. beforeSomeNode or afterSomeNode).
32
 */
33
class Visitor implements VisitorInterface
34
{
35
    private const AFTER = 'after';
36
    private const BEFORE = 'before';
37
38
    /**
39
     * @var array
40
     */
41
    private $hooks = [
42
        self::AFTER => [],
43
        self::BEFORE => [],
44
    ];
45
46
    public function after(string $name, callable $hook): void
47
    {
48
        $this->hooks[self::AFTER][strtolower($name)] = $hook;
49
    }
50
51
    public function before(string $name, callable $hook): void
52
    {
53
        $this->hooks[self::BEFORE][strtolower($name)] = $hook;
54
    }
55
56
    public function visitAfter(Node $node): void
57
    {
58
        $this->visit(self::AFTER, $node);
59
    }
60
61
    public function visitBefore(Node $node): void
62
    {
63
        $this->visit(self::BEFORE, $node);
64
    }
65
66
    private function visit(string $prefix, Node $node): void
67
    {
68
        if ($node->getName()) {
69
            $this->dispatch($prefix, $node->getName(), $node);
70
        }
71
72
        if ($node->getType() && $node->getType() != $node->getName()) {
73
            $this->dispatch($prefix, $node->getType(), $node);
74
        }
75
    }
76
77
    private function dispatch(string $prefix, string $name, Node $node): void
78
    {
79
        ($this->hooks[$prefix][strtolower($name)] ?? function () {})($node); // phpcs:ignore
80
81
        $method = $prefix . $name;
82
83
        if (method_exists($this, $method)) {
84
            $this->$method($node);
85
        }
86
    }
87
}
88