Skip to content

Instantly share code, notes, and snippets.

@palypster
Last active March 14, 2020 08:50
Show Gist options
  • Save palypster/5f6705b0c5769d4008daa6e75e961d83 to your computer and use it in GitHub Desktop.
Save palypster/5f6705b0c5769d4008daa6e75e961d83 to your computer and use it in GitHub Desktop.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contract extends Model
{
public $timestamps = false;
protected $casts = [
'valid_range' => \App\Casts\DateRangeCast::class,
];
public function newEloquentBuilder($query): ExtendedQueryBuilder
{
return new ExtendedQueryBuilder($query);
}
}
<?php
namespace App;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
class DateRange
{
private ?CarbonInterface $from;
private ?CarbonInterface $to;
public function __construct($from = null, $to = null, $fromBound = "[", $toBound = "]")
{
$this->from = is_string($from) ? $this->parseFrom($from) : $from;
$this->to = is_string($to) ? $this->parseTo($to) : $to;
// when exclusive bound is set,
// let's canonicalize it to inclusive bounds
if ($fromBound === '(') {
$this->from = $this->from->addDay();
}
if ($toBound === ')') {
$this->to = $this->to->subDay();
}
}
private function parseFrom(string $from) : CarbonInterface
{
return CarbonImmutable::parse($from);
}
private function parseTo(string $to) : CarbonInterface
{
return CarbonImmutable::parse($to);
}
public function from(): ?CarbonInterface
{
return $this->from;
}
public function to(): ?CarbonInterface
{
return $this->to;
}
}
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class DateRangeCast implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
preg_match('/([\[\(]{1})(.*)\,(.*)([\]\)]{1})/', $attributes['valid_range'], $matches);
return new \App\DateRange($matches[2], $matches[3], $matches[1], $matches[4]);
}
public function set($model, $key, $value, $attributes)
{
return [
'valid_range' => $this->serializeRange($value)
];
}
private function serializeRange($range)
{
return "[" .
optional(optional($range)->from())->toDateString() .
"," .
optional(optional($range)->to())->toDateString() .
"]";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment