1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Shoot\Shoot; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Represents the data available to a view. |
8
|
|
|
*/ |
9
|
|
|
class PresentationModel |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Constructs an instance of PresentationModel. Takes an associative array of variables to be set on the model. Only |
13
|
|
|
* sets variables which have been defined in the model. |
14
|
|
|
* |
15
|
|
|
* @param mixed[] $variables |
16
|
|
|
*/ |
17
|
33 |
|
final public function __construct(array $variables = []) |
18
|
|
|
{ |
19
|
33 |
|
$this->setVariables($variables); |
20
|
32 |
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Returns the name of the presentation model. |
24
|
|
|
* |
25
|
|
|
* @return string |
26
|
|
|
*/ |
27
|
3 |
|
final public function getName(): string |
28
|
|
|
{ |
29
|
3 |
|
return static::class; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Returns a single variable, or the given default value it it's missing. |
34
|
|
|
* |
35
|
|
|
* @param string $variable |
36
|
|
|
* @param mixed $default |
37
|
|
|
* |
38
|
|
|
* @return mixed |
39
|
|
|
*/ |
40
|
5 |
|
final public function getVariable(string $variable, $default = null) |
41
|
|
|
{ |
42
|
5 |
|
return $this->$variable ?? $default; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Returns all variables defined in the model. |
47
|
|
|
* |
48
|
|
|
* @return mixed[] |
49
|
|
|
*/ |
50
|
20 |
|
final public function getVariables(): array |
51
|
|
|
{ |
52
|
20 |
|
return get_object_vars($this); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Returns a clone of this presentation model with the new variables set. |
57
|
|
|
* |
58
|
|
|
* @param mixed[] $variables |
59
|
|
|
* |
60
|
|
|
* @return PresentationModel |
61
|
|
|
*/ |
62
|
10 |
|
final public function withVariables(array $variables): self |
63
|
|
|
{ |
64
|
10 |
|
$new = clone $this; |
65
|
10 |
|
$new->setVariables($variables); |
66
|
|
|
|
67
|
10 |
|
return $new; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @param mixed[] $variables |
72
|
|
|
* |
73
|
|
|
* @return void |
74
|
|
|
*/ |
75
|
33 |
|
private function setVariables(array $variables): void |
76
|
|
|
{ |
77
|
33 |
|
foreach ($variables as $variable => $value) { |
78
|
15 |
|
if ($this->variableExists($variable)) { |
79
|
14 |
|
$this->$variable = $value; |
80
|
|
|
} |
81
|
|
|
} |
82
|
32 |
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* @param string $variable |
86
|
|
|
* |
87
|
|
|
* @return bool |
88
|
|
|
*/ |
89
|
14 |
|
private function variableExists(string $variable): bool |
90
|
|
|
{ |
91
|
14 |
|
if (static::class === self::class) { |
|
|
|
|
92
|
2 |
|
return true; |
93
|
|
|
} |
94
|
|
|
|
95
|
12 |
|
return property_exists($this, $variable); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|