TimeType   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 94.44%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 17
c 1
b 0
f 0
dl 0
loc 51
rs 10
ccs 17
cts 18
cp 0.9444

3 Methods

Rating   Name   Duplication   Size   Complexity  
A serialize() 0 7 2
A parseValue() 0 18 4
A parseLiteral() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Api\Scalar;
6
7
use Cake\Chronos\ChronosTime;
8
use GraphQL\Error\Error;
9
use GraphQL\Language\AST\Node;
10
use GraphQL\Language\AST\StringValueNode;
11
use GraphQL\Type\Definition\ScalarType;
12
use GraphQL\Utils\Utils;
13
14
final class TimeType extends ScalarType
15
{
16
    public ?string $description = 'A time of the day including only hour and minutes (local time, no timezone). Accepted formats are "14h35", "14:35" or "14h".';
17
18
    /**
19
     * Serializes an internal value to include in a response.
20
     */
21 1
    public function serialize(mixed $value): mixed
22
    {
23 1
        if ($value instanceof ChronosTime) {
24 1
            return $value->format('H:i');
25
        }
26
27
        return $value;
28
    }
29
30
    /**
31
     * Parses an externally provided value (query variable) to use as an input.
32
     */
33 18
    public function parseValue(mixed $value): ?ChronosTime
34
    {
35 18
        if (!is_string($value)) {
36 1
            throw new Error('Cannot represent value as ChronosTime: ' . Utils::printSafe($value));
37
        }
38
39 17
        if ($value === '') {
40 2
            return null;
41
        }
42
43 15
        if (!preg_match('~^(?<hour>\d{1,2})(([h:]$)|([h:](?<minute>\d{1,2}))?$)~', trim($value), $m)) {
44 1
            throw new Error('Invalid format for ChronosTime. Expected "14h35", "14:35" or "14h", but got: ' . Utils::printSafe($value));
45
        }
46
47 14
        $value = $m['hour'] . ':' . ($m['minute'] ?? '00');
48 14
        $time = new ChronosTime($value);
49
50 14
        return $time;
51
    }
52
53
    /**
54
     * Parses an externally provided literal value to use as an input (e.g. in Query AST).
55
     */
56 9
    public function parseLiteral(Node $valueNode, ?array $variables = null): ?ChronosTime
57
    {
58
        // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL
59
        // error location in query:
60 9
        if (!($valueNode instanceof StringValueNode)) {
61 1
            throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, $valueNode);
62
        }
63
64 8
        return $this->parseValue($valueNode->value);
65
    }
66
}
67