Completed
Pull Request — master (#21)
by Eugene
05:40
created

DateTimeTransformer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace App\MessagePack;
4
5
use MessagePack\BufferUnpacker;
6
use MessagePack\Packer;
7
use MessagePack\TypeTransformer\Extension;
8
9
class DateTimeTransformer implements Extension
10
{
11
    private $type;
12
13
    public function __construct($type)
14
    {
15
        $this->type = $type;
16
    }
17
18
    public function getType()
19
    {
20
        return $this->type;
21
    }
22
23
    public function pack(Packer $packer, $value)
24
    {
25
        if (!$value instanceof \DateTimeInterface && !$value instanceof \DateTime) {
26
            return null;
27
        }
28
29
        $data = $packer->packStr($value->format(\DateTime::RFC3339));
30
31
        return $packer->packExt($this->type, $data);
32
    }
33
34
    public function unpack(BufferUnpacker $unpacker, $length)
35
    {
36
        $unpacker->skip(1);
37
        $data = $unpacker->unpackStr($length - 1);
38
39
        return new \DateTime($data);
40
    }
41
}
42