ldc-flucollector/app/Casts/NutrionalValuesCast.php
2023-09-26 17:58:43 +02:00

61 lines
2.2 KiB
PHP

<?php
namespace App\Casts;
use App\Lib\XmlInco\NutritionalValues;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
class NutrionalValuesCast implements CastsAttributes
{
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array<string,mixed> $attributes
* @return mixed
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
*/
public function get(Model $model, string $key, mixed $value, array $attributes): mixed
{
// phpcs:enable
if (\is_null($value)) {
return $value;
}
if (!\is_string($value)) {
$value = \strval($value);
}
$value = \json_decode($value, true);
/** @var array<string,float|integer|null|string> $value */
return new NutritionalValues($value);
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array<string,mixed> $attributes
* @return mixed
* @throws \RuntimeException If $value is not an intance of PortionAmount.
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
*/
public function set(Model $model, string $key, mixed $value, array $attributes): mixed
{
// phpcs:enable
if (\is_null($value)) {
return $value;
}
if (\is_object($value) and $value instanceof NutritionalValues) {
return $value->toJson();
}
throw new \RuntimeException("Cannot cast {$key}, need instance of " . NutritionalValues::class);
}
}