Completed
Push — master ( 69a9cb...2b24be )
by Hannes
01:54
created

Visitor::visit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 0
loc 8
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). By
32
 * convention such visitor methods should type hint the specific node type
33
 * (eg. beforeSomeNode(SomeNode $node)).
34
 */
35
class Visitor implements VisitorInterface
36
{
37
    public function visitBefore(Node $node): void
38
    {
39
        $this->visit('before', $node);
40
    }
41
42
    public function visitAfter(Node $node): void
43
    {
44
        $this->visit('after', $node);
45
    }
46
47
    private function visit(string $prefix, Node $node): void
48
    {
49
        $this->dispatch($prefix . $node->getName(), $node);
50
51
        if ($node->getType() != $node->getName()) {
52
            $this->dispatch($prefix . $node->getType(), $node);
53
        }
54
    }
55
56
    private function dispatch(string $method, Node $node): void
57
    {
58
        if (method_exists($this, $method)) {
59
            $this->$method($node);
60
        }
61
62
        if (property_exists($this, $method) && is_callable($this->$method)) {
63
            ($this->$method)($node);
64
        }
65
    }
66
}
67