-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModelTrait.php
More file actions
127 lines (112 loc) · 2.69 KB
/
ModelTrait.php
File metadata and controls
127 lines (112 loc) · 2.69 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<?php
/**
* This file is part of Piko - Web micro framework
*
* @copyright 2019-2022 Sylvain PHILIP
* @license LGPL-3.0; see LICENSE.txt
* @link https://github.com/piko-framework/core
*/
declare(strict_types=1);
namespace Piko;
/**
* Base model trait.
*
* @author Sylvain PHILIP <contact@sphilip.com>
*/
trait ModelTrait
{
/**
* Errors hash container
*
* @var array<string>
*/
protected $errors = [];
/**
* Get the public properties reprenting the data model
*
* @return array<mixed>
*/
protected function getAttributes(): array
{
$class = get_called_class();
$reflection = new \ReflectionClass($class);
$properties = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
$attributes = [];
foreach ($properties as $property) {
/* @var $property \ReflectionProperty */
if ($property->class === $class) {
$attributes[$property->name] = $property->getValue($this);
}
}
return $attributes;
}
/**
* Bind the data to the model attribubes.
*
* @param array<mixed> $data An array of data (name-value pairs).
* @return void
*/
public function bind(array $data): void
{
$attributes = $this->getAttributes();
foreach ($data as $key => $value) {
if (array_key_exists($key, $attributes)) {
$this->$key = $value;
}
}
}
/**
* Get the model data as an associative array.
*
* @return array<mixed>
*/
public function toArray(): array
{
return $this->getAttributes();
}
/**
* Return the errors hash container
*
* @return array<string>
*/
public function getErrors(): array
{
return $this->errors;
}
/**
* Set an error that will be appended to the errors container
*
* @param string $errorName
* @param string $errorMsg
*
* @see ModelTrait::$errors
*/
protected function setError(string $errorName, string $errorMsg): void
{
$this->errors[$errorName] = $errorMsg;
}
/**
* Validate this model (Should be extended).
* Inherited method should fill the errors array using the setError method if the model is not valid.
*
* @see ModelTrait::setError()
* @see ModelTrait::isValid()
*
* @codeCoverageIgnore
*
* @return void
*/
protected function validate(): void
{
}
/**
* Check if the model is valid
*
* @return boolean
*/
public function isValid(): bool
{
$this->validate();
return empty($this->errors);
}
}