59 lines
2.3 KiB
PHP
59 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Casts;
|
|
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
|
use Illuminate\Support\Carbon;
|
|
|
|
class IntToEpochCast implements CastsAttributes
|
|
{
|
|
/**
|
|
* Cast the given value.
|
|
*
|
|
* @param \Illuminate\Database\Eloquent\Model $model
|
|
* @param string $key
|
|
* @param mixed $value
|
|
* @param array $attributes
|
|
* @return mixed
|
|
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
|
|
*/
|
|
public function get($model, string $key, $value, array $attributes)
|
|
{
|
|
// phpcs:enable
|
|
if (\is_null($value)) {
|
|
return null;
|
|
}
|
|
$epoch = Carbon::createFromTimestamp(0)->timezone('utc');
|
|
$time = Carbon::now()->timezone('utc')->parse(\intval($value));
|
|
$minutesDiff = $time->diffInMinutes($epoch);
|
|
$hoursDiff = str_pad(floor($minutesDiff / 60), 2, '0', STR_PAD_LEFT);
|
|
$minutesDiff = str_pad($minutesDiff % 60, 2, '0', STR_PAD_LEFT);
|
|
return "{$hoursDiff}:{$minutesDiff}";
|
|
}
|
|
|
|
/**
|
|
* Prepare the given value for storage.
|
|
*
|
|
* @param \Illuminate\Database\Eloquent\Model $model
|
|
* @param string $key
|
|
* @param mixed $value
|
|
* @param array $attributes
|
|
* @return mixed
|
|
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
|
|
*/
|
|
public function set($model, string $key, $value, array $attributes)
|
|
{
|
|
// phpcs:enable
|
|
if (\is_null($value) or !\is_string($value)) {
|
|
return null;
|
|
}
|
|
$time = explode(':', $value);
|
|
$time = $time ? $time : [];
|
|
return Carbon::createFromTimestamp(0)->timezone('utc')
|
|
->setTime($time[0] ?? 0, $time[1] ?? 0)->timestamp;
|
|
}
|
|
}
|