8000 [5.7] Custom Eloquent attribute casts by Propaganistas · Pull Request #24124 · laravel/framework · GitHub
[go: up one dir, main page]

Skip to content

[5.7] Custom Eloquent attribute casts #24124

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

Closed
wants to merge 1 commit into from
Closed
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
68 changes: 65 additions & 3 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Database\Eloquent\Concerns;

use Closure;
use LogicException;
use DateTimeInterface;
use Illuminate\Support\Arr;
Expand Down Expand Up @@ -70,6 +71,13 @@ trait HasAttributes
*/
public static $snakeAttributes = true;

/**
* The registered custom casts.
*
* @var array
*/
protected static $customCasts = [];

/**
* The cache of the mutated attributes for each class.
*
Expand Down Expand Up @@ -471,7 +479,7 @@ protected function castAttribute($key, $value)
return $value;
}

switch ($this->getCastType($key)) {
switch ($cast = $this->getCastType($key)) {
case 'int':
case 'integer':
return (int) $value;
Expand All @@ -498,9 +506,13 @@ protected function castAttribute($key, $value)
return $this->asDateTime($value);
case 'timestamp':
return $this->asTimestamp($value);
default:
return $value;
}

if ($this->isCustomCast($cast, 'as')) {
return $this->customCastValue($cast, $value, 'as');
}

return $value;
}

/**
Expand Down Expand Up @@ -566,6 +578,10 @@ public function setAttribute($key, $value)
return $this->fillJsonAttribute($key, $value);
}

if ($this->isCustomCast($cast = $this->getCastType($key), 'from')) {
$value = $this->customCastValue($cast, $value, 'from');
}

$this->attributes[$key] = $value;

return $this;
Expand Down Expand Up @@ -774,6 +790,21 @@ protected function asTimestamp($value)
return $this->asDateTime($value)->getTimestamp();
}

/**
* Custom cast an attribute to a chosen PHP value.
*
* @param string $cast
* @param mixed $value
* @param string $direction
* @return mixed
*/
protected function customCastValue($cast, $value, $direction)
{
$callback = static::$customCasts[$cast][$direction];

return $callback->call($this, $value);
}

/**
* Prepare a date for array / JSON serialization.
*
Expand Down Expand Up @@ -852,6 +883,37 @@ public function getCasts()
return $this->casts;
}

/**
* Register a custom cast Closure.
*
* @param string $cast
* @param \Closure $as
* @param \Closure|null $from
* @return void
*/
public static function extendCasts($cast, Closure $as = null, Closure $from = null)
{
if (! is_null($as)) {
static::$customCasts[$cast]['as'] = $as;
}

if (! is_null($from)) {
static::$customCasts[$cast]['from'] = $from;
}
}

/**
* Determine whether a cast name is a custom cast for the given direction.
*
* @param string $cast
* @param string $direction
* @return bool
*/
protected function isCustomCast($cast, $direction)
{
return Arr::has(static::$customCasts, $cast.'.'.$direction);
}

/**
* Determine whether a value is Date / DateTime castable for inbound manipulation.
*
Expand Down
18 changes: 18 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1607,6 +1607,23 @@ public function testModelAttributeCastingFailsOnUnencodableData()
$model->getAttributes();
}

public function testModelAttributesCanUseCustomCasts()
{
EloquentModelCastingStub::extendCasts('foo', function ($value) {
return $value[0];
}, function ($value) {
return [$value, 'foo'];
});

$model = new EloquentModelCastingStub;
$model->fooAttribute = 'some_value';

$this->assertEquals('some_value', $model->fooAttribute);

$attributes = $model->getAttributes();
$this->assertEquals(['some_value', 'foo'], $attributes['fooAttribute']);
}

public function testUpdatingNonExistentModelFails()
{
$model = new EloquentModelStub;
Expand Down Expand Up @@ -2048,6 +2065,7 @@ class EloquentModelCastingStub extends Model
'dateAttribute' => 'date',
'datetimeAttribute' => 'datetime',
'timestampAttribute' => 'timestamp',
'fooAttribute' => 'foo',
];

public function jsonAttributeValue()
Expand Down
0