Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
],
"require": {
"php": "^8.4",
"illuminate/contracts": "^12.0",
"illuminate/contracts": "^12.1",
"spatie/laravel-package-tools": "^1.16"
},
"require-dev": {
Expand Down
28 changes: 27 additions & 1 deletion config/stateful-resources.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
<?php

use Farbcode\StatefulResources\Enums\Variant;

return [
//
/*
|--------------------------------------------------------------------------
| States
|--------------------------------------------------------------------------
|
| Below you may register the resource states that you want to use inside
| your stateful resources. These can be instances of a ResourceState
| or simple strings.
|
*/
'states' => [
...Variant::cases(),
//
],

/*
|--------------------------------------------------------------------------
| Default State
|--------------------------------------------------------------------------
|
| This state will be used when no state is explicitly set on the resource.
| If not set, the first state in the states array will be used.
|
*/
'default_state' => Variant::Full,
];
7 changes: 7 additions & 0 deletions docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,15 @@ export default defineConfig({
text: 'Basics',
items: [
{ text: 'Installation', link: '/installation' },
{ text: 'Basic Usage', link: '/basic-usage' },
]
},
{
text: 'Advanced Usage',
items: [
{ text: 'Extending States', link: '/extending-states' }
]
}
],

socialLinks: [
Expand Down
162 changes: 162 additions & 0 deletions docs/pages/basic-usage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# Basic Usage

Laravel Stateful Resources allows you to create dynamic API responses by changing the structure of your JSON resources based on different states. This is especially useful when you need to return different levels of detail for the same model depending on the context.

## Generating a Stateful Resource

The package provides an Artisan command to quickly generate a new stateful resource:

```bash
php artisan make:stateful-resource UserResource
```

This command creates a new resource class in `app/Http/Resources/` that extends `StatefulJsonResource`:

```php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Farbcode\StatefulResources\StatefulJsonResource;

class UserResource extends StatefulJsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return parent::toArray($request);
}
}
```

## Built-in States

The package comes with three built-in states defined in the `Variant` enum:

- **`Full`** - For all available attributes
- **`Table`** - For attributes suitable for table/listing views
- **`Minimal`** - For only essential attributes

See the [Extending States](extending-states.md) documentation for how to configure this and add custom states.

## Using States in Resources

Inside your stateful resource, you can use conditional methods to control which attributes are included based on the current state:

```php
<?php

namespace App\Http\Resources;

use Farbcode\StatefulResources\Enums\Variant;
use Farbcode\StatefulResources\StatefulJsonResource;
use Illuminate\Http\Request;

class UserResource extends StatefulJsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->whenState(Variant::Full, $this->email),
'profile' => $this->whenStateIn([Variant::Full], [
'bio' => $this->bio,
'avatar' => $this->avatar,
'created_at' => $this->created_at,
]),
'role' => $this->whenStateIn([Variant::Full, Variant::Table], $this->role),
'last_login' => $this->unlessState(Variant::Minimal, $this->last_login_at),
];
}
}
```

You can also use the string representation of states instead of enum cases:

```php
'email' => $this->whenState('full', $this->email),
'name' => $this->unlessState('minimal', $this->full_name),
```

## Available Conditional Methods

The package provides several methods to conditionally include attributes:

### `whenState`

Include a value only when the current state matches the specified state:

```php
'email' => $this->whenState(Variant::Full, $this->email),
'admin_notes' => $this->whenState(Variant::Full, $this->admin_notes, 'N/A'),
```

### `unlessState`

Include a value unless the current state matches the specified state:

```php
'public_info' => $this->unlessState(Variant::Minimal, $this->public_information),
```

### `whenStateIn`

Include a value when the current state is one of the specified states:

```php
'detailed_info' => $this->whenStateIn([Variant::Full, Variant::Table], [
'department' => $this->department,
'position' => $this->position,
]),
```

### `unlessStateIn`

Include a value unless the current state is one of the specified states:

```php
'sensitive_data' => $this->unlessStateIn([Variant::Minimal, Variant::Table], $this->sensitive_info),
```

### Magic Conditionals

You can also use magic methods with for cleaner syntax:

```php
'email' => $this->whenStateFull($this->email),
'name' => $this->unlessStateMinimal($this->full_name),
```

## Using Stateful Resources

### Setting the State Explicitly

Use the static `state()` method to create a resource with a specific state:

```php
$user = UserResource::state(Variant::Minimal)->make($user);
```

### Using Magic Methods

You can also use magic methods for a more fluent syntax:

```php
// This is equivalent to the explicit state() call
$user = UserResource::minimal()->make($user);
```

### Default State

If no state is specified, the resource will use the default state. You can change the default state in the package's configuration file: `config/stateful-resources.php`.

```php
// Uses the default state
$user = UserResource::make($user);
```
79 changes: 79 additions & 0 deletions docs/pages/extending-states.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Extending States

You may find yourself being too limited with the three Variant states included in the package's `Variant` enum.
This package allows you to register custom states that you can then use in your resources.

## Registering Custom States

Before using a custom state, register it in the package's `stateful-resources.states` configuration:

```php
<?php

return [
'states' => [
...Variant::cases(), // The built-in states
'custom', // Your custom state as a string
...CustomResourceState::cases(), // Or as cases of a custom enum
],
];
```

## Creating a Custom State Enum

Instead of using strings, you may want to create your own state enum to define custom states. This enum should implement the `ResourceState` interface provided by the package.

```php
<?php

namespace App\Enums;

use Farbcode\StatefulResources\Contracts\ResourceState;

enum CustomResourceState: string implements ResourceState
{
case Compact = 'compact';
case Extended = 'extended';
case Debug = 'debug';
}
```

## Using Custom States

Now that you have created and registered your custom state enum, you can use it just like the built-in states inside your resources.

```php
<?php

namespace App\Http\Resources;

use Farbcode\StatefulResources\StatefulJsonResource;
use App\Enums\CustomResourceState;

class UserResource extends StatefulJsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->whenState(CustomResourceState::Extended, $this->email),
'debug_info' => $this->whenStateDebug([
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]),
'avatar' => $this->unlessState('custom', $this->avatar),
];
}
}
```

You can then apply the custom states to your resource in the same way you would with the built-in states:

```php
// Using the static method
UserResource::state(CustomResourceState::Compact)->make($user);

// Using the magic method (if the state name matches the case name)
UserResource::compact()->make($user);
```
2 changes: 1 addition & 1 deletion docs/pages/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
## Requirements

- PHP \>= 8.4
- Laravel 12.x
- Laravel \>= 12.1

## Installation

Expand Down
24 changes: 20 additions & 4 deletions src/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,35 @@

namespace Farbcode\StatefulResources;

use Farbcode\StatefulResources\Enums\ResourceState;
use Farbcode\StatefulResources\Concerns\ResolvesState;
use Farbcode\StatefulResources\Contracts\ResourceState;
use Illuminate\Support\Facades\Context;

/**
* Builder for creating resource instances with a specific state.
*
* @internal
*/
class Builder
{
use ResolvesState;

private string $resourceClass;

private ResourceState $state;
private string $state;

public function __construct(string $resourceClass, ResourceState $state)
public function __construct(string $resourceClass, string|ResourceState $state)
{
$state = $this->resolveState($state);

$registeredState = app(StateRegistry::class)->tryFrom($state);

if ($registeredState === null) {
throw new \InvalidArgumentException("State \"{$state}\" is not registered.");
}

$this->resourceClass = $resourceClass;
$this->state = $state;
$this->state = $registeredState;
}

/**
Expand Down
25 changes: 25 additions & 0 deletions src/Concerns/ResolvesState.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Farbcode\StatefulResources\Concerns;

use Farbcode\StatefulResources\Contracts\ResourceState;
use Farbcode\StatefulResources\StateRegistry;

trait ResolvesState
{
/**
* Resolve the value of a given state.
*
* @throws \InvalidArgumentException
*/
private function resolveState(ResourceState|string $state): string
{
$stateString = $state instanceof ResourceState ? (string) $state->value : $state;

if (app(StateRegistry::class)->tryFrom($stateString) === null) {
throw new \InvalidArgumentException("State \"{$stateString}\" is not registered.");
}

return $stateString;
}
}
Loading