|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace MartinGeorgiev\Doctrine\ORM\Query\AST\Functions; |
|
6
|
|
|
|
|
7
|
|
|
use Doctrine\ORM\Query\AST\Literal; |
|
8
|
|
|
use Doctrine\ORM\Query\AST\Node; |
|
9
|
|
|
use MartinGeorgiev\Doctrine\ORM\Query\AST\Functions\Exception\InvalidTruncFieldException; |
|
10
|
|
|
use MartinGeorgiev\Doctrine\ORM\Query\AST\Functions\Traits\TimezoneValidationTrait; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Implementation of PostgreSQL DATE_TRUNC(). |
|
14
|
|
|
* |
|
15
|
|
|
* @see https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC |
|
16
|
|
|
* @since 3.7 |
|
17
|
|
|
* |
|
18
|
|
|
* @author Jan Klan <[email protected]> |
|
19
|
|
|
* |
|
20
|
|
|
* @example Using it in DQL: "SELECT DATE_TRUNC('day', e.timestampWithTz, 'Australia/Adelaide') FROM Entity e" |
|
21
|
|
|
*/ |
|
22
|
|
|
class DateTrunc extends BaseVariadicFunction |
|
23
|
|
|
{ |
|
24
|
|
|
use TimezoneValidationTrait; |
|
|
|
|
|
|
25
|
|
|
|
|
26
|
7 |
|
protected function getNodeMappingPattern(): array |
|
27
|
|
|
{ |
|
28
|
7 |
|
return ['StringPrimary']; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
7 |
|
protected function getFunctionName(): string |
|
32
|
|
|
{ |
|
33
|
7 |
|
return 'date_trunc'; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
7 |
|
protected function getMinArgumentCount(): int |
|
37
|
|
|
{ |
|
38
|
7 |
|
return 2; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
7 |
|
protected function getMaxArgumentCount(): int |
|
42
|
|
|
{ |
|
43
|
7 |
|
return 3; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
6 |
|
protected function validateArguments(Node ...$arguments): void |
|
47
|
|
|
{ |
|
48
|
6 |
|
parent::validateArguments(...$arguments); |
|
49
|
|
|
|
|
50
|
5 |
|
$this->validateTruncField($arguments[0]); |
|
51
|
|
|
|
|
52
|
|
|
// Validate that the third parameter is a valid timezone if provided |
|
53
|
5 |
|
if (\count($arguments) === 3) { |
|
54
|
5 |
|
$this->validateTimezone($arguments[2], $this->getFunctionName()); |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Validates that the given node represents a valid trunc field value. |
|
60
|
|
|
* |
|
61
|
|
|
* @throws InvalidTruncFieldException If the field value is invalid |
|
62
|
|
|
*/ |
|
63
|
5 |
|
protected function validateTruncField(Node $node): void |
|
64
|
|
|
{ |
|
65
|
5 |
|
if (!$node instanceof Literal || !\is_string($node->value)) { |
|
66
|
|
|
throw InvalidTruncFieldException::forNonLiteralNode($node::class, $this->getFunctionName()); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|