Completed
Push — pagerfanta-fix ( 187c46...923c07 )
by Kamil
25:06 queued 03:45
created

RecursiveTransformer::transform()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 8
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 4
nc 1
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\ResourceBundle\Form\DataTransformer;
13
14
use Doctrine\Common\Collections\Collection;
15
use Symfony\Component\Form\DataTransformerInterface;
16
use Symfony\Component\Form\Exception\TransformationFailedException;
17
18
/**
19
 * @author Arkadiusz Krakowiak <[email protected]>
20
 */
21
final class RecursiveTransformer implements DataTransformerInterface
22
{
23
    /**
24
     * @var DataTransformerInterface
25
     */
26
    private $decoratedTransformer;
27
28
    /**
29
     * @param DataTransformerInterface $decoratedTransformer
30
     */
31
    public function __construct(DataTransformerInterface $decoratedTransformer)
32
    {
33
        $this->decoratedTransformer = $decoratedTransformer;
34
    }
35
36
    /**
37
     * {@inheritDoc}
38
     */
39
    public function transform($values)
40
    {
41
        $this->assertTransformationValueType($values, Collection::class);
42
43
        return $values->map(function ($value) {
44
            return $this->decoratedTransformer->transform($value);
45
        });
46
    }
47
48
    /**
49
     * {@inheritDoc}
50
     */
51
    public function reverseTransform($values)
52
    {
53
        $this->assertTransformationValueType($values, Collection::class);
54
55
        return $values->map(function ($value) {
56
            return $this->decoratedTransformer->reverseTransform($value);
57
        });
58
    }
59
60
    /**
61
     * @param string $value
62
     * @param string $expectedType
63
     *
64
     * @throws TransformationFailedException
65
     */
66
    private function assertTransformationValueType($value, $expectedType)
67
    {
68
        if (!($value instanceof $expectedType)) {
69
            throw new TransformationFailedException(
70
                sprintf(
71
                    'Expected "%s", but got "%s"',
72
                    $expectedType,
73
                    is_object($value) ? get_class($value) : gettype($value)
74
                )
75
            );
76
        }
77
    }
78
}
79