Passed
Push — master ( 18e126...c5fa10 )
by Dmitry
02:44
created

CollectionModelTransformer   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 6
Bugs 0 Features 1
Metric Value
wmc 10
c 6
b 0
f 1
lcom 1
cbo 3
dl 0
loc 57
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A supports() 0 10 4
B transform() 0 22 5
1
<?php
2
3
namespace Tonic\Component\ApiLayer\ModelTransformer;
4
5
use Tonic\Component\ApiLayer\ModelTransformer\Exception\UnsupportedTransformationException;
6
7
/**
8
 * Handles homogeneous collection of objects.
9
 */
10
class CollectionModelTransformer implements ModelTransformerInterface
11
{
12
    /**
13
     * @var ModelTransformer
14
     */
15
    private $modelTransformer;
16
17
    /**
18
     * Constructor.
19
     *
20
     * @param ModelTransformer $modelTransformer
21
     */
22
    public function __construct(ModelTransformer $modelTransformer)
23
    {
24
        $this->modelTransformer = $modelTransformer;
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function supports($object, $targetClass)
31
    {
32
        if (!(is_array($object) || $object instanceof \Traversable)) {
33
            return false;
34
        }
35
36
        // if at least one object supported in homogeneous collection
37
        // it is assumed that all other objects are supported
38
        return ((count($object) == 0) || $this->modelTransformer->supports(reset($object), $targetClass));
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function transform($object, $targetClass)
45
    {
46
        if (count($object) == 0) {
47
            return [];
48
        }
49
50
        $modelTransformer = $this->modelTransformer->findSupportedModelTransformer(reset($object), $targetClass);
51
        if (!$modelTransformer) {
52
            throw new UnsupportedTransformationException();
53
        }
54
55
        $elements = [];
56
        foreach ($object as $element) {
57
            if (!$this->modelTransformer->supports($element, $targetClass)) {
58
                throw new UnsupportedTransformationException();
59
            }
60
61
            $elements[] = $modelTransformer->transform($element, $targetClass);
62
        }
63
64
        return $elements;
65
    }
66
}
67