Passed
Push — fix_868 ( 40f1e3...04efbf )
by Fabio
12:45 queued 08:02
created

Prado::autoload()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
/**
3
 * Prado class file.
4
 *
5
 * This is the file that establishes the PRADO component model
6
 * and error handling mechanism.
7
 *
8
 * @author Qiang Xue <[email protected]>
9
 * @link https://github.com/pradosoft/prado
10
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
11
 */
12
13
namespace Prado;
14
15
use Prado\Exceptions\TInvalidDataValueException;
16
use Prado\Exceptions\TInvalidOperationException;
17
use Prado\Exceptions\TPhpErrorException;
18
use Prado\Exceptions\TPhpFatalErrorException;
19
use Prado\Util\TLogger;
20
use Prado\Util\TVarDumper;
21
use Prado\I18N\Translation;
22
23
// Defines the PRADO framework installation path.
24
if (!defined('PRADO_DIR')) {
25
	define('PRADO_DIR', __DIR__);
26
}
27
28
// Defines the default permission for writable directories
29
// @todo, the test on PRADO_CHMOD must be remove in the next major release
30
if (!defined('PRADO_DIR_CHMOD')) {
31
	define('PRADO_DIR_CHMOD', !defined('PRADO_CHMOD') ? 0755 : PRADO_CHMOD);
32
}
33
34
// Defines the default permission for writable files
35
// @todo, the test on PRADO_CHMOD must be removed in the next major release
36
if (!defined('PRADO_FILE_CHMOD')) {
37
	define('PRADO_FILE_CHMOD', !defined('PRADO_CHMOD') ? 0644 : PRADO_CHMOD);
38
}
39
40
// Defines the default permission for writable directories and files
41
// @todo, adding this define must be removed in the next major release
42
if (!defined('PRADO_CHMOD')) {
43
	define('PRADO_CHMOD', 0777);
44
}
45
46
// Defines the Composer's vendor/ path.
47
if (!defined('PRADO_VENDORDIR')) {
48
	$reflector = new \ReflectionClass('\Composer\Autoload\ClassLoader');
49
	define('PRADO_VENDORDIR', dirname((string) $reflector->getFileName(), 2));
50
	unset($reflector);
51
}
52
53
/**
54
 * Prado class.
55
 *
56
 * Prado implements a few fundamental static methods.
57
 *
58
 * To use the static methods, Use Prado as the class name rather than Prado.
59
 * Prado is meant to serve as the base class of Prado. The latter might be
60
 * rewritten for customization.
61
 *
62
 * @author Qiang Xue <[email protected]>
63
 * @since 3.0
64
 */
65
class Prado
66
{
67
	/**
68
	 * File extension for Prado class files.
69
	 */
70
	public const CLASS_FILE_EXT = '.php';
71
	/**
72
	 * @var array<string, string> list of path aliases
73
	 */
74
	private static $_aliases = [
75
		'Prado' => PRADO_DIR,
76
		'Vendor' => PRADO_VENDORDIR
77
		];
78
	/**
79
	 * @var array<string, string> list of namespaces currently in use
80
	 */
81
	private static $_usings = [
82
		'Prado' => PRADO_DIR
83
		];
84
	/**
85
	 * @var array<string, string> list of namespaces currently in use
86
	 */
87
	public static $classMap = [];
88
	/**
89
	 * @var null|TApplication the application instance
90
	 */
91
	private static $_application;
92
	/**
93
	 * @var null|TLogger logger instance
94
	 */
95
	private static $_logger;
96
	/**
97
	 * @var array<string, bool> list of class exists checks
98
	 */
99
	protected static $classExists = [];
100
	/**
101
	 * @return string the version of Prado framework
102
	 */
103
	public static function getVersion(): string
104
	{
105
		return '4.2.1';
106
	}
107
108
	/**
109
	 * Initializes the Prado static class
110
	 */
111
	public static function init(): void
112
	{
113
		static::initAutoloader();
114
		static::initErrorHandlers();
115
	}
116
117
	/**
118
	 * Loads the static classmap and registers the autoload function.
119
	 */
120
	public static function initAutoloader(): void
121
	{
122
		self::$classMap = require(__DIR__ . '/classes.php');
123
124
		spl_autoload_register([static::class, 'autoload']);
125
	}
126
127
	/**
128
	 * Initializes error handlers.
129
	 * This method set error and exception handlers to be functions
130
	 * defined in this class.
131
	 */
132
	public static function initErrorHandlers(): void
133
	{
134
		/**
135
		 * Sets error handler to be Prado::phpErrorHandler
136
		 */
137
		set_error_handler([static::class, 'phpErrorHandler']);
138
		/**
139
		 * Sets shutdown function to be Prado::phpFatalErrorHandler
140
		 */
141
		register_shutdown_function([static::class, 'phpFatalErrorHandler']);
142
		/**
143
		 * Sets exception handler to be Prado::exceptionHandler
144
		 */
145
		set_exception_handler([static::class, 'exceptionHandler']);
146
		/**
147
		 * Disable php's builtin error reporting to avoid duplicated reports
148
		 */
149
		ini_set('display_errors', '0');
150
	}
151
152
	/**
153
	 * Class autoload loader.
154
	 * This method is provided to be registered within an spl_autoload_register() method.
155
	 * @param string $className class name
156
	 */
157
	public static function autoload($className): void
158
	{
159
		static::using($className);
160
	}
161
162
	/**
163
	 * @param int $logoType the type of "powered logo". Valid values include 0 and 1.
164
	 * @return string a string that can be displayed on your Web page showing powered-by-PRADO information
165
	 */
166
	public static function poweredByPrado($logoType = 0): string
167
	{
168
		$logoName = $logoType == 1 ? 'powered2' : 'powered';
169
		if (self::$_application !== null) {
170
			$am = self::$_application->getAssetManager();
171
			$url = $am->publishFilePath((string) self::getPathOfNamespace('Prado\\' . $logoName, '.gif'));
172
		} else {
173
			$url = 'http://pradosoft.github.io/docs/' . $logoName . '.gif';
174
		}
175
		return '<a title="Powered by PRADO" href="https://github.com/pradosoft/prado" target="_blank"><img src="' . $url . '" style="border-width:0px;" alt="Powered by PRADO" /></a>';
176
	}
177
178
	/**
179
	 * PHP error handler.
180
	 * This method should be registered as PHP error handler using
181
	 * {@link set_error_handler}. The method throws an exception that
182
	 * contains the error information.
183
	 * @param int $errno the level of the error raised
184
	 * @param string $errstr the error message
185
	 * @param string $errfile the filename that the error was raised in
186
	 * @param int $errline the line number the error was raised at
187
	 */
188
	public static function phpErrorHandler($errno, $errstr, $errfile, $errline): bool
189
	{
190
		if (error_reporting() & $errno) {
191
			throw new TPhpErrorException($errno, $errstr, $errfile, $errline);
192
		}
193
		return true;
194
	}
195
196
	/**
197
	 * PHP shutdown function used to catch fatal errors.
198
	 * This method should be registered as PHP error handler using
199
	 * {@link register_shutdown_function}. The method throws an exception that
200
	 * contains the error information.
201
	 */
202
	public static function phpFatalErrorHandler(): void
203
	{
204
		$error = error_get_last();
205
		if ($error &&
206
			TPhpErrorException::isFatalError($error) &&
207
			error_reporting() & $error['type']) {
208
			self::exceptionHandler(new TPhpFatalErrorException($error['type'], $error['message'], $error['file'], $error['line']));
209
		}
210
	}
211
212
	/**
213
	 * Default exception handler.
214
	 * This method should be registered as default exception handler using
215
	 * {@link set_exception_handler}. The method tries to use the errorhandler
216
	 * module of the Prado application to handle the exception.
217
	 * If the application or the module does not exist, it simply echoes the
218
	 * exception.
219
	 * @param \Throwable $exception exception that is not caught
220
	 */
221
	public static function exceptionHandler($exception): void
222
	{
223
		if (self::$_application !== null && ($errorHandler = self::$_application->getErrorHandler()) !== null) {
224
			$errorHandler->handleError(null, $exception);
225
		} else {
226
			echo $exception;
227
		}
228
		exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
229
	}
230
231
	/**
232
	 * Stores the application instance in the class static member.
233
	 * This method helps implement a singleton pattern for TApplication.
234
	 * Repeated invocation of this method or the application constructor
235
	 * will cause the throw of an exception.
236
	 * This method should only be used by framework developers.
237
	 * @param TApplication $application the application instance
238
	 * @throws TInvalidOperationException if this method is invoked twice or more.
239
	 */
240
	public static function setApplication($application): void
241
	{
242
		if (self::$_application !== null && !defined('PRADO_TEST_RUN')) {
243
			throw new TInvalidOperationException('prado_application_singleton_required');
244
		}
245
		self::$_application = $application;
246
	}
247
248
	/**
249
	 * @return null|TApplication the application singleton, null if the singleton has not be created yet.
250
	 */
251
	public static function getApplication(): ?TApplication
252
	{
253
		return self::$_application;
254
	}
255
256
	/**
257
	 * @return string the path of the framework
258
	 */
259
	public static function getFrameworkPath(): string
260
	{
261
		return PRADO_DIR;
262
	}
263
264
	/**
265
	 * @deprecated deprecated since version 4.2.2, replaced by @getDefaultDirPermissions and @getDefaultFilePermissions
266
	 * @return int chmod permissions, defaults to 0777
267
	 */
268
	public static function getDefaultPermissions(): int
269
	{
270
		return PRADO_CHMOD;
271
	}
272
273
	/**
274
	 * @return int chmod dir permissions, defaults to 0755
275
	 */
276
	public static function getDefaultDirPermissions(): int
277
	{
278
		return PRADO_DIR_CHMOD;
279
	}
280
281
	/**
282
	 * @return int chmod file permissions, defaults to 0644
283
	 */
284
	public static function getDefaultFilePermissions(): int
285
	{
286
		return PRADO_FILE_CHMOD;
287
	}
288
289
	/**
290
	 * Convert old Prado namespaces to PHP namespaces
291
	 * @param string $type old class name in Prado3 namespace format
292
	 * @return string Equivalent class name in PHP namespace format
293
	 */
294
	protected static function prado3NamespaceToPhpNamespace($type): string
295
	{
296
		if (substr($type, 0, 6) === 'System') {
297
			$type = 'Prado' . substr($type, 6);
298
		}
299
300
		if (false === strpos($type, '\\')) {
301
			return str_replace('.', '\\', $type);
302
		} else {
303
			return $type;
304
		}
305
	}
306
307
	/**
308
	 * Creates a component with the specified type.
309
	 * A component type can be either the component class name
310
	 * or a namespace referring to the path of the component class file.
311
	 * For example, 'TButton', '\Prado\Web\UI\WebControls\TButton' are both
312
	 * valid component type.
313
	 * This method can also pass parameters to component constructors.
314
	 * All parameters passed to this method except the first one (the component type)
315
	 * will be supplied as component constructor parameters.
316
	 * @template T
317
	 * @param class-string<T> $requestedType component type
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
318
	 * @param array<mixed> $params
319
	 * @throws TInvalidDataValueException if the component type is unknown
320
	 * @return T component instance of the specified type
321
	 */
322
	public static function createComponent($requestedType, ...$params)
323
	{
324
		$properties = null;
325
		if (is_array($requestedType)) {
326
			$properties = $requestedType;
327
			$requestedType = $properties['class'];
328
			unset($properties['class']);
329
		}
330
		$type = static::prado3NamespaceToPhpNamespace($requestedType);
331
		if (!isset(self::$classExists[$type])) {
332
			self::$classExists[$type] = class_exists($type, false);
333
		}
334
335
		if (!isset(self::$_usings[$type]) && !self::$classExists[$type]) {
336
			static::using($type);
337
			self::$classExists[$type] = class_exists($type, false);
338
		}
339
340
		/*
341
		 * Old apps compatibility support: if the component name has been specified using the
342
		 * old namespace syntax (eg. Application.Common.MyDataModule), assume that the calling
343
		 * code expects the class not to be php5.3-namespaced (eg: MyDataModule instead of
344
		 * \Application\Common\MyDataModule)
345
		 * Skip this if the class is inside the Prado\* namespace, since all Prado classes are now namespaced
346
		 */
347
		if (($pos = strrpos($type, '\\')) !== false && ($requestedType != $type) && strpos($type, 'Prado\\') !== 0) {
348
			$type = substr($type, $pos + 1);
349
		}
350
351
		if (count($params) > 0) {
352
			$object = new $type(...$params);
353
		} else {
354
			$object = new $type();
355
		}
356
		if ($properties) {
357
			foreach ($properties as $property => $value) {
358
				$object->setSubProperty($property, $value);
359
			}
360
		}
361
		return $object;
362
	}
363
364
	/**
365
	 * Uses a namespace.
366
	 * A namespace ending with an asterisk '*' refers to a directory, otherwise it represents a PHP file.
367
	 * If the namespace corresponds to a directory, the directory will be appended
368
	 * to the include path. If the namespace corresponds to a file, it will be included (include_once).
369
	 * @param string $namespace namespace to be used
370
	 * @throws TInvalidDataValueException if the namespace is invalid
371
	 */
372
	public static function using($namespace): void
373
	{
374
		$namespace = static::prado3NamespaceToPhpNamespace($namespace);
375
376
		if (isset(self::$_usings[$namespace]) ||
377
			class_exists($namespace, false) ||
378
			interface_exists($namespace, false)) {
379
			return;
380
		}
381
382
		if (array_key_exists($namespace, self::$classMap)) {
383
			// fast autoload a Prado3 class name
384
			$phpNamespace = self::$classMap[$namespace];
385
			if (class_exists($phpNamespace, true) || interface_exists($phpNamespace, true)) {
386
				if (!class_exists($namespace) && !interface_exists($namespace)) {
387
					class_alias($phpNamespace, $namespace);
388
				}
389
				return;
390
			}
391
		} elseif (($pos = strrpos($namespace, '\\')) === false) {
392
			// trying to autoload an old class name
393
			foreach (self::$_usings as $k => $v) {
394
				$path = $v . DIRECTORY_SEPARATOR . $namespace . self::CLASS_FILE_EXT;
395
				if (file_exists($path)) {
396
					$phpNamespace = '\\' . $k . '\\' . $namespace;
397
					if (class_exists($phpNamespace, true) || interface_exists($phpNamespace, true)) {
398
						if (!class_exists($namespace) && !interface_exists($namespace)) {
399
							class_alias($phpNamespace, $namespace);
400
						}
401
						return;
402
					}
403
				}
404
			}
405
		} elseif (($path = self::getPathOfNamespace($namespace, self::CLASS_FILE_EXT)) !== null) {
406
			$className = substr($namespace, $pos + 1);
407
			if ($className === '*') {  // a directory
408
				self::$_usings[substr($namespace, 0, $pos)] = $path;
409
			} else {  // a file
410
				if (class_exists($className, false) || interface_exists($className, false)) {
411
					return;
412
				}
413
414
				if (file_exists($path)) {
415
					include_once($path);
416
					if (!class_exists($className, false) && !interface_exists($className, false)) {
417
						class_alias($namespace, $className);
418
					}
419
				}
420
			}
421
		}
422
	}
423
424
	/**
425
	 * Translates a namespace into a file path.
426
	 * The first segment of the namespace is considered as a path alias
427
	 * which is replaced with the actual path. The rest segments are
428
	 * subdirectory names appended to the aliased path.
429
	 * If the namespace ends with an asterisk '*', it represents a directory;
430
	 * Otherwise it represents a file whose extension name is specified by the second parameter (defaults to empty).
431
	 * Note, this method does not ensure the existence of the resulting file path.
432
	 * @param string $namespace namespace
433
	 * @param string $ext extension to be appended if the namespace refers to a file
434
	 * @return null|string file path corresponding to the namespace, null if namespace is invalid
435
	 */
436
	public static function getPathOfNamespace($namespace, $ext = ''): ?string
437
	{
438
		$namespace = static::prado3NamespaceToPhpNamespace($namespace);
439
440
		if (self::CLASS_FILE_EXT === $ext || empty($ext)) {
441
			if (isset(self::$_usings[$namespace])) {
442
				return self::$_usings[$namespace];
443
			}
444
445
			if (isset(self::$_aliases[$namespace])) {
446
				return self::$_aliases[$namespace];
447
			}
448
		}
449
450
		$segs = explode('\\', $namespace);
451
		$alias = array_shift($segs);
452
453
		if (null !== ($file = array_pop($segs)) && null !== ($root = self::getPathOfAlias($alias))) {
454
			return rtrim($root . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $segs), '/\\') . (($file === '*') ? '' : DIRECTORY_SEPARATOR . $file . $ext);
455
		}
456
457
		return null;
458
	}
459
460
	/**
461
	 * @param string $alias alias to the path
462
	 * @return null|string the path corresponding to the alias, null if alias not defined.
463
	 */
464
	public static function getPathOfAlias($alias): ?string
465
	{
466
		return self::$_aliases[$alias] ?? null;
467
	}
468
469
	/**
470
	 * @return array<string, string> list of path aliases
471
	 */
472
	protected static function getPathAliases(): array
473
	{
474
		return self::$_aliases;
475
	}
476
477
	/**
478
	 * @param string $alias alias to the path
479
	 * @param string $path the path corresponding to the alias
480
	 * @throws TInvalidOperationException $alias if the alias is already defined
481
	 * @throws TInvalidDataValueException $path if the path is not a valid file path
482
	 */
483
	public static function setPathOfAlias($alias, $path): void
484
	{
485
		if (isset(self::$_aliases[$alias]) && !defined('PRADO_TEST_RUN')) {
486
			throw new TInvalidOperationException('prado_alias_redefined', $alias);
487
		} elseif (($rp = realpath($path)) !== false && is_dir($rp)) {
488
			if (strpos($alias, '.') === false) {
489
				self::$_aliases[$alias] = $rp;
490
			} else {
491
				throw new TInvalidDataValueException('prado_aliasname_invalid', $alias);
492
			}
493
		} else {
494
			throw new TInvalidDataValueException('prado_alias_invalid', $alias, $path);
495
		}
496
	}
497
498
	/**
499
	 * Fatal error handler.
500
	 * This method displays an error message together with the current call stack.
501
	 * The application will exit after calling this method.
502
	 * @param string $msg error message
503
	 */
504
	public static function fatalError($msg): void
505
	{
506
		echo '<h1>Fatal Error</h1>';
507
		echo '<p>' . $msg . '</p>';
508
		if (!function_exists('debug_backtrace')) {
509
			return;
510
		}
511
		echo '<h2>Debug Backtrace</h2>';
512
		echo '<pre>';
513
		$index = -1;
514
		foreach (debug_backtrace() as $t) {
515
			$index++;
516
			if ($index == 0) {  // hide the backtrace of this function
517
				continue;
518
			}
519
			echo '#' . $index . ' ';
520
			if (isset($t['file'])) {
521
				echo basename($t['file']) . ':' . $t['line'];
522
			} else {
523
				echo '<PHP inner-code>';
524
			}
525
			echo ' -- ';
526
			if (isset($t['class'])) {
527
				echo $t['class'] . $t['type'];
528
			}
529
			echo $t['function'] . '(';
530
			if (isset($t['args']) && count($t['args']) > 0) {
531
				$count = 0;
532
				foreach ($t['args'] as $item) {
533
					if (is_string($item)) {
534
						$str = htmlentities(str_replace("\r\n", "", $item), ENT_QUOTES);
535
						if (strlen($item) > 70) {
536
							echo "'" . substr($str, 0, 70) . "...'";
537
						} else {
538
							echo "'" . $str . "'";
539
						}
540
					} elseif (is_int($item) || is_float($item)) {
541
						echo $item;
542
					} elseif (is_object($item)) {
543
						echo get_class($item);
544
					} elseif (is_array($item)) {
545
						echo 'array(' . count($item) . ')';
546
					} elseif (is_bool($item)) {
547
						echo $item ? 'true' : 'false';
548
					} elseif ($item === null) {
549
						echo 'NULL';
550
					} elseif (is_resource($item)) {
551
						echo get_resource_type($item);
552
					}
553
					$count++;
554
					if (count($t['args']) > $count) {
555
						echo ', ';
556
					}
557
				}
558
			}
559
			echo ")\n";
560
		}
561
		echo '</pre>';
562
		exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
563
	}
564
565
	/**
566
	 * Returns a list of user preferred languages.
567
	 * The languages are returned as an array. Each array element
568
	 * represents a single language preference. The languages are ordered
569
	 * according to user preferences. The first language is the most preferred.
570
	 * @return array<string> list of user preferred languages.
571
	 */
572
	public static function getUserLanguages(): array
573
	{
574
		static $languages = null;
575
		if ($languages === null) {
576
			if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
577
				$languages[0] = 'en';
578
			} else {
579
				$languages = [];
580
				foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $language) {
581
					$array = explode(';q=', trim($language));
582
					$languages[trim($array[0])] = isset($array[1]) ? (float) $array[1] : 1.0;
583
				}
584
				arsort($languages);
585
				$languages = array_keys($languages);
586
				if (count($languages) == 0) {
587
					$languages[0] = 'en';
588
				}
589
			}
590
		}
591
		return $languages;
592
	}
593
594
	/**
595
	 * Returns the most preferred language by the client user.
596
	 * @return string the most preferred language by the client user, defaults to English.
597
	 */
598
	public static function getPreferredLanguage(): string
599
	{
600
		static $language = null;
601
		if ($language === null) {
602
			$langs = Prado::getUserLanguages();
603
			$lang = explode('-', $langs[0]);
604
			if (empty($lang[0]) || !ctype_alpha($lang[0])) {
605
				$language = 'en';
606
			} else {
607
				$language = $lang[0];
608
			}
609
		}
610
		return $language;
611
	}
612
613
	/**
614
	 * Writes a log message.
615
	 * This method wraps {@link log()} by checking the application mode.
616
	 * When the application is in Debug mode, debug backtrace information is appended
617
	 * to the message and the message is logged at DEBUG level.
618
	 * When the application is in Performance mode, this method does nothing.
619
	 * Otherwise, the message is logged at INFO level.
620
	 * @param string $msg message to be logged
621
	 * @param string $category category of the message
622
	 * @param null|\Prado\Web\UI\TControl|string $ctl control of the message
623
	 * @see log, getLogger
624
	 */
625
	public static function trace($msg, $category = 'Uncategorized', $ctl = null): void
626
	{
627
		if (self::$_application && self::$_application->getMode() === TApplicationMode::Performance) {
628
			return;
629
		}
630
		if (!self::$_application || self::$_application->getMode() === TApplicationMode::Debug) {
631
			$trace = debug_backtrace();
632
			if (isset($trace[0]['file']) && isset($trace[0]['line'])) {
633
				$msg .= " (line {$trace[0]['line']}, {$trace[0]['file']})";
634
			}
635
			$level = TLogger::DEBUG;
636
		} else {
637
			$level = TLogger::INFO;
638
		}
639
		self::log($msg, $level, $category, $ctl);
640
	}
641
642
	/**
643
	 * Logs a message.
644
	 * Messages logged by this method may be retrieved via {@link TLogger::getLogs}
645
	 * and may be recorded in different media, such as file, email, database, using
646
	 * {@link TLogRouter}.
647
	 * @param string $msg message to be logged
648
	 * @param int $level level of the message. Valid values include
649
	 * TLogger::DEBUG, TLogger::INFO, TLogger::NOTICE, TLogger::WARNING,
650
	 * TLogger::ERROR, TLogger::ALERT, TLogger::FATAL.
651
	 * @param string $category category of the message
652
	 * @param null|\Prado\Web\UI\TControl|string $ctl control of the message
653
	 */
654
	public static function log($msg, $level = TLogger::INFO, $category = 'Uncategorized', $ctl = null): void
655
	{
656
		if (self::$_logger === null) {
657
			self::$_logger = new TLogger();
658
		}
659
		self::$_logger->log($msg, $level, $category, $ctl);
660
	}
661
662
	/**
663
	 * @return TLogger message logger
664
	 */
665
	public static function getLogger(): TLogger
666
	{
667
		if (self::$_logger === null) {
668
			self::$_logger = new TLogger();
669
		}
670
		return self::$_logger;
671
	}
672
673
	/**
674
	 * Converts a variable into a string representation.
675
	 * This method achieves the similar functionality as var_dump and print_r
676
	 * but is more robust when handling complex objects such as PRADO controls.
677
	 * @param mixed $var variable to be dumped
678
	 * @param int $depth maximum depth that the dumper should go into the variable. Defaults to 10.
679
	 * @param bool $highlight whether to syntax highlight the output. Defaults to false.
680
	 * @return string the string representation of the variable
681
	 */
682
	public static function varDump($var, $depth = 10, $highlight = false): string
683
	{
684
		return TVarDumper::dump($var, $depth, $highlight);
685
	}
686
687
	/**
688
	 * Localize a text to the locale/culture specified in the globalization handler.
689
	 * @param string $text text to be localized.
690
	 * @param array<string, string> $parameters a set of parameters to substitute.
691
	 * @param string $catalogue a different catalogue to find the localize text.
692
	 * @param string $charset the input AND output charset.
693
	 * @return string localized text.
694
	 * @see TTranslate::formatter()
695
	 * @see TTranslate::init()
696
	 */
697
	public static function localize($text, $parameters = [], $catalogue = null, $charset = null): string
698
	{
699
		$params = [];
700
		foreach ($parameters as $key => $value) {
701
			$params['{' . $key . '}'] = $value;
702
		}
703
704
		// no translation handler provided
705
		if (self::$_application === null
706
			|| ($app = self::$_application->getGlobalization(false)) === null
707
			|| ($config = $app->getTranslationConfiguration()) === null) {
708
			return strtr($text, $params);
709
		}
710
711
		if ($catalogue === null) {
712
			$catalogue = $config['catalogue'] ?? 'messages';
713
		}
714
715
		Translation::init($catalogue);
716
717
		//globalization charset
718
		if (empty($charset)) {
719
			$charset = $app->getCharset();
720
		}
721
722
		//default charset
723
		if (empty($charset)) {
724
			$charset = $app->getDefaultCharset();
725
		}
726
727
		return Translation::formatter($catalogue)->format($text, $params, $catalogue, $charset);
728
	}
729
}
730
731
/**
732
 * Initialize Prado autoloader and error handler
733
 */
734
Prado::init();
735
736
/**
737
 * Defines Prado in global namespace
738
 */
739
class_alias('\Prado\Prado', 'Prado');
740