Completed
Push — v2 ( 58ecad...2e5c25 )
by Guillaume
06:46
created

GetSetDate   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 0
dl 0
loc 55
c 0
b 0
f 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B getDateField() 0 20 7
B setDateField() 0 19 7
1
<?php
2
3
namespace ETNA\Doctrine\Extensions;
4
5
/**
6
 * Ce trait permet de mettre a disposition un getter et setter générique pour des dates
7
 */
8
trait GetSetDate
9
{
10
    /**
11
     * Recupère un champs date
12
     *
13
     * @param  string      $field_name nom du champs
14
     * @param  string|null $format     format du datetime
15
     *
16
     * @return \Datetime
17
     */
18
    protected function getDateField($field_name, $format = null)
19
    {
20
        if (!property_exists($this, $field_name)) {
21
            throw new \InvalidArgumentException(
22
                "No property {$field_name} found",
23
                400
24
            );
25
        }
26
27
        switch (true) {
28
            case is_string($this->{$field_name}):
29
            case is_object($this->{$field_name}) && get_class($this->{$field_name}) !== 'DateTime':
30
                throw new \Exception("{$field_name} is not a datetime", 400);
31
            case $this->{$field_name} === null:
32
            case $format === null:
33
                return $this->{$field_name};
34
            default:
35
                return $this->{$field_name}->format($format);
36
        }
37
    }
38
39
    /**
40
     * @param string $field_name
41
     * @param mixed  $date
42
     */
43
    protected function setDateField($field_name, $date)
44
    {
45
        if (!property_exists($this, $field_name)) {
46
            throw new \InvalidArgumentException(
47
                "No property {$field_name} found",
48
                400
49
            );
50
        }
51
52
        switch (true) {
53
            case is_object($date) && get_class($date) !== 'DateTime':
54
            case is_string($date) && !preg_match("#^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$#", trim($date)):
55
                throw new \Exception("bad deleted_at provided", 400);
56
            default:
57
                $this->deleted_at = $date instanceof \DateTime ? $date : new \DateTime($date);
0 ignored issues
show
Bug introduced by
The property deleted_at does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
58
        }
59
60
        return $this;
61
    }
62
}
63