| 1: | <?php |
| 2: | namespace TIC\CoreBundle\Form\DataTransformer; |
| 3: | |
| 4: | use Symfony\Component\Form\DataTransformerInterface; |
| 5: | use Symfony\Component\Form\Exception\TransformationFailedException; |
| 6: | |
| 7: | |
| 8: | |
| 9: | |
| 10: | |
| 11: | |
| 12: | class ListToStringTransformer implements DataTransformerInterface |
| 13: | { |
| 14: | protected $sep = ','; |
| 15: | protected $glue = null; |
| 16: | protected $trim = " \n\r\t\v\x00"; |
| 17: | protected $skip = false; |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | |
| 23: | |
| 24: | |
| 25: | |
| 26: | |
| 27: | public function __construct(string $sep = null, string $glue = null, bool $trim = true, bool $skip = false) |
| 28: | { |
| 29: | if ($sep !== null) $this->sep = $sep; |
| 30: | if ($glue !== null) $this->glue = $glue; |
| 31: | else switch ($this->sep) { |
| 32: | case "," : $this->glue = ", "; break; |
| 33: | case "\n" : $this->glue = "\r\n"; break; |
| 34: | default : $this->glue = $this->sep; break; |
| 35: | } |
| 36: | if ($trim === false) $this->trim = null; |
| 37: | if ($skip !== null) $this->skip = $skip; |
| 38: | } |
| 39: | |
| 40: | |
| 41: | |
| 42: | |
| 43: | |
| 44: | |
| 45: | |
| 46: | |
| 47: | public function transform(mixed $values): ?string |
| 48: | { |
| 49: | if ($values === null) return null; |
| 50: | |
| 51: | if (! \is_array($values)) throw new TransformationFailedException("Expected an array."); |
| 52: | |
| 53: | return \implode($this->glue, \array_map(function($v){ |
| 54: | if ($v === null) return ''; |
| 55: | |
| 56: | if (! \is_scalar($v)) throw new TransformationFailedException("Expected a simple array (list of scalars): ".\print_r($v,true)); |
| 57: | |
| 58: | $v = \str_replace($this->sep, '', $v); |
| 59: | |
| 60: | return ($this->trim === null) ? $v : \trim($v, $this->trim); |
| 61: | }, $values)); |
| 62: | } |
| 63: | |
| 64: | |
| 65: | |
| 66: | |
| 67: | |
| 68: | |
| 69: | |
| 70: | |
| 71: | public function reverseTransform(mixed $values): ?array |
| 72: | { |
| 73: | if ($values === null) return null; |
| 74: | |
| 75: | if (! \is_string($values)) throw new TransformationFailedException("Expected a string."); |
| 76: | |
| 77: | return array_map(function($v){ |
| 78: | if ($v === '') return null; |
| 79: | return ($this->trim === null) ? $v : \trim($v, $this->trim); |
| 80: | }, \explode($this->sep, $values)); |
| 81: | } |
| 82: | |
| 83: | } |
| 84: | |