Completed
Pull Request — 2.0 (#75)
by Julien
02:32
created

PgTimestamp::checkData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 19
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 19
loc 19
rs 9.4285
cc 3
eloc 12
nc 3
nop 1
1
<?php
2
/*
3
 * This file is part of PommProject's Foundation package.
4
 *
5
 * (c) 2014 - 2015 Grégoire HUBERT <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace PommProject\Foundation\Converter;
11
12
use PommProject\Foundation\Session\Session;
13
use PommProject\Foundation\Exception\ConverterException;
14
15
/**
16
 * PgTimestamp
17
 *
18
 * Date and timestamp converter
19
 *
20
 * @package   Foundation
21
 * @copyright 2014 - 2015 Grégoire HUBERT
22
 * @author    Grégoire HUBERT <[email protected]>
23
 * @license   X11 {@link http://opensource.org/licenses/mit-license.php}
24
 * @see       ConverterInterface
25
 */
26
class PgTimestamp implements ConverterInterface
27
{
28
    const TS_FORMAT = 'Y-m-d H:i:s.uP';
29
30
    /**
31
     * fromPg
32
     *
33
     * @see ConverterInterface
34
     */
35
    public function fromPg($data, $type, Session $session)
36
    {
37
        $data = trim($data);
38
39
        return $data !== '' ? new \DateTime($data) : null;
40
    }
41
42
    /**
43
     * toPg
44
     *
45
     * @see ConverterInterface
46
     */
47 View Code Duplication
    public function toPg($data, $type, Session $session)
48
    {
49
        return
50
            $data !== null
51
            ? sprintf("%s '%s'", $type, $this->checkData($data)->format(static::TS_FORMAT))
52
            : sprintf("NULL::%s", $type)
53
            ;
54
    }
55
56
    /**
57
     * toPgStandardFormat
58
     *
59
     * @see ConverterInterface
60
     */
61
    public function toPgStandardFormat($data, $type, Session $session)
62
    {
63
        return
64
            $data !== null
65
            ? $this->checkData($data)->format(static::TS_FORMAT)
66
            : null
67
            ;
68
    }
69
70
    /**
71
     * checkData
72
     *
73
     * Ensure a DateTime instance.
74
     *
75
     * @access protected
76
     * @param  mixed $data
77
     * @throws ConverterException
78
     * @return \DateTime
79
     */
80 View Code Duplication
    protected function checkData($data)
81
    {
82
        if (!$data instanceof \DateTime) {
83
            try {
84
                $data = new \DateTime($data);
85
            } catch (\Exception $e) {
86
                throw new ConverterException(
87
                    sprintf(
88
                        "Cannot convert data from invalid datetime representation '%s'.",
89
                        $data
90
                    ),
91
                    null,
92
                    $e
93
                );
94
            }
95
        }
96
97
        return $data;
98
    }
99
}
100