DispatchingSerializer::addSerializer()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
ccs 3
cts 3
cp 1
crap 1
1
<?php
2
3
namespace Serializers;
4
5
use InvalidArgumentException;
6
use Serializers\Exceptions\UnsupportedObjectException;
7
8
/**
9
 * @since 1.0
10
 *
11
 * @license GPL-2.0-or-later
12
 * @author Jeroen De Dauw < [email protected] >
13
 */
14
class DispatchingSerializer implements DispatchableSerializer {
15
16
	/**
17
	 * @var DispatchableSerializer[]
18
	 */
19
	private $serializers;
20
21
	/**
22
	 * @param DispatchableSerializer[] $serializers
23
	 */
24 7
	public function __construct( array $serializers = [] ) {
25 7
		$this->assertAreSerializers( $serializers );
26 6
		$this->serializers = $serializers;
27 6
	}
28
29 7
	private function assertAreSerializers( array $serializers ) {
30 7
		foreach ( $serializers as $serializer ) {
31 5
			if ( !( $serializer instanceof DispatchableSerializer ) ) {
32 1
				throw new InvalidArgumentException(
33 1
					'Got an object that is not an instance of DispatchableSerializer'
34
				);
35
			}
36
		}
37 6
	}
38
39 5
	public function serialize( $object ) {
40 5
		foreach ( $this->serializers as $serializer ) {
41 4
			if ( $serializer->isSerializerFor( $object ) ) {
42 3
				return $serializer->serialize( $object );
43
			}
44
		}
45
46 2
		throw new UnsupportedObjectException( $object );
47
	}
48
49 2
	public function isSerializerFor( $object ) {
50 2
		foreach ( $this->serializers as $serializer ) {
51 1
			if ( $serializer->isSerializerFor( $object ) ) {
52 1
				return true;
53
			}
54
		}
55
56 2
		return false;
57
	}
58
59
	/**
60
	 * @since 3.0
61
	 *
62
	 * @param DispatchableSerializer $serializer
63
	 */
64 1
	public function addSerializer( DispatchableSerializer $serializer ) {
65 1
		$this->serializers[] = $serializer;
66 1
	}
67
68
}
69