ldc-legaulois/app/Casts/HtmlColor.php
2022-02-10 16:14:58 +01:00

47 lines
1.4 KiB
PHP

<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
/**
* Custom cast Html Color
* https://laravel.com/docs/8.x/eloquent-mutators#custom-casts
*/
//phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
//phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
class HtmlColor implements CastsAttributes
{
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return string
*/
public function get($model, $key, $value, $attributes)
{
return "#" . $this->zeropad(dechex($value), 6);
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param array $value
* @param array $attributes
* @return integer
*/
public function set($model, $key, $value, $attributes)
{
return \intval(hexdec(ltrim($value, '#')));
}
private function zeropad($num, $lim)
{
return (strlen($num) >= $lim) ? $num : $this->zeropad("0" . $num, $lim);
}
}