ValuetoModelsOrNullTransformer   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 0
dl 0
loc 67
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B reverseTransform() 0 20 5
B transform() 0 22 6
1
<?php
2
3
namespace Black\Common\Application\Form\Transformer;
4
5
use Black\Common\Infrastructure\Doctrine\Manager;
6
use Symfony\Component\Form\DataTransformerInterface;
7
8
/**
9
 * Class ValuetoModelsOrNullTransformer
10
 *
11
 * ValuetoModelsOrNullTransformer transfom data from collection to an array.
12
 * It works both with ORM or ODM
13
 */
14
class ValuetoModelsOrNullTransformer implements DataTransformerInterface
15
{
16
    /**
17
     * @var
18
     */
19
    protected $manager;
20
21
    /**
22
     * Construct the Transformer
23
     *
24
     * @param Manager $manager
25
     */
26
    public function __construct(Manager $manager)
27
    {
28
        $this->manager = $manager;
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function reverseTransform($data)
35
    {
36
        if (null === $data) {
37
            return null;
38
        }
39
40
        if (is_array($data) || is_object($data)) {
41
            $collection = array();
42
43
            foreach ($data as $id) {
44
                $collection[] = $this->manager->getRepository()->findOneBy(['id' => $id]);
45
            }
46
47
            return $collection;
48
        }
49
50
        $model = $this->manager->getRepository()->findOneBy(['id' => $data]);
51
52
        return $model;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function transform($data)
59
    {
60
        if (empty($data)) {
61
            return null;
62
        }
63
64
        if (is_array($data) || is_object($data)) {
65
            $collection = array();
66
67
            if (in_array('getId', get_class_methods($data))) {
68
                return $data->getId();
69
            }
70
71
            foreach ($data as $model) {
72
                $collection[] = $model->getId();
73
            }
74
75
            return $collection;
76
        }
77
78
        return $data;
79
    }
80
}
81