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

59 lines
2.1 KiB
PHP

<?php
namespace App\Casts;
use App\Lib\XmlInco\PortionAmount;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
class PortionAmountCast 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_numeric($value)) {
$value = \intval($value);
}
return PortionAmount::fromDatabase($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 PortionAmount) {
return $value->toDatabaseValue();
}
throw new \RuntimeException("Cannot cast {$key}, need instance of " . PortionAmount::class);
}
}