DatetimeToStringConverter   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
wmc 5
eloc 17
c 2
b 1
f 1
dl 0
loc 42
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A __invoke() 0 18 4
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