Completed
Push — master ( b7da96...b87c29 )
by Kamil
13s
created

TaxonsToCodesTransformer   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A transform() 0 12 3
B reverseTransform() 0 22 6
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Bundle\CoreBundle\Form\DataTransformer;
13
14
use Doctrine\Common\Collections\ArrayCollection;
15
use Doctrine\Common\Collections\Collection;
16
use Sylius\Component\Core\Model\TaxonInterface;
17
use Sylius\Component\Resource\Exception\UnexpectedTypeException;
18
use Sylius\Component\Taxonomy\Repository\TaxonRepositoryInterface;
19
use Symfony\Component\Form\DataTransformerInterface;
20
21
/**
22
 * @author Mateusz Zalewski <[email protected]>
23
 */
24
class TaxonsToCodesTransformer implements DataTransformerInterface
25
{
26
    /**
27
     * @var TaxonRepositoryInterface
28
     */
29
    private $taxonRepository;
30
31
    /**
32
     * @param TaxonRepositoryInterface $taxonRepository
33
     */
34
    public function __construct(TaxonRepositoryInterface $taxonRepository)
35
    {
36
        $this->taxonRepository = $taxonRepository;
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function transform($value)
43
    {
44
        if (!is_array($value)) {
45
            throw new UnexpectedTypeException($value, 'array');
46
        }
47
48
        if (empty($value)) {
49
            return new ArrayCollection();
50
        }
51
52
        return new ArrayCollection($this->taxonRepository->findBy(['code' => $value['taxons']]));
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function reverseTransform($value)
59
    {
60
        if (!$value instanceof Collection) {
61
            throw new UnexpectedTypeException($value, Collection::class);
62
        }
63
64
        if ($value->isEmpty() || null === $value->get('taxons')) {
65
            return [];
66
        }
67
68
        if (!is_array($value->get('taxons'))) {
69
            throw new \InvalidArgumentException('"taxons" element of collection should be an array.');
70
        }
71
72
        $taxons = [];
73
        /** @var TaxonInterface $taxon */
74
        foreach ($value->get('taxons') as $taxon) {
75
            $taxons[] = $taxon->getCode();
76
        }
77
78
        return ['taxons' => $taxons];
79
    }
80
}
81