Refactored exception handling in various cast classes to use fully qualified class names for InvalidArgumentException and UnexpectedValueException.
61 lines
2.2 KiB
PHP
61 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Casts;
|
|
|
|
use Domain\Models\ValueObjects\DeliveryAddress;
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Arr;
|
|
|
|
/** @implements CastsAttributes<DeliveryAddress,DeliveryAddress> */
|
|
class DeliveryAddressCast implements CastsAttributes
|
|
{
|
|
private const string DEFAULT_STRING = 'Non renseigné';
|
|
|
|
private const string DEFAULT_POSTCODE = '00000';
|
|
|
|
/** @param array<string, mixed> $attributes */
|
|
public function get(Model $model, string $key, mixed $value, array $attributes): DeliveryAddress
|
|
{
|
|
if ($value === null) {
|
|
return new DeliveryAddress(
|
|
name: self::DEFAULT_STRING,
|
|
address: self::DEFAULT_STRING,
|
|
postcode: self::DEFAULT_POSTCODE,
|
|
city: self::DEFAULT_STRING,
|
|
);
|
|
}
|
|
|
|
if (! is_string($value)) {
|
|
throw new \InvalidArgumentException('The value must be a string.');
|
|
}
|
|
|
|
$data = Arr::wrap(json_decode($value, true));
|
|
|
|
return new DeliveryAddress(
|
|
name: Arr::string($data, 'name', self::DEFAULT_STRING),
|
|
address: Arr::string($data, 'address', self::DEFAULT_STRING),
|
|
postcode: Arr::string($data, 'postcode', self::DEFAULT_POSTCODE),
|
|
city: Arr::string($data, 'city', self::DEFAULT_STRING),
|
|
phone: ! empty(Arr::get($data, 'phone')) ?
|
|
Arr::string($data, 'phone') : null,
|
|
latitude: ! empty(Arr::get($data, 'latitude')) ?
|
|
Arr::string($data, 'latitude') : null,
|
|
longitude: ! empty(Arr::get($data, 'longitude')) ?
|
|
Arr::string($data, 'longitude') : null,
|
|
);
|
|
}
|
|
|
|
/** @param array<string, mixed> $attributes */
|
|
public function set(Model $model, string $key, mixed $value, array $attributes): string
|
|
{
|
|
if (! $value instanceof DeliveryAddress) {
|
|
throw new \InvalidArgumentException('The value must be an instance of DeliveryAddress.');
|
|
}
|
|
|
|
return json_encode($value->toArray(), JSON_UNESCAPED_UNICODE) ?:
|
|
throw new \InvalidArgumentException('Cannot encode DeliveryAddress to JSON.');
|
|
}
|
|
}
|