Completed
Push — master ( 6e1c48...7d90f1 )
by John
03:00
created

DateTimeSerializer::deserialize()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.6737
c 0
b 0
f 0
cc 6
eloc 11
nc 5
nop 2
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of the KleijnWeb\PhpApi\Descriptions\Hydrator package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace KleijnWeb\PhpApi\Descriptions\Hydrator;
10
11
use KleijnWeb\PhpApi\Descriptions\Description\Schema\ScalarSchema;
12
use KleijnWeb\PhpApi\Descriptions\Description\Schema\Schema;
13
use KleijnWeb\PhpApi\Descriptions\Hydrator\Exception\DateTimeNotParsableException;
14
15
/**
16
 * @author John Kleijn <[email protected]>
17
 */
18
class DateTimeSerializer
19
{
20
    const FORMAT_RFC3339_USEC = 'Y-m-d\TH:i:s.uP';
21
    const FORMAT_RFC3339_MSEC = \DateTime::RFC3339_EXTENDED;
22
    const FORMAT_RFC3339      = \DateTime::RFC3339;
23
    const FORMAT_ISO8601      = \DateTime::ATOM;
24
25
    /**
26
     * @var string
27
     */
28
    protected $outputFormat;
29
30
    /**
31
     * @var string
32
     */
33
    protected $inputDateTimeFormats = [
34
        self::FORMAT_RFC3339_USEC,
35
        self::FORMAT_RFC3339_MSEC,
36
        self::FORMAT_RFC3339,
37
        self::FORMAT_ISO8601,
38
    ];
39
40
    /**
41
     * DateTimeSerializer constructor.
42
     *
43
     * @param string|string[] ...$formats
44
     */
45
    public function __construct(string ...$formats)
46
    {
47
        if (isset($formats[0])) {
48
            $this->outputFormat = $formats[0];
0 ignored issues
show
Documentation Bug introduced by
It seems like $formats[0] can also be of type array<integer,string>. However, the property $outputFormat is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
49
        }
50
51
        $this->inputDateTimeFormats = $formats + $this->inputDateTimeFormats;
52
    }
53
54
    /**
55
     * @param \DateTimeInterface $value
56
     * @param Schema             $schema
57
     *
58
     * @return string
59
     */
60
    public function serialize(\DateTimeInterface $value, Schema $schema): string
61
    {
62
        if ($schema instanceof ScalarSchema && $schema->hasFormat(Schema::FORMAT_DATE)) {
63
            return $value->format('Y-m-d');
64
        }
65
66
        return $value->format($this->outputFormat ?: self::FORMAT_RFC3339_USEC);
67
    }
68
69
    /**
70
     * @param mixed  $value
71
     * @param Schema $schema
72
     *
73
     * @return \DateTime
74
     *
75
     */
76
    public function deserialize($value, Schema $schema): \DateTime
77
    {
78
        if ($schema instanceof ScalarSchema && $schema->hasFormat(Schema::FORMAT_DATE)) {
79
            if (false === $result = \DateTime::createFromFormat('Y-m-d H:i:s', "$value 00:00:00")) {
80
                throw new DateTimeNotParsableException(
81
                    sprintf("'%s' not parsable in YYYY-MM-DD format", $value)
82
                );
83
            }
84
85
            return $result;
86
        }
87
88
        foreach ($this->inputDateTimeFormats as $format) {
0 ignored issues
show
Bug introduced by
The expression $this->inputDateTimeFormats of type string is not traversable.
Loading history...
89
            if (false !== $result = \DateTime::createFromFormat($format, $value)) {
90
                return $result;
91
            }
92
        }
93
94
        throw new DateTimeNotParsableException(
95
            sprintf("Datetime '%s' not parsable as one of '%s'", $value, implode(', ', $this->inputDateTimeFormats))
96
        );
97
    }
98
}
99