Passed
Push — master ( 09ab0e...29349d )
by Leszek
42s
created

DispatchingValueParser::parse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.0123

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
ccs 8
cts 9
cp 0.8889
rs 9.4285
cc 3
eloc 10
nc 3
nop 1
crap 3.0123
1
<?php
2
3
namespace ValueParsers;
4
5
use InvalidArgumentException;
6
7
/**
8
 * A generic value parser that forwards parsing to a list of other value parsers and returns the
9
 * result of the first parse attempt that succeeded.
10
 *
11
 * @since 0.3
12
 *
13
 * @license GPL-2.0+
14
 * @author Thiemo Mättig
15
 */
16
class DispatchingValueParser implements ValueParser {
17
18
	/**
19
	 * @var ValueParser[]
20
	 */
21
	private $parsers;
22
23
	/**
24
	 * @see ParseException::getExpectedFormat
25
	 *
26
	 * @var string
27
	 */
28
	private $format;
29
30
	/**
31
	 * @param ValueParser[] $parsers
32
	 * @param string $format An identifier describing the expected format of the values to parse.
33
	 *
34
	 * @throws InvalidArgumentException
35
	 */
36 5
	public function __construct( array $parsers, $format ) {
37 5
		if ( empty( $parsers ) ) {
38 1
			throw new InvalidArgumentException( '$parsers must be a non-empty array' );
39
		}
40
41 4
		if ( !is_string( $format ) || $format === '' ) {
42 2
			throw new InvalidArgumentException( '$format must be a non-empty string' );
43
		}
44
45 2
		$this->parsers = $parsers;
46 2
		$this->format = $format;
47 2
	}
48
49
	/**
50
	 * @param mixed $value
51
	 *
52
	 * @throws ParseException
53
	 * @return mixed
54
	 */
55 2
	public function parse( $value ) {
56 2
		foreach ( $this->parsers as $parser ) {
57
			try {
58 2
				return $parser->parse( $value );
59 1
			} catch ( ParseException $ex ) {
60 1
				continue;
61
			}
62
		}
63
64 1
		throw new ParseException(
65 1
			'The value is not recognized by the configured parsers',
66
			$value,
67 1
			$this->format
68
		);
69
	}
70
71
}
72