Skip to content

Commit

Permalink
Add meta value caster
Browse files Browse the repository at this point in the history
  • Loading branch information
iamgergo committed Mar 9, 2023
1 parent 5bb1c93 commit f8fb1a7
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
34 changes: 34 additions & 0 deletions src/Casts/MetaValue.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Cone\Root\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Stringable;

class MetaValue implements CastsAttributes
{
/**
* Cast the given value.
*
* @param array<string, mixed> $attributes
*/
public function get(Model $model, string $key, mixed $value, array $attributes): mixed
{
return json_decode($value, true) ?? $value;
}

/**
* Prepare the given value for storage.
*
* @param array<string, mixed> $attributes
*/
public function set(Model $model, string $key, mixed $value, array $attributes): mixed
{
if ($value instanceof Stringable) {
return $value->__toString();
}

return json_encode($value) ?: (string) $value;
}
}
3 changes: 2 additions & 1 deletion src/Models/Meta.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Cone\Root\Models;

use Cone\Root\Casts\MetaValue;
use Cone\Root\Database\Factories\MetaFactory;
use Cone\Root\Interfaces\Models\Meta as Contract;
use Cone\Root\Traits\InteractsWithProxy;
Expand Down Expand Up @@ -31,7 +32,7 @@ class Meta extends Model implements Contract
* @var array<string, string>
*/
protected $casts = [
'value' => 'json',
'value' => MetaValue::class,
];

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Root.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ abstract class Root
*
* @var string
*/
public const VERSION = '1.1.0';
public const VERSION = '1.1.3';

/**
* The registered callbacks.
Expand Down

0 comments on commit f8fb1a7

Please sign in to comment.