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

[8.x] Allow serializing custom casts when converting a model to an array #34702

Merged
merged 4 commits into from
Oct 6, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Illuminate\Contracts\Database\Eloquent;

interface SerializesCastableAttributes
{
/**
* Serialize the attribute when converting the model to an array.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return mixed
*/
public function serialize($model, string $key, $value, array $attributes);
}
35 changes: 35 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,10 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt
$attributes[$key] = $this->serializeDate($attributes[$key]);
}

if ($attributes[$key] && $this->isClassSerializable($key)) {
$attributes[$key] = $this->serializeClassCastableAttribute($key, $attributes[$key]);
}

if ($attributes[$key] instanceof Arrayable) {
$attributes[$key] = $attributes[$key]->toArray();
}
Expand Down Expand Up @@ -604,6 +608,19 @@ protected function getCastType($key)
return trim(strtolower($this->getCasts()[$key]));
}

/**
* Serialize the given attribute using the custom cast class.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function serializeClassCastableAttribute($key, $value)
{
return $this->resolveCasterClass($key)
->serialize($this, $key, $value, $this->attributes);
}

/**
* Determine if the cast type is a custom date time cast.
*
Expand Down Expand Up @@ -1090,6 +1107,24 @@ protected function isClassCastable($key)
throw new InvalidCastException($this->getModel(), $key, $castType);
}

/**
* Determine if the key is serializable using a custom class.
*
* @param string $key
* @return bool
* @throws InvalidCastException
ragulka marked this conversation as resolved.
Show resolved Hide resolved
*/
protected function isClassSerializable($key)
{
if (! $this->isClassCastable($key)) {
return false;
}

$castType = $this->parseCasterClass($this->getCasts()[$key]);

return method_exists($castType, 'serialize');
}

/**
* Resolve the custom caster class for a given key.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;
use Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes;
use Illuminate\Database\Eloquent\InvalidCastException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
Expand Down Expand Up @@ -134,6 +135,24 @@ public function testGetOriginalWithCastValueObjects()
$this->assertNull($model->address);
}

public function testSerializableCasts()
{
$model = new TestEloquentModelWithCustomCast;
$model->price = '123.456';

$expectedValue = (new Decimal('123.456'))->getValue();

$this->assertSame($expectedValue, $model->price->getValue());
$this->assertSame('123.456', $model->getAttributes()['price']);
$this->assertSame('123.456', $model->toArray()['price']);

$unserializedModel = unserialize(serialize($model));

$this->assertSame($expectedValue, $unserializedModel->price->getValue());
$this->assertSame('123.456', $unserializedModel->getAttributes()['price']);
$this->assertSame('123.456', $unserializedModel->toArray()['price']);
}

public function testOneWayCasting()
{
// CastsInboundAttributes is used for casting that is unidirectional... only use case I can think of is one-way hashing...
Expand Down Expand Up @@ -231,6 +250,7 @@ class TestEloquentModelWithCustomCast extends Model
*/
protected $casts = [
'address' => AddressCaster::class,
'price' => DecimalCaster::class,
'password' => HashCaster::class,
'other_password' => HashCaster::class.':md5',
'uppercase' => UppercaseCaster::class,
Expand Down Expand Up @@ -306,6 +326,24 @@ public function set($model, $key, $value, $attributes)
}
}

class DecimalCaster implements CastsAttributes, SerializesCastableAttributes
{
public function get($model, $key, $value, $attributes)
{
return new Decimal($value);
}

public function set($model, $key, $value, $attributes)
{
return (string) $value;
}

public function serialize($model, $key, $value, $attributes)
{
return (string) $value;
}
}

class ValueObjectCaster implements CastsAttributes
{
private $argument;
Expand Down Expand Up @@ -386,6 +424,30 @@ public function __construct($lineOne, $lineTwo)
}
}

final class Decimal
{
private $value;
private $scale;

public function __construct($value)
{
$parts = explode('.', (string) $value);

$this->scale = strlen($parts[1]);
$this->value = (int) str_replace('.', '', $value);
}

public function getValue()
{
return $this->value;
}

public function __toString()
{
return substr_replace($this->value, '.', -$this->scale, 0);
}
}

class DateObjectCaster implements CastsAttributes
{
private $argument;
Expand Down