Skip to content
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
wants to merge 42 commits into from
Closed
Show file tree
Hide file tree
Changes from 31 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
7ac1a3c
clean slate
Jasonej Oct 31, 2021
8871029
update: implicit naming of format definitions
Jasonej Nov 3, 2021
2457fe8
update: explicit naming of format definitions
Jasonej Nov 3, 2021
eac1a13
update: alias names of format definitions
Jasonej Nov 3, 2021
cf05bad
update: detection of explicit defaults
Jasonej Nov 3, 2021
0da55cf
update: format manager to detect all formats for a given object
Jasonej Nov 3, 2021
aed3ebe
update: prevent format name collisions
Jasonej Nov 4, 2021
5456cb2
update: prevent format name collisions
Jasonej Nov 4, 2021
b987074
fix: limit format detection to methods with the Format attribute
Jasonej Nov 4, 2021
61dfc62
update: detect implicit and explicit default formats for a given object
Jasonej Nov 4, 2021
de53979
update: prevent multiple explicit default formats
Jasonej Nov 4, 2021
43724ec
update: selecting and retrieving the current format
Jasonej Nov 5, 2021
d6feec6
update: checking for format existence
Jasonej Nov 5, 2021
182d6ac
update: checking for format non-existence
Jasonej Nov 5, 2021
ec65546
update: fail when selecting a format that does not exist
Jasonej Nov 5, 2021
56a3e83
build: require phpunit 9
Jasonej Nov 5, 2021
ef25ab2
style: end of file blank lines
Jasonej Nov 5, 2021
28a0f32
update: default format inheritance is handled
Jasonej Nov 6, 2021
dd74d8e
update: resource supports formatting
Jasonej Nov 7, 2021
6d82ae7
update: ResourceCollection supports formatting
Jasonej Nov 7, 2021
919b3d4
update: AnonymousResourceCollection supports formatting
Jasonej Nov 7, 2021
eef0548
update: resource modifications
Jasonej Nov 10, 2021
64acbc1
update: except enhancement
Jasonej Nov 10, 2021
3869516
update: only enhancement
Jasonej Nov 10, 2021
c009d6a
update: test method naming
Jasonej Nov 10, 2021
98bffc8
update: support collection modifications
Jasonej Nov 10, 2021
80cb68c
update: support setting the response status for resources and collect…
Jasonej Nov 11, 2021
3f57a5f
update: support conversion of objects to resources.
Jasonej Nov 11, 2021
b5dfd4e
test: ensure that modifications can be applied to paginated collections
Jasonej Nov 11, 2021
0f938c0
fix: remove passing modifications list through to each modification
Jasonej Nov 11, 2021
95a5378
docs: document v4 functionality
Jasonej Nov 11, 2021
f830c19
docs: fix link
Jasonej Nov 11, 2021
1b6364a
fix: remove references to service provider that was removed
Jasonej Nov 12, 2021
b05e6e2
docs: testing added to readme
Jasonej Dec 8, 2021
4825deb
build: add php 8.1 to the test matrix
Jasonej Dec 9, 2021
09db0e3
docs: correct trait usage for only enhancement
Jasonej Feb 10, 2022
e1891e9
update: support laravel 9
Jasonej Feb 19, 2022
f35f9a7
update: allow testbench ^7.0
Jasonej Feb 19, 2022
b0b058b
build: cache based on composer.json not composer.lock
Jasonej Feb 19, 2022
e0c91c9
update: support nunomaduro/collision ^6.0
Jasonej Feb 19, 2022
74ff099
update: resolve AnonymousResourceCollection from the container to all…
Jasonej Feb 19, 2022
5dd33b4
fix: name arguments when resolving AnonymousResourceCollection
Jasonej Feb 19, 2022
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
319 changes: 318 additions & 1 deletion README.md
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;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be HasOnlyEnhancement?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed, thanks!

Copy link

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

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();
```
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
},
"require-dev": {
"nunomaduro/collision": "^5.10",
"orchestra/testbench": "^6.22"
"orchestra/testbench": "^6.22",
"phpunit/phpunit": "^9.0"
},
"extra": {
"laravel": {
Expand Down
Loading