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