wallabag/src/Form/DataTransformer/StringToListTransformer.php

58 lines
1.2 KiB
PHP
Raw Permalink Normal View History

2015-10-11 15:30:58 +00:00
<?php
2024-02-19 00:30:12 +00:00
namespace Wallabag\Form\DataTransformer;
2015-10-11 15:30:58 +00:00
use Symfony\Component\Form\DataTransformerInterface;
/**
* Transforms a comma-separated list to a proper PHP array.
2015-12-08 08:20:03 +00:00
* Example: the string "foo, bar" will become the array ["foo", "bar"].
*/
2015-10-11 15:30:58 +00:00
class StringToListTransformer implements DataTransformerInterface
{
/**
* @var string
*/
2015-10-11 15:30:58 +00:00
private $separator;
/**
2016-08-17 12:18:28 +00:00
* @param string $separator The separator used in the list
*/
2015-10-11 15:30:58 +00:00
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.
*
2015-12-08 08:20:03 +00:00
* @param string $string
2015-10-11 15:30:58 +00:00
*
* @return array|null
*/
public function reverseTransform($string)
{
2017-10-09 14:47:15 +00:00
if (null === $string) {
2023-08-08 01:27:21 +00:00
return null;
2015-10-11 15:30:58 +00:00
}
return array_values(array_filter(array_map('trim', explode($this->separator, $string))));
2015-10-11 15:30:58 +00:00
}
}