### Install Honeystone DTO Tools Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Installs the honeystone/laravel-dto-tools package using Composer. This is the primary step to integrate the DTO tools into your Laravel project. ```shell composer require honeystone/laravel-dto-tools ``` -------------------------------- ### Basic ModelTransformer Setup Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Defines a basic ArticleTransformer extending the abstract ModelTransformer. It specifies the target DTO class (`ArticleData`) and prepares for model transformations. ```PHP relationships()->hasToMany('bar'); $data->relationships()->getManyRelated('bar'); //plus any additions, minus any removals $data->relationships()->getManyAdditions('bar'); $data->relationships()->getManyRemovals('bar'); $data->relationships()->addToManyRelation('bar', 123, []); //param 3 optional $data->relationships()->removeToManyRelation('bar', 123); $data->relationships()->replaceToMany('bar', 123, []); //param 3 optional, clears addition and removals $data->relationships()->resetToMany('bar'); //clears addition and removals $data->relationships()->getMetaData('bar'); $data->relationships()->setMetaData('bar', []); ``` -------------------------------- ### PHP Available Caster Attributes Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Lists and describes the available built-in caster attributes for DTOs, including DateTimeCaster, EnumCaster, NullCaster, and ScalarCaster, with examples of their parameters. ```PHP #[DateTimeCaster('Y-m-d')] //takes a format string, or defaults to iso-8601 #[EnumCaster(Status::class, State::class)] //takes one or more enum class strings #[NullCaster('', '-')] //takes one or more values that should be converted to null #[ScalarCaster('bool', 'null')] //takes one or more accepted types, if no types match it will cast to the last type ``` -------------------------------- ### PHP: Get Serialized Relationships Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Explains how to retrieve serialized relationship data from a DTO, either as part of the full storable array or as a separate collection of relationships. ```php Serialized relationships are included in `toStorableArray()`, or you can grab just the relationships with `getRelationships()`. ``` -------------------------------- ### Force Nullable Property to be Storable Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md This PHP example demonstrates the use of the `force()` method to explicitly mark a property with a null value as storable, overriding the default exclusion behavior in patching mode. `getForced()` can retrieve a list of these forced properties. ```php $data = echo SomeData::make(foo: 'value', bar: null); $data->force('bar'); $data->isStorable('bar'); //true ``` -------------------------------- ### Serialize Storable Data Excluding Nulls Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md This PHP example shows how `toStorableArray()` serializes a `Storable` object in patching mode. Null values for properties are automatically excluded from the resulting array, unlike the standard `toArray()` method. ```php echo SomeData::make(foo: 'value', bar: null)->toStorableArray(); //['foo' => 'value'] echo SomeData::make(foo: 'value', bar: null)->toArray(); //['foo' => 'value', 'bar => null] ``` -------------------------------- ### Publish Configuration File Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Publishes the configuration file for the honeystone/laravel-dto-tools package to your Laravel project. This allows for customization of package behavior. ```shell php artisan vendor:publish --tag=honeystone-dto-tools-config ``` -------------------------------- ### Instantiate DTO with Property Casting Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Shows how to create an instance of a DTO using the static `make()` method. This method facilitates property casting and transformation of source data, such as converting string representations to enums or formatted dates. ```php $data = ArticleData::make( title: $source['title'], description: $source['description'] === '' ? null : $source['description'], status: $source['status'] === 'published' ? Status::PUBLISHED : Status::DRAFT, modified: Carbon::make($source['modified'])->toIso8601String(), ); ``` -------------------------------- ### PHP DTO Property Transformation (Incoming) Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Demonstrates how to transform incoming data parameters for a DTO by implementing a static `transformIncoming` method, modifying all parameters before they are used. ```PHP final readonly class SomeData implements Transferable { use HasTransferableData; public function __construct( public string $foo, public string $bar, ) { } protected static function transformIncoming(array $parameters): array { return array_map(static fn (string $value): string => "🔥 $value 🔥", $parameters); } } ``` ```PHP echo SomeData::make(['foo', 'bar'])->getAttributes(); //['foo' => '🔥 foo 🔥', 'bar' => '🔥 bar 🔥'] ``` -------------------------------- ### PHP: ToOne Relationship Methods Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Demonstrates the methods available for managing to-one relationships, such as checking for existence, retrieving, setting, and unsetting a single related item. ```php $data->relationships()->hasToOne('foo'); $data->relationships()->getOneRelated('foo'); $data->relationships()->setOneRelated('foo', 123); $data->relationships()->unsetOneRelated('foo'); ``` -------------------------------- ### Passing Parameters to transform() Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Demonstrates how to pass additional parameters to the `transform()` and `transformCollection()` methods, which can then be utilized within the `map()` method. ```PHP $transformer->transform(Article::first(), foo: 'bar'); $transformer->transformCollection(Article::all(), foo: 'bar', bar: 'baz'); ``` -------------------------------- ### On-the-Fly Transformation Adjustments Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Shows how to modify the transformation process dynamically using `exclude()` and `override()` methods chained before calling `transform()` or `transformCollection()`. ```PHP $transformer ->exclude('foo', 'bar') ->override(['status' => 'preview']) ->transform(Article::first()); //transform() or transformCollection() ``` -------------------------------- ### Transforming Models with ArticleTransformer Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Demonstrates how to use the configured ArticleTransformer to transform single Models or collections of Models into DTOs. It utilizes the `transform()` and `transformCollection()` methods. ```PHP $transformer = app(ArticleTransformer::class); $transformer->transform(Article::first()); $transformer->transformCollection(Article::all()); ``` -------------------------------- ### PHP Custom Caster Attributes Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Illustrates the implementation of custom caster attributes in PHP, extending the `CastsValues` interface to define specific value casting logic. ```PHP use Attribute; use Honeystone\DtoTools\Casters\Contracts\CastsValues; #[Attribute] final readonly class MyCaster implements CastsValues { public function cast(mixed $value): mixed { //... } } ``` -------------------------------- ### PHP DTO with Property Casting Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Demonstrates using PHP attributes to cast and mutate DTO property values before instantiation. Includes casting to null, enums, and ISO-8601 date formats. ```PHP use App\Domains\Articles\Data\Enums\Status; use Honeystone\DtoTools\Casters\DateTimeCaster; use Honeystone\DtoTools\Casters\EnumCaster; use Honeystone\DtoTools\Casters\NullCaster; final readonly class ArticleData implements Transferable { use HasTransferableData; public function __construct( public string $title, #[NullCaster('')] public ?string $description, #[EnumCaster(Status::class)] public Status $status, #[DateTimeCaster] public string $modified, ) { } } ``` -------------------------------- ### Customizing Transformation with map() Method Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Illustrates how to implement a custom `map()` method in the ModelTransformer to control the transformation logic, allowing for data manipulation and conditional mapping. ```PHP final class ArticleTransformer extends ModelTransformer { protected string $dataClass = ArticleData::class; protected function map(Model $model): array { return [ 'title' => Str::title($model->title), 'status' => in_array($model->status, ['published', 'active']) ? 'published' : 'draft', ...$model->only('description', 'modified'), ]; } } ``` -------------------------------- ### PHP: Supported Relationship Attributes Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Lists the supported relationship attributes for defining to-one and to-many relationships in DTOs, specifying the allowed data types for the relationship IDs. ```php 'int|string|null'])] #[ToMany(['bar' => 'int|string|empty'])] ``` -------------------------------- ### Transforming Relationships with ModelTransformer Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Explains how to handle model relationships during transformation using `includeRelated()` and `requireRelated()`, which leverage configured ModelTransformers for related models. ```PHP final class ArticleTransformer extends ModelTransformer { protected string $dataClass = ArticleData::class; protected function map(Model $model): array { return [ 'title' => Str::title($model->title), 'status' => in_array($model->status, ['published', 'active']) ? 'published' : 'draft', ...$model->only('description', 'modified'), 'tags' => $this->includeRelated('tags', $model->tags), 'category' => $this->requireRelated('category', $model->category), ]; } } ``` -------------------------------- ### Passing Parameters to Related Transformations Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Demonstrates passing additional parameters, including `exclude` and `override` options, to `includeRelated()` and `requireRelated()` methods, which are then forwarded to the respective related ModelTransformers. ```PHP final class ArticleTransformer extends ModelTransformer { protected string $dataClass = ArticleData::class; protected function map(Model $model): array { return [ //... 'category' => $this->requireRelated( 'category', $model->category, exclude: ['foo', 'bar'], override: ['status' => 'preview'], bar: 'baz', //passed onto map() method ), ]; } } ``` -------------------------------- ### Specifying Fields for Transformation Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Shows how to use the `$only` property within the ModelTransformer to explicitly define which model attributes should be included in the DTO transformation. ```PHP final class ArticleTransformer extends ModelTransformer { protected string $dataClass = ArticleData::class; protected array $only = [ 'title', 'description', 'status', 'modified', ]; } ``` -------------------------------- ### Define ArticlePatchData with Storable Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md This PHP code defines an `ArticlePatchData` class that implements the `Storable` contract and uses the `HasStorableData` trait. It's designed to handle partial updates for article data, including title, description, status, and modification timestamp. ```php getAttributes(); //['someProperty' => 'value'] echo SomeData::make(some_property: 'value')->toArray(); //['some_property' => 'value'] ``` -------------------------------- ### PHP DTO Property Transformation (Outgoing) Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Shows how to transform outgoing data for DTO serialization using a static `transformOutgoing` method, affecting how data is represented when serialized. ```PHP final readonly class SomeData implements Transferable { use HasTransferableData public function __construct( public string $foo, public string $bar, ) { } protected static function transformOutgoing(array $parameters): array { return array_map(static fn (string $value): string => "🔥 $value 🔥", $parameters); } } ``` ```PHP echo SomeData::make(['foo', 'bar'])->getAttributes(); //['foo' => 'foo', 'bar' => 'bar'] echo SomeData::make(['foo', 'bar'])->toArray(); //['foo' => '🔥 foo 🔥', 'bar' => '🔥 bar 🔥'] ``` -------------------------------- ### PHP: Add Item to ToMany Relationship with Metadata Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Shows how to add an item to a to-many relationship using the `addToManyRelation` method. It illustrates adding an item with its ID and optional metadata. ```php $data = ArticlePatchData::make(...); $data->relationships()->addToManyRelation('foo', 123, ['priority' => 5]); ``` -------------------------------- ### Define a Laravel DTO with Transferable Contract Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Demonstrates how to define a Data Transfer Object (DTO) in PHP for Laravel. The DTO must implement the `Transferable` contract and use the `HasTransferableData` trait provided by the package. ```php relationships()->addToManyRelation('foo', TagData::make(...), TagMetaData::make(...)); ``` -------------------------------- ### PHP: Define Storable Relationship with ToMany Attribute Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md Demonstrates how to define a to-many relationship for tags in a Laravel DTO using the `ToMany` attribute. This approach provides type safety and allows for adding, removing, or replacing related items. ```php 'int|empty'])] final class ArticlePatchData implements Storable { use HasStorableData; public function __construct( //... ) { } } ``` -------------------------------- ### Check if Property is Storable Source: https://github.com/honeystone/laravel-dto-tools/blob/master/README.md This PHP code illustrates how to use the `isStorable()` method to determine if a specific property of a `Storable` object is eligible for serialization, considering the patching mode and nullability. ```php $data = echo SomeData::make(foo: 'value', bar: null); $data->isStorable('foo'); //true $data->isStorable('bar'); //false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.