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