Completed
Push — master ( 366a32...09b547 )
by Paweł
87:56 queued 75:08
created

TaxonsToCodesTransformer::reverseTransform()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 4
nop 1
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
final 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) && !is_null($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]));
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function reverseTransform($taxons)
59
    {
60
        if (!$taxons instanceof Collection) {
61
            throw new UnexpectedTypeException($taxons, Collection::class);
62
        }
63
64
        if (null === $taxons) {
65
            return [];
66
        }
67
68
        $taxonCodes = [];
69
70
        /** @var TaxonInterface $taxon */
71
        foreach ($taxons as $taxon) {
72
            $taxonCodes[] = $taxon->getCode();
73
        }
74
75
        return $taxonCodes;
76
    }
77
}
78