1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\Plates\Extension\Data; |
4
|
|
|
|
5
|
|
|
use League\Plates; |
6
|
|
|
|
7
|
|
|
/** The DataExtension adds the ability to hydrate data into a template before it gets rendered. */ |
8
|
|
|
final class DataExtension implements Plates\Extension |
9
|
|
|
{ |
10
|
24 |
|
public function register(Plates\Engine $plates) { |
11
|
24 |
|
$c = $plates->getContainer(); |
12
|
24 |
|
$c->add('data.globals', []); |
13
|
24 |
|
$c->add('data.template_data', []); |
14
|
|
|
|
15
|
24 |
|
$plates->defineConfig(['merge_parent_data' => true]); |
|
|
|
|
16
|
24 |
|
$plates->pushComposers(function($c) { |
|
|
|
|
17
|
24 |
|
return array_filter([ |
18
|
24 |
|
'data.addGlobals' => $c->get('data.globals') ? addGlobalsCompose($c->get('data.globals')) : null, |
19
|
24 |
|
'data.mergeParentData' => $c->get('config')['merge_parent_data'] ? mergeParentDataCompose() : null, |
20
|
24 |
|
'data.perTemplateData' => $c->get('data.template_data') ? perTemplateDataCompose($c->get('data.template_data')) : null, |
21
|
|
|
]); |
22
|
24 |
|
}); |
23
|
|
|
|
24
|
24 |
|
$plates->addMethods([ |
25
|
24 |
|
'addGlobals' => function(Plates\Engine $e, array $data) { |
26
|
4 |
|
$c = $e->getContainer(); |
27
|
4 |
|
$c->merge('data.globals', $data); |
28
|
24 |
|
}, |
29
|
24 |
|
'addGlobal' => function(Plates\Engine $e, $name, $value) { |
30
|
|
|
$e->getContainer()->merge('data.globals', [$name => $value]); |
31
|
24 |
|
}, |
32
|
24 |
|
'addData' => function(Plates\Engine $e, $data, $name = null) { |
33
|
4 |
|
if (!$name) { |
34
|
|
|
return $e->addGlobals($data); |
|
|
|
|
35
|
|
|
} |
36
|
|
|
|
37
|
4 |
|
$template_data = $e->getContainer()->get('data.template_data'); |
38
|
4 |
|
if (!isset($template_data[$name])) { |
39
|
4 |
|
$template_data[$name] = []; |
40
|
|
|
} |
41
|
4 |
|
$template_data[$name] = array_merge($template_data[$name], $data); |
42
|
4 |
|
$e->getContainer()->add('data.template_data', $template_data); |
43
|
24 |
|
} |
44
|
|
|
]); |
45
|
24 |
|
} |
46
|
|
|
} |
47
|
|
|
|
If you implement
__call
and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.This is often the case, when
__call
is implemented by a parent class and only the child class knows which methods exist: