]>
Commit | Line | Data |
---|---|---|
f19f9f62 KG |
1 | <?php |
2 | ||
3 | namespace Wallabag\CoreBundle\Form\DataTransformer; | |
4 | ||
f19f9f62 | 5 | use Symfony\Component\Form\DataTransformerInterface; |
f19f9f62 | 6 | |
003fa774 KG |
7 | /** |
8 | * Transforms a comma-separated list to a proper PHP array. | |
347fa6be | 9 | * Example: the string "foo, bar" will become the array ["foo", "bar"]. |
003fa774 | 10 | */ |
f19f9f62 KG |
11 | class StringToListTransformer implements DataTransformerInterface |
12 | { | |
003fa774 KG |
13 | /** |
14 | * @var string | |
15 | */ | |
f19f9f62 KG |
16 | private $separator; |
17 | ||
003fa774 | 18 | /** |
0cecfa25 | 19 | * @param string $separator The separator used in the list |
003fa774 | 20 | */ |
f19f9f62 KG |
21 | public function __construct($separator = ',') |
22 | { | |
23 | $this->separator = $separator; | |
24 | } | |
25 | ||
26 | /** | |
27 | * Transforms a list to a string. | |
28 | * | |
29 | * @param array|null $list | |
30 | * | |
31 | * @return string | |
32 | */ | |
33 | public function transform($list) | |
34 | { | |
35 | if (null === $list) { | |
36 | return ''; | |
37 | } | |
38 | ||
39 | return implode($this->separator, $list); | |
40 | } | |
41 | ||
42 | /** | |
43 | * Transforms a string to a list. | |
44 | * | |
347fa6be | 45 | * @param string $string |
f19f9f62 KG |
46 | * |
47 | * @return array|null | |
48 | */ | |
49 | public function reverseTransform($string) | |
50 | { | |
003fa774 | 51 | if ($string === null) { |
347fa6be | 52 | return; |
f19f9f62 KG |
53 | } |
54 | ||
003fa774 | 55 | return array_values(array_filter(array_map('trim', explode($this->separator, $string)))); |
f19f9f62 KG |
56 | } |
57 | } |