Skip to content

feat(transformer): implement data transformation system and test cove… #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,5 @@ tests/lista_de_arquivos.php
tests/lista_de_arquivos_test.php
lista_de_arquivos.txt
lista_de_arquivos_tests.txt
add_static_to_providers.php
test_files_generate.php
/composer.lock
41 changes: 41 additions & 0 deletions src/Exception/DateTransformerException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace KaririCode\Transformer\Exception;

use KaririCode\Exception\AbstractException;

final class DateTransformerException extends AbstractException
{
private const CODE_INVALID_TIMEZONE = 5101;
private const CODE_INVALID_FORMAT = 5102;
private const CODE_INVALID_DATE = 5103;

public static function invalidTimezone(string $timezone): self
{
return self::createException(
self::CODE_INVALID_TIMEZONE,
'INVALID_TIMEZONE',
"Invalid timezone: {$timezone}"
);
}

public static function invalidFormat(string $format, string $value): self
{
return self::createException(
self::CODE_INVALID_FORMAT,
'INVALID_FORMAT',
"Invalid date format. Expected {$format}, got '{$value}'"
);
}

public static function invalidDate(string $date): self
{
return self::createException(
self::CODE_INVALID_DATE,
'INVALID_DATE',
"Invalid date: {$date}"
);
}
}
8 changes: 1 addition & 7 deletions src/Processor/Array/ArrayFlattenTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,9 @@

use KaririCode\Contract\Processor\ConfigurableProcessor;
use KaririCode\Transformer\Processor\AbstractTransformerProcessor;
use KaririCode\Transformer\Trait\ArrayTransformerTrait;

class ArrayFlattenTransformer extends AbstractTransformerProcessor implements ConfigurableProcessor
{
use ArrayTransformerTrait;

private int $depth = -1;
private string $separator = '.';

Expand Down Expand Up @@ -40,10 +37,7 @@ private function flattenArray(array $array, string $prefix = '', int $depth = -1
$newKey = $prefix ? $prefix . $this->separator . $key : $key;

if (is_array($value) && ($depth > 0 || -1 === $depth)) {
$result = array_merge(
$result,
$this->flattenArray($value, $newKey, $depth > 0 ? $depth - 1 : -1)
);
$result += $this->flattenArray($value, $newKey, $depth > 0 ? $depth - 1 : -1);
} else {
$result[$newKey] = $value;
}
Expand Down
3 changes: 0 additions & 3 deletions src/Processor/Array/ArrayGroupTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,9 @@

use KaririCode\Contract\Processor\ConfigurableProcessor;
use KaririCode\Transformer\Processor\AbstractTransformerProcessor;
use KaririCode\Transformer\Trait\ArrayTransformerTrait;

class ArrayGroupTransformer extends AbstractTransformerProcessor implements ConfigurableProcessor
{
use ArrayTransformerTrait;

private string $groupBy = '';
private bool $preserveKeys = false;

Expand Down
41 changes: 9 additions & 32 deletions src/Processor/Array/ArrayKeyTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,7 @@ class ArrayKeyTransformer extends AbstractTransformerProcessor implements Config
{
use ArrayTransformerTrait;

private const CASE_SNAKE = 'snake';
private const CASE_CAMEL = 'camel';
private const CASE_PASCAL = 'pascal';
private const CASE_KEBAB = 'kebab';

private string $case = self::CASE_SNAKE;
private string $case = 'snake'; // Valores possíveis: snake, camel, pascal, kebab
private bool $recursive = true;

public function configure(array $options): void
Expand All @@ -37,44 +32,26 @@ public function process(mixed $input): array
return [];
}

return $this->transformArrayKeys($input);
// Transforma as chaves apenas no nível principal se recursive for false
return $this->recursive
? $this->transformArrayKeys($input, $this->case)
: $this->transformKeysNonRecursive($input, $this->case);
}

private function transformArrayKeys(array $array): array
private function transformKeysNonRecursive(array $array, string $case): array
{
$result = [];

foreach ($array as $key => $value) {
$transformedKey = $this->transformKey((string) $key);

if (is_array($value) && $this->recursive) {
$result[$transformedKey] = $this->transformArrayKeys($value);
} else {
$result[$transformedKey] = $value;
}
$transformedKey = $this->transformKeyByCase((string) $key, $case);
$result[$transformedKey] = $value; // Mantém o valor original, sem recursão
}

return $result;
}

private function transformKey(string $key): string
{
return match ($this->case) {
self::CASE_SNAKE => $this->toSnakeCase($key),
self::CASE_CAMEL => $this->toCamelCase($key),
self::CASE_PASCAL => $this->toPascalCase($key),
self::CASE_KEBAB => $this->toKebabCase($key),
default => $key,
};
}

private function getAllowedCases(): array
{
return [
self::CASE_SNAKE,
self::CASE_CAMEL,
self::CASE_PASCAL,
self::CASE_KEBAB,
];
return ['snake', 'camel', 'pascal', 'kebab'];
}
}
13 changes: 6 additions & 7 deletions src/Processor/Array/ArrayMapTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class ArrayMapTransformer extends AbstractTransformerProcessor implements Config
private array $mapping = [];
private bool $removeUnmapped = false;
private bool $recursive = true;
private ?string $case = null;

public function configure(array $options): void
{
Expand All @@ -25,6 +26,7 @@ public function configure(array $options): void
$this->mapping = $options['mapping'];
$this->removeUnmapped = $options['removeUnmapped'] ?? $this->removeUnmapped;
$this->recursive = $options['recursive'] ?? $this->recursive;
$this->case = $options['case'] ?? null; // Opcional
}

public function process(mixed $input): array
Expand All @@ -35,26 +37,23 @@ public function process(mixed $input): array
return [];
}

return $this->mapArray($input);
$mappedArray = $this->mapArray($input);

return $this->case ? $this->transformArrayKeys($mappedArray, $this->case) : $mappedArray;
}

private function mapArray(array $array): array
{
$result = [];

foreach ($array as $key => $value) {
if (is_array($value) && $this->recursive) {
$result[$key] = $this->mapArray($value);
continue;
}

$mappedKey = $this->mapping[$key] ?? $key;

if ($this->removeUnmapped && !isset($this->mapping[$key])) {
continue;
}

$result[$mappedKey] = $value;
$result[$mappedKey] = is_array($value) && $this->recursive ? $this->mapArray($value) : $value;
}

return $result;
Expand Down
90 changes: 66 additions & 24 deletions src/Processor/Data/DateTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,52 +5,90 @@
namespace KaririCode\Transformer\Processor\Data;

use KaririCode\Contract\Processor\ConfigurableProcessor;
use KaririCode\Transformer\Exception\DateTransformerException;
use KaririCode\Transformer\Processor\AbstractTransformerProcessor;

class DateTransformer extends AbstractTransformerProcessor implements ConfigurableProcessor
final class DateTransformer extends AbstractTransformerProcessor implements ConfigurableProcessor
{
private string $inputFormat = 'Y-m-d';
private string $outputFormat = 'Y-m-d';
private ?string $inputTimezone = null;
private ?string $outputTimezone = null;
private const DEFAULT_FORMAT = 'Y-m-d';
private const ERROR_INVALID_STRING = 'notString';
private const ERROR_INVALID_DATE = 'invalidDate';

private string $inputFormat = self::DEFAULT_FORMAT;
private string $outputFormat = self::DEFAULT_FORMAT;
private ?\DateTimeZone $inputTimezone = null;
private ?\DateTimeZone $outputTimezone = null;

public function configure(array $options): void
{
$this->inputFormat = $options['inputFormat'] ?? $this->inputFormat;
$this->outputFormat = $options['outputFormat'] ?? $this->outputFormat;
$this->inputTimezone = $options['inputTimezone'] ?? $this->inputTimezone;
$this->outputTimezone = $options['outputTimezone'] ?? $this->outputTimezone;
$this->configureFormats($options);
$this->configureTimezones($options);
}

public function process(mixed $input): string
{
if (!is_string($input)) {
$this->setInvalid('notString');

if (!$this->isValidInput($input)) {
return '';
}

try {
$date = $this->createDateTime($input);

return $this->formatDate($date);
} catch (\Exception $e) {
$this->setInvalid('invalidDate');
return $this->transformDate($input);
} catch (DateTransformerException) {
$this->setInvalid(self::ERROR_INVALID_DATE);

return '';
}
}

private function createDateTime(string $input): \DateTime
private function configureFormats(array $options): void
{
$this->inputFormat = $options['inputFormat'] ?? self::DEFAULT_FORMAT;
$this->outputFormat = $options['outputFormat'] ?? self::DEFAULT_FORMAT;
}

private function configureTimezones(array $options): void
{
$date = \DateTime::createFromFormat($this->inputFormat, $input);
$this->inputTimezone = $this->createTimezone($options['inputTimezone'] ?? null);
$this->outputTimezone = $this->createTimezone($options['outputTimezone'] ?? null);
}

private function createTimezone(?string $timezone): ?\DateTimeZone
{
if (!$timezone) {
return null;
}

try {
return new \DateTimeZone($timezone);
} catch (\Exception) {
throw DateTransformerException::invalidTimezone($timezone);
}
}

if (false === $date) {
throw new \RuntimeException('Invalid date format');
private function isValidInput(mixed $input): bool
{
if (is_string($input)) {
return true;
}

if ($this->inputTimezone) {
$date->setTimezone(new \DateTimeZone($this->inputTimezone));
$this->setInvalid(self::ERROR_INVALID_STRING);

return false;
}

private function transformDate(string $input): string
{
$date = $this->createDateTime($input);

return $this->formatDate($date);
}

private function createDateTime(string $input): \DateTime
{
$date = \DateTime::createFromFormat($this->inputFormat, $input, $this->inputTimezone);

if (!$date) {
throw DateTransformerException::invalidFormat($this->inputFormat, $input);
}

return $date;
Expand All @@ -59,7 +97,11 @@ private function createDateTime(string $input): \DateTime
private function formatDate(\DateTime $date): string
{
if ($this->outputTimezone) {
$date->setTimezone(new \DateTimeZone($this->outputTimezone));
try {
$date->setTimezone($this->outputTimezone);
} catch (\Exception) {
throw DateTransformerException::invalidDate($date->format('Y-m-d H:i:s'));
}
}

return $date->format($this->outputFormat);
Expand Down
Loading
Loading