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

Allow disabling default Optional values in CreationContext #931

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
44 changes: 44 additions & 0 deletions docs/as-a-data-transfer-object/factories.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,50 @@ It is also possible to ignore the magical creation methods when creating a data
SongData::factory()->ignoreMagicalMethod('fromString')->from('Never gonna give you up'); // Won't work since the magical method is ignored
```

## Disabling optional values

When creating a data object that has optional properties, it is possible choose whether missing properties from the payload should be created as `Optional`. This can be helpful when you want to have a `null` value instead of an `Optional` object - for example, when creating the DTO from an Eloquent model with `null` values.

```php
use \Spatie\LaravelData\Optional;

class SongData extends Data {
public function __construct(
public string $title,
public string $artist,
public Optional|null|string $album,
) {
}
}

SongData::factory()
->withoutOptionalValues()
->from(['title' => 'Never gonna give you up', 'artist' => 'Rick Astley']); // album will `null` instead of `Optional`
```

Note that when an Optional property has no default value, and is not nullable, and the payload does not contain a value for this property, the DTO will not have the property set - so accessing it can throw `Typed property must not be accessed before initialization` error. Therefore, it's advisable to either set a default value or make the property nullable, when using `withoutOptionalValues`.

```php
class SongData extends Data {
public function __construct(
public string $title,
public string $artist,
public Optional|string $album, // careful here!
public Optional|string $publisher = 'unknown',
public Optional|string|null $label,
) {
}
}

$data = SongData::factory()
->withoutOptionalValues()
->from(['title' => 'Never gonna give you up', 'artist' => 'Rick Astley']);

$data->toArray(); // ['title' => 'Never gonna give you up', 'artist' => 'Rick Astley', 'publisher' => 'unknown', 'label' => null]

$data->album; // accessing the album will throw an error, unless the property is set before accessing it
```

## Adding additional global casts

When creating a data object, it is possible to add additional casts to the data object:
Expand Down
2 changes: 1 addition & 1 deletion src/DataPipes/DefaultValuesDataPipe.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function handle(
continue;
}

if ($property->type->isOptional) {
if ($property->type->isOptional && $creationContext->useOptionalValues) {
$properties[$name] = Optional::create();

continue;
Expand Down
1 change: 1 addition & 0 deletions src/Support/Creation/CreationContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public function __construct(
public ValidationStrategy $validationStrategy,
public readonly bool $mapPropertyNames,
public readonly bool $disableMagicalCreation,
public readonly bool $useOptionalValues,
public readonly ?array $ignoredMagicalMethods,
public readonly ?GlobalCastsCollection $casts,
) {
Expand Down
18 changes: 18 additions & 0 deletions src/Support/Creation/CreationContextFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public function __construct(
public ValidationStrategy $validationStrategy,
public bool $mapPropertyNames,
public bool $disableMagicalCreation,
public bool $useOptionalValues,
public ?array $ignoredMagicalMethods,
public ?GlobalCastsCollection $casts,
) {
Expand All @@ -47,6 +48,7 @@ public static function createFromConfig(
validationStrategy: ValidationStrategy::from($config['validation_strategy']),
mapPropertyNames: true,
disableMagicalCreation: false,
useOptionalValues: true,
ignoredMagicalMethods: null,
casts: null,
);
Expand All @@ -61,6 +63,7 @@ public static function createFromCreationContext(
validationStrategy: $creationContext->validationStrategy,
mapPropertyNames: $creationContext->mapPropertyNames,
disableMagicalCreation: $creationContext->disableMagicalCreation,
useOptionalValues: $creationContext->useOptionalValues,
ignoredMagicalMethods: $creationContext->ignoredMagicalMethods,
casts: $creationContext->casts,
);
Expand Down Expand Up @@ -122,6 +125,20 @@ public function withMagicalCreation(bool $withMagicalCreation = true): self
return $this;
}

public function withOptionalValues(bool $withOptionalValues = true): self
{
$this->useOptionalValues = $withOptionalValues;

return $this;
}

public function withoutOptionalValues(bool $withoutOptionalValues = true): self
{
$this->useOptionalValues = ! $withoutOptionalValues;

return $this;
}

public function ignoreMagicalMethod(string ...$methods): self
{
$this->ignoredMagicalMethods ??= [];
Expand Down Expand Up @@ -173,6 +190,7 @@ public function get(): CreationContext
validationStrategy: $this->validationStrategy,
mapPropertyNames: $this->mapPropertyNames,
disableMagicalCreation: $this->disableMagicalCreation,
useOptionalValues: $this->useOptionalValues,
ignoredMagicalMethods: $this->ignoredMagicalMethods,
casts: $this->casts,
);
Expand Down
24 changes: 24 additions & 0 deletions tests/CreationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1240,3 +1240,27 @@ public static function pipeline(): DataPipeline
[10, SimpleData::from('Hello World')]
);
})->todo();

it('can be created without optional values', function () {
$dataClass = new class () extends Data {
public string $name;

public string|null|Optional $description;

public int|Optional $year = 2025;

public string|Optional $slug;

};

$data = $dataClass::factory()
->withoutOptionalValues()
->from([
'name' => 'Ruben',
]);

expect($data->name)->toBe('Ruben');
expect($data->description)->toBeNull();
expect($data->year)->toBe(2025);
expect(isset($data->slug))->toBeFalse();
});
16 changes: 16 additions & 0 deletions tests/Support/Creation/CreationContextFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,22 @@
expect($context->disableMagicalCreation)->toBeFalse();
});

it('is possible to disable optional values', function () {
$context = CreationContextFactory::createFromConfig(
SimpleData::class
)->withoutOptionalValues();

expect($context->useOptionalValues)->toBeFalse();
});

it('is possible to enable optional values', function () {
$context = CreationContextFactory::createFromConfig(
SimpleData::class
)->withOptionalValues();

expect($context->useOptionalValues)->toBeTrue();
});

it('is possible to set ignored magical methods', function () {
$context = CreationContextFactory::createFromConfig(
SimpleData::class
Expand Down
Loading