Passed
Push — main ( 553a30...c3cb08 )
by Martin
11:04 queued 10s
created

TimezoneValidationTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Test Coverage

Coverage 90.91%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 11
c 1
b 0
f 1
dl 0
loc 28
ccs 10
cts 11
cp 0.9091
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validateTimezone() 0 10 4
A isValidTimezone() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MartinGeorgiev\Doctrine\ORM\Query\AST\Functions\Traits;
6
7
use Doctrine\ORM\Query\AST\Literal;
8
use Doctrine\ORM\Query\AST\Node;
9
use MartinGeorgiev\Doctrine\ORM\Query\AST\Functions\Exception\InvalidTimezoneException;
10
11
/**
12
 * Provides timezone validation functionality for functions that use valid PHP timezones.
13
 *
14
 * @since 3.1
15
 *
16
 * @author Martin Georgiev <[email protected]>
17
 */
18
trait TimezoneValidationTrait
19
{
20
    /**
21
     * Validates that the given node represents a valid PHP timezone.
22
     *
23
     * @throws InvalidTimezoneException If the timezone is invalid
24
     */
25 4
    protected function validateTimezone(Node $node, string $functionName): void
26
    {
27 4
        if (!$node instanceof Literal || !\is_string($node->value)) {
28
            throw InvalidTimezoneException::forNonLiteralNode($node::class, $functionName);
29
        }
30
31 4
        $timezone = \trim((string) $node->value, "'\"");
32
33 4
        if (!$this->isValidTimezone($timezone)) {
34 2
            throw InvalidTimezoneException::forInvalidTimezone($timezone, $functionName);
35
        }
36
    }
37
38 4
    private function isValidTimezone(string $timezone): bool
39
    {
40
        try {
41 4
            new \DateTimeZone($timezone);
42
43 2
            return true;
44 2
        } catch (\Exception) {
45 2
            return false;
46
        }
47
    }
48
}
49