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

Prefer::__toString()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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