1: <?php
2: /**
3: * This file is part of the Autarky package.
4: *
5: * (c) Andreas Lutro <anlutro@gmail.com>
6: *
7: * For the full copyright and license information, please view the LICENSE
8: * file that was distributed with this source code.
9: */
10:
11: namespace Autarky\TwigTemplating;
12:
13: /**
14: * Class representation of template context - the variables that are available
15: * inside a template.
16: */
17: class TemplateContext
18: {
19: /**
20: * @var array
21: */
22: protected $data = [];
23:
24: /**
25: * @param array $context
26: */
27: public function __construct(array $context = null)
28: {
29: if ($context) {
30: $this->data = $context;
31: }
32: }
33:
34: /**
35: * Add data to the context, replacing existing data.
36: *
37: * @param array $data
38: *
39: * @return void
40: */
41: public function replace(array $data)
42: {
43: $this->data = array_replace($this->data, $data);
44: }
45:
46: /**
47: * Add data to the context without replacing existing data.
48: *
49: * @param array $data
50: *
51: * @return void
52: */
53: public function add(array $data)
54: {
55: $this->data += $data;
56: }
57:
58: public function &__get($key)
59: {
60: if (!array_key_exists($key, $this->data)) {
61: throw new \OutOfBoundsException("Undefined index for context: $key");
62: }
63:
64: return $this->data[$key];
65: }
66:
67: public function __isset($key)
68: {
69: return array_key_exists($key, $this->data);
70: }
71:
72: public function __set($key, $value)
73: {
74: $this->data[$key] = $value;
75: }
76:
77: public function __unset($key)
78: {
79: unset($this->data[$key]);
80: }
81:
82: public function &offsetGet($key)
83: {
84: if (!array_key_exists($key, $this->data)) {
85: throw new \OutOfBoundsException("Undefined index for context: $key");
86: }
87:
88: return $this->data[$key];
89: }
90:
91: public function offsetExists($key)
92: {
93: return array_key_exists($key, $this->data);
94: }
95:
96: public function offsetSet($key, $value)
97: {
98: $this->data[$key] = $value;
99: }
100:
101: public function offsetUnset($key)
102: {
103: unset($this->data[$key]);
104: }
105:
106: public function toArray()
107: {
108: return $this->data;
109: }
110: }
111: