aboutsummaryrefslogtreecommitdiff
path: root/lib/Minz/View.php
blob: eebd7ee92e051cb3801fe4831683fe88f9132ef4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
<?php
declare(strict_types=1);

/**
 * MINZ - Copyright 2011 Marien Fressinaud
 * Sous licence AGPL3 <http://www.gnu.org/licenses/>
*/

/**
 * The Minz_View represents a view in the MVC paradigm
 */
class Minz_View {
	private const VIEWS_PATH_NAME = '/views';
	private const LAYOUT_PATH_NAME = '/layout/';
	private const LAYOUT_DEFAULT = 'layout';

	private string $view_filename = '';
	private string $layout_filename = '';
	/** @var array<string> */
	private static array $base_pathnames = [APP_PATH];
	private static string $title = '';
	/** @var array<array{media:string,url:string}> */
	private static array $styles = [];
	/** @var array<array{url:string,id:string,defer:bool,async:bool}> */
	private static array $scripts = [];
	/** @var string|array{dark?:string,light?:string,default?:string} */
	private static $themeColors;
	/** @var array<string,mixed> */
	private static array $params = [];

	/**
	 * Determines if a layout is used or not
	 * @throws Minz_ConfigurationException
	 */
	public function __construct() {
		$this->_layout(self::LAYOUT_DEFAULT);
		$conf = Minz_Configuration::get('system');
		self::$title = $conf->title;
	}

	/**
	 * Change the view file based on controller and action.
	 */
	#[Deprecated('Use Minz_View::_path() instead.')]
	public function change_view(string $controller_name, string $action_name): void {
		Minz_Log::warning('Minz_View::change_view is deprecated, it will be removed in a future version. Please use Minz_View::_path instead.');
		$this->_path($controller_name . '/' . $action_name . '.phtml');
	}

	/**
	 * Change the view file based on a pathname relative to VIEWS_PATH_NAME.
	 *
	 * @param string $path the new path
	 */
	public function _path(string $path): void {
		$this->view_filename = self::VIEWS_PATH_NAME . '/' . $path;
	}

	/**
	 * Add a base pathname to search views.
	 *
	 * New pathnames will be added at the beginning of the list.
	 *
	 * @param string $base_pathname the new base pathname.
	 */
	public static function addBasePathname(string $base_pathname): void {
		array_unshift(self::$base_pathnames, $base_pathname);
	}

	/**
	 * Builds the view filename based on controller and action.
	 */
	public function build(): void {
		if ($this->layout_filename !== '') {
			$this->buildLayout();
		} else {
			$this->render();
		}
	}

	/**
	 * Include a view file.
	 *
	 * The file is searched inside list of $base_pathnames.
	 *
	 * @param string $filename the name of the file to include.
	 * @return bool true if the file has been included, false else.
	 */
	private function includeFile(string $filename): bool {
		// We search the filename in the list of base pathnames. Only the first view
		// found is considered.
		foreach (self::$base_pathnames as $base) {
			$absolute_filename = $base . $filename;
			if (file_exists($absolute_filename)) {
				include $absolute_filename;
				return true;
			}
		}

		return false;
	}

	/**
	 * Builds the layout
	 */
	public function buildLayout(): void {
		header('Content-Type: text/html; charset=UTF-8');
		if (!$this->includeFile($this->layout_filename)) {
			Minz_Log::notice('File not found: `' . $this->layout_filename . '`');
		}
	}

	/**
	 * Displays the View itself
	 */
	public function render(): void {
		if (!$this->includeFile($this->view_filename)) {
			Minz_Log::notice('File not found: `' . $this->view_filename . '`');
		}
	}

	public function renderToString(): string {
		ob_start();
		$this->render();
		return ob_get_clean() ?: '';
	}

	/**
	 * Adds a layout element
	 * @param string $part the partial element to be added
	 */
	public function partial(string $part): void {
		$fic_partial = self::LAYOUT_PATH_NAME . '/' . $part . '.phtml';
		if (!$this->includeFile($fic_partial)) {
			Minz_Log::warning('File not found: `' . $fic_partial . '`');
		}
	}

	/**
	 * Displays a graphic element located in APP./views/helpers/
	 * @param string $helper the element to be displayed
	 */
	public function renderHelper(string $helper): void {
		$fic_helper = '/views/helpers/' . $helper . '.phtml';
		if (!$this->includeFile($fic_helper)) {
			Minz_Log::warning('File not found: `' . $fic_helper . '`');
		}
	}

	/**
	 * Returns renderHelper() in a string
	 * @param string $helper the element to be treated
	 */
	public function helperToString(string $helper): string {
		ob_start();
		$this->renderHelper($helper);
		return ob_get_clean() ?: '';
	}

	/**
	 * Choose the current view layout.
	 * @param string|null $layout the layout name to use, null to use no layouts.
	 */
	public function _layout(?string $layout): void {
		if ($layout != null) {
			$this->layout_filename = self::LAYOUT_PATH_NAME . $layout . '.phtml';
		} else {
			$this->layout_filename = '';
		}
	}

	/**
	 * Choose if we want to use the layout or not.
	 * @param bool $use true if we want to use the layout, false else
	 */
	#[Deprecated('Use Minz_View::_layout() instead.')]
	public function _useLayout(bool $use): void {
		Minz_Log::warning('Minz_View::_useLayout is deprecated, it will be removed in a future version. Please use Minz_View::_layout instead.');
		if ($use) {
			$this->_layout(self::LAYOUT_DEFAULT);
		} else {
			$this->_layout(null);
		}
	}

	/**
	 * Title management
	 */
	public static function title(): string {
		return self::$title;
	}
	public static function headTitle(): string {
		return '<title>' . self::$title . '</title>' . "\n";
	}
	public static function _title(string $title): void {
		self::$title = $title;
	}
	public static function prependTitle(string $title): void {
		self::$title = $title . self::$title;
	}
	public static function appendTitle(string $title): void {
		self::$title = self::$title . $title;
	}

	/**
	 * Style sheet management
	 */
	public static function headStyle(): string {
		$styles = '';
		foreach (self::$styles as $style) {
			$styles .= '<link rel="stylesheet" ' .
				($style['media'] === 'all' ? '' : 'media="' . $style['media'] . '" ') .
				'href="' . $style['url'] . '" />';
			$styles .= "\n";
		}

		return $styles;
	}

	/**
	 * Prepends a <link> element referencing stylesheet.
	 * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
	 */
	public static function prependStyle(string $url, string $media = 'all', bool $cond = false): void {
		if ($url === '') {
			return;
		}
		array_unshift(self::$styles, [
			'url' => $url,
			'media' => $media,
		]);
	}

	/**
	 * Append a `<link>` element referencing stylesheet.
	 * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
	 */
	public static function appendStyle(string $url, string $media = 'all', bool $cond = false): void {
		if ($url === '') {
			return;
		}
		self::$styles[] = [
			'url' => $url,
			'media' => $media,
		];
	}

	/**
	 * @param string|array{dark?:string,light?:string,default?:string} $themeColors
	 */
	public static function appendThemeColors(string|array $themeColors): void {
		self::$themeColors = $themeColors;
	}

	/**
	 * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name/theme-color
	 */
	public static function metaThemeColor(): string {
		$meta = '';
		if (is_array(self::$themeColors)) {
			if (!empty(self::$themeColors['light'])) {
				$meta .= '<meta name="theme-color" media="(prefers-color-scheme: light)" content="' . htmlspecialchars(self::$themeColors['light']) . '" />';
			}
			if (!empty(self::$themeColors['dark'])) {
				$meta .= '<meta name="theme-color" media="(prefers-color-scheme: dark)" content="' . htmlspecialchars(self::$themeColors['dark']) . '" />';
			}
			if (!empty(self::$themeColors['default'])) {
				$meta .= '<meta name="theme-color" content="' . htmlspecialchars(self::$themeColors['default']) . '" />';
			}
		} elseif (is_string(self::$themeColors)) {
			$meta .= '<meta name="theme-color" content="' . htmlspecialchars(self::$themeColors) . '" />';
		}
		return $meta;
	}

	/**
	 * JS script management
	 */
	public static function headScript(): string {
		$scripts = '';
		foreach (self::$scripts as $script) {
			$scripts .= '<script src="' . $script['url'] . '"';
			if (!empty($script['id'])) {
				$scripts .= ' id="' . $script['id'] . '"';
			}
			if ($script['defer']) {
				$scripts .= ' defer="defer"';
			}
			if ($script['async']) {
				$scripts .= ' async="async"';
			}
			$scripts .= '></script>';
			$scripts .= "\n";
		}

		return $scripts;
	}
	/**
	 * Prepend a `<script>` element.
	 * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
	 * @param bool $defer Use `defer` flag
	 * @param bool $async Use `async` flag
	 * @param string $id Add a script `id` attribute
	 */
	public static function prependScript(string $url, bool $cond = false, bool $defer = true, bool $async = true, string $id = ''): void {
		if ($url === '') {
			return;
		}
		array_unshift(self::$scripts, [
			'url' => $url,
			'defer' => $defer,
			'async' => $async,
			'id' => $id,
		]);
	}

	/**
	 * Append a `<script>` element.
	 * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
	 * @param bool $defer Use `defer` flag
	 * @param bool $async Use `async` flag
	 * @param string $id Add a script `id` attribute
	 */
	public static function appendScript(string $url, bool $cond = false, bool $defer = true, bool $async = true, string $id = ''): void {
		if ($url === '') {
			return;
		}
		self::$scripts[] = [
			'url' => $url,
			'defer' => $defer,
			'async' => $async,
			'id' => $id,
		];
	}

	/**
	 * Management of parameters added to the view
	 */
	public static function _param(string $key, mixed $value): void {
		self::$params[$key] = $value;
	}

	public function attributeParams(): void {
		foreach (Minz_View::$params as $key => $value) {
			// @phpstan-ignore property.dynamicName
			$this->$key = $value;
		}
	}
}