MacroSet   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 66
rs 10
c 0
b 0
f 0
wmc 7
lcom 1
cbo 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A addMacro() 0 6 2
A apply() 0 18 3
A cache() 0 4 1
1
<?php
2
/**
3
 * This file is part of PHP-Yacc 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 PhpYacc\Yacc;
11
12
use PhpYacc\Grammar\Context;
13
use PhpYacc\Yacc\Macro\DollarExpansion;
14
15
/**
16
 * Class MacroSet.
17
 */
18
class MacroSet
19
{
20
    /**
21
     * @var array
22
     */
23
    protected $macros = [];
24
25
    /**
26
     * MacroSet constructor.
27
     *
28
     * @param MacroAbstract[] ...$macros
29
     */
30
    public function __construct(MacroAbstract ...$macros)
31
    {
32
        $this->addMacro(new DollarExpansion());
33
        $this->addMacro(...$macros);
34
    }
35
36
    /**
37
     * @param MacroAbstract[] ...$macros
38
     */
39
    public function addMacro(MacroAbstract ...$macros)
40
    {
41
        foreach ($macros as $macro) {
42
            $this->macros[] = $macro;
43
        }
44
    }
45
46
    /**
47
     * @param Context $ctx
48
     * @param array   $symbols
49
     * @param array   $tokens
50
     * @param int     $n
51
     * @param array   $attribute
52
     *
53
     * @return array
54
     */
55
    public function apply(Context $ctx, array $symbols, array $tokens, int $n, array $attribute): array
56
    {
57
        $tokens = new \ArrayIterator($tokens);
58
        $macroCount = \count($this->macros);
59
60
        if ($macroCount === 1) {
61
            // special case
62
            return \iterator_to_array($this->macros[0]->apply($ctx, $symbols, $tokens, $n, $attribute));
63
        }
64
65
        foreach ($this->macros as $macro) {
66
            $tokens = $macro->apply($ctx, $symbols, $tokens, $n, $attribute);
67
        }
68
69
        $tokens = self::cache($tokens);
70
71
        return \iterator_to_array($tokens);
72
    }
73
74
    /**
75
     * @param \Traversable $t
76
     *
77
     * @return \Traversable
78
     */
79
    public static function cache(\Traversable $t): \Traversable
80
    {
81
        return new \ArrayIterator(iterator_to_array($t));
82
    }
83
}
84