Completed
Pull Request — master (#65)
by no
02:44
created

DispatchingValueParser   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 94.12%

Importance

Changes 0
Metric Value
wmc 7
c 0
b 0
f 0
lcom 1
cbo 2
dl 0
loc 56
ccs 16
cts 17
cp 0.9412
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 4
A parse() 0 15 3
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