asrock-memory-qvl-scraper/src/Encoder/CsvEncoder.php

48 lines
1.2 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
{
$buffer = implode($this->columnSeparator, $this->normalizer->getHeaders());
$buffer .= $this->rowSeparator;
$items->values()->each(function (object $object) use (&$buffer) {
$normalized = $this->normalizer->normalize($object);
$buffer .= collect($normalized)
->map([static::class, 'formatBoolean'])
->map([static::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;
}
}