1 <?php
2
3 namespace Alo\Controller;
4
5 if (!defined('GEN_START')) {
6 http_response_code(404);
7 die();
8 }
9
10 /**
11 * The controller superclass
12 *
13 * @author Art <a.molcanovas@gmail.com>
14 */
15 abstract class AbstractController {
16
17 /**
18 * Whether to echo contents on object destruct
19 *
20 * @var boolean
21 */
22 private $echo_on_destruct;
23
24 /**
25 * Instantiates the class
26 *
27 * @param boolean $echo_on_destruct Whether to echo contents on object destruct
28 * @author Art <a.molcanovas@gmail.com>
29 */
30 function __construct($echo_on_destruct = true) {
31 ob_start();
32 $this->echo_on_destruct = (bool)$echo_on_destruct;
33 }
34
35 /**
36 * Returns if echoOnDestruct is true or false if called without a parameter
37 * or sets it to true/false if the parameter is set
38 *
39 * @param boolean|null $switch The parameter
40 * @return boolean|AbstractController
41 */
42 protected function echoOnDestruct($switch = null) {
43 if ($switch === null) {
44 return $this->echo_on_destruct;
45 } else {
46 $this->echo_on_destruct = (bool)$switch;
47
48 return $this;
49 }
50 }
51
52 /**
53 * Forces a HTTP error page to be displayed instead
54 *
55 * @author Art <a.molcanovas@gmail.com>
56 * @param int $code The HTTP response code
57 */
58 protected function http_error($code = 404) {
59 $this->echo_on_destruct = true;
60 ob_end_clean();
61
62 $controller = \Alo::$router->getErrController();
63 \Alo::$controller = new $controller;
64 \Alo::$controller->error($code);
65 die();
66 }
67
68 /**
69 * Loads a view
70 *
71 * @author Art <a.molcanovas@gmail.com>
72 * @param string $name The name of the view without ".php".
73 * @param array $params Associative array of parameters to pass on to the view
74 * @param boolean $return If set to TRUE, will return the view, if FALSE,
75 * will echo it
76 * @return null|string
77 */
78 protected function loadView($name, $params = [], $return = false) {
79 $name = strtolower($name);
80
81 if (substr($name, -4) == '.php') {
82 $name = substr($name, 0, -4);
83 }
84
85 $path = DIR_APP . 'view' . DIRECTORY_SEPARATOR . $name . '.php';
86
87 if (!file_exists($path)) {
88 trigger_error('View file for ' . $name . ' could not be found', E_USER_ERROR);
89 } else {
90 extract($params);
91
92 if ($return) {
93 ob_start();
94 }
95
96 //not include_once so the view can be reused
97 include $path;
98
99 if ($return) {
100 return ob_get_clean();
101 }
102 }
103
104 return null;
105 }
106
107 /**
108 * Method to avoid errors. Should always be overridden.
109 *
110 * @author Art <a.molcanovas@gmail.com>
111 */
112 function index() {
113 $this->http_error(404);
114 }
115
116 /**
117 * Closure operations
118 *
119 * @author Art <a.molcanovas@gmail.com>
120 */
121 function __destruct() {
122 if ($this->echo_on_destruct) {
123 $ob = ob_get_clean();
124
125 if (\Alo::$router->is_cli_request()) {
126 $ob = strip_tags($ob);
127 }
128
129 echo $ob;
130 } else {
131 ob_end_clean();
132 }
133 }
134
135 }