Passed
Push — master ( e6bc2a...a7212f )
by Kirill
04:45
created

Utils::findName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 9
cp 0
rs 9.9332
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\SDL\Builder;
11
12
use Railt\Io\Readable;
13
use Railt\Parser\Ast\RuleInterface;
14
use Railt\SDL\Exception\SyntaxException;
15
16
/**
17
 * Class Utils
18
 */
19
class Utils
20
{
21
    /**
22
     * @param RuleInterface $rule
23
     * @return string|null
24
     */
25
    public static function findName(RuleInterface $rule): ?string
26
    {
27
        foreach ($rule->getChildren() as $child) {
28
            if ($child->getName() === 'Name') {
29
                return $child->getValue();
30
            }
31
        }
32
33
        return null;
34
    }
35
36
    /**
37
     * @param Readable $file
38
     * @param RuleInterface $rule
39
     * @return string
40
     * @throws SyntaxException
41
     */
42
    public static function getName(Readable $file, RuleInterface $rule): string
43
    {
44
        if (($name = static::findName($rule)) !== null) {
45
            return $name;
46
        }
47
48
        $exception = new SyntaxException('Unable to determine type name');
49
        $exception->throwsIn($file, $rule->getOffset());
50
51
        throw $exception;
52
    }
53
54
    /**
55
     * @param RuleInterface $rule
56
     * @return string|null
57
     */
58
    public static function findDescription(RuleInterface $rule): ?string
59
    {
60
        return static::leaf($rule, 'Description');
61
    }
62
63
    /**
64
     * @param RuleInterface $rule
65
     * @param string $name
66
     * @param int $group
67
     * @return string|null
68
     */
69
    public static function leaf(RuleInterface $rule, string $name, int $group = 0): ?string
70
    {
71
        if ($rule = static::rule($rule, $name)) {
72
            return $rule->getValue($group);
73
        }
74
75
        return null;
76
    }
77
78
    /**
79
     * @param RuleInterface $rule
80
     * @param string $name
81
     * @return RuleInterface|null
82
     */
83
    public static function rule(RuleInterface $rule, string $name): ?RuleInterface
84
    {
85
        foreach ($rule->getChildren() as $child) {
86
            if ($child->getName() === $name) {
87
                return $child;
88
            }
89
        }
90
91
        return null;
92
    }
93
}
94