4
0

View.php 9.6 KB

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