Skip to content
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
456 changes: 297 additions & 159 deletions docs-v2/content/en/api/actions.md

Large diffs are not rendered by default.

86 changes: 85 additions & 1 deletion docs-v2/content/en/api/fields.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ Each Field generally extends the `Binaryk\LaravelRestify\Fields\Field` class fro
a fluent API for a variety of mutators, interceptors and validators.

To add a field to a repository, we can simply add it to the repository's fields method. Typically, fields may be created
using their static `new` or `make` method. These methods accept the underlying database column as argument:
using their static `new` or `make` method.

The first argument is always the attribute name, and usually matches the database `column`.

```php

Expand Down Expand Up @@ -45,6 +47,39 @@ field('email')

</alert>

### Computed field

The second optional argument is a callback or invokable, and it represents the displayable value of the field either in `show` or `index` requests.

```php
field('name', fn() => 'John Doe')
```

The field above will always return the `name` value as `John Doe`. The field is still writeable, so you can update or create an entity using it.

### Readonly field

If you don't want a field to be writeable you can mark it readonly:

```php
field('title')->readonly()
```

The `readonly` accepts a request as well as you can use:

```php
field('title')->readonly(fn($request) => $request->user()->isGuest())
```

### Virtual field

A virtual field, is a field that's [computed](#computed-field) and [readonly](#readonly-field).

```php
field('name', fn() => "$this->first_name $this->last_name")->readonly()
```


## Authorization

The `Field` class provides few methods to authorize certain actions. Each authorization method accept a `Closure` that
Expand Down Expand Up @@ -240,6 +275,55 @@ Field::new('password')->showRequest(function ($value) {
return Hash::make($value);
});
```

### Fields actionable

Sometime storing attributes might require the stored model before saving it.

For example, say the Post model uses the [media library](https://spatie.be/docs/laravel-medialibrary/v9/introduction) and has the `media` relationship, that's a list of Media files:

```php
// PostRepository

public function fields(RestifyRequest $request): array
{
return [
field('title'),

field('files',
fn () => $this->model()->media()->pluck('file_name')
)
->action(new AttachPostFileRestifyAction),
];
}
```

So we have a virtual `files` field (it's not an actual database column) that uses a [computed field](#computed-field) to display the list of Post's files names. The `->action()` call, accept an instance of a class that extends `Binaryk\LaravelRestify\Actions\Action`:

```php
class AttachPostFileRestifyAction extends Action
{
public function handle(RestifyRequest $request, Post $post): void
{
$post->addMediaFromRequest('file');
}
}
```

The action gets the `$request` and the current `$post` model. Say the frontend has to create a post with a file:

```javascript
const data = new FormData;
data.append('file', blobFile);
data.append('title', 'Post title');

axios.post(`api/restify/posts`, data);
```

In a single request we're able to create the post and attach file using media library, otherwise it would involve 2 separate requests (post creation and file attaching).

Actionable fields handle [store](/repositories#store-request), put, [bulk store](/repositories#store-bulk-flow) and bulk update requests.

## Fallbacks

### Default Stored Value
Expand Down
2 changes: 2 additions & 0 deletions docs-v2/content/en/search/advanced-filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ class ReadyPostsFilter extends AdvancedFilter
};
```

### Register filter

Then add the filter to the repository `filters` method:

```php
Expand Down
13 changes: 12 additions & 1 deletion src/Actions/Action.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

/**
* Class Action
* @method JsonResponse handle(Request $request, Model|Collection $models)
* @method JsonResponse handle(Request $request, Model|Collection $models, ?int $row)
* @package Binaryk\LaravelRestify\Actions
*/
abstract class Action implements JsonSerializable
Expand Down Expand Up @@ -107,9 +107,20 @@ public function canRun(Closure $callback)
/**
* Get the payload available on the action.
*
* @deprecated Use rules instead
* @return array
*/
public function payload(): array
{
return $this->rules();
}

/**
* Validation rules to be applied before the action is called.
*
* @return array
*/
public function rules(): array
{
return [];
}
Expand Down
4 changes: 0 additions & 4 deletions src/Fields/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,6 @@ public function __construct($attribute, callable|Closure $resolveCallback = null
} else {
$this->attribute = $attribute ?? str_replace(' ', '_', Str::lower($attribute));
}

if (is_callable($resolveCallback)) {
$this->readonly();
}
}

public function indexCallback(callable|Closure $callback)
Expand Down
12 changes: 8 additions & 4 deletions src/Fields/FieldCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,10 @@ public function forStore(RestifyRequest $request, $repository): self
})->values();
}

public function withActions(RestifyRequest $request, $repository): self
public function withActions(RestifyRequest $request, $repository, $row = null): self
{
return $this
->inRequest($request)
->inRequest($request, $row)
->filter(fn (Field $field) => $field->isActionable())
->values();
}
Expand Down Expand Up @@ -154,10 +154,14 @@ public function findFieldByAttribute($attribute, $default = null)
return null;
}

public function inRequest(RestifyRequest $request): self
public function inRequest(RestifyRequest $request, $row = null): self
{
return $this
->filter(fn (Field $field) => $request->has($field->attribute) || $request->hasFile($field->attribute))
->filter(
fn (Field $field) =>
$request->hasAny($field->attribute, $row.'.'.$field->attribute)
|| $request->hasFile($field->attribute)
)
->values();
}
}
16 changes: 16 additions & 0 deletions src/Repositories/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,7 @@ public function storeBulk(RepositoryStoreBulkRequest $request)
$this->resource,
$fields = $this->collectFields($request)
->forStoreBulk($request, $this)
->withoutActions($request, $this)
->authorizedUpdateBulk($request),
$row
);
Expand All @@ -680,6 +681,13 @@ public function storeBulk(RepositoryStoreBulkRequest $request)

$fields->each(fn (Field $field) => $field->invokeAfter($request, $this->resource));

$this
->collectFields($request)
->forStoreBulk($request, $this)
->withActions($request, $this, $row)
->authorizedUpdateBulk($request)
->each(fn (Field $field) => $field->actionHandler->handle($request, $this->resource, $row));

return $this->resource;
});
});
Expand Down Expand Up @@ -764,12 +772,20 @@ public function updateBulk(RestifyRequest $request, $repositoryId, int $row)
{
$fields = $this->collectFields($request)
->forUpdateBulk($request, $this)
->withoutActions($request, $this)
->authorizedUpdateBulk($request);

static::fillBulkFields($request, $this->resource, $fields, $row);

$this->resource->save();

$this
->collectFields($request)
->forUpdateBulk($request, $this)
->withActions($request, $this, $row)
->authorizedUpdateBulk($request)
->each(fn (Field $field) => $field->actionHandler->handle($request, $this->resource, $row));

static::updatedBulk($this->resource, $request);

return response()->json();
Expand Down
2 changes: 1 addition & 1 deletion src/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function data(mixed $data = [], int $status = 200, array $headers = [], $options
if (! function_exists('ok')) {
function ok()
{
return response('', 204);
return response('', 204)->json([], 204);
}
}

Expand Down
106 changes: 106 additions & 0 deletions tests/Actions/FieldActionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,110 @@ public function handle(RestifyRequest $request, Post $post)
->etc()
);
}

/** @test */
public function can_use_actionable_field_on_bulk_store(): void
{
$action = new class extends Action {
public bool $showOnShow = true;

public function handle(RestifyRequest $request, Post $post, int $row)
{
$description = data_get($request[$row], 'description');

$post->update([
'description' => 'Actionable ' . $description,
]);
}
};

PostRepository::partialMock()
->shouldReceive('fieldsForStoreBulk')
->andreturn([
Field::new('title'),

Field::new('description')->action($action),
]);

$this
->withoutExceptionHandling()
->postJson(PostRepository::to('bulk'), [
[
'title' => $title1 = 'First title',
'description' => 'first description',
],
[
'title' => $title2 = 'Second title',
'description' => 'second description',
],
])
->assertJson(
fn (AssertableJson $json) => $json
->where('data.0.title', $title1)
->where('data.0.description', 'Actionable first description')
->where('data.1.title', $title2)
->where('data.1.description', 'Actionable second description')
->etc()
);
}

/** @test */
public function can_use_actionable_field_on_bulk_update(): void
{
$action = new class extends Action {
public bool $showOnShow = true;

public function handle(RestifyRequest $request, Post $post, int $row)
{
$description = data_get($request[$row], 'description');

$post->update([
'description' => 'Actionable ' . $description,
]);
}
};

PostRepository::partialMock()
->shouldReceive('fieldsForUpdateBulk')
->andreturn([
Field::new('title'),

Field::new('description')->action($action),
]);

$postId1 = $this
->withoutExceptionHandling()
->postJson(PostRepository::to(), [
'title' => 'First title',
])->json('data.id');

$postId2 = $this
->withoutExceptionHandling()
->postJson(PostRepository::to(), [
'title' => 'Second title',
])->json('data.id');

$this
->withoutExceptionHandling()
->postJson(PostRepository::to('bulk/update'), [
[
'id' => $postId1,
'description' => 'first description',
],
[
'id' => $postId2,
'description' => 'second description',
],
])->assertOk();

$this->assertSame(
'Actionable first description',
Post::find($postId1)->description
);

$this->assertSame(
'Actionable second description',
Post::find($postId2)->description
);
}
}
2 changes: 1 addition & 1 deletion tests/Actions/PerformActionControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public function test_show_action_not_need_repositories()
$this->assertEquals(1, ActivateAction::$applied[0]->id);
}

public function test_could_perform_standalone_action()
public function test_could_perform_standalone_action(): void
{
$this->postJson('users/action?action='.(new DisableProfileAction())->uriKey())
->assertSuccessful()
Expand Down
Loading