Completed
Push — components-poc ( 6ce8f4...e1010e )
by
unknown
13:39
created

Data::shareWithAll()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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
    public function add(array $data, $templates = null)
31
    {
32
        if (is_null($templates)) {
33
            return $this->shareWithAll($data);
34
        }
35
36
        if (is_array($templates)) {
37
            return $this->shareWithSome($data, $templates);
38
        }
39
40
        if (is_string($templates)) {
41
            return $this->shareWithSome($data, array($templates));
42
        }
43
44
        throw new LogicException(
45
            'The templates variable must be null, an array or a string, ' . gettype($templates) . ' given.'
46
        );
47
    }
48
49
    /**
50
     * Add data shared with all templates.
51
     * @param  array $data;
52
     * @return Data
53
     */
54
    public function shareWithAll($data)
55
    {
56
        $this->sharedVariables = array_merge($this->sharedVariables, $data);
57
58
        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
    public function shareWithSome($data, array $templates)
68
    {
69
        foreach ($templates as $template) {
70
            if (isset($this->templateVariables[$template])) {
71
                $this->templateVariables[$template] = array_merge($this->templateVariables[$template], $data);
72
            } else {
73
                $this->templateVariables[$template] = $data;
74
            }
75
        }
76
77
        return $this;
78
    }
79
80
    /**
81
     * Get template data.
82
     * @param  null|string $template;
83
     * @return array
84
     */
85
    public function get($template = null)
86
    {
87
        if (isset($template, $this->templateVariables[$template])) {
88
            return array_merge($this->sharedVariables, $this->templateVariables[$template]);
89
        }
90
91
        return $this->sharedVariables;
92
    }
93
}
94