1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
<?php
namespace ipl\Orm\Contract;
use ipl\Orm\Model;
use OutOfBoundsException;
abstract class PropertyBehavior implements RetrieveBehavior, PersistBehavior
{
/** @var array Property names of which the value should be processed */
protected $properties;
/**
* PropertyBehavior constructor
*
* @param array $properties Property names to process, as values
*/
public function __construct(array $properties)
{
if (is_int(key($properties))) {
$this->properties = array_flip($properties);
} else {
$this->properties = $properties;
}
}
public function retrieve(Model $model)
{
foreach ($this->properties as $key => $ctx) {
if ($model->hasProperty($key)) {
$model[$key] = $this->fromDb($model[$key], $key, $ctx);
}
}
}
public function persist(Model $model)
{
foreach ($this->properties as $key => $ctx) {
try {
$model[$key] = $this->toDb($model[$key], $key, $ctx);
} catch (OutOfBoundsException $_) {
// pass
}
}
}
/**
* Transform the given value, just fetched from the database
*
* @param mixed $value
* @param string $key
*
* @return mixed
*/
public function retrieveProperty($value, $key)
{
if (! isset($this->properties[$key])) {
return $value;
}
return $this->fromDb($value, $key, $this->properties[$key]);
}
/**
* Transform the given value, about to be persisted to the database
*
* @param mixed $value
* @param string $key
*
* @return mixed
*/
public function persistProperty($value, $key)
{
if (! isset($this->properties[$key])) {
return $value;
}
return $this->toDb($value, $key, $this->properties[$key]);
}
/**
* Transform the given value which has just been fetched from the database
*
* @param mixed $value
* @param string $key
* @param mixed $context
*
* @return mixed
*/
abstract public function fromDb($value, $key, $context);
/**
* Transform the given value which is about to be persisted to the database
*
* @param mixed $value
* @param string $key
* @param mixed $context
*
* @return mixed
*/
abstract public function toDb($value, $key, $context);
}
|