Completed
Push — develop ( 34db25...1b1cc6 )
by Paul
02:36
created

AbstractNodeParser   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 55
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getNodeParser() 0 6 2
A parseSubNodes() 0 10 3
A hasNodeParser() 0 7 2
1
<?php
2
3
namespace PhpUnitGen\Parser\NodeParser;
4
5
use PhpUnitGen\Exception\ParseException;
6
use PhpUnitGen\Model\PropertyInterface\NodeInterface;
7
use PhpUnitGen\Parser\NodeParser\NodeParserInterface\NodeParserInterface;
8
use Respect\Validation\Validator;
9
10
/**
11
 * Class AbstractNodeParser.
12
 *
13
 * @author     Paul Thébaud <[email protected]>.
14
 * @copyright  2017-2018 Paul Thébaud <[email protected]>.
15
 * @license    https://opensource.org/licenses/MIT The MIT license.
16
 * @link       https://github.com/paul-thebaud/phpunit-generator
17
 * @since      Class available since Release 2.0.0.
18
 */
19
abstract class AbstractNodeParser implements NodeParserInterface
20
{
21
    /**
22
     * @var NodeParserInterface[] $nodeParsers Mapping array between PhpParser node class and PhpUnitGen node parser.
23
     */
24
    protected $nodeParsers = [];
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public function parseSubNodes(array $nodes, NodeInterface $parent): void
30
    {
31
        foreach ($nodes as $node) {
32
            // Get the node class
33
            $class = get_class($node);
34
35
            // If a node parser exists
36
            if ($this->hasNodeParser($class)) {
37
                // Parse the node
38
                $this->getNodeParser($class)->invoke($node, $parent);
39
            }
40
        }
41
    }
42
43
    /**
44
     * Check if this node parser instance has a node parser.
45
     *
46
     * @param string $class The node parser for this class.
47
     *
48
     * @return bool True if the node parser exists.
49
     */
50
    protected function hasNodeParser(string $class): bool
51
    {
52
        if (Validator::key($class, Validator::instance(NodeParserInterface::class))
53
            ->validate($this->nodeParsers)) {
54
            return true;
55
        }
56
        return false;
57
    }
58
59
    /**
60
     * Get a node parser.
61
     *
62
     * @param string $class The node parser for this class.
63
     *
64
     * @return NodeParserInterface The node parser.
65
     *
66
     * @throws ParseException If the node parser does not exists.
67
     */
68
    protected function getNodeParser(string $class): NodeParserInterface
69
    {
70
        if ($this->hasNodeParser($class)) {
71
            return $this->nodeParsers[$class];
72
        }
73
        throw new ParseException(sprintf('The node parser for "%s" cannot be found.', $class));
74
    }
75
}
76