|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Tpetry\QueryExpressions\Function\Time; |
| 6 | + |
| 7 | +use Illuminate\Contracts\Database\Query\Expression; |
| 8 | +use Illuminate\Database\Grammar; |
| 9 | +use InvalidArgumentException; |
| 10 | +use Tpetry\QueryExpressions\Concerns\IdentifiesDriver; |
| 11 | +use Tpetry\QueryExpressions\Concerns\StringizeExpression; |
| 12 | + |
| 13 | +class ExtractDatePart implements Expression |
| 14 | +{ |
| 15 | + use IdentifiesDriver; |
| 16 | + use StringizeExpression; |
| 17 | + |
| 18 | + /** |
| 19 | + * @param 'year' $part |
| 20 | + */ |
| 21 | + public function __construct( |
| 22 | + private readonly string|Expression $column, |
| 23 | + private readonly string $part, |
| 24 | + ) {} |
| 25 | + |
| 26 | + public function getValue(Grammar $grammar): string |
| 27 | + { |
| 28 | + $column = $this->stringize($grammar, $this->column); |
| 29 | + |
| 30 | + return match ($this->part) { |
| 31 | + 'year' => $this->extractYear($grammar, $column), // @phpstan-ignore-line match.alwaysTrue |
| 32 | + default => throw new InvalidArgumentException("Invalid date part: '{$this->part}'."), |
| 33 | + }; |
| 34 | + } |
| 35 | + |
| 36 | + private function extractYear(Grammar $grammar, string $column): string |
| 37 | + { |
| 38 | + return match ($this->identify($grammar)) { |
| 39 | + 'mariadb', 'mysql', 'sqlsrv' => "(year({$column}))", |
| 40 | + 'pgsql' => "extract(year from {$column})::int", |
| 41 | + 'sqlite' => "cast(strftime('%Y', {$column}) as integer)", |
| 42 | + }; |
| 43 | + } |
| 44 | +} |
0 commit comments