63 lines
1.9 KiB
PHP
63 lines
1.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Casts;
|
|
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use IPLib\Address\AddressInterface;
|
|
use IPLib\Factory;
|
|
use RuntimeException;
|
|
|
|
/**
|
|
* @template TGet
|
|
* @template TSet
|
|
*/
|
|
class Ip implements CastsAttributes
|
|
{
|
|
/**
|
|
* Transform the attribute from the underlying model values.
|
|
*
|
|
* @param array<string,mixed> $attributes
|
|
* @return AddressInterface|null
|
|
*
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
|
|
*
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
|
|
*/
|
|
public function get(Model $model, string $key, mixed $value, array $attributes)
|
|
{
|
|
// phpcs:enable
|
|
return Factory::parseAddressString($value);
|
|
}
|
|
|
|
/**
|
|
* Transform the attribute to its underlying model values.
|
|
*
|
|
* @param AddressInterface|string|null $value
|
|
* @param array<string,mixed> $attributes
|
|
* @return mixed
|
|
*
|
|
* @throws RuntimeException If value is not or instance of \IPLib\Address\AddressInterface.
|
|
*
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
|
|
*
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
|
|
*/
|
|
public function set(Model $model, string $key, mixed $value, array $attributes)
|
|
{
|
|
// phpcs:enable
|
|
if (is_null($value)) {
|
|
return null;
|
|
}
|
|
if (is_string($value)) {
|
|
$value = Factory::parseAddressString($value);
|
|
}
|
|
throw_if(! is_object($value) || ! ($value instanceof AddressInterface), RuntimeException::class, "{$key} has to be instance of " .
|
|
AddressInterface::class);
|
|
$value->getAddressType();
|
|
|
|
return $value;
|
|
}
|
|
}
|