46 lines
1.3 KiB
PHP
46 lines
1.3 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Casts;
|
||
|
|
|
||
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
||
|
|
use Illuminate\Database\Eloquent\Model;
|
||
|
|
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||
|
|
|
||
|
|
/** @implements CastsAttributes<StorageFilePath|null, StorageFilePath|string|null> */
|
||
|
|
class FilePathCast implements CastsAttributes
|
||
|
|
{
|
||
|
|
/** @param array<string, mixed> $attributes */
|
||
|
|
public function get(Model $model, string $key, mixed $value, array $attributes): ?StorageFilePath
|
||
|
|
{
|
||
|
|
if ($value === null) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (! is_string($value)) {
|
||
|
|
throw new \InvalidArgumentException('The given value is not a valid file path string.');
|
||
|
|
}
|
||
|
|
|
||
|
|
return new StorageFilePath($value);
|
||
|
|
}
|
||
|
|
|
||
|
|
/** @param array<string, mixed> $attributes */
|
||
|
|
public function set(Model $model, string $key, mixed $value, array $attributes): ?string
|
||
|
|
{
|
||
|
|
if ($value === null) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($value instanceof StorageFilePath) {
|
||
|
|
return $value->value;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (is_string($value)) {
|
||
|
|
return (new StorageFilePath($value))->value;
|
||
|
|
}
|
||
|
|
|
||
|
|
throw new \InvalidArgumentException('The given value is not a valid StorageFilePath instance or path string.');
|
||
|
|
}
|
||
|
|
}
|