SchemaDateAttribute::serialize()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 11
rs 10
1
<?php
2
3
namespace Ipag\Sdk\Model\Schema;
4
5
use DateTimeInterface;
6
use Ipag\Sdk\Model\Schema\Exception\SchemaAttributeParseException;
7
use Ipag\Sdk\Util\DateUtil;
8
9
/**
10
 * @codeCoverageIgnore
11
 */
12
class SchemaDateAttribute extends SchemaAttribute
13
{
14
    protected string $format;
15
16
    public function __construct(Schema $schema, string $name, string $format = DateTimeInterface::RFC3339)
17
    {
18
        parent::__construct($schema, $name);
19
        $this->format = $format;
20
    }
21
22
    //
23
24
    public function getFormat(): string
25
    {
26
        return $this->format;
27
    }
28
29
    public function format(string $format): self
30
    {
31
        $this->format = $format;
32
        return $this;
33
    }
34
35
    //
36
37
    public function parseContextual($value)
38
    {
39
        if (is_string($value) && $this->format) {
40
            $value = DateUtil::tryParseDate($value, $this->format);
41
        }
42
43
        if (!$value instanceof DateTimeInterface) {
44
            throw new SchemaAttributeParseException($this, "Provided value is not a valid date");
45
        }
46
47
        return $value;
48
    }
49
50
    public function serialize($value)
51
    {
52
        if (is_null($value)) {
53
            return $value;
54
        }
55
56
        if ($this->getFormat()) {
57
            return $value->format($this->getFormat());
58
        }
59
60
        return $value;
61
    }
62
63
    public static function from(Schema $schema, string $name): self
64
    {
65
        return parent::from($schema, $name);
0 ignored issues
show
Bug Best Practice introduced by
The expression return parent::from($schema, $name) returns the type Ipag\Sdk\Model\Schema\SchemaAttribute which includes types incompatible with the type-hinted return Ipag\Sdk\Model\Schema\SchemaDateAttribute.
Loading history...
66
    }
67
}