|
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); |
|
|
|
|
|
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
return $this; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: