Implode.php
41 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AC\Formatter\Collection; |
| 6 | |
| 7 | use AC\CollectionFormatter; |
| 8 | use AC\Type\Value; |
| 9 | use AC\Type\ValueCollection; |
| 10 | |
| 11 | class Implode implements CollectionFormatter |
| 12 | { |
| 13 | |
| 14 | private string $separator; |
| 15 | |
| 16 | public function __construct(?string $separator = null) |
| 17 | { |
| 18 | $this->separator = $separator ?? ', '; |
| 19 | } |
| 20 | |
| 21 | public function format(ValueCollection $collection): Value |
| 22 | { |
| 23 | $values = []; |
| 24 | |
| 25 | foreach ($collection as $item) { |
| 26 | $value = (string)$item; |
| 27 | |
| 28 | if ('' === $value) { |
| 29 | continue; |
| 30 | } |
| 31 | |
| 32 | $values[] = $value; |
| 33 | } |
| 34 | |
| 35 | return new Value( |
| 36 | $collection->get_id(), |
| 37 | implode($this->separator, $values) |
| 38 | ); |
| 39 | } |
| 40 | |
| 41 | } |