Skip to content

Commit

Permalink
feat: add fieldsBefore and fieldsAfter ApiResource extenders (#4106)
Browse files Browse the repository at this point in the history
  • Loading branch information
SychO9 authored Nov 9, 2024
1 parent c401e67 commit 3b69af2
Show file tree
Hide file tree
Showing 3 changed files with 403 additions and 331 deletions.
48 changes: 48 additions & 0 deletions framework/core/src/Extend/ApiResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ class ApiResource implements ExtenderInterface
private array $removeEndpoints = [];
private array $endpoint = [];
private array $fields = [];
private array $fieldsBefore = [];
private array $fieldsAfter = [];
private array $removeFields = [];
private array $field = [];
private array $sorts = [];
Expand Down Expand Up @@ -93,6 +95,32 @@ public function fields(callable|string $fields): self
return $this;
}

/**
* Add fields to the resource before a certain field.
*
* @param string $before the name of the field to add the new fields before.
* @param callable|class-string $fields must be a callable that returns an array of objects that implement \Tobyz\JsonApiServer\Schema\Field.
*/
public function fieldsBefore(string $before, callable|string $fields): self
{
$this->fieldsBefore[] = [$before, $fields];

return $this;
}

/**
* Add fields to the resource after a certain field.
*
* @param string $after the name of the field to add the new fields after.
* @param callable|class-string $fields must be a callable that returns an array of objects that implement \Tobyz\JsonApiServer\Schema\Field.
*/
public function fieldsAfter(string $after, callable|string $fields): self
{
$this->fieldsAfter[] = [$after, $fields];

return $this;
}

/**
* Remove fields from the resource.
*
Expand Down Expand Up @@ -221,6 +249,26 @@ function (array $endpoints, Resource $resource) use ($container): array {
$fields = array_merge($fields, $newFieldsCallback());
}

foreach ($this->fieldsBefore as [$before, $newFieldsCallback]) {
$newFieldsCallback = ContainerUtil::wrapCallback($newFieldsCallback, $container);
$newFields = $newFieldsCallback();
$beforeIndex = array_search($before, array_column($fields, 'name'));

if ($beforeIndex !== false) {
array_splice($fields, $beforeIndex, 0, $newFields);
}
}

foreach ($this->fieldsAfter as [$after, $newFieldsCallback]) {
$newFieldsCallback = ContainerUtil::wrapCallback($newFieldsCallback, $container);
$newFields = $newFieldsCallback();
$afterIndex = array_search($after, array_column($fields, 'name'));

if ($afterIndex !== false) {
array_splice($fields, $afterIndex + 1, 0, $newFields);
}
}

foreach ($this->removeFields as $field) {
[$fieldsToRemove, $condition] = $field;

Expand Down
Loading

0 comments on commit 3b69af2

Please sign in to comment.