Skip to content

Commit

Permalink
improve transforming date fields
Browse files Browse the repository at this point in the history
  • Loading branch information
Max Snow committed Dec 5, 2024
1 parent bff7360 commit 3483c3e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"api-ecosystem-for-laravel/dingo-api": "^4.1",
"php-open-source-saver/jwt-auth": "^2.1",
"illuminate/support": "^10.0",
"ramsey/uuid": "^4.3"
"ramsey/uuid": "^4.3",
"nesbot/carbon": "^2.0|^3.0"
},
"require-dev": {
"ext-json": "*",
Expand Down
38 changes: 35 additions & 3 deletions src/Transformers/RestfulTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@

namespace Specialtactics\L5Api\Transformers;

use DateTimeInterface;
use Carbon\Carbon;
use League\Fractal\TransformerAbstract;
use Specialtactics\L5Api\APIBoilerplate;
use Specialtactics\L5Api\Models\RestfulModel;
use Illuminate\Database\Eloquent\Model as EloquentModel;

class RestfulTransformer extends TransformerAbstract
{
public const DATE_CAST_TYPES = ['date', 'datetime', 'immutable_date', 'immutable_datetime'];

/**
* @var RestfulModel The model to be transformed
*/
Expand Down Expand Up @@ -82,11 +86,19 @@ public function transformRestfulModel(EloquentModel $model)
}, ARRAY_FILTER_USE_KEY);

/*
* Format all dates as Iso8601 strings, this includes the created_at and updated_at columns
* Format all dates as Iso8601 strings, this includes timestamped columns
*/
foreach ($model->getDates() as $dateColumn) {
foreach ($this->getModelDateFields($model) as $dateColumn) {
if (! empty($model->$dateColumn) && ! in_array($dateColumn, $filterOutAttributes)) {
$transformed[$dateColumn] = $model->$dateColumn->toIso8601String();
if ($model->$dateColumn instanceof DateTimeInterface) {
$transformed[$dateColumn] = Carbon::instance($model->$dateColumn)->toIso8601String();
} else {
try {
$transformed[$dateColumn] = Carbon::parse($model->$dateColumn)->toIso8601String();
} catch (\Error $e) {
$transformed[$dateColumn] = $model->$dateColumn;
}
}
}
}

Expand Down Expand Up @@ -253,4 +265,24 @@ protected function transformRelations(array $transformed)

return $transformed;
}

protected function getModelDateFields(EloquentModel $model): array
{
$dateFields = [];

foreach ($model->getDates() as $dateColumn) {
$dateFields[] = $dateColumn;
}

// For previous versions of Eloquent, dates were stored as arrays
$dateFields = array_merge($model->dates, $dateFields);

foreach ($model->getCasts() as $field => $castType) {
if (in_array($castType, static::DATE_CAST_TYPES)) {
$dateFields[] = $field;
}
}

return array_unique($dateFields);
}
}

0 comments on commit 3483c3e

Please sign in to comment.