CollectionModelTransformer   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 2
dl 0
loc 56
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B supports() 0 14 5
A transform() 0 17 4
1
<?php
2
3
namespace Tonic\Component\ApiLayer\ModelTransformer;
4
5
use Tonic\Component\ApiLayer\ModelTransformer\Exception\UnsupportedTransformationException;
6
7
/**
8
 * Handles 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
                    return false;
36
                }
37
            }
38
39
            return true;
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
        if (!$this->supports($object, $targetClass)) {
55
            throw new UnsupportedTransformationException();
56
        }
57
58
        $elements = [];
59
        foreach ($object as $element) {
60
            $elements[] = $this->modelTransformer->transform($element, $targetClass);
61
        }
62
63
        return $elements;
64
    }
65
}
66