]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Form/DataTransformer/StringToListTransformer.php
Add tests for the StringToListTransformer class
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Form / DataTransformer / StringToListTransformer.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Form\DataTransformer;
4
5 use Doctrine\Common\Persistence\ObjectManager;
6 use Symfony\Component\Form\DataTransformerInterface;
7 use Symfony\Component\Form\Exception\TransformationFailedException;
8
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 */
13 class StringToListTransformer implements DataTransformerInterface
14 {
15 /**
16 * @var string
17 */
18 private $separator;
19
20 /**
21 * @param string $separator The separator used in the list.
22 */
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 {
53 if ($string === null) {
54 return null;
55 }
56
57 return array_values(array_filter(array_map('trim', explode($this->separator, $string))));
58 }
59 }