View.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * MINZ - Copyright 2011 Marien Fressinaud
  5. * Sous licence AGPL3 <http://www.gnu.org/licenses/>
  6. */
  7. /**
  8. * The Minz_View represents a view in the MVC paradigm
  9. */
  10. class Minz_View {
  11. private const VIEWS_PATH_NAME = '/views';
  12. private const LAYOUT_PATH_NAME = '/layout/';
  13. private const LAYOUT_DEFAULT = 'layout';
  14. private string $view_filename = '';
  15. private string $layout_filename = '';
  16. /** @var array<string> */
  17. private static array $base_pathnames = [APP_PATH];
  18. private static string $title = '';
  19. /** @var array<array{'media':string,'url':string}> */
  20. private static array $styles = [];
  21. /** @var array<array{'url':string,'id':string,'defer':bool,'async':bool}> */
  22. private static array $scripts = [];
  23. /** @var string|array{'dark'?:string,'light'?:string,'default'?:string} */
  24. private static $themeColors;
  25. /** @var array<string,mixed> */
  26. private static array $params = [];
  27. /**
  28. * Determines if a layout is used or not
  29. * @throws Minz_ConfigurationException
  30. */
  31. public function __construct() {
  32. $this->_layout(self::LAYOUT_DEFAULT);
  33. $conf = Minz_Configuration::get('system');
  34. self::$title = $conf->title;
  35. }
  36. /**
  37. * @deprecated Change the view file based on controller and action.
  38. */
  39. public function change_view(string $controller_name, string $action_name): void {
  40. Minz_Log::warning('Minz_View::change_view is deprecated, it will be removed in a future version. Please use Minz_View::_path instead.');
  41. $this->_path($controller_name . '/' . $action_name . '.phtml');
  42. }
  43. /**
  44. * Change the view file based on a pathname relative to VIEWS_PATH_NAME.
  45. *
  46. * @param string $path the new path
  47. */
  48. public function _path(string $path): void {
  49. $this->view_filename = self::VIEWS_PATH_NAME . '/' . $path;
  50. }
  51. /**
  52. * Add a base pathname to search views.
  53. *
  54. * New pathnames will be added at the beginning of the list.
  55. *
  56. * @param string $base_pathname the new base pathname.
  57. */
  58. public static function addBasePathname(string $base_pathname): void {
  59. array_unshift(self::$base_pathnames, $base_pathname);
  60. }
  61. /**
  62. * Builds the view filename based on controller and action.
  63. */
  64. public function build(): void {
  65. if ($this->layout_filename !== '') {
  66. $this->buildLayout();
  67. } else {
  68. $this->render();
  69. }
  70. }
  71. /**
  72. * Include a view file.
  73. *
  74. * The file is searched inside list of $base_pathnames.
  75. *
  76. * @param string $filename the name of the file to include.
  77. * @return bool true if the file has been included, false else.
  78. */
  79. private function includeFile(string $filename): bool {
  80. // We search the filename in the list of base pathnames. Only the first view
  81. // found is considered.
  82. foreach (self::$base_pathnames as $base) {
  83. $absolute_filename = $base . $filename;
  84. if (file_exists($absolute_filename)) {
  85. include $absolute_filename;
  86. return true;
  87. }
  88. }
  89. return false;
  90. }
  91. /**
  92. * Builds the layout
  93. */
  94. public function buildLayout(): void {
  95. header('Content-Type: text/html; charset=UTF-8');
  96. if (!$this->includeFile($this->layout_filename)) {
  97. Minz_Log::notice('File not found: `' . $this->layout_filename . '`');
  98. }
  99. }
  100. /**
  101. * Displays the View itself
  102. */
  103. public function render(): void {
  104. if (!$this->includeFile($this->view_filename)) {
  105. Minz_Log::notice('File not found: `' . $this->view_filename . '`');
  106. }
  107. }
  108. public function renderToString(): string {
  109. ob_start();
  110. $this->render();
  111. return ob_get_clean() ?: '';
  112. }
  113. /**
  114. * Adds a layout element
  115. * @param string $part the partial element to be added
  116. */
  117. public function partial(string $part): void {
  118. $fic_partial = self::LAYOUT_PATH_NAME . '/' . $part . '.phtml';
  119. if (!$this->includeFile($fic_partial)) {
  120. Minz_Log::warning('File not found: `' . $fic_partial . '`');
  121. }
  122. }
  123. /**
  124. * Displays a graphic element located in APP./views/helpers/
  125. * @param string $helper the element to be displayed
  126. */
  127. public function renderHelper(string $helper): void {
  128. $fic_helper = '/views/helpers/' . $helper . '.phtml';
  129. if (!$this->includeFile($fic_helper)) {
  130. Minz_Log::warning('File not found: `' . $fic_helper . '`');
  131. }
  132. }
  133. /**
  134. * Returns renderHelper() in a string
  135. * @param string $helper the element to be treated
  136. */
  137. public function helperToString(string $helper): string {
  138. ob_start();
  139. $this->renderHelper($helper);
  140. return ob_get_clean() ?: '';
  141. }
  142. /**
  143. * Choose the current view layout.
  144. * @param string|null $layout the layout name to use, null to use no layouts.
  145. */
  146. public function _layout(?string $layout): void {
  147. if ($layout != null) {
  148. $this->layout_filename = self::LAYOUT_PATH_NAME . $layout . '.phtml';
  149. } else {
  150. $this->layout_filename = '';
  151. }
  152. }
  153. /**
  154. * Choose if we want to use the layout or not.
  155. * @deprecated Please use the `_layout` function instead.
  156. * @param bool $use true if we want to use the layout, false else
  157. */
  158. public function _useLayout(bool $use): void {
  159. Minz_Log::warning('Minz_View::_useLayout is deprecated, it will be removed in a future version. Please use Minz_View::_layout instead.');
  160. if ($use) {
  161. $this->_layout(self::LAYOUT_DEFAULT);
  162. } else {
  163. $this->_layout(null);
  164. }
  165. }
  166. /**
  167. * Title management
  168. */
  169. public static function title(): string {
  170. return self::$title;
  171. }
  172. public static function headTitle(): string {
  173. return '<title>' . self::$title . '</title>' . "\n";
  174. }
  175. public static function _title(string $title): void {
  176. self::$title = $title;
  177. }
  178. public static function prependTitle(string $title): void {
  179. self::$title = $title . self::$title;
  180. }
  181. public static function appendTitle(string $title): void {
  182. self::$title = self::$title . $title;
  183. }
  184. /**
  185. * Style sheet management
  186. */
  187. public static function headStyle(): string {
  188. $styles = '';
  189. foreach (self::$styles as $style) {
  190. $styles .= '<link rel="stylesheet" ' .
  191. ($style['media'] === 'all' ? '' : 'media="' . $style['media'] . '" ') .
  192. 'href="' . $style['url'] . '" />';
  193. $styles .= "\n";
  194. }
  195. return $styles;
  196. }
  197. /**
  198. * Prepends a <link> element referencing stylesheet.
  199. * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
  200. */
  201. public static function prependStyle(string $url, string $media = 'all', bool $cond = false): void {
  202. if ($url === '') {
  203. return;
  204. }
  205. array_unshift(self::$styles, [
  206. 'url' => $url,
  207. 'media' => $media,
  208. ]);
  209. }
  210. /**
  211. * Append a `<link>` element referencing stylesheet.
  212. * @param string $url
  213. * @param string $media
  214. * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
  215. */
  216. public static function appendStyle(string $url, string $media = 'all', bool $cond = false): void {
  217. if ($url === '') {
  218. return;
  219. }
  220. self::$styles[] = [
  221. 'url' => $url,
  222. 'media' => $media,
  223. ];
  224. }
  225. /**
  226. * @param string|array{'dark'?:string,'light'?:string,'default'?:string} $themeColors
  227. */
  228. public static function appendThemeColors($themeColors): void {
  229. self::$themeColors = $themeColors;
  230. }
  231. /**
  232. * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name/theme-color
  233. */
  234. public static function metaThemeColor(): string {
  235. $meta = '';
  236. if (is_array(self::$themeColors)) {
  237. if (!empty(self::$themeColors['light'])) {
  238. $meta .= '<meta name="theme-color" media="(prefers-color-scheme: light)" content="' . htmlspecialchars(self::$themeColors['light']) . '" />';
  239. }
  240. if (!empty(self::$themeColors['dark'])) {
  241. $meta .= '<meta name="theme-color" media="(prefers-color-scheme: dark)" content="' . htmlspecialchars(self::$themeColors['dark']) . '" />';
  242. }
  243. if (!empty(self::$themeColors['default'])) {
  244. $meta .= '<meta name="theme-color" content="' . htmlspecialchars(self::$themeColors['default']) . '" />';
  245. }
  246. } elseif (is_string(self::$themeColors)) {
  247. $meta .= '<meta name="theme-color" content="' . htmlspecialchars(self::$themeColors) . '" />';
  248. }
  249. return $meta;
  250. }
  251. /**
  252. * JS script management
  253. */
  254. public static function headScript(): string {
  255. $scripts = '';
  256. foreach (self::$scripts as $script) {
  257. $scripts .= '<script src="' . $script['url'] . '"';
  258. if (!empty($script['id'])) {
  259. $scripts .= ' id="' . $script['id'] . '"';
  260. }
  261. if ($script['defer']) {
  262. $scripts .= ' defer="defer"';
  263. }
  264. if ($script['async']) {
  265. $scripts .= ' async="async"';
  266. }
  267. $scripts .= '></script>';
  268. $scripts .= "\n";
  269. }
  270. return $scripts;
  271. }
  272. /**
  273. * Prepend a `<script>` element.
  274. * @param string $url
  275. * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
  276. * @param bool $defer Use `defer` flag
  277. * @param bool $async Use `async` flag
  278. * @param string $id Add a script `id` attribute
  279. */
  280. public static function prependScript(string $url, bool $cond = false, bool $defer = true, bool $async = true, string $id = ''): void {
  281. if ($url === '') {
  282. return;
  283. }
  284. array_unshift(self::$scripts, [
  285. 'url' => $url,
  286. 'defer' => $defer,
  287. 'async' => $async,
  288. 'id' => $id,
  289. ]);
  290. }
  291. /**
  292. * Append a `<script>` element.
  293. * @param string $url
  294. * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
  295. * @param bool $defer Use `defer` flag
  296. * @param bool $async Use `async` flag
  297. * @param string $id Add a script `id` attribute
  298. */
  299. public static function appendScript(string $url, bool $cond = false, bool $defer = true, bool $async = true, string $id = ''): void {
  300. if ($url === '') {
  301. return;
  302. }
  303. self::$scripts[] = [
  304. 'url' => $url,
  305. 'defer' => $defer,
  306. 'async' => $async,
  307. 'id' => $id,
  308. ];
  309. }
  310. /**
  311. * Management of parameters added to the view
  312. * @param mixed $value
  313. */
  314. public static function _param(string $key, $value): void {
  315. self::$params[$key] = $value;
  316. }
  317. public function attributeParams(): void {
  318. foreach (Minz_View::$params as $key => $value) {
  319. // @phpstan-ignore property.dynamicName
  320. $this->$key = $value;
  321. }
  322. }
  323. }