DatetimeToStringConverter::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 11
c 1
b 0
f 1
dl 0
loc 18
rs 9.9
cc 4
nc 4
nop 1
1
<?php
2
3
namespace Jackal\Copycat\Converter\ValueConverter;
4
5
use DateTime;
6
use RuntimeException;
7
8
/**
9
 * Class DatetimeToStringConverter
10
 * @package Jackal\Copycat\Converter\ValueConverter
11
 */
12
class DatetimeToStringConverter extends AbstractConverter
13
{
14
    /**
15
     * @var string
16
     */
17
    protected $format;
18
    protected $allowNulls;
19
20
    /**
21
     * DatetimeToStringConverter constructor.
22
     * @param $fieldName
23
     * @param string $format
24
     */
25
    public function __construct($fieldName, $outputFormat = 'Y-m-d H:i:s',$allowNulls = false)
26
    {
27
        parent::__construct($fieldName);
28
        $this->format = $outputFormat;
29
        $this->allowNulls = $allowNulls;
30
    }
31
32
    /**
33
     * @param $value
34
     * @return mixed|null
35
     */
36
    public function __invoke($value)
37
    {
38
        $dateValue = &$value[$this->fieldName];
39
40
        if ($dateValue === null) {
41
            if($this->allowNulls == false){
42
                throw new RuntimeException('Input must be DateTime object.');
43
            }else{
44
                $dateValue = null;
45
            }
46
        }else {
47
            if (!($dateValue instanceof DateTime)) {
48
                throw new RuntimeException('Input must be DateTime object.');
49
            }
50
51
            $dateValue = $dateValue->format($this->format);
52
        }
53
        return $value;
54
    }
55
}
56