Skip to content

Commit

Permalink
Speed improvements, upgrade guide, changelog
Browse files Browse the repository at this point in the history
  • Loading branch information
rubenvanassche committed Jan 19, 2024
1 parent 2dc1de6 commit 03ec7cf
Show file tree
Hide file tree
Showing 32 changed files with 294 additions and 147 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ All notable changes to `laravel-data` will be documented in this file.
- Addition of collect method
- Removal of collection method
- Add support for using Laravel Model attributes as data properties
- Add support for class defined defaults
- Allow creating data objects using `from` without parameters
- Add support for a Dto and Resource object
- Added contexts to the creation and transformation process
- Allow creating a data object or collection using a factory
- Speed up the process of creating and transforming data objects

## 3.11.0 - 2023-12-21

Expand Down
233 changes: 192 additions & 41 deletions UPGRADING.md
Original file line number Diff line number Diff line change
@@ -1,48 +1,189 @@
# Upgrading

Because there are many breaking changes an upgrade is not that easy. There are many edge cases this guide does not cover. We accept PRs to improve this guide.
Because there are many breaking changes an upgrade is not that easy. There are many edge cases this guide does not
cover. We accept PRs to improve this guide.

## From v3 to v4

The following things are required when upgrading:

- Laravel 10 is now required
- Start by going through your code and replace all static `SomeData::collection($items)` method calls with `SomeData::collect($items, DataCollection::class)`
- Use `DataPaginatedCollection::class` when you're expecting a paginated collection
- Use `DataCursorPaginatedCollection::class` when you're expecting a cursor paginated collection
- For a more gentle upgrade you can also use the `WithDeprecatedCollectionMethod` trait which adds the collection method again, but this trait will be removed in v5
- If you were using `$_collectionClass`, `$_paginatedCollectionClass` or `$_cursorPaginatedCollectionClass` then take a look at the magic collect functionality on information about how to replace these
- If you were manually working with `$_includes`, ` $_excludes`, `$_only`, `$_except` or `$_wrap` these can now be found within the `$_dataContext`
- We split up some traits and interfaces, if you're manually using these on you own data implementation then take a look what has changed
- DataTrait (T) and PrepareableData (T/I) were removed
- EmptyData (T/I) and ContextableData (T/I) was added
- If you were calling the transform method on a data object, a `TransformationContextFactory` or `TransformationContext` is now the only parameter you can pass
- Take a look within the docs what has changed
- If you have implemented a custom `Transformer`, update the `transform` method signature with the new `TransformationContext` parameter
- If you have implemented a custom `Cast`
- The `$castContext` parameter is renamed to `$properties` and changed it type from `array` to `collection`
- A new `$context` parameter is added of type `CreationContext`
- If you have implemented a custom DataPipe, update the `handle` method signature with the new `TransformationContext` parameter
- If you manually created `ValidatePropertiesDataPipe` using the `allTypes` parameter, please now use the creation context for this
- The `withoutMagicalCreationFrom` method was removed from data in favour for creation by factory
- If you were using internal data structures like `DataClass` and `DataProperty` then take a look at what has been changed
- The `DataCollectableTransformer` and `DataTransformer` were replaced with their appropriate resolvers
- If you've cached the data structures, be sure to clear the cache
- In previous versions, when trying to include, exclude, only or except certain data properties that did not exist not exception was thrown. This is now the case, these exceptions can be silenced by setting `ignore_invalid_partials` to true within the config file
**Dependency changes (Likelihood Of Impact: High)**

The package now requires Laravel 10 as a minimum.

**Data::collection removal (Likelihood Of Impact: High)**

We've removed the Data::collection method in favour of the collect method. The collect method will return as type what
it gets as a type, so passing in an array will return an array of data objects. With the second parameter the output
type can be overwritten:

```php
// v3
SomeData::collection($items); // DataCollection

// v4
SomeData::collect($items); // array of SomeData

SomeData::collect($items, DataCollection::class); // DataCollection
```

If you were using the `$_collectionClass`, `$_paginatedCollectionClass` or `$_cursorPaginatedCollectionClass` properties
then take a look at the magic collect functionality on information about how to replace these.

If you want to keep the old behaviour, you can use the `WithDeprecatedCollectionMethod` trait and `DeprecatedData`
interface on your data objects which adds the collection method again, this trait will probably be removed in v5.

**Transformers (Likelihood Of Impact: High)**

If you've implemented a custom transformer, then add the new `TransformationContext` parameter to the `transform` method
signature.

```php
// v3
public function transform(DataProperty $property, mixed $value): mixed
{
// ...
}

// v4
public function transform(DataProperty $property,mixed $value,TransformationContext $context): mixed
{
// ...
}
```

**Casts (Likelihood Of Impact: High)**

If you've implemented a custom cast, then add the new $context `CreationContext` parameter to the `cast` method
signature and rename the old $context parameter to $properties.

```php
// v3
public function cast(DataProperty $property, mixed $value, array $context): mixed;
{
// ...
}

// v4
public function cast(DataProperty $property, mixed $value, array $properties, CreationContext $context): mixed
{
// ...
}
```

**The transform method (Likelihood Of Impact: Medium)**

The transform method singature was changed to use a factory pattern instead of paramaters:

```php
// v3
$data->transform(
transformValues:true,
wrapExecutionType:WrapExecutionType::Disabled,
mapPropertyNames:true,
);

// v4
$data->transform(
TransformationContextFactory::create()
->transformValues()
->wrapExecutionType(WrapExecutionType::Disabled)
->mapPropertyNames()
);
```

**Data Pipes (Likelihood Of Impact: Medium)**

If you've implemented a custom data pipe, then add the new `CreationContext` parameter to the `handle` method
signature and change the type of the $properties parameter from `Collection` to `array`. Lastly, return an `array` of
properties instead of a `Collection`.

```php
// v3
public function handle(mixed $payload, DataClass $class, Collection $properties): Collection
{
// ...
}

// v4
public function handle(mixed $payload, DataClass $class, array $properties, CreationContext $creationContext): array
{
// ...
}

```

**Invalid partials (Likelihood Of Impact: Medium)**

Previously when trying to include, exclude, only or except certain data properties that did not exist the package
continued working. From now on an exception will be thrown, these exceptions can be silenced by
setting `ignore_invalid_partials` to `true` within the config file

**Internal data structure changes (Likelihood Of Impact: Low)**

If you use internal data structures like `DataClass` and `DataProperty` then take a look at these classes, a lot as
changed and the creation process now uses factories instead of static constructors.

**Data interfaces and traits (Likelihood Of Impact: Low)**

We've split up some interfaces and traits, if you were manually using these on your own data implementation then take a
look what has changed:

- DataTrait was removed, you can easily build it yourself if required
- PrepareableData (interface and trait) were merged with BaseData
- An EmptyData (interface and trait) was added
- An ContextableData (interface and trait) was added

**ValidatePropertiesDataPipe (Likelihood Of Impact: Low)**

If you've used the `ValidatePropertiesDataPipe::allTypes` parameter to validate all types, then please use the new
context when creating a data object to enable this or update your `data.php` config file with the new default.

**Removal of `withoutMagicalCreationFrom` (Likelihood Of Impact: Low)**

If you used the `withoutMagicalCreationFrom` method on a data object, the now use the context to disable magical data
object creation:

```php
// v3
SomeData::withoutMagicalCreationFrom($payload);

// v4
SomeData::factory()->withoutMagicalCreation()->from($payload);
```

**Partials (Likelihood Of Impact: Low)**

If you we're manually setting the `$_includes`, ` $_excludes`, `$_only`, `$_except` or `$_wrap` properties on a data
object, these have now been removed. Instead, you should use the new DataContext and add the partial.

**Removal of `DataCollectableTransformer` and `DataTransformer` (Likelihood Of Impact: Low)**

If you were using the `DataCollectableTransformer` or `DataTransformer` then please use the `TransformedDataCollectableResolver` and `TransformedDataResolver` instead.

**Some advice with this new version of laravel-data**

We advise you to take a look at the following things:
- Take a look within your data objects if `DataCollection`'s, `DataPaginatedCollection`'s and `DataCursorPaginatedCollection`'s can be replaced with regular arrays, Laravel Collections and Paginator

- If you've cached data structures, be sure to clear the cache
- Take a look within your data objects if `DataCollection`'s, `DataPaginatedCollection`'s
and `DataCursorPaginatedCollection`'s can be replaced with regular arrays, Laravel Collections and Paginators making code a lot more readable
- Replace `DataCollectionOf` attributes with annotations, providing IDE completion and more info for static analyzers
- Replace some `extends Data` definitions with `extends Resource` or `extends Dto` for more minimal data objects
- When using `only` and `except` at the same time on a data object/collection, previously only the except would be executed. From now on, we first execute the except and then the only.
- When using `only` and `except` at the same time on a data object/collection, previously only the except would be
executed. From now on, we first execute the except and then the only.

## From v2 to v3

Upgrading to laravel data shouldn't take long, we've documented all possible changes just to provide the whole context. You probably won't have to do anything:
Upgrading to laravel data shouldn't take long, we've documented all possible changes just to provide the whole context.
You probably won't have to do anything:

- Laravel 9 is now required
- validation is completely rewritten
- rules are now generated based upon the payload provided, not what a payload possibly could be. This means rules can change depending on the provided payload.
- When you're injecting a `$payload`, `$relativePayload` or `$path` parameter in a custom rules method in your data object, then remove this and use the new `ValidationContext`:
- validation is completely rewritten
- rules are now generated based upon the payload provided, not what a payload possibly could be. This means rules
can change depending on the provided payload.
- When you're injecting a `$payload`, `$relativePayload` or `$path` parameter in a custom rules method in your data
object, then remove this and use the new `ValidationContext`:

```php
class SomeData extends Data {
Expand All @@ -62,14 +203,19 @@ class SomeData extends Data {
}
}
```
- The type of `$rules` in the RuleInferrer handle method changed from `RulesCollection` to `PropertyRules`
- RuleInferrers now take a $context parameter which is a `ValidationContext` in their handle method
- Validation attributes now keep track where they are being evaluated when you have nested data objects. Now field references are relative to the object and not to the root validated object
- Some resolvers are removed like: `DataClassValidationRulesResolver`, `DataPropertyValidationRulesResolver`
- The default order of rule inferrers has been changed
- The $payload parameter in the `getValidationRules` method is now required
- The $fields parameter was removed from the `getValidationRules` method, this now should be done outside of the package
- all data specific properties are now prefixed with _, to avoid conflicts with properties with your own defined properties. This is especially important when overwriting `$collectionClass`, `$paginatedCollectionClass`, `$cursorPaginatedCollectionClass`, be sure to add the extra _ within your data classes.

- The type of `$rules` in the RuleInferrer handle method changed from `RulesCollection` to `PropertyRules`
- RuleInferrers now take a $context parameter which is a `ValidationContext` in their handle method
- Validation attributes now keep track where they are being evaluated when you have nested data objects. Now field
references are relative to the object and not to the root validated object
- Some resolvers are removed like: `DataClassValidationRulesResolver`, `DataPropertyValidationRulesResolver`
- The default order of rule inferrers has been changed
- The $payload parameter in the `getValidationRules` method is now required
- The $fields parameter was removed from the `getValidationRules` method, this now should be done outside of the package
- all data specific properties are now prefixed with _, to avoid conflicts with properties with your own defined
properties. This is especially important when
overwriting `$collectionClass`, `$paginatedCollectionClass`, `$cursorPaginatedCollectionClass`, be sure to add the
extra _ within your data classes.
- Serialization logic is now updated and will only include data specific properties

## From v1 to v2
Expand All @@ -79,7 +225,9 @@ High impact changes
- Please check the most recent `data.php` config file and change yours accordingly
- The `Cast` interface now has a `$context` argument in the `cast` method
- The `RuleInferrer` interface now has a `RulesCollection` argument instead of an `array`
- By default, it is now impossible to include/exclude properties using a request parameter until manually specified. This behaviour can be overwritten by adding these methods to your data object:
- By default, it is now impossible to include/exclude properties using a request parameter until manually specified.
This behaviour can be overwritten by adding these methods to your data object:

```php
public static function allowedRequestIncludes(): ?array
{
Expand All @@ -91,8 +239,10 @@ High impact changes
return null;
}
```

- The `validate` method on a data object will not create a data object after validation, use `validateAndCreate` instead
- `DataCollection` is now being split into a `DataCollection`, `PaginatedDataCollection` and `CursorPaginatedDataCollection`
- `DataCollection` is now being split into a `DataCollection`, `PaginatedDataCollection`
and `CursorPaginatedDataCollection`

Low impact changes

Expand All @@ -105,4 +255,5 @@ Low impact changes
- The `DataTypeScriptTransformer` is updated for this new version, if you extend this then please take a look
- The `DataTransformer` and `DataCollectionTransformer` now use a `WrapExecutionType`
- The `filter` method was removed from paginated data collections
- The `through` and `filter` operations on a `DataCollection` will now happen instant instead of waiting for the transforming process
- The `through` and `filter` operations on a `DataCollection` will now happen instant instead of waiting for the
transforming process
2 changes: 1 addition & 1 deletion src/Casts/Cast.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@

interface Cast
{
public function cast(DataProperty $property, mixed $value, Collection $properties, CreationContext $context): mixed;
public function cast(DataProperty $property, mixed $value, array $properties, CreationContext $context): mixed;
}
3 changes: 1 addition & 2 deletions src/Casts/DateTimeInterfaceCast.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use DateTimeInterface;
use DateTimeZone;
use Illuminate\Support\Collection;
use Spatie\LaravelData\Exceptions\CannotCastDate;
use Spatie\LaravelData\Support\Creation\CreationContext;
use Spatie\LaravelData\Support\DataProperty;
Expand All @@ -19,7 +18,7 @@ public function __construct(
) {
}

public function cast(DataProperty $property, mixed $value, Collection $properties, CreationContext $context): DateTimeInterface|Uncastable
public function cast(DataProperty $property, mixed $value, array $properties, CreationContext $context): DateTimeInterface|Uncastable
{
$formats = collect($this->format ?? config('data.date_format'));

Expand Down
2 changes: 1 addition & 1 deletion src/Casts/EnumCast.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public function __construct(
) {
}

public function cast(DataProperty $property, mixed $value, Collection $properties, CreationContext $context): BackedEnum | Uncastable
public function cast(DataProperty $property, mixed $value, array $properties, CreationContext $context): BackedEnum | Uncastable
{
$type = $this->type ?? $property->type->type->findAcceptedTypeForBaseType(BackedEnum::class);

Expand Down
2 changes: 1 addition & 1 deletion src/Concerns/BaseData.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public static function pipeline(): DataPipeline
->through(CastPropertiesDataPipe::class);
}

public static function prepareForPipeline(Collection $properties): Collection
public static function prepareForPipeline(array $properties): array
{
return $properties;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Concerns/TransformableData.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function transform(

$resolver = match (true) {
$this instanceof BaseDataContract => DataContainer::get()->transformedDataResolver(),
$this instanceof BaseDataCollectableContract => DataContainer::get()->transformedDataCollectionResolver(),
$this instanceof BaseDataCollectableContract => DataContainer::get()->transformedDataCollectableResolver(),
default => throw new Exception('Cannot transform data object')
};

Expand Down
2 changes: 1 addition & 1 deletion src/Contracts/BaseData.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public static function factory(?CreationContext $creationContext = null): Creati

public static function normalizers(): array;

public static function prepareForPipeline(Collection $properties): Collection;
public static function prepareForPipeline(array $properties): array;

public static function pipeline(): DataPipeline;

Expand Down
4 changes: 2 additions & 2 deletions src/DataPipes/AuthorizedDataPipe.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ class AuthorizedDataPipe implements DataPipe
public function handle(
mixed $payload,
DataClass $class,
Collection $properties,
array $properties,
CreationContext $creationContext
): Collection {
): array {
if (! $payload instanceof Request) {
return $properties;
}
Expand Down
6 changes: 3 additions & 3 deletions src/DataPipes/CastPropertiesDataPipe.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ public function __construct(
public function handle(
mixed $payload,
DataClass $class,
Collection $properties,
array $properties,
CreationContext $creationContext
): Collection {
): array {
foreach ($properties as $name => $value) {
$dataProperty = $class->properties->first(fn (DataProperty $dataProperty) => $dataProperty->name === $name);

Expand All @@ -43,7 +43,7 @@ public function handle(
protected function cast(
DataProperty $property,
mixed $value,
Collection $properties,
array $properties,
CreationContext $creationContext
): mixed {
$shouldCast = $this->shouldBeCasted($property, $value);
Expand Down
Loading

0 comments on commit 03ec7cf

Please sign in to comment.