All::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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