aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/Wallabag/CoreBundle/Form/DataTransformer/StringToListTransformer.php
blob: cb4bee83069562aa3caca4bced262dab32408dcf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php

namespace Wallabag\CoreBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

/**
 * Transforms a comma-separated list to a proper PHP array.
 * Example: the string "foo, bar" will become the array ["foo", "bar"].
 */
class StringToListTransformer implements DataTransformerInterface
{
    /**
     * @var string
     */
    private $separator;

    /**
     * @param string $separator The separator used in the list
     */
    public function __construct($separator = ',')
    {
        $this->separator = $separator;
    }

    /**
     * Transforms a list to a string.
     *
     * @param array|null $list
     *
     * @return string
     */
    public function transform($list)
    {
        if (null === $list) {
            return '';
        }

        return implode($this->separator, $list);
    }

    /**
     * Transforms a string to a list.
     *
     * @param string $string
     *
     * @return array|null
     */
    public function reverseTransform($string)
    {
        if ($string === null) {
            return;
        }

        return array_values(array_filter(array_map('trim', explode($this->separator, $string))));
    }
}