ArrayToStringTransformer   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A transform() 0 12 3
A reverseTransform() 0 16 4
1
<?php
2
3
namespace JD\FormBundle\Form\DataTransformer;
4
5
use Symfony\Component\Form\DataTransformerInterface;
6
use Symfony\Component\Form\Exception\TransformationFailedException;
7
8
/**
9
 *
10
 */
11
final class ArrayToStringTransformer implements DataTransformerInterface
12
{
13
    /**
14
     * @var string
15
     */
16
    private $delimiter;
17
18
    /**
19
     * @param string $delimiter
20
     */
21
    public function __construct($delimiter)
22
    {
23
        $this->delimiter = $delimiter;
24
    }
25
26
    /**
27
     * @param string[]|null $value The value in the original representation
28
     *
29
     * @return string The value in the transformed representation
30
     *
31
     * @throws TransformationFailedException When the transformation fails.
32
     */
33
    public function transform($value)
34
    {
35
        if (null === $value) {
36
            return '';
37
        }
38
39
        if (!is_array($value)) {
40
            throw new TransformationFailedException('Expected an array.');
41
        }
42
43
        return implode($this->delimiter, $value);
44
    }
45
46
    /**
47
     * @param string $value The value in the transformed representation
48
     *
49
     * @return string[] The value in the original representation
50
     *
51
     * @throws TransformationFailedException When the transformation fails.
52
     */
53
    public function reverseTransform($value)
54
    {
55
        if (null === $value) {
56
            return [];
57
        }
58
59
        if (!is_string($value)) {
60
            throw new TransformationFailedException('Expected a string.');
61
        }
62
63
        if (empty($value)) {
64
            return [];
65
        }
66
67
        return explode($this->delimiter, $value);
68
    }
69
}
70