Ubiquity 2.5.2
php rapid development framework
Loading...
Searching...
No Matches
Startup.php
Go to the documentation of this file.
1<?php
2
4
6use Ubiquity\controllers\traits\StartupConfigTrait;
10
19class Startup extends StartupConfigTrait {
20
21 public static $urlParts;
22 public static $templateEngine;
23 protected static $controller;
24 protected static $action;
25 protected static $actionParams;
26
27 protected static function parseUrl(&$url): array {
28 if (!$url) {
29 return self::$urlParts = [$url = '_default'];
30 }
31 return self::$urlParts = \explode('/', \rtrim($url, '/'));
32 }
33
34 protected static function _getControllerInstance(string $controllerName): ?object {
35 if (\class_exists($controllerName, true)) {
36 $controller = new $controllerName ();
37 // Dependency injection
38 if (isset (self::$config ['di']) && \is_array(self::$config ['di'])) {
39 self::injectDependencies($controller);
40 }
41 return $controller;
42 }
43 return null;
44 }
45
46 protected static function startTemplateEngine(array &$config): void {
47 try {
48 $templateEngine = $config ['templateEngine'];
49 $engineOptions = $config ['templateEngineOptions'] ?? ['cache' => false];
50 $engine = new $templateEngine ($engineOptions);
51 if ($engine instanceof TemplateEngine) {
52 self::$templateEngine = $engine;
53 }
54 } catch (\Exception $e) {
55 echo $e->getTraceAsString();
56 }
57 }
58
59 protected static function setMainParams($controller, $mainParams) {
60 foreach ($mainParams as $k => $v) {
61 if (\method_exists($controller, $k)) {
62 $controller->$k($v);
63 } else {
64 $controller->$k = $v;
65 }
66 }
67 }
68
74 public static function run(array &$config): void {
75 self::init($config);
76 self::forward($_GET ['c']);
77 }
78
84 public static function init(array &$config): void {
85 self::$config = $config;
86 if (isset ($config ['templateEngine'])) {
87 self::startTemplateEngine($config);
88 }
89 if (isset ($config ['sessionName'])) {
90 USession::start($config ['sessionName']);
91 }
92 self::$ctrlNS = self::getNS();
93 }
94
102 public static function forward(string $url, bool $initialize = true, bool $finalize = true): void {
103 $u = self::parseUrl($url);
104 if (\is_array(Router::getRoutes()) && ($ru = Router::getRoute($url, true, self::$config ['debug'] ?? false)) !== false) {
105 if (\is_array($ru)) {
106 if (isset ($ru ['controller'])) {
107 static::runAction($ru, $initialize, $finalize);
108 } else {
109 self::runCallable($ru);
110 }
111 } else {
112 echo $ru; // Displays route response from cache
113 }
114 } else {
115 $ru = ['controller' => self::$ctrlNS . $u [0], 'action' => $u [1] ?? 'index', 'params' => \array_slice($u, 2)];
116 static::runAction($ru, $initialize, $finalize);
117 }
118 }
119
125 public static function getTemplateEngineInstance(): ?TemplateEngine {
126 $config = self::$config;
127 if (isset ($config ['templateEngine'])) {
128 $templateEngine = $config ['templateEngine'];
129 return new $templateEngine ([]);
130 }
131 return null;
132 }
133
139 public static function startDefaultTemplateEngine(): TemplateEngine {
140 if (self::$templateEngine === null || !self::$templateEngine instanceof \Ubiquity\views\engine\twig\Twig) {
141 $config = self::$config;
142 $config['templateEngine'] = \Ubiquity\views\engine\twig\Twig::class;
143 self::startTemplateEngine($config);
144 }
145 return self::$templateEngine;
146 }
147
155 public static function runAction(array &$u, bool $initialize = true, bool $finalize = true): void {
156 self::$controller = $ctrl = $u ['controller'];
157 self::$action = $action = $u ['action'] ?? 'index';
158 self::$actionParams = $u['params'] ?? [];
159
160 try {
161 if (null !== $controller = self::_getControllerInstance($ctrl)) {
162 if ($mainParams = $u['mainParams'] ?? false) {
163 static::setMainParams($controller, $mainParams);
164 }
165 if (!$controller->isValid($action)) {
166 $controller->onInvalidControl();
167 } else {
168 if ($initialize) {
169 $controller->initialize();
170 }
171 try {
172 $controller->$action (...(self::$actionParams));
173 } catch (\Error $e) {
174 if (!\method_exists($controller, $action)) {
175 static::onError(404, "This action does not exist on the controller " . $ctrl, $controller);
176 } else {
177 static::logError($e->getCode(), $e->getMessage());
178 if (self::$config ['debug']) {
179 throw $e;
180 } else {
181 static::onError(500, $e->getMessage(), $controller);
182 }
183 }
184 }
185 if ($finalize) {
186 $controller->finalize();
187 }
188 }
189 } else {
190 Logger::warn('Startup', "The controller `$ctrl` doesn't exist! <br/>", 'runAction');
191 static::onError(404, "The controller `$ctrl` doesn't exist! <br/>");
192 }
193 } catch (\Error $eC) {
194 static::logError($eC->getCode(), $eC->getMessage());
195 if (self::$config ['debug']) {
196 throw $eC;
197 } else {
198 static::onError(500, $eC->getMessage());
199 }
200 }
201 }
202
208 public static function runCallable(array &$u): void {
209 self::$actionParams = $u['params'] ?? [];
210 if (isset (self::$config ['di'])) {
211 $di = self::$config ['di'];
212 if (\is_array($di)) {
213 self::$actionParams += \array_values($di);
214 }
215 }
216 $func = $u ['callback'];
217 $func (...(self::$actionParams));
218 }
219
225 public static function injectDependencies($controller): void {
226 $di = DiManager::fetch($controller);
227 if ($di !== false) {
228 foreach ($di as $k => $v) {
229 $setter = 'set' . \ucfirst($k);
230 if (\method_exists($controller, $setter)) {
231 $controller->$setter ($v ($controller));
232 } else {
233 $controller->$k = $v ($controller);
234 }
235 }
236 }
237
238 $di = self::$config ['di'] ?? [];
239 if (isset ($di ['@exec'])) {
240 foreach ($di ['@exec'] as $k => $v) {
241 $controller->$k = $v ($controller);
242 }
243 }
244 }
245
254 public static function runAsString(array &$u, bool $initialize = true, bool $finalize = true): string {
255 \ob_start();
256 self::runAction($u, $initialize, $finalize);
257 return \ob_get_clean();
258 }
259
260 public static function onError(int $code, ?string $message = null, $controllerInstance = null) {
261 $onError = self::$config ['onError'] ?? (function ($code, $message = null, $controllerInstance = null) {
262 switch ($code) {
263 case 404 :
264 self::getHttpInstance()->header('HTTP/1.0 404 Not Found', '', true, 404);
265 echo $message ?? "The page you are looking for doesn't exist!";
266 break;
267
268 case 500 :
269 echo $message ?? "A server error occurred!";
270 break;
271 }
272 });
273 $onError ($code, $message, $controllerInstance);
274 }
275
276 public static function logError(int $code, string $message) {
277 if ($code <= E_ERROR) {
278 Logger::critical('Startup', $message, 'runAction');
279 } elseif ($code <= E_WARNING) {
280 Logger::error('Startup', $message, 'runAction');
281 } else {
282 Logger::warn('Startup', $message, 'runAction');
283 }
284 }
285
291 public static function getController(): ?string {
292 return self::$controller;
293 }
294
300 public static function getControllerSimpleName(): string {
301 return (new \ReflectionClass (self::$controller))->getShortName();
302 }
303
309 public static function getViewNameFileExtension(): string {
310 return self::$config ['templateEngineOptions']['fileExt'] ?? 'html';
311 }
312
318 public static function getAction(): ?string {
319 return self::$action;
320 }
321
327 public static function getActionParams(): array {
328 return self::$actionParams;
329 }
330
336 public static function getFrameworkDir(): string {
337 return \dirname(__FILE__);
338 }
339
345 public static function getApplicationDir(): string {
346 return \dirname(\ROOT);
347 }
348
354 public static function getApplicationName(): string {
355 return \basename(\dirname(\ROOT));
356 }
357}
Starts the framework.
Definition Startup.php:19
static getController()
Returns the active controller name.
Definition Startup.php:291
static runCallable(array &$u)
Runs a callback.
Definition Startup.php:208
static getControllerSimpleName()
Returns the class simple name of the active controller.
Definition Startup.php:300
static forward(string $url, bool $initialize=true, bool $finalize=true)
Forwards to url.
Definition Startup.php:102
static startTemplateEngine(array &$config)
Definition Startup.php:46
static runAction(array &$u, bool $initialize=true, bool $finalize=true)
Runs an action on a controller.
Definition Startup.php:155
static logError(int $code, string $message)
Definition Startup.php:276
static run(array &$config)
Handles the request.
Definition Startup.php:74
static init(array &$config)
Initialize the app with $config array.
Definition Startup.php:84
static injectDependencies($controller)
Injects the dependencies from the di config key in a controller.
Definition Startup.php:225
static setMainParams($controller, $mainParams)
Definition Startup.php:59
static getTemplateEngineInstance()
Returns the template engine instance.
Definition Startup.php:125
static _getControllerInstance(string $controllerName)
Definition Startup.php:34
static getApplicationName()
Returns the application name.
Definition Startup.php:354
static startDefaultTemplateEngine()
Starts the default Template engine (Twig for Webtools).
Definition Startup.php:139
static getApplicationDir()
Returns the application directory (app directory)
Definition Startup.php:345
static runAsString(array &$u, bool $initialize=true, bool $finalize=true)
Runs an action on a controller and returns a string.
Definition Startup.php:254
static onError(int $code, ?string $message=null, $controllerInstance=null)
Definition Startup.php:260
static getViewNameFileExtension()
Returns the extension for view files.
Definition Startup.php:309
static getActionParams()
Returns the active parameters.
Definition Startup.php:327
static getFrameworkDir()
Returns the framework directory.
Definition Startup.php:336
static getAction()
Returns tha active action.
Definition Startup.php:318
Manage dependency injection.
Definition DiManager.php:17
Abstract class for logging Ubiquity\log$Logger This class is part of Ubiquity.
Definition Logger.php:14
Http Session utilities This class is part of Ubiquity.
Definition USession.php:16
Class Configuration \config.