Skip to content

Commit

Permalink
feat: implement custom serializer to handle attribute filtering
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohammad-Alavi committed Jun 1, 2024
1 parent b768290 commit 960ece8
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/Serializers/DataArraySerializer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace Apiato\Core\Serializers;

use Illuminate\Support\Facades\Request;
use League\Fractal\Serializer\ArraySerializer;

class DataArraySerializer extends ArraySerializer
{
public function collection(string|null $resourceKey, array $data): array
{
return $this->filterResponse($data);
}

private function filterResponse(array $data): array
{
if ($requestFilters = Request::get('filter')) {
return ['data' => $this->filterResponseRecursively($data, explode(';', $requestFilters))];
}

return compact('data');
}

private function filterResponseRecursively(array $responseArray, array $filters): array
{
foreach ($responseArray as $key => $value) {
if (in_array($key, $filters, true)) {
// we have found our element - so continue with the next one
continue;
}

if (is_array($value)) {
// it is an array - so go one step deeper
$value = $this->filterResponseRecursively($value, $filters);
$responseArray[$key] = $value;
} elseif (!in_array($key, $filters, true)) {
unset($responseArray[$key]);
}
}

return $responseArray;
}

public function item(string|null $resourceKey, array $data): array
{
return $this->filterResponse($data);
}

public function null(): array|null
{
return ['data' => []];
}
}

0 comments on commit 960ece8

Please sign in to comment.