Completed
Push — master ( c80620...0cd8d9 )
by Martijn
03:25
created

SpacingContextTrait   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 41
rs 10
c 0
b 0
f 0
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A popSpacer() 0 3 1
A skipSpacing() 0 17 5
A pushSpacer() 0 3 3
1
<?php
2
3
namespace Vanderlee\Comprehend\Core\Context;
4
5
use Vanderlee\Comprehend\Core\ArgumentsTrait;
6
use Vanderlee\Comprehend\Parser\Parser;
7
8
trait SpacingContextTrait
9
{
10
    use ArgumentsTrait;
11
12
    /**
13
     * List of spacers.
14
     *  -  Parser for a normal spacer.
15
     *  -  `null` to disable spacing.
16
     *  -  `true` to use the top-most spacer.
17
     *
18
     * @var Parser[]|null[]|bool[]
19
     */
20
    private $spacers = [];
21
22
    public function pushSpacer($skipper = null)
23
    {
24
        $this->spacers[] = ($skipper === null || $skipper === true) ? $skipper : $this->getArgument($skipper);
25
    }
26
27
    public function popSpacer()
28
    {
29
        array_pop($this->spacers);
30
    }
31
32
    public function skipSpacing($in, $offset)
33
    {
34
        $spacer = end($this->spacers);
35
36
        // If `true`; use top-most Parser instance in stack.
37
        if ($spacer === true) {
38
            do {
39
                $spacer = prev($this->spacers);
40
            } while ($spacer !== false && !($spacer instanceof Parser));
41
        }
42
43
        if ($spacer instanceof Parser) {
44
            $match = $spacer->match($in, $offset);
45
            return $match->match ? $match->length : false;
46
        }
47
48
        return 0;
49
    }
50
}