-
Notifications
You must be signed in to change notification settings - Fork 0
/
Engine.php
executable file
·748 lines (648 loc) · 25.9 KB
/
Engine.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
<?php
namespace Cherrycake;
/**
* The main class that loads modules and configurations, and the entry point of the application.
* Cherrycake uses global variables for configuring modules and global configuration, be sure to set "register_globals" to "off" in php.ini to avoid security issues.
*
* @package Cherrycake
* @category Main
*/
class Engine {
/**
* @var string $appNamespace The namespace of the App
*/
private $appNamespace;
/**
* @var string $appName The name of the App
*/
private $appName = "CherrycakeApp";
/**
* @var bool $isDevel Whether the App is in development environment or not
*/
private $isDevel = false;
/**
* @var bool $isUnderMaintenance Whether the App is under maintenance or not
*/
private $isUnderMaintenance = false;
/**
* @var bool $isCli Whether the engine is running as cli or not
*/
private $isCli = null;
/**
* @var array $underMaintenanceExceptionIps An array of IPs that will be considered as exceptions to the "under maintenance" mode when connecting
*/
private $underMaintenanceExceptionIps = [];
/**
* @var string $configDir The App directory where configuration files reside
*/
private $configDir = "config";
/**
* @var string $appModulesDir The App directory where app modules reside
*/
private $appModulesDir = "src";
/**
* @var string $appClassesDir The App directory where app classes reside
*/
private $appClassesDir = "src";
/**
* @var string $timeZone The system's timezone. All modules, including Database for date/time retrievals/saves will be made taking this timezone into account. The server is expected to run on this timezone. Standard "Etc/UTC" is recommended.
*/
private $timezoneName = "Etc/UTC";
/**
* @var int $timezoneId The system's timezone. The same as timezoneName, but the matching id on the cherrycake timezones database table
*/
private $timezoneId = "532";
/**
* @var Cache $cache Holds the bottom-level Cache object
*/
public $cache;
/**
* @var array $loadedModules Stores the names of all included modules
*/
private $loadedModules;
/**
* @var array $moduleLoadingHistory Stores a history of the loaded modules.
*/
private $moduleLoadingHistory;
/**
* @var int $executionStartHrTime The system's high resolution time where the execution started
*/
private $executionStartHrTime;
/**
* Initializes the engine
*
* @param string $appNamespace The namespace of the app.
* @param array $setup The initial engine configuration information, with the following possible keys
*
* * appName: The App name
* * isDevel: Whether the App is in development mode or not
* * isUnderMaintenance: Whether the App is under maintenance or not
* * isCli: Whether the engine is running as cli or not. When not specified, it will autodetect.
* * configDir: The directory where configuration files are stored
* * appModulesDir: The directory where app modules are stored
* * appClassesDir: The directory where app classes are stored
* * timezoneName: The system's timezone. All modules, including Database for date/time retrievals/saves will be made taking this timezone into account. The server is expected to run on this timezone. Standard "Etc/UTC" is recommended.
* * timezoneId: The system's timezone. The same as timezoneName, but the matching id on the cherrycake timezones database table
* * baseCoreModules: An ordered array of the base Core module names that has to be always loaded on application start. Defaults to ["Actions"]. This list should include the Actions module to provide some kind of functionality to the app, since otherwise it wouldn't be answering any requests and will be completely unusable, except if you're experimenting with different ways of using the Cherrycake engine.
* * baseAppModules: An ordered array of the base App module names that has to be always loaded on application start.
* * additionalAppConfigFiles: An ordered array of any additional App config files to load that are found under the App config directory
*
* @return boolean Whether all the modules have been loaded ok
*/
function init($appNamespace, $setup = false) {
$this->appNamespace = $appNamespace;
if (!isset($setup["isCli"]))
$setup["isCli"] = defined("STDIN");
if (!isset($setup["appName"]))
$setup["appName"] = md5(($_SERVER["HOSTNAME"] ?? false ?: "").$_SERVER["DOCUMENT_ROOT"]);
foreach ([
"appName",
"isDevel",
"isUnderMaintenance",
"isCli",
"configDir",
"appModulesDir",
"appClassesDir",
"timezoneName",
"timezoneId"
] as $key)
if (isset($setup[$key]))
$this->$key = $setup[$key];
if ($this->isDevel())
$this->executionStartHrTime = hrtime(true);
$this->engineCache = new EngineCache;
if ($this->isUnderMaintenance()) {
header("HTTP/1.1 503 Service Temporarily Unavailable");
echo file_get_contents("errors/maintenance.html");
die;
}
date_default_timezone_set($this->getTimezoneName());
if (isset($setup["additionalAppConfigFiles"])) {
foreach ($setup["additionalAppConfigFiles"] as $additionalAppConfigFile)
require APP_DIR."/config/".$additionalAppConfigFile;
}
foreach ($setup["baseCoreModules"] ?? ["Actions"] as $module) {
if (!$this->loadCoreModule($module, MODULE_LOADING_ORIGIN_BASE))
return false;
}
if (isset($setup["baseAppModules"])) {
foreach ($setup["baseAppModules"] as $module) {
if (!$this->loadAppModule($module, MODULE_LOADING_ORIGIN_BASE))
return false;
}
}
return true;
}
/**
* @param string $directory The directory on which to search for modules
* @return mixed An array of the module names found on the specified directory, or false if none found or the directory couldn't be opened.
*/
function getAvailableModuleNamesOnDirectory($directory) {
$cacheBucketName = "AvailableModuleNamesOnDirectory";
$cacheKey = [$directory];
$cacheTtl = $this->isDevel() ? 1 : 60;
if ($this->engineCache->isKeyExistsInBucket($cacheBucketName, $cacheKey))
return $this->engineCache->getFromBucket($cacheBucketName, $cacheKey);
if (!is_dir($directory)) {
$this->engineCache->setInBucket($cacheBucketName, $cacheKey, [], $cacheTtl);
return false;
}
$moduleNames = false;
if (!$handler = opendir($directory))
return false;
while (false !== ($file = readdir($handler))) {
if ($file == "." || $file == "..")
continue;
if (is_dir($directory."/".$file))
$moduleNames[] = $file;
}
closedir($handler);
$this->engineCache->setInBucket($cacheBucketName, $cacheKey, $moduleNames ?? false, $cacheTtl);
return $moduleNames;
}
/**
* @return array All the available Core module names
*/
function getAvailableCoreModuleNames() {
return $this->getAvailableModuleNamesOnDirectory(ENGINE_DIR."/src/Modules");
}
/**
* @return array All the available App module names
*/
function getAvailableAppModuleNames() {
return $this->getAvailableModuleNamesOnDirectory($this->getAppModulesDir());
}
/**
* @param string $methodName the name of the method
* @return array The Core module names that implement the specified method
*/
function getAvailableCoreModuleNamesWithMethod($methodName) {
return $this->getAvailableModuleNamesWithMethod("Cherrycake", ENGINE_DIR."/src", $methodName);
}
/**
* @param string $methodName the name of the method
* @return array The App module names that implement the specified method
*/
function getAvailableAppModuleNamesWithMethod($methodName) {
return $this->getAvailableModuleNamesWithMethod($this->getAppNamespace(), $this->getAppModulesDir(), $methodName);
}
/*
* @param string $nameSpace The namespace to use
* @param string $modulesDirectory The directory where the specified module is stored
* @param string $methodName the name of the method to check
* @return array The module names that imeplement the specified method, o,r false if no modules found
*/
function getAvailableModuleNamesWithMethod($nameSpace, $modulesDirectory, $methodName) {
$cacheBucketName = "AvailableModuleNamesWithMethod";
$cacheKey = [$nameSpace, $modulesDirectory, $methodName];
$cacheTtl = $this->isDevel() ? 2 : 600;
if ($this->engineCache->isKeyExistsInBucket($cacheBucketName, $cacheKey))
return $this->engineCache->getFromBucket($cacheBucketName, $cacheKey);
if (!$moduleNames = $this->getAvailableModuleNamesOnDirectory($modulesDirectory)) {
$this->engineCache->setInBucket($cacheBucketName, $cacheKey, [], $cacheTtl);
return false;
}
foreach ($moduleNames as $moduleName) {
if (!$this->isModuleExists($modulesDirectory, $moduleName))
continue;
if ($this->isModuleImplementsMethod($nameSpace, $moduleName, $methodName))
$modulesWithMethod[] = $moduleName;
}
$this->engineCache->setInBucket($cacheBucketName, $cacheKey, $modulesWithMethod ?? false, $cacheTtl);
return $modulesWithMethod ?? false;
}
/**
* @param string $nameSpace The namespace to use
* @param string $moduleName The name of the module to check
* @param string $methodName the name of the method to check
* @return boolean True if the specified module implements the specified method
*/
function isModuleImplementsMethod($nameSpace, $moduleName, $methodName) {
return $this->isClassMethodImplemented($nameSpace."\\".$moduleName."\\".$moduleName, $methodName);
}
/**
* @param string $className The name of the class
* @param string $methodname The name of the method
* @return boolean True if the method is implemented on the specified class, false if it isn't.
*/
function isClassMethodImplemented($className, $methodName) {
$reflector = new \ReflectionMethod($className, $methodName);
return $reflector->class == $className;
}
/**
* @return string The namespace used by the App
*/
function getAppNamespace() {
return $this->appNamespace;
}
/**
* @return string The name of the App
*/
function getAppName() {
return $this->appName;
}
/**
* @return bool Whether the App is in development mode or not
*/
function isDevel() {
return $this->isDevel;
}
/**
* @return bool Whether the App is in "under maintenance" mode for the current client or not
*/
function isUnderMaintenance() {
global $underMaintenanceExceptionIps;
return $this->isUnderMaintenance && !in_array($_SERVER["REMOTE_ADDR"], $this->underMaintenanceExceptionIps);
}
/**
* @return bool Whether the app is running as cli or not
*/
function isCli() {
return $this->isCli;
}
/**
* @return string The App directory where configuration files reside
*/
function getConfigDir() {
return APP_DIR."/".$this->configDir;
}
/**
* @return string The App directory where app modules reside
*/
function getAppModulesDir() {
return APP_DIR."/".$this->appModulesDir;
}
/**
* @return string The App directory where app classes reside
*/
function getAppClassesDir() {
return APP_DIR."/".$this->appClassesDir;
}
/**
* @return string A string that identifies the system timezone
*/
function getTimezoneName() {
return $this->timezoneName;
}
/**
* @return integer The system timezone id matching the one in the cherrycake timezones database table
*/
function getTimezoneId() {
return $this->timezoneId;
}
/**
* Loads a Core module. Core modules are classes extending the module class that provide engine-specific functionalities.
*
* @param string $moduleName The name of the module to load
* @param int $origin The origin from where the module is being loaded, one of the MODULE_LOADING_ORIGIN_? constants, defaults to MODULE_LOADING_ORIGIN_MANUAL
* @param string $requiredByModuleName The name of the module that required this module, if any.
*
* @return boolean Whether the module has been loaded ok
*/
function loadCoreModule($moduleName, $origin = MODULE_LOADING_ORIGIN_MANUAL, $requiredByModuleName = false) {
return $this->loadModule(ENGINE_DIR."/modules", $this->getConfigDir(), $moduleName, __NAMESPACE__, $origin, $requiredByModuleName);
}
/**
* Loads an App module. App modules are classes extending the module class that provide app-specific functionalities.
*
* @param string $moduleName The name of the module to load
* @param int $origin The origin from where the module is being loaded, one of the MODULE_LOADING_ORIGIN_? constants, defaults to MODULE_LOADING_ORIGIN_MANUAL
* @param string $requiredByModuleName The name of the module that required this module, if any.
*
* @return boolean Whether the module has been loaded ok
*/
function loadAppModule($moduleName, $origin = MODULE_LOADING_ORIGIN_MANUAL, $requiredByModuleName = false) {
return $this->loadModule($this->getAppModulesDir(), $this->getConfigDir(), $moduleName, $this->getAppNamespace(), $origin, $requiredByModuleName);
}
/**
* Loads a module when it's not known whether it's an app or a core module
*
* @param string $moduleName The name of the module to load
* @param int $origin The origin from where the module is being loaded, one of the MODULE_LOADING_ORIGIN_? constants, defaults to MODULE_LOADING_ORIGIN_MANUAL
* @param string $requiredByModuleName The name of the module that required this module, if any.
* @return boolean Whether the module has been loaded ok
*/
function loadUnknownModule($moduleName, $origin = MODULE_LOADING_ORIGIN_MANUAL, $requiredByModuleName = false) {
if ($this->isCoreModuleExists($moduleName))
return $this->loadCoreModule($moduleName, $requiredByModuleName);
return $this->loadAppModule($moduleName, $requiredByModuleName);
}
/**
* Generic method to load a module. Modules are classes extending the module class providing specific functionalities in a modular-type framework. Module can have its own configuration file.
*
* @param string $modulesDirectory Directory where modules are stored
* @param string $configDirectory Directory where module configuration files are stored with the syntax [module name].config.php
* @param string $moduleName The name of the module to load
* @param string $namespace The namespace of the module
* @param int $origin The origin from where the module is being loaded, one of the MODULE_LOADING_ORIGIN_? constants, defaults to MODULE_LOADING_ORIGIN_MANUAL
* @param string $requiredByModuleName The name of the module that required this module, if any.
*
* @return boolean Whether the module has been loaded and initted ok
*/
function loadModule($modulesDirectory, $configDirectory, $moduleName, $namespace, $origin = MODULE_LOADING_ORIGIN_MANUAL, $requiredByModuleName = false) {
if ($this->isDevel()) {
$moduleLoadingHistoryId = uniqid();
$this->moduleLoadingHistory[$moduleLoadingHistoryId] = [
"loadingStartHrTime" => hrtime(true),
"loadedModule" => $moduleName,
"namespace" => $namespace,
"origin" => $origin,
"requiredBy" => $requiredByModuleName
];
}
// Avoids a module to be loaded more than once
if (is_array($this->loadedModules) && in_array($moduleName, $this->loadedModules)) {
if ($this->isDevel())
$this->moduleLoadingHistory[$moduleLoadingHistoryId]["isAlreadyLoaded"] = true;
return true;
}
$this->loadedModules[] = $moduleName;
eval("\$this->".$moduleName." = new \\".$namespace."\\".$moduleName."\\".$moduleName."();");
if ($this->isDevel())
$this->moduleLoadingHistory[$moduleLoadingHistoryId]["initStartHrTime"] = hrtime(true);
if(!$this->$moduleName->init()) {
if ($this->isDevel())
$this->moduleLoadingHistory[$moduleLoadingHistoryId]["isInitFailed"] = true;
$this->end();
die;
}
if ($this->isDevel())
$this->moduleLoadingHistory[$moduleLoadingHistoryId]["initEndHrTime"] = hrtime(true);
return true;
}
/**
* @param string $moduleName The name of the module to check
* @return bool Whether the specified module has been loaded
*/
function isModuleLoaded($moduleName) {
return isset($this->$moduleName);
}
/**
* @param string $modulesDirectory Directory where modules are stored
* @param string $moduleName The name of the module whose class must be included
* @return string The file path of the specified module
*/
function getModuleFilePath($modulesDirectory, $moduleName) {
return $modulesDirectory."/".$moduleName."/".$moduleName.".php";
}
/**
* @param string $modulesDirectory Directory where modules are stored
* @param string $moduleName The name of the module whose class must be included
* @return boolean Whether the specified module file exists
*/
function isModuleExists($modulesDirectory, $moduleName) {
return file_exists($this->getModuleFilePath($modulesDirectory, $moduleName));
}
/**
* @param string $moduleName The name of the module
* @return boolean Whether the specified module exists and is a core module
*/
function isCoreModuleExists($moduleName) {
return $this->isModuleExists(ENGINE_DIR."/modules", $moduleName);
}
/**
* @param string $moduleName The name of the module
* @return boolean Whether the specified module exists and is an app module
*/
function isAppModuleExists($moduleName) {
return $this->isModuleExists($this->getAppModulesDir(), $moduleName);
}
// /**
// * Magic get method that tries to load modules if the the requested property is not found
// * @param string $key The key of the property or module name to get.
// * @return mixed The data. Null if data with the given key is not set.
// */
// function __get($key) {
// // if (property_exists($this, $key))
// // return $this->$key;
// if ($this->loadUnknownModule($key, MODULE_LOADING_ORIGIN_GETTER))
// return $this->$key;
// return false;
// }
/**
* Calls the specified static method on all the available Cherrycake and App modules where it's implemented, and then loads those modules
* @param string $methodName The method name to call
*/
function callMethodOnAllModules($methodName) {
// Call the static method
$coreModuleNames = $this->getAvailableCoreModuleNamesWithMethod($methodName);
if (is_array($coreModuleNames)) {
foreach ($coreModuleNames as $coreModuleName) {
forward_static_call(["\\Cherrycake\\".$coreModuleName."\\".$coreModuleName, $methodName]);
}
reset($coreModuleNames);
}
$appModuleNames = $this->getAvailableAppModuleNamesWithMethod($methodName);
if (is_array($appModuleNames)) {
foreach ($appModuleNames as $appModuleName) {
forward_static_call(["\\".$this->getAppNamespace()."\\".$appModuleName."\\".$appModuleName, $methodName]);
}
reset($appModuleNames);
}
// Load the modules
// if (is_array($coreModuleNames)) {
// foreach ($coreModuleNames as $coreModuleName) {
// $this->loadCoreModule($coreModuleName);
// }
// }
// if (is_array($appModuleNames)) {
// foreach ($appModuleNames as $appModuleName) {
// $this->loadAppModule($appModuleName);
// }
// }
}
/**
* Attends the request received from a web server by calling Actions::run with the requested URI string
*/
function attendWebRequest() {
$this->Actions->run($_SERVER["REQUEST_URI"]);
}
/**
* Attends the request received by the PHP cli by calling Actions:run with the first command line argument, which should be a URI
*/
function attendCliRequest() {
global $argv, $argc;
if (!$this->isCli()) {
header("HTTP/1.1 404");
return false;
}
if ($argc < 2) {
$this->Errors->trigger(ERROR_SYSTEM, [
"errorDescription" => "No action name specified"
]);
die;
}
$actionName = $argv[1];
if (!$action = $this->Actions->getAction($actionName)) {
$this->Errors->trigger(ERROR_SYSTEM, [
"errorDescription" => "Unknown action",
"errorVariables" => [
"actionName" => $actionName
]
]);
die;
}
// If it has get parameters, parse them and put them in $_GET
$_GET = $this->parseCommandLineArguments(array_slice($argv, 2));
if (!$action->request->retrieveParameterValues())
die;
$action->run();
}
/**
* Method by mbirth@webwriters.de found at https://www.php.net/manual/en/function.getopt.php#83414
* @param array $params The array of parameters to parse, as received by $GLOBALS['argv']. Usually, array_slice($GLOBALS['argv'], 1) will be passed to first remove the first item, which is the executable name
* @param array $noopt An array of parameter names that aren't optional
* @return array A hash array of each found parameter as the key, and its values
*/
function parseCommandLineArguments($params, $noopt = array()) {
$result = array();
// could use getopt() here (since PHP 5.3.0), but it doesn't work relyingly
reset($params);
foreach ($params as $tmp => $p) {
if ($p[0] == '-') {
$pname = substr($p, 1);
$value = true;
if ($pname[0] == '-') {
// long-opt (--<param>)
$pname = substr($pname, 1);
if (strpos($p, '=') !== false) {
// value specified inline (--<param>=<value>)
list($pname, $value) = explode('=', substr($p, 2), 2);
}
}
// check if next parameter is a descriptor or a value
$nextparm = current($params);
if (!in_array($pname, $noopt) && $value === true && $nextparm !== false && $nextparm[0] != '-') list($tmp, $value) = each($params);
$result[$pname] = $value;
} else {
// param doesn't belong to any option
$result[] = $p;
}
}
return $result;
}
/**
* Returns information about the engine and its current status, including the loaded modules, the mapped actions and some benchmarks.
* Note that some information on the return array will be missing if the isDevel option has not been activated when initializing the engine.
*
* @return array A hash array with the information
*/
function getStatus() {
$r = [
"appNamespace" => $this->getAppNamespace(),
"appName" => $this->getAppName(),
"isDevel" => $this->isDevel(),
"isUnderMaintenance" => $this->isUnderMaintenance(),
"documentRoot" => $_SERVER["DOCUMENT_ROOT"],
"appModulesDir" => $this->getAppModulesDir(),
"appClassesDir" => $this->getAppClassesDir(),
"timezoneName" => $this->getTimezonename(),
"timezoneId" => $this->getTimezoneId(),
"executionStartHrTime" => $this->executionStartHrTime,
"runningHrTime" =>
$this->isDevel() ?
hrtime(true) - $this->executionStartHrTime
:
null,
"memoryUse" => memory_get_usage(),
"memoryUsePeak" => memory_get_peak_usage(),
"memoryAllocated" => memory_get_usage(true),
"memoryAllocatedPeak" => memory_get_peak_usage(true),
"hostname" => $_SERVER["HOSTNAME"] ?? false,
"host" => $_SERVER["HTTP_HOST"] ?? false,
"ip" => $_SERVER["REMOTE_ADDR"] ?? false,
"os" => PHP_OS,
"phpVersion" => phpversion(),
"serverSoftware" => $_SERVER["SERVER_SOFTWARE"],
"serverGatewayInterface" => $_SERVER["GATEWAY_INTERFACE"],
"serverApi" => PHP_SAPI
];
if (is_array($this->loadedModules))
$r["loadedModules"] = $this->loadedModules;
if (is_array($this->moduleLoadingHistory)) {
$lastHrTime = null;
$r["moduleLoadingHistory"] = $this->moduleLoadingHistory;
reset($this->moduleLoadingHistory);
}
if ($this->isModuleLoaded("Actions"))
$r["actions"] = $this->Actions->getStatus();
if ($this->isModuleLoaded("Css"))
$r["css"] = $this->Css->getStatus();
if ($this->isModuleLoaded("Javascript"))
$r["javascript"] = $this->Javascript->getStatus();
return $r;
}
/**
* Returns a human-readable version of the status information provided by the getStatus method.
* @return array A hash array with the status information in a human readable format
*/
function getStatusHumanReadable() {
$status = $this->getStatus();
foreach ($status as $key => $value) {
switch ($key) {
case "runningHrTime":
$r[$key] = number_format($value / 1000000, 4)."ms";
break;
case "moduleLoadingHistory":
foreach ($value as $historyItem) {
if ($historyItem["isAlreadyLoaded"] ?? false)
continue;
$r[$key][] =
$historyItem["namespace"]."/".$historyItem["loadedModule"].
" / ".
[
MODULE_LOADING_ORIGIN_MANUAL => "Manually loaded",
MODULE_LOADING_ORIGIN_BASE => "Base module",
MODULE_LOADING_ORIGIN_DEPENDENCY => "Required by ".$historyItem["requiredBy"],
MODULE_LOADING_ORIGIN_AUTOLOAD => "Autoloaded",
MODULE_LOADING_ORIGIN_GETTER => "Loaded in getter"
][$historyItem["origin"]].
" / loaded at ".number_format(($historyItem["loadingStartHrTime"] - $status["executionStartHrTime"]) / 1000000, 4)."ms".
($historyItem["initEndHrTime"] ?? false ?
" / init took ".number_format(($historyItem["initEndHrTime"] - $historyItem["initStartHrTime"]) / 1000000, 4)."ms"
:
" / didn't finish"
);
}
break;
case "actions":
$r[$key] = $value["brief"] ?? false;
break;
default:
$r[$key] = $value;
break;
}
}
return $r;
}
/**
* Returns an HTML version of the status in a human readable format.
* @return string The HTML code
*/
function getStatusHtml() {
return prettyprint($this->getStatusHumanReadable(), true);
}
/**
* Ends the application by calling the end methods of all the loaded modules.
*/
function end() {
if (is_array($this->loadedModules))
foreach ($this->loadedModules as $moduleName)
$this->$moduleName->end();
die;
}
}
/**
* A helper function that pretty prints out a variable for debugging purposes
* @param $var The variable to debug
*/
function prettyprint($var, $isReturn = false, $isHtml = true) {
$pretty =
($isHtml ? "<pre>" : null).
print_r($var, true). //json_encode($var, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS).
($isHtml ? "<pre>" : null);
if ($isReturn)
return $pretty;
else
echo $pretty;
}