Debian Codegraph @

vendor/ipl/orm/src/Contract/PropertyBehavior.php

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