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

All::parse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 3
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Vanderlee\Comprehend\Parser\Structure;
4
5
use Vanderlee\Comprehend\Core\ArgumentsTrait;
6
use Vanderlee\Comprehend\Core\Context;
7
use Vanderlee\Comprehend\Parser\Parser;
8
9
/**
10
 * Matches if and only if all parsers individually match. Returned length is the shortest length of all matches
11
 *
12
 * @author Martijn
13
 */
14
class All extends Parser
15
{
16
17
    use ArgumentsTrait;
18
19
    /**
20
     * @var Parser[]
21
     */
22
    private $parsers = [];
23
24
    public function __construct(...$arguments)
25
    {
26
        if (count($arguments) < 2) {
27
            throw new \InvalidArgumentException('Less than 2 arguments provided');
28
        }
29
        $this->parsers = self::getArguments($arguments);
30
    }
31
32
    protected function parse(&$input, $offset, Context $context)
33
    {
34
        $length = PHP_INT_MAX;
35
        foreach ($this->parsers as $parser) {
36
            $match  = $parser->parse($input, $offset, $context);
37
            $length = min($length, $match->length);
38
            if (!$match->match) {
39
                return $this->failure($input, $offset, $length);
40
            }
41
        }
42
        return $this->success($input, $offset, $length);
43
    }
44
45
    public function __toString()
46
    {
47
        return '( ' . join(' + ', $this->parsers) . ' )';
48
    }
49
50
}
51