Passed
Push — master ( d212d2...18e126 )
by Dmitry
02:37
created

CollectionModelTransformer::transform()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 1
Metric Value
c 5
b 0
f 1
dl 0
loc 22
rs 8.6737
cc 5
eloc 12
nc 5
nop 2
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
            foreach ($object as $element) {
34
                if ($this->modelTransformer->supports($element, $targetClass)) {
35
                    // if at least one object supported in homogeneous collection
36
                    // it is assumed that all other objects are supported
37
                    return true;
38
                }
39
            }
40
        }
41
42
        return false;
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function transform($object, $targetClass)
49
    {
50
        if (count($object) == 0) {
51
            return [];
52
        }
53
54
        $modelTransformer = $this->modelTransformer->findSupportedModelTransformer(reset($object), $targetClass);
55
        if (!$modelTransformer) {
56
            throw new UnsupportedTransformationException();
57
        }
58
59
        $elements = [];
60
        foreach ($object as $element) {
61
            if (!$this->modelTransformer->supports($element, $targetClass)) {
62
                throw new UnsupportedTransformationException();
63
            }
64
65
            $elements[] = $modelTransformer->transform($element, $targetClass);
66
        }
67
68
        return $elements;
69
    }
70
}
71