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

CollectionToStringTransformer   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 59
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A transform() 0 19 4
A reverseTransform() 0 17 4
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\ArrayCollection;
15
use Doctrine\Common\Collections\Collection;
16
use Symfony\Component\Form\DataTransformerInterface;
17
use Symfony\Component\Form\Exception\TransformationFailedException;
18
19
/**
20
 * @author Arkadiusz Krakowiak <[email protected]>
21
 */
22
final class CollectionToStringTransformer implements DataTransformerInterface
23
{
24
    /**
25
     * @var string
26
     */
27
    private $delimiter;
28
29
    /**
30
     * @param string $delimiter
31
     */
32
    public function __construct($delimiter)
33
    {
34
        $this->delimiter = $delimiter;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function transform($values)
41
    {
42
        $expectedType = Collection::class;
43
        if (!($values instanceof $expectedType)) {
44
            throw new TransformationFailedException(
45
                sprintf(
46
                    'Expected "%s", but got "%s"',
47
                    $expectedType,
48
                    is_object($values) ? get_class($values) : gettype($values)
49
                )
50
            );
51
        }
52
53
        if ($values->isEmpty()) {
54
            return '';
55
        }
56
57
        return implode($this->delimiter, $values->toArray());
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function reverseTransform($value)
64
    {
65
        if (!is_string($value)) {
66
            throw new TransformationFailedException(
67
                sprintf(
68
                    'Expected string, but got "%s"',
69
                    is_object($value) ? get_class($value) : gettype($value)
70
                )
71
            );
72
        }
73
74
        if ('' === $value) {
75
            return new ArrayCollection();
76
        }
77
78
        return new ArrayCollection(explode($this->delimiter, $value));
79
    }
80
}
81