ArrayToStringTransformer   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
c 1
b 0
f 0
lcom 0
cbo 1
dl 0
loc 44
rs 10
ccs 13
cts 13
cp 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A transform() 0 11 2
A reverseTransform() 0 15 3
1
<?php
2
3
namespace Pgs\RestfonyBundle\Form\DataTransformer;
4
5
use Symfony\Component\Form\DataTransformerInterface;
6
use Symfony\Component\Form\Exception\TransformationFailedException;
7
8
/**
9
 * Class transforms norm data into view data.
10
 */
11
class ArrayToStringTransformer implements DataTransformerInterface
12
{
13
    /**
14
     * Transforms an array to a csv set of strings.
15
     *
16
     * @param array|null $array
17
     *
18
     * @return string
19
     */
20 3
    public function transform($array)
21
    {
22 3
        if (!is_array($array)) {
23 1
            throw new TransformationFailedException(sprintf(
24 1
                '%s is not an array',
25
                gettype($array)
26
            ));
27
        }
28
29 2
        return implode(',', $array);
30
    }
31
32
    /**
33
     * Transforms a string into an array.
34
     *
35
     * @param string $string
36
     *
37
     * @return array
38
     */
39 5
    public function reverseTransform($string)
40
    {
41
        //JSON requests will already be strings
42 5
        if (is_array($string)) {
43 2
            return $string;
44
        }
45
        //strip any whitespace
46 3
        $string = preg_replace('/^\s+|\s+$/u', '', $string);
47 3
        $string = preg_replace('/\s+,\s*/u', ',', $string);
48 3
        if (empty($string)) {
49 1
            return [];
50
        }
51
52 2
        return explode(',', $string);
53
    }
54
}
55