View.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * MINZ - Copyright 2011 Marien Fressinaud
  5. * Sous licence AGPL3 <https://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. * Writes renderHelper() into a file, without keeping the whole output in memory
  145. * @param string $helper the element to be treated
  146. * @param string $filename the path of the file to write
  147. * @throws Minz_PermissionDeniedException
  148. */
  149. public function helperToFile(string $helper, string $filename): void {
  150. $file = fopen($filename, 'wb');
  151. if ($file === false) {
  152. throw new Minz_PermissionDeniedException($filename);
  153. }
  154. $written = true;
  155. ob_start(static function (string $buffer) use ($file, &$written): string {
  156. $written = $written && fwrite($file, $buffer) !== false;
  157. return '';
  158. }, 65536); // Write to the file by chunks of 64 KiB
  159. try {
  160. $this->renderHelper($helper);
  161. } finally {
  162. ob_end_flush();
  163. $written = fclose($file) && $written;
  164. }
  165. if (!$written) {
  166. throw new Minz_PermissionDeniedException($filename);
  167. }
  168. }
  169. /**
  170. * Choose the current view layout.
  171. * @param string|null $layout the layout name to use, null to use no layouts.
  172. */
  173. public function _layout(?string $layout): void {
  174. if ($layout != null) {
  175. $this->layout_filename = self::LAYOUT_PATH_NAME . $layout . '.phtml';
  176. } else {
  177. $this->layout_filename = '';
  178. }
  179. }
  180. /**
  181. * Choose if we want to use the layout or not.
  182. * @param bool $use true if we want to use the layout, false else
  183. */
  184. #[Deprecated('Use Minz_View::_layout() instead.')]
  185. public function _useLayout(bool $use): void {
  186. Minz_Log::warning('Minz_View::_useLayout is deprecated, it will be removed in a future version. Please use Minz_View::_layout instead.');
  187. if ($use) {
  188. $this->_layout(self::LAYOUT_DEFAULT);
  189. } else {
  190. $this->_layout(null);
  191. }
  192. }
  193. /**
  194. * Title management
  195. */
  196. public static function title(): string {
  197. return self::$title;
  198. }
  199. public static function headTitle(): string {
  200. return '<title>' . self::$title . '</title>' . "\n";
  201. }
  202. public static function _title(string $title): void {
  203. self::$title = $title;
  204. }
  205. public static function prependTitle(string $title): void {
  206. self::$title = $title . self::$title;
  207. }
  208. public static function appendTitle(string $title): void {
  209. self::$title = self::$title . $title;
  210. }
  211. /**
  212. * Style sheet management
  213. */
  214. public static function headStyle(): string {
  215. $styles = '';
  216. foreach (self::$styles as $style) {
  217. $styles .= '<link rel="stylesheet" ' .
  218. ($style['media'] === 'all' ? '' : 'media="' . $style['media'] . '" ') .
  219. 'href="' . $style['url'] . '" />';
  220. $styles .= "\n";
  221. }
  222. return $styles;
  223. }
  224. /**
  225. * Prepends a <link> element referencing stylesheet.
  226. * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
  227. */
  228. public static function prependStyle(string $url, string $media = 'all', bool $cond = false): void {
  229. if ($url === '') {
  230. return;
  231. }
  232. foreach (self::$styles as $style) {
  233. if ($style['url'] === $url) {
  234. return;
  235. }
  236. }
  237. array_unshift(self::$styles, [
  238. 'url' => $url,
  239. 'media' => $media,
  240. ]);
  241. }
  242. /**
  243. * Append a `<link>` element referencing stylesheet.
  244. * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
  245. */
  246. public static function appendStyle(string $url, string $media = 'all', bool $cond = false): void {
  247. if ($url === '') {
  248. return;
  249. }
  250. foreach (self::$styles as $style) {
  251. if ($style['url'] === $url) {
  252. return;
  253. }
  254. }
  255. self::$styles[] = [
  256. 'url' => $url,
  257. 'media' => $media,
  258. ];
  259. }
  260. /**
  261. * @param string|array{dark?:string,light?:string,default?:string} $themeColors
  262. */
  263. public static function appendThemeColors(string|array $themeColors): void {
  264. self::$themeColors = $themeColors;
  265. }
  266. /**
  267. * https://developer.mozilla.org/docs/Web/HTML/Reference/Elements/meta/name/theme-color
  268. */
  269. public static function metaThemeColor(): string {
  270. $meta = '';
  271. if (is_array(self::$themeColors)) {
  272. if (!empty(self::$themeColors['light'])) {
  273. $meta .= '<meta name="theme-color" media="(prefers-color-scheme: light)" content="' . htmlspecialchars(self::$themeColors['light']) . '" />';
  274. }
  275. if (!empty(self::$themeColors['dark'])) {
  276. $meta .= '<meta name="theme-color" media="(prefers-color-scheme: dark)" content="' . htmlspecialchars(self::$themeColors['dark']) . '" />';
  277. }
  278. if (!empty(self::$themeColors['default'])) {
  279. $meta .= '<meta name="theme-color" content="' . htmlspecialchars(self::$themeColors['default']) . '" />';
  280. }
  281. } elseif (is_string(self::$themeColors)) {
  282. $meta .= '<meta name="theme-color" content="' . htmlspecialchars(self::$themeColors) . '" />';
  283. }
  284. return $meta;
  285. }
  286. /**
  287. * JS script management
  288. */
  289. public static function headScript(): string {
  290. $scripts = '';
  291. foreach (self::$scripts as $script) {
  292. $scripts .= '<script src="' . $script['url'] . '"';
  293. if (!empty($script['id'])) {
  294. $scripts .= ' id="' . $script['id'] . '"';
  295. }
  296. if ($script['defer']) {
  297. $scripts .= ' defer="defer"';
  298. }
  299. if ($script['async']) {
  300. $scripts .= ' async="async"';
  301. }
  302. $scripts .= '></script>';
  303. $scripts .= "\n";
  304. }
  305. return $scripts;
  306. }
  307. /**
  308. * Prepend a `<script>` element.
  309. * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
  310. * @param bool $defer Use `defer` flag
  311. * @param bool $async Use `async` flag
  312. * @param string $id Add a script `id` attribute
  313. */
  314. public static function prependScript(string $url, bool $cond = false, bool $defer = true, bool $async = true, string $id = ''): void {
  315. if ($url === '') {
  316. return;
  317. }
  318. foreach (self::$scripts as $script) {
  319. if ($script['url'] === $url) {
  320. return;
  321. }
  322. }
  323. array_unshift(self::$scripts, [
  324. 'url' => $url,
  325. 'defer' => $defer,
  326. 'async' => $async,
  327. 'id' => $id,
  328. ]);
  329. }
  330. /**
  331. * Append a `<script>` element.
  332. * @param bool $cond Conditional comment for IE, now deprecated and ignored @deprecated
  333. * @param bool $defer Use `defer` flag
  334. * @param bool $async Use `async` flag
  335. * @param string $id Add a script `id` attribute
  336. */
  337. public static function appendScript(string $url, bool $cond = false, bool $defer = true, bool $async = true, string $id = ''): void {
  338. if ($url === '') {
  339. return;
  340. }
  341. foreach (self::$scripts as $script) {
  342. if ($script['url'] === $url) {
  343. return;
  344. }
  345. }
  346. self::$scripts[] = [
  347. 'url' => $url,
  348. 'defer' => $defer,
  349. 'async' => $async,
  350. 'id' => $id,
  351. ];
  352. }
  353. /**
  354. * Management of parameters added to the view
  355. */
  356. public static function _param(string $key, mixed $value): void {
  357. self::$params[$key] = $value;
  358. }
  359. public function attributeParams(): void {
  360. foreach (Minz_View::$params as $key => $value) {
  361. // @phpstan-ignore property.dynamicName
  362. $this->$key = $value;
  363. }
  364. }
  365. }