Prefer   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 59
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 2
A __toString() 0 10 4
A parse() 0 7 1
1
<?php
2
3
namespace Vanderlee\Comprehend\Directive;
4
5
use DomainException;
6
use Vanderlee\Comprehend\Core\ArgumentsTrait;
7
use Vanderlee\Comprehend\Core\Context;
8
use Vanderlee\Comprehend\Parser\Parser;
9
10
/**
11
 * Description of OrDirective.
12
 *
13
 * @author Martijn
14
 */
15
class Prefer extends Parser
16
{
17
    const FIRST = 'first';
18
    const LONGEST = 'longest';
19
    const SHORTEST = 'shortest';
20
21
    use ArgumentsTrait;
22
23
    /**
24
     * @var Parser;
25
     */
26
    private $parser = null;
27
28
    /**
29
     * One of self::*.
30
     *
31
     * @var int
32
     */
33
    private $preference = null;
34
35
    /**
36
     * @param mixed $preference
37
     * @param mixed $parser
38
     *
39
     * @throws DomainException
40
     */
41 2
    public function __construct($preference, $parser)
42
    {
43 2
        if (!in_array($preference, [
44 2
            self::FIRST,
45 2
            self::LONGEST,
46 2
            self::SHORTEST,
47
        ])) {
48 1
            throw new DomainException('Invalid preference `' . $preference . '`');
49
        }
50 1
        $this->preference = $preference;
51
52 1
        $this->parser = self::getArgument($parser);
53 1
    }
54
55 6
    protected function parse(&$input, $offset, Context $context)
56
    {
57 6
        $context->pushPreference($this->preference);
58 6
        $match = $this->parser->parse($input, $offset, $context);
59 6
        $context->popPreference();
60
61 6
        return $match;
62
    }
63
64 6
    public function __toString()
65
    {
66 6
        switch ($this->preference) {
67
            default:
68 6
            case self::FIRST:
69 2
                return (string)$this->parser;
70 4
            case self::LONGEST:
71 2
                return 'longest-of' . $this->parser;
72 2
            case self::SHORTEST:
73 2
                return 'shortest-of' . $this->parser;
74
        }
75
    }
76
}
77