-
Notifications
You must be signed in to change notification settings - Fork 0
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
Version 4 #25
Closed
Version 4 #25
Changes from 31 commits
Commits
Show all changes
42 commits
Select commit
Hold shift + click to select a range
7ac1a3c
clean slate
Jasonej 8871029
update: implicit naming of format definitions
Jasonej 2457fe8
update: explicit naming of format definitions
Jasonej eac1a13
update: alias names of format definitions
Jasonej cf05bad
update: detection of explicit defaults
Jasonej 0da55cf
update: format manager to detect all formats for a given object
Jasonej aed3ebe
update: prevent format name collisions
Jasonej 5456cb2
update: prevent format name collisions
Jasonej b987074
fix: limit format detection to methods with the Format attribute
Jasonej 61dfc62
update: detect implicit and explicit default formats for a given object
Jasonej de53979
update: prevent multiple explicit default formats
Jasonej 43724ec
update: selecting and retrieving the current format
Jasonej d6feec6
update: checking for format existence
Jasonej 182d6ac
update: checking for format non-existence
Jasonej ec65546
update: fail when selecting a format that does not exist
Jasonej 56a3e83
build: require phpunit 9
Jasonej ef25ab2
style: end of file blank lines
Jasonej 28a0f32
update: default format inheritance is handled
Jasonej dd74d8e
update: resource supports formatting
Jasonej 6d82ae7
update: ResourceCollection supports formatting
Jasonej 919b3d4
update: AnonymousResourceCollection supports formatting
Jasonej eef0548
update: resource modifications
Jasonej 64acbc1
update: except enhancement
Jasonej 3869516
update: only enhancement
Jasonej c009d6a
update: test method naming
Jasonej 98bffc8
update: support collection modifications
Jasonej 80cb68c
update: support setting the response status for resources and collect…
Jasonej 3f57a5f
update: support conversion of objects to resources.
Jasonej b5dfd4e
test: ensure that modifications can be applied to paginated collections
Jasonej 0f938c0
fix: remove passing modifications list through to each modification
Jasonej 95a5378
docs: document v4 functionality
Jasonej f830c19
docs: fix link
Jasonej 1b6364a
fix: remove references to service provider that was removed
Jasonej b05e6e2
docs: testing added to readme
Jasonej 4825deb
build: add php 8.1 to the test matrix
Jasonej 09db0e3
docs: correct trait usage for only enhancement
Jasonej e1891e9
update: support laravel 9
Jasonej f35f9a7
update: allow testbench ^7.0
Jasonej b0b058b
build: cache based on composer.json not composer.lock
Jasonej e0c91c9
update: support nunomaduro/collision ^6.0
Jasonej 74ff099
update: resolve AnonymousResourceCollection from the container to all…
Jasonej 5dd33b4
fix: name arguments when resolving AnonymousResourceCollection
Jasonej File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,318 @@ | ||
# Enhanced Resources | ||
# Enhanced Resources | ||
|
||
Enhancements for Laravel's API resources. | ||
|
||
## Installation | ||
|
||
``` | ||
$ composer require sourcetoad/enhanced-resources | ||
``` | ||
|
||
## Basic Usage | ||
|
||
To create an enhanced resource you simply extend `Sourcetoad\EnhancedResources\Resource` instead of `Illuminate\Http\Resources\Json\JsonResource` and provide a format method. | ||
|
||
```php | ||
<?php | ||
|
||
use Sourcetoad\EnhancedResources\Formatting\Attributes\Format; | ||
use Sourcetoad\EnhancedResources\Resource; | ||
|
||
class ExampleResource extends Resource | ||
{ | ||
#[Format] | ||
public function foo(): array | ||
{ | ||
return []; | ||
} | ||
} | ||
``` | ||
|
||
## Formatting | ||
|
||
With EnhancedResources you can have multiple formats for a single resource by adding format methods. Format methods are defined using the `#[Format]` attribute. | ||
|
||
If only a single format method is defined, as is the case in the example above in the [basic usage](#basic-usage) section, that format will be the default format that is used when resolving the resource. However, you can define as many formats as you like. | ||
|
||
```php | ||
<?php | ||
|
||
use Sourcetoad\EnhancedResources\Formatting\Attributes\Format; | ||
use Sourcetoad\EnhancedResources\Resource; | ||
|
||
class ExampleResource extends Resource | ||
{ | ||
#[Format] | ||
public function bar(): array | ||
{ | ||
return []; | ||
} | ||
|
||
#[Format] | ||
public function foo(): array | ||
{ | ||
return []; | ||
} | ||
|
||
#[Format] | ||
public function foobar(): array | ||
{ | ||
return []; | ||
} | ||
} | ||
``` | ||
|
||
In cases like the one above you'll need to specify the format to be used by providing its name to the `format()` method. By default the format uses the same name as the method, so in this example we have format names of `bar`, `foo`, and `foobar`. | ||
|
||
```php | ||
ExampleResource::make($object)->format('foo'); | ||
``` | ||
|
||
Failing to specify the format in a situation where there is no default format will result in a `NoFormatSelectedException` being thrown. | ||
|
||
### Specifying a Default | ||
|
||
If you don't want to always explicitly specify the format to be used when you have a resource with multiple formats you can specify one format as default using the `#[IsDefault]` attribute. | ||
|
||
```php | ||
<?php | ||
|
||
use Sourcetoad\EnhancedResources\Formatting\Attributes\Format; | ||
use Sourcetoad\EnhancedResources\Formatting\Attributes\IsDefault; | ||
use Sourcetoad\EnhancedResources\Resource; | ||
|
||
class ExampleResource extends Resource | ||
{ | ||
#[Format] | ||
public function bar(): array | ||
{ | ||
return []; | ||
} | ||
|
||
#[IsDefault, Format] | ||
public function foo(): array | ||
{ | ||
return []; | ||
} | ||
|
||
#[Format] | ||
public function foobar(): array | ||
{ | ||
return []; | ||
} | ||
} | ||
``` | ||
|
||
After adding the `#[IsDefault]` attribute to one of your format methods it will be used unless the format is explicitly specified via the `format()` method. | ||
|
||
Specifying more than one default method via the `#[IsDefault]` attribute will result in a `MultipleDefaultFormatsException` being thrown. | ||
|
||
The `#[IsDefault]` attribute is detected on a per-class basis up the inheritance chain, so you can define a format as `#[IsDefault]` on a parent resource and override it with another `#[IsDefault]` format on the child resource without triggering a `MultipleDefaultFormatsException`. However, if no `#[IsDefault]` format is defined on the child resource the one on the parent will still be used. | ||
|
||
### Naming Formats | ||
|
||
You can also override the name of formats and even provide multiple names for a single format. Let's look at the following example: | ||
|
||
```php | ||
<?php | ||
|
||
use Sourcetoad\EnhancedResources\Formatting\Attributes\Format; | ||
use Sourcetoad\EnhancedResources\Formatting\Attributes\IsDefault; | ||
use Sourcetoad\EnhancedResources\Resource; | ||
|
||
class ExampleResource extends Resource | ||
{ | ||
#[Format, Format('a')] | ||
public function bar(): array | ||
{ | ||
return []; | ||
} | ||
|
||
#[Format, Format('b'), Format('something-else')] | ||
public function foo(): array | ||
{ | ||
return []; | ||
} | ||
|
||
#[Format('c')] | ||
public function foobar(): array | ||
{ | ||
return []; | ||
} | ||
} | ||
``` | ||
|
||
In this example we have three formats, but six names: | ||
- The `bar` method can be used with the names `bar`, and `a`. | ||
- The `foo` method can be used with the names `foo`, `b`, and `something-else`. | ||
- The `foobar` method can be used with the name `c`. | ||
|
||
The primary name of each format is the first instance of the `#[Format]` attribute, and the rest are aliases. This means that the primary names would be: `bar`, `foo`, and `c` in the example above. In most cases this distinction should not come into play. | ||
|
||
### Collections | ||
|
||
Both anonymous collections and defined resource collections utilize the formats of the underlying resource objects, and follow all the same rules. | ||
|
||
## Modifications | ||
|
||
Modifications allow you to tweak the output of resources on the fly. They are applied similarly to how `state` is applied for Eloquent factories. The most basic form of modification is a simple array merge modification done by providing an array to the `modify` method of a resource: | ||
|
||
```php | ||
ExampleResource::make($object)->modify(['some_key' => 'some_value']); | ||
``` | ||
|
||
To accomplish more complex modifications you can also pass any callable that accepts `(array $data, Resource $resource)`. It is important when using these types of modifications to return the data as failing to do so will result in resource's data being replaced with `null`. | ||
|
||
```php | ||
ExampleResource::make($object)->modify(function (array $data) { | ||
$data['some_key'] = 'some_value'; | ||
|
||
return $data; | ||
}) | ||
``` | ||
|
||
You can also define methods on the resource class itself that can make modifications via calling the `modify` method. | ||
|
||
```php | ||
<?php | ||
|
||
use Sourcetoad\EnhancedResources\Formatting\Attributes\Format; | ||
use Sourcetoad\EnhancedResources\Formatting\Attributes\IsDefault; | ||
use Sourcetoad\EnhancedResources\Resource; | ||
|
||
class ExampleResource extends Resource | ||
{ | ||
#[Format] | ||
public function foo(): array | ||
{ | ||
return [ | ||
'value' => $this->resource['value'], | ||
]; | ||
} | ||
|
||
public function double(): static | ||
{ | ||
return $this->modify(function (array $data) { | ||
$data['value'] *= 2; | ||
|
||
return $data; | ||
}); | ||
} | ||
} | ||
|
||
ExampleResource::make(['value' => 1])->double()->toArray(); // ['value' => 2] | ||
``` | ||
|
||
### Except | ||
The except enhancement is a modification class and trait combination that allows for the easy exclusion of certain fields from a resource. | ||
|
||
```php | ||
<?php | ||
|
||
use Sourcetoad\EnhancedResources\Enhancements\Except; | ||
use Sourcetoad\EnhancedResources\Enhancements\Traits\HasExceptEnhancement; | ||
use Sourcetoad\EnhancedResources\Formatting\Attributes\Format; | ||
use Sourcetoad\EnhancedResources\Formatting\Attributes\IsDefault; | ||
use Sourcetoad\EnhancedResources\Resource; | ||
|
||
class ExampleResource extends Resource | ||
{ | ||
use HasExceptEnhancement; | ||
|
||
#[Format] | ||
public function foo(): array | ||
{ | ||
return [ | ||
'first_name' => $this->resource->firstName, | ||
'id' => $this->resource->id, | ||
'last_name' => $this->resource->lastName, | ||
]; | ||
} | ||
} | ||
|
||
ExampleResource::make(new class { | ||
public string $firstName = 'John'; | ||
public int $id = 1; | ||
public string $lastName = 'Doe'; | ||
})->except('id'); // ['first_name' => 'John', 'last_name' => 'Doe'] | ||
|
||
// Without the trait you can still use the Except enhancement. | ||
ExampleResource::make(new class { | ||
public string $firstName = 'John'; | ||
public int $id = 1; | ||
public string $lastName = 'Doe'; | ||
})->modify(new Except(['id'])); // ['first_name' => 'John', 'last_name' => 'Doe'] | ||
``` | ||
|
||
### Only | ||
The only enhancement is a modification class and trait combination that allows for the easy exclusion of certain fields from a resource. | ||
|
||
```php | ||
<?php | ||
|
||
use Sourcetoad\EnhancedResources\Enhancements\Only; | ||
use Sourcetoad\EnhancedResources\Enhancements\Traits\HasExceptEnhancement; | ||
use Sourcetoad\EnhancedResources\Formatting\Attributes\Format; | ||
use Sourcetoad\EnhancedResources\Formatting\Attributes\IsDefault; | ||
use Sourcetoad\EnhancedResources\Resource; | ||
|
||
class ExampleResource extends Resource | ||
{ | ||
use HasExceptEnhancement; | ||
|
||
#[Format] | ||
public function foo(): array | ||
{ | ||
return [ | ||
'first_name' => $this->resource->firstName, | ||
'id' => $this->resource->id, | ||
'last_name' => $this->resource->lastName, | ||
]; | ||
} | ||
} | ||
|
||
ExampleResource::make(new class { | ||
public string $firstName = 'John'; | ||
public int $id = 1; | ||
public string $lastName = 'Doe'; | ||
})->only('id'); // ['id' => 1] | ||
|
||
// Without the trait you can still use the Only enhancement. | ||
ExampleResource::make(new class { | ||
public string $firstName = 'John'; | ||
public int $id = 1; | ||
public string $lastName = 'Doe'; | ||
})->modify(new Only(['id'])); // ['id' => 1] | ||
``` | ||
|
||
## Additional Enhancements | ||
EnhancedResources also includes a couple of other helpful enhancements. | ||
|
||
### Status Codes | ||
You can now tweak the status code of the resource response with a simple call to the `setResponseStatus()` method. | ||
|
||
```php | ||
use Symfony\Component\HttpFoundation\Response; | ||
|
||
ExampleResource::make($object)->setResponseStatus(Response::HTTP_I_AM_A_TEAPOT); | ||
``` | ||
|
||
### ConvertsToResource | ||
You can provide any object with a `toResource` method with a simple trait and attribute combination: | ||
|
||
```php | ||
use Illuminate\Database\Eloquent\Model; | ||
use Sourcetoad\EnhancedResources\Resourceable\AsResource; | ||
use Sourcetoad\EnhancedResources\Resourceable\ConvertsToResource; | ||
|
||
/** | ||
* @method ExampleResource toResource() | ||
*/ | ||
#[AsResource(ExampleResource::class)] | ||
class Example extends Model | ||
{ | ||
use ConvertsToResource; | ||
} | ||
|
||
(new Example)->toResource(); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this be
HasOnlyEnhancement
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed, thanks!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure. Excited about all this new stuff! I like how the features are becoming more explicit and transparent