Passed
Push — master ( 7db1e7...88fb1f )
by Aimeos
02:53
created

Standard::add()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
/**
4
 * @license LGPLv3, https://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2015-2026
6
 * @package Base
7
 * @subpackage View
8
 */
9
10
11
namespace Aimeos\Base\View;
12
13
14
/**
15
 * Default view implementation.
16
 *
17
 * @method mixed config(string $name = null, string|array $default = null) Returns the config value for the given key
18
 * @method \Aimeos\Base\View\Helper\Iface csrf() Returns the CSRF helper object
19
 * @method string date(string $date) Returns the formatted date
20
 * @method \Aimeos\Base\View\Helper\Iface encoder() Returns the encoder helper object
21
 * @method string formparam(string|array $names) Returns the name for the HTML form parameter
22
 * @method \Aimeos\Base\Mail\Message\Iface mail() Returns the e-mail message object
23
 * @method string number(integer|float|decimal $number, integer $decimals = 2) Returns the formatted number
24
 * @method string|array param(string|null $name, string|array $default) Returns the parameter value
25
 * @method string partial(string $filepath, array $params = [] ) Renders the partial template
26
 * @method \Aimeos\Base\View\Helper\Iface request() Returns the request helper object
27
 * @method string translate(string $domain, string $singular, string $plural = '', integer $number = 1) Returns the translated string or the original one if no translation is available
28
 * @method string url(string|null $target, string|null $controller = null, string|null $action = null, array $params = [], array $trailing = [], array $config = []) Returns the URL assembled from the given arguments
29
 *
30
 * @package Base
31
 * @subpackage View
32
 */
33
class Standard implements \Aimeos\Base\View\Iface
34
{
35
	private array $helper = [];
36
	private array $values = [];
37
	private array $engines;
38
	private array $paths;
39
40
41
	/**
42
	 * Initializes the view object
43
	 *
44
	 * @param array $paths Associative list of base paths as keys and list of relative paths as value
45
	 * @param \Aimeos\Base\View\Engine\Iface[] $engines Associative list of file extensions as keys and engine objects as values
46
	 */
47
	public function __construct( array $paths = [], array $engines = [] )
48
	{
49
		$this->engines = $engines;
50
		$this->paths = $paths;
51
	}
52
53
54
	/**
55
	 * Calls the view helper with the given name and arguments and returns it's output.
56
	 *
57
	 * @param string $name Name of the view helper
58
	 * @param array $args Arguments passed to the view helper
59
	 * @return mixed Output depending on the view helper
60
	 */
61
	public function __call( string $name, array $args )
62
	{
63
		if( !isset( $this->helper[$name] ) )
64
		{
65
			if( ctype_alnum( $name ) === false )
66
			{
67
				$classname = is_string( $name ) ? '\Aimeos\Base\View\Helper\\' . $name : '<not a string>';
0 ignored issues
show
introduced by
The condition is_string($name) is always true.
Loading history...
68
				throw new \Aimeos\Base\View\Exception( sprintf( 'Invalid characters in class name "%1$s"', $classname ) );
69
			}
70
71
			$iface = \Aimeos\Base\View\Helper\Iface::class;
72
			$classname = '\Aimeos\Base\View\Helper\\' . ucfirst( $name ) . '\Standard';
73
74
			if( class_exists( $classname ) === false ) {
75
				throw new \Aimeos\Base\View\Exception( sprintf( 'Class "%1$s" not available', $classname ) );
76
			}
77
78
			$helper = new $classname( $this );
79
80
			if( !( $helper instanceof $iface ) ) {
81
				throw new \Aimeos\Base\View\Exception( sprintf( 'Class "%1$s" does not implement interface "%2$s"', $classname, $iface ) );
82
			}
83
84
			$this->helper[$name] = $helper;
85
		}
86
87
		return call_user_func_array( array( $this->helper[$name], 'transform' ), $args );
88
	}
89
90
91
	/**
92
	 * Clones internal objects of the view.
93
	 */
94
	public function __clone()
95
	{
96
		foreach( $this->helper as $name => $helper )
97
		{
98
			$helper = clone $helper;
99
100
			// reset view so view helpers will use the current one (for translation, etc.)
101
			$helper->setView( $this );
102
103
			$this->helper[$name] = $helper;
104
		}
105
	}
106
107
108
	/**
109
	 * Returns the value associated to the given key.
110
	 *
111
	 * @param string $key Name of the value that should be returned
112
	 * @return mixed Value associated to the given key
113
	 * @throws \Aimeos\Base\View\Exception If the requested key isn't available
114
	 */
115
	public function __get( string $key )
116
	{
117
		if( !isset( $this->values[$key] ) ) {
118
			throw new \Aimeos\Base\View\Exception( sprintf( 'No value for key "%1$s" found', $key ) );
119
		}
120
121
		return $this->values[$key];
122
	}
123
124
125
	/**
126
	 * Tests if a key with the given name exists.
127
	 *
128
	 * @param string $key Name of the value that should be tested
129
	 * @return bool True if the key exists, false if not
130
	 */
131
	public function __isset( string $key ) : bool
132
	{
133
		return isset( $this->values[$key] );
134
	}
135
136
137
	/**
138
	 * Removes a key from the stored values.
139
	 *
140
	 * @param string $key Name of the value that should be removed
141
	 */
142
	public function __unset( string $key )
143
	{
144
		unset( $this->values[$key] );
145
	}
146
147
148
	/**
149
	 * Sets a new value for the given key.
150
	 *
151
	 * @param string $key Name of the value that should be set
152
	 * @param mixed $value Value associated to the given key
153
	 */
154
	public function __set( string $key, $value )
155
	{
156
		$this->values[$key] = $value;
157
	}
158
159
160
	/**
161
	 * Adds several key/value pairs at once to the view.
162
	 * Overwrites existing key/value pairs.
163
	 *
164
	 * @param array $values Associative list of key/value pairs
165
	 * @return \Aimeos\Base\View\Iface View object for method chaining
166
	 */
167
	public function add( array $values ) : Iface
168
	{
169
		foreach( $values as $key => $value ) {
170
			$this->set( $key, $value );
171
		}
172
173
		return $this;
174
	}
175
176
177
	/**
178
	 * Adds a view helper instance to the view.
179
	 *
180
	 * @param string $name Name of the view helper as called in the template
181
	 * @param \Aimeos\Base\View\Helper\Iface $helper View helper instance
182
	 * @return \Aimeos\Base\View\Iface View object for method chaining
183
	 */
184
	public function addHelper( string $name, \Aimeos\Base\View\Helper\Iface $helper ) : Iface
185
	{
186
		$this->helper[$name] = $helper;
187
		return $this;
188
	}
189
190
191
	/**
192
	 * Assigns a whole set of values at once to the view.
193
	 * This method replaces all existing key/value pairs set by the magic method.
194
	 *
195
	 * @param array $values Associative list of key/value pairs
196
	 * @return \Aimeos\Base\View\Iface View object for method chaining
197
	 */
198
	public function assign( array $values ) : Iface
199
	{
200
		$this->values = $values;
201
		return $this;
202
	}
203
204
205
	/**
206
	 * Returns the value associated to the given key or the default value if the key is not available.
207
	 *
208
	 * @param string $key Name of the value that should be returned
209
	 * @param mixed $default Default value returned if ths key is not available
210
	 * @return mixed Value associated to the given key or the default value
211
	 */
212
	public function get( string $key, $default = null )
213
	{
214
		$values = $this->values;
215
216
		foreach( explode( '/', ltrim( $key, '/' ) ) as $part )
217
		{
218
			if( ( is_array( $values ) || $values instanceof \ArrayAccess ) && isset( $values[$part] ) ) {
219
				$values = $values[$part];
220
			} else {
221
				return $default;
222
			}
223
		}
224
225
		return $values;
226
	}
227
228
229
	/**
230
	 * Assigns the value to the given key in the view.
231
	 *
232
	 * @param string $key Name of the key that should be set
233
	 * @param mixed $value Value that should be assigned to the key
234
	 * @return \Aimeos\Base\View\Iface View object for method chaining
235
	 */
236
	public function set( string $key, $value )
237
	{
238
		$values = &$this->values;
239
240
		foreach( explode( '/', ltrim( $key, '/' ) ) as $part )
241
		{
242
			if( !is_array( $values ) || !isset( $values[$part] ) ) {
243
				$values[$part] = [];
244
			}
245
246
			$values = &$values[$part];
247
		}
248
249
		$values = $value;
250
		return $this;
251
	}
252
253
254
	/**
255
	 * Renders the output based on the given template file name and the key/value pairs.
256
	 *
257
	 * @param array|string $filenames File name or list of file names for the view templates
258
	 * @return string Output generated by the template or null for none
259
	 * @throws \Aimeos\Base\View\Exception If the template isn't found
260
	 */
261
	public function render( $filenames ) : string
262
	{
263
		foreach( $this->engines as $fileext => $engine )
264
		{
265
			if( ( $filepath = $this->resolve( $filenames, $fileext ) ) !== null ) {
266
				return str_replace( ["\t", '    '], '', $engine->render( $this, $filepath, $this->values ) );
267
			}
268
		}
269
270
		if( ( $filepath = $this->resolve( $filenames, '.php' ) ) === null )
271
		{
272
			$files = is_array( $filenames ) ? print_r( $filenames, true ) : $filenames;
273
			throw new \Aimeos\Base\View\Exception( sprintf( 'Template not available: %1$s', $files ) );
0 ignored issues
show
Bug introduced by
It seems like $files can also be of type true; however, parameter $values of sprintf() does only seem to accept double|integer|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

273
			throw new \Aimeos\Base\View\Exception( sprintf( 'Template not available: %1$s', /** @scrutinizer ignore-type */ $files ) );
Loading history...
274
		}
275
276
		try
277
		{
278
			ob_start();
279
280
			$this->includeFile( $filepath );
281
282
			return str_replace( ["\t", '    '], '', ob_get_clean() );
283
		}
284
		catch( \Throwable $t )
285
		{
286
			ob_end_clean();
287
			throw $t;
288
		}
289
	}
290
291
292
	/**
293
	 * Includes the template file and processes the PHP instructions.
294
	 * The filename is passed as first argument but without variable name to prevent messing the variable scope.
295
	 */
296
	protected function includeFile()
297
	{
298
		include func_get_arg( 0 );
299
	}
300
301
302
	/**
303
	 * Returns the absolute file name for the given relative one
304
	 *
305
	 * @param array|string $files File name of list of file names for the view templates
306
	 * @param string $fileext File extension including dot
307
	 * @return string|null Absolute path to the template file of null if not found
308
	 */
309
	protected function resolve( $files, string $fileext )
310
	{
311
		foreach( (array) $files as $file )
312
		{
313
			if( is_file( $file . $fileext ) ) {
314
				return $file . $fileext;
315
			}
316
317
			$ds = DIRECTORY_SEPARATOR;
318
319
			foreach( array_reverse( $this->paths ) as $path => $relPaths )
320
			{
321
				foreach( $relPaths as $relPath )
322
				{
323
					$absPath = $path . $ds . $relPath . $ds . $file . $fileext;
324
325
					if( $ds !== '/' ) {
326
						$absPath = str_replace( '/', $ds, $absPath );
327
					}
328
329
					if( is_file( $absPath ) ) {
330
						return $absPath;
331
					}
332
				}
333
			}
334
		}
335
336
		return null;
337
	}
338
}
339