, array|string|null> */ class EmployeeSitesCast implements CastsAttributes { /** * Cast the given value. * * @param array $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 $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); } }