49 lines
1.3 KiB
PHP
49 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace Encoder;
|
|
|
|
use Domain\Normalizer\Normalizer;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class CsvEncoder implements StringEncoder
|
|
{
|
|
public function __construct(
|
|
private Normalizer $normalizer,
|
|
private string $columnSeparator = ',',
|
|
private string $rowSeparator = PHP_EOL,
|
|
)
|
|
{
|
|
}
|
|
|
|
public function encode(Collection $items): string
|
|
{
|
|
$items = $items->values();
|
|
$buffer = implode($this->columnSeparator, $this->normalizer->getHeaders());
|
|
$buffer .= $this->rowSeparator;
|
|
|
|
$items->each(function (object $object) use (&$buffer) {
|
|
$normalized = $this->normalizer->normalize($object);
|
|
$buffer .= collect($normalized)
|
|
->map([CsvEncoder::class, 'formatBoolean'])
|
|
->map([CsvEncoder::class, 'formatEmpty'])
|
|
->implode($this->columnSeparator);
|
|
$buffer .= $this->rowSeparator;
|
|
});
|
|
|
|
return $buffer;
|
|
}
|
|
|
|
public static function formatBoolean(mixed $value): mixed
|
|
{
|
|
if (!is_bool($value)) {
|
|
return $value;
|
|
}
|
|
return true === $value ? 'yes' : 'no';
|
|
}
|
|
|
|
public static function formatEmpty(mixed $value): mixed
|
|
{
|
|
return empty($value) ? '-' : $value;
|
|
}
|
|
}
|