Skip to content

Commit

Permalink
[Name Cast]: Don't attempt to store computed columns to the database (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
rawilk authored May 16, 2023
1 parent a1516fc commit 64157c9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
17 changes: 14 additions & 3 deletions src/Casts/NameCast.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ public function __construct(protected ?string $firstName = null, protected ?stri

public function get($model, string $key, $value, array $attributes): Name
{
if ($value) {
// We're probably dealing with a single column instead of a combination
// of two columns.
if (Arr::has($attributes, $key)) {
return Name::from($value);
}

Expand All @@ -28,8 +30,17 @@ public function get($model, string $key, $value, array $attributes): Name
return Name::from("{$firstName} {$lastName}");
}

public function set($model, string $key, $value, array $attributes): string
public function set($model, string $key, $value, array $attributes): array
{
return (string) $value;
// We're probably dealing with a single column instead of a combination
// of two columns.
if (! $value instanceof Name) {
return [$key => $value];
}

return [
$this->firstName => $value->first,
$this->lastName => $value->last,
];
}
}
14 changes: 13 additions & 1 deletion tests/Feature/NameCastTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
->and($model->name->first)->toBe('John')
->and($model->name->last)->toBe('Smith')
->and($model->name->full)->toBe('John Smith')
->and((string) $model->name)->toBe('John Smith');
->and((string) $model->name)->toBe('John Smith')
->and($model->getDirty())->toHaveKey('name')
->and($model->getDirty()['name'])->toBe('John Smith');
});

it('can be casted from first and last name on a model', function () {
Expand All @@ -30,3 +32,13 @@
->and($model->custom_name->first)->toBe('John')
->and($model->custom_name->last)->toBe('Smith');
});

it('will not attempt to store a computed column to the database if it is accessed before saving the model', function () {
$model = new Model(['given_name' => 'John', 'family_name' => 'Smith']);

$model->custom_name;

expect($model->getDirty())->not->toHaveKey('custom_name')
->toHaveKey('given_name')
->toHaveKey('family_name');
});

0 comments on commit 64157c9

Please sign in to comment.