1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\Plates\Template; |
4
|
|
|
|
5
|
|
|
use LogicException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Preassigned template data. |
9
|
|
|
*/ |
10
|
|
|
class Data |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Variables shared by all templates. |
14
|
|
|
* @var array |
15
|
|
|
*/ |
16
|
|
|
protected $sharedVariables = array(); |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Specific template variables. |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
protected $templateVariables = array(); |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Add template data. |
26
|
|
|
* @param array $data; |
27
|
|
|
* @param null|string|array $templates; |
28
|
|
|
* @return Data |
29
|
|
|
*/ |
30
|
16 |
|
public function add(array $data, $templates = null) |
31
|
|
|
{ |
32
|
16 |
|
if (is_null($templates)) { |
33
|
4 |
|
return $this->shareWithAll($data); |
34
|
|
|
} |
35
|
|
|
|
36
|
12 |
|
if (is_array($templates)) { |
37
|
4 |
|
return $this->shareWithSome($data, $templates); |
38
|
|
|
} |
39
|
|
|
|
40
|
8 |
|
if (is_string($templates)) { |
41
|
6 |
|
return $this->shareWithSome($data, array($templates)); |
42
|
|
|
} |
43
|
|
|
|
44
|
2 |
|
throw new LogicException( |
45
|
2 |
|
'The templates variable must be null, an array or a string, ' . gettype($templates) . ' given.' |
46
|
2 |
|
); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Add data shared with all templates. |
51
|
|
|
* @param array $data; |
52
|
|
|
* @return Data |
53
|
|
|
*/ |
54
|
4 |
|
public function shareWithAll($data) |
55
|
|
|
{ |
56
|
4 |
|
$this->sharedVariables = array_merge($this->sharedVariables, $data); |
57
|
|
|
|
58
|
4 |
|
return $this; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Add data shared with some templates. |
63
|
|
|
* @param array $data; |
64
|
|
|
* @param array $templates; |
65
|
|
|
* @return Data |
66
|
|
|
*/ |
67
|
10 |
|
public function shareWithSome($data, array $templates) |
68
|
|
|
{ |
69
|
10 |
|
foreach ($templates as $template) { |
70
|
10 |
|
if (isset($this->templateVariables[$template])) { |
71
|
2 |
|
$this->templateVariables[$template] = array_merge($this->templateVariables[$template], $data); |
72
|
2 |
|
} else { |
73
|
10 |
|
$this->templateVariables[$template] = $data; |
74
|
|
|
} |
75
|
10 |
|
} |
76
|
|
|
|
77
|
10 |
|
return $this; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* Get template data. |
82
|
|
|
* @param null|string $template; |
83
|
|
|
* @return array |
84
|
|
|
*/ |
85
|
76 |
|
public function get($template = null) |
86
|
|
|
{ |
87
|
76 |
|
if (isset($template, $this->templateVariables[$template])) { |
88
|
10 |
|
return array_merge($this->sharedVariables, $this->templateVariables[$template]); |
89
|
|
|
} |
90
|
|
|
|
91
|
66 |
|
return $this->sharedVariables; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|