shase Integer tutup casting yapabilirsiniz.
app/Casts/TimeCast.php:
<?php
namespace App\Casts;
use Exception;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class TimeCast implements CastsAttributes
{
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return mixed
*/
public function get($model, $key, $value, $attributes)
{
return self::toDuration($value);
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return mixed
*/
public function set($model, $key, $value, $attributes)
{
return self::toSeconds($value);
}
/**
* Convert duration to seconds
*
* @param string $value
* @return int
*/
public static function toSeconds(string $value): int
{
throw_unless(preg_match('/^\d+:\d{2}:\d{2}$/', $value), Exception::class, 'Geçersiz süre');
list($hours, $minutes, $seconds) = array_map('intval', explode(':', $value));
return $hours * 3600 + $minutes * 60 + $seconds;
}
/**
* Convert seconds to duration
*
* @param int $value
* @return string
*/
public static function toDuration(int $value): string
{
return sprintf("%02d:%02d:%02d", floor($value / 3600), ($value / 60) % 60, $value % 60);
}
}
class Lesson extends Model
{
protected $casts = [
'duration' => TimeCast::class
];
/**
* @param $duration
* @return bool
* @throws \Exception
*/
public function addDuration($duration): bool
{
if (is_string($duration)) {
$amount = TimeCast::toSeconds($duration);
} elseif (is_int($duration)) {
$amount = $duration;
} else {
throw new Exception("Geçersiz süre");
}
$this->duration = TimeCast::toDuration($this->getRawOriginal('duration') + $amount);
return $this->save();
}
}
Sadece accessor/mutator kullanılarak daha basit yoldan da yapılabilir belki...