xref: /webtrees/app/View.php (revision 76a5e7c78a07f5736a3cd5b7437c8f18dc196a5e)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2017 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16namespace Fisharebest\Webtrees;
17
18/**
19 * Simple view/template class.
20 */
21class View {
22	/**
23	 * @var string The (file) name of the view.
24	 */
25	private $name;
26
27	/**
28	 * @var mixed[] Data to be inserted into the view.
29	 */
30	private $data;
31
32	/**
33	 * Createa view from a template name and optional data.
34	 *
35	 * @param       $name
36	 * @param array $data
37	 */
38	public function __construct($name, $data = []) {
39		$this->name = $name;
40		$this->data = $data;
41	}
42
43	/**
44	 * Render a view.
45	 *
46	 * @return string
47	 */
48	public function render() {
49		extract($this->data);
50
51		ob_start();
52		require WT_ROOT . 'resources/views/' . $this->name . '.php';
53		return ob_get_clean();
54	}
55
56	/**
57	 * Check whether a view exists.
58	 *
59	 * @param string $view_name
60	 *
61	 * @return bool
62	 */
63	public static function exists($view_name) {
64		return file_exists(WT_ROOT . 'resources/views/' . $view_name . '.php');
65	}
66
67	/**
68	 * Cerate and render a view in a single operation.
69	 *
70	 * @param string  $name
71	 * @param mixed[] $data
72	 *
73	 * @return string
74	 */
75	public static function make($name, $data = []) {
76		$view = new static($name, $data);
77
78		return $view->render();
79	}
80}
81