82 lines
2.1 KiB
PHP
82 lines
2.1 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Casts;
|
||
|
|
|
||
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
||
|
|
use Illuminate\Database\Eloquent\Model;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @implements CastsAttributes<array<int, string>, array<mixed>|string|null>
|
||
|
|
*/
|
||
|
|
class EmployeeSitesCast implements CastsAttributes
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* Cast the given value.
|
||
|
|
*
|
||
|
|
* @param array<string, mixed> $attributes
|
||
|
|
* @return string[]
|
||
|
|
*/
|
||
|
|
public function get(Model $model, string $key, mixed $value, array $attributes)
|
||
|
|
{
|
||
|
|
if ($value === null || $value === '') {
|
||
|
|
return [];
|
||
|
|
}
|
||
|
|
|
||
|
|
if (is_string($value)) {
|
||
|
|
$decoded = json_decode($value, true);
|
||
|
|
$value = is_array($decoded) ? $decoded : [];
|
||
|
|
}
|
||
|
|
|
||
|
|
if (! is_array($value)) {
|
||
|
|
return [];
|
||
|
|
}
|
||
|
|
|
||
|
|
$sites = [];
|
||
|
|
foreach ($value as $item) {
|
||
|
|
if (is_string($item)) {
|
||
|
|
$sites[] = $item;
|
||
|
|
} elseif (is_scalar($item) || $item instanceof \Stringable) {
|
||
|
|
$sites[] = (string) $item;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return $sites;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Prepare the given value for storage.
|
||
|
|
*
|
||
|
|
* @param array<string, mixed> $attributes
|
||
|
|
*/
|
||
|
|
public function set(Model $model, string $key, mixed $value, array $attributes): string
|
||
|
|
{
|
||
|
|
if ($value === null) {
|
||
|
|
return (string) json_encode([]);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (is_string($value)) {
|
||
|
|
$decoded = json_decode($value, true);
|
||
|
|
$value = is_array($decoded) ? $decoded : [$value];
|
||
|
|
}
|
||
|
|
|
||
|
|
if (! is_array($value)) {
|
||
|
|
throw new \UnexpectedValueException('Employee sites must be an array, string or null.');
|
||
|
|
}
|
||
|
|
|
||
|
|
$sites = [];
|
||
|
|
foreach ($value as $item) {
|
||
|
|
if (is_string($item)) {
|
||
|
|
$sites[] = $item;
|
||
|
|
} elseif (is_scalar($item) || $item instanceof \Stringable) {
|
||
|
|
$sites[] = (string) $item;
|
||
|
|
} else {
|
||
|
|
throw new \UnexpectedValueException('Each employee site must be convertable to string.');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return (string) json_encode($sites);
|
||
|
|
}
|
||
|
|
}
|