Passed
Push — master ( 4fc6c5...494471 )
by Fabio
07:54 queued 03:10
created

Prado::isCallingSelf()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 2
nc 4
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 0
cts 0
cp 0
crap 20
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') ? 0o755 : PRADO_CHMOD);
0 ignored issues
show
Bug introduced by
The constant Prado\0o755 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
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') ? 0o644 : PRADO_CHMOD);
0 ignored issues
show
Bug introduced by
The constant Prado\0o644 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
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', 0o777);
0 ignored issues
show
Bug introduced by
The constant Prado\0o777 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
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.2';
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
			trait_exists($namespace, false)) {
380
			return;
381
		}
382
383
		if (array_key_exists($namespace, self::$classMap)) {
384
			// fast autoload a Prado3 class name
385
			$phpNamespace = self::$classMap[$namespace];
386
			if (class_exists($phpNamespace, true) ||
387
				interface_exists($phpNamespace, true) ||
388
				trait_exists($phpNamespace, true)) {
389
				if (!class_exists($namespace) &&
390
					!interface_exists($namespace) &&
391
					!trait_exists($namespace)) {
392
					class_alias($phpNamespace, $namespace);
393
				}
394
				return;
395
			}
396
		} elseif (($pos = strrpos($namespace, '\\')) === false) {
397
			// trying to autoload an old class name
398
			foreach (self::$_usings as $k => $v) {
399
				$path = $v . DIRECTORY_SEPARATOR . $namespace . self::CLASS_FILE_EXT;
400
				if (file_exists($path)) {
401
					$phpNamespace = '\\' . $k . '\\' . $namespace;
402
					if (class_exists($phpNamespace, true) ||
403
						interface_exists($phpNamespace, true) ||
404
						trait_exists($phpNamespace, true)) {
405
						if (!class_exists($namespace) &&
406
							!interface_exists($namespace) &&
407
							!trait_exists($namespace)) {
408
							class_alias($phpNamespace, $namespace);
409
						}
410
						return;
411
					}
412
				}
413
			}
414
		} elseif (($path = self::getPathOfNamespace($namespace, self::CLASS_FILE_EXT)) !== null) {
415
			$className = substr($namespace, $pos + 1);
416
			if ($className === '*') {  // a directory
417
				self::$_usings[substr($namespace, 0, $pos)] = $path;
418
			} else {  // a file
419
				if (class_exists($className, false) ||
420
					interface_exists($className, false) ||
421
					trait_exists($className, false)) {
422
					return;
423
				}
424
425
				if (file_exists($path)) {
426
					include_once($path);
427
					if (!class_exists($className, false) &&
428
						!interface_exists($className, false) &&
429
						!trait_exists($className, false)) {
430
						class_alias($namespace, $className);
431
					}
432
				}
433
			}
434
		}
435
	}
436
437
	/**
438
	 * This conforms PHP's Magic Methods to PHP's Visibility standards for public,
439
	 * protected, and private properties, methods, and constants. This method checks
440
	 * if the object calling your method can access your object's property, method,
441
	 * or constant based upon the defined visibility.  External objects can only access
442
	 * public properties, methods, and constants.  When calling the self, private
443
	 * properties, methods, and constants are allowed to be accessed by the same class.
444
	 * @param object|string $object_or_class The object to check for the method within
445
	 *   and for visibility to the calling object.
446
	 * @param string $method
447
	 * @return bool Does the method exist and is publicly callable.
448
	 * @since 4.2.3
449
	 */
450
	public static function method_visible($object_or_class, string $method): bool
451
	{
452
		if (method_exists($object_or_class, $method)) {
453
			$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 3);
454
			$reflection = new \ReflectionMethod($object_or_class, $method);
455
			if (empty($trace[2]) || empty($trace[1]['object']) || empty($trace[2]['object']) || $trace[1]['object'] !== $trace[2]['object']) {
456
				return $reflection->isPublic();
457
			} elseif ($reflection->isPrivate()) {
458
				return $trace[2]['class'] === $reflection->class;
459
			}
460
			return true;
461
		}
462
		return false;
463
	}
464
465
	/**
466
	 * This checks if object calling your object method is the same object.  In effect,
467
	 * this signifies if self, parents, and children have visibility to "protected"
468
	 * properties, methods, and constants.
469
	 * @return bool Does the method exist and is publicly callable.
470
	 * @since 4.2.3
471
	 */
472
	public static function isCallingSelf(): bool
473
	{
474
		$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 3);
475
		return isset($trace[2]) && isset($trace[1]['object']) && isset($trace[2]['object']) && $trace[1]['object'] === $trace[2]['object'];
476
	}
477
478
	/**
479
	 * This checks if object calling your object method is the same object and same class.
480
	 * In effect, this allows only the self to have visibility to "private" properties,
481
	 * methods, and constants.
482
	 * @return bool Does the method exist and is publicly callable.
483
	 * @since 4.2.3
484
	 */
485
	public static function isCallingSelfClass(): bool
486
	{
487
		$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 3);
488
		return isset($trace[2]) && isset($trace[1]['object']) && isset($trace[2]['object']) && $trace[1]['object'] === $trace[2]['object'] && $trace[1]['class'] === $trace[2]['class'];
489
	}
490
491
	/**
492
	 * Translates a namespace into a file path.
493
	 * The first segment of the namespace is considered as a path alias
494
	 * which is replaced with the actual path. The rest segments are
495
	 * subdirectory names appended to the aliased path.
496
	 * If the namespace ends with an asterisk '*', it represents a directory;
497
	 * Otherwise it represents a file whose extension name is specified by the second parameter (defaults to empty).
498
	 * Note, this method does not ensure the existence of the resulting file path.
499
	 * @param string $namespace namespace
500
	 * @param string $ext extension to be appended if the namespace refers to a file
501
	 * @return null|string file path corresponding to the namespace, null if namespace is invalid
502
	 */
503
	public static function getPathOfNamespace($namespace, $ext = ''): ?string
504
	{
505
		$namespace = static::prado3NamespaceToPhpNamespace($namespace);
506
507
		if (self::CLASS_FILE_EXT === $ext || empty($ext)) {
508
			if (isset(self::$_usings[$namespace])) {
509
				return self::$_usings[$namespace];
510
			}
511
512
			if (isset(self::$_aliases[$namespace])) {
513
				return self::$_aliases[$namespace];
514
			}
515
		}
516
517
		$segs = explode('\\', $namespace);
518
		$alias = array_shift($segs);
519
520
		if (null !== ($file = array_pop($segs)) && null !== ($root = self::getPathOfAlias($alias))) {
521
			return rtrim($root . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $segs), '/\\') . (($file === '*') ? '' : DIRECTORY_SEPARATOR . $file . $ext);
522
		}
523
524
		return null;
525
	}
526
527
	/**
528
	 * @param string $alias alias to the path
529
	 * @return null|string the path corresponding to the alias, null if alias not defined.
530
	 */
531
	public static function getPathOfAlias($alias): ?string
532
	{
533
		return self::$_aliases[$alias] ?? null;
534
	}
535
536
	/**
537
	 * @return array<string, string> list of path aliases
538
	 */
539
	protected static function getPathAliases(): array
540
	{
541
		return self::$_aliases;
542
	}
543
544
	/**
545
	 * @param string $alias alias to the path
546
	 * @param string $path the path corresponding to the alias
547
	 * @throws TInvalidOperationException $alias if the alias is already defined
548
	 * @throws TInvalidDataValueException $path if the path is not a valid file path
549
	 */
550
	public static function setPathOfAlias($alias, $path): void
551
	{
552
		if (isset(self::$_aliases[$alias]) && !defined('PRADO_TEST_RUN')) {
553
			throw new TInvalidOperationException('prado_alias_redefined', $alias);
554
		} elseif (($rp = realpath($path)) !== false && is_dir($rp)) {
555
			if (strpos($alias, '.') === false) {
556
				self::$_aliases[$alias] = $rp;
557
			} else {
558
				throw new TInvalidDataValueException('prado_aliasname_invalid', $alias);
559
			}
560
		} else {
561
			throw new TInvalidDataValueException('prado_alias_invalid', $alias, $path);
562
		}
563
	}
564
565
	/**
566
	 * Fatal error handler.
567
	 * This method displays an error message together with the current call stack.
568
	 * The application will exit after calling this method.
569
	 * @param string $msg error message
570
	 */
571
	public static function fatalError($msg): void
572
	{
573
		echo '<h1>Fatal Error</h1>';
574
		echo '<p>' . $msg . '</p>';
575
		if (!function_exists('debug_backtrace')) {
576
			return;
577
		}
578
		echo '<h2>Debug Backtrace</h2>';
579
		echo '<pre>';
580
		$index = -1;
581
		foreach (debug_backtrace() as $t) {
582
			$index++;
583
			if ($index == 0) {  // hide the backtrace of this function
584
				continue;
585
			}
586
			echo '#' . $index . ' ';
587
			if (isset($t['file'])) {
588
				echo basename($t['file']) . ':' . $t['line'];
589
			} else {
590
				echo '<PHP inner-code>';
591
			}
592
			echo ' -- ';
593
			if (isset($t['class'])) {
594
				echo $t['class'] . $t['type'];
595
			}
596
			echo $t['function'] . '(';
597
			if (isset($t['args']) && count($t['args']) > 0) {
598
				$count = 0;
599
				foreach ($t['args'] as $item) {
600
					if (is_string($item)) {
601
						$str = htmlentities(str_replace("\r\n", "", $item), ENT_QUOTES);
602
						if (strlen($item) > 70) {
603
							echo "'" . substr($str, 0, 70) . "...'";
604
						} else {
605
							echo "'" . $str . "'";
606
						}
607
					} elseif (is_int($item) || is_float($item)) {
608
						echo $item;
609
					} elseif (is_object($item)) {
610
						echo $item::class;
611
					} elseif (is_array($item)) {
612
						echo 'array(' . count($item) . ')';
613
					} elseif (is_bool($item)) {
614
						echo $item ? 'true' : 'false';
615
					} elseif ($item === null) {
616
						echo 'NULL';
617
					} elseif (is_resource($item)) {
618
						echo get_resource_type($item);
619
					}
620
					$count++;
621
					if (count($t['args']) > $count) {
622
						echo ', ';
623
					}
624
				}
625
			}
626
			echo ")\n";
627
		}
628
		echo '</pre>';
629
		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...
630
	}
631
632
	/**
633
	 * Returns a list of user preferred languages.
634
	 * The languages are returned as an array. Each array element
635
	 * represents a single language preference. The languages are ordered
636
	 * according to user preferences. The first language is the most preferred.
637
	 * @return array<string> list of user preferred languages.
638
	 */
639
	public static function getUserLanguages(): array
640
	{
641
		static $languages = null;
642
		if ($languages === null) {
643
			if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
644
				$languages[0] = 'en';
645
			} else {
646
				$languages = [];
647
				foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $language) {
648
					$array = explode(';q=', trim($language));
649
					$languages[trim($array[0])] = isset($array[1]) ? (float) $array[1] : 1.0;
650
				}
651
				arsort($languages);
652
				$languages = array_keys($languages);
653
				if (count($languages) == 0) {
654
					$languages[0] = 'en';
655
				}
656
			}
657
		}
658
		return $languages;
659
	}
660
661
	/**
662
	 * Returns the most preferred language by the client user.
663
	 * @return string the most preferred language by the client user, defaults to English.
664
	 */
665
	public static function getPreferredLanguage(): string
666
	{
667
		static $language = null;
668
		if ($language === null) {
669
			$langs = Prado::getUserLanguages();
670
			$lang = explode('-', $langs[0]);
671
			if (empty($lang[0]) || !ctype_alpha($lang[0])) {
672
				$language = 'en';
673
			} else {
674
				$language = $lang[0];
675
			}
676
		}
677
		return $language;
678
	}
679
680
	/**
681
	 * Writes a log message.
682
	 * This method wraps {@link log()} by checking the application mode.
683
	 * When the application is in Debug mode, debug backtrace information is appended
684
	 * to the message and the message is logged at DEBUG level.
685
	 * When the application is in Performance mode, this method does nothing.
686
	 * Otherwise, the message is logged at INFO level.
687
	 * @param string $msg message to be logged
688
	 * @param string $category category of the message
689
	 * @param null|\Prado\Web\UI\TControl|string $ctl control of the message
690
	 * @see log, getLogger
691
	 */
692
	public static function trace($msg, $category = 'Uncategorized', $ctl = null): void
693
	{
694
		if (self::$_application && self::$_application->getMode() === TApplicationMode::Performance) {
695
			return;
696
		}
697
		if (!self::$_application || self::$_application->getMode() === TApplicationMode::Debug) {
698
			$trace = debug_backtrace();
699
			if (isset($trace[0]['file']) && isset($trace[0]['line'])) {
700
				$msg .= " (line {$trace[0]['line']}, {$trace[0]['file']})";
701
			}
702
			$level = TLogger::DEBUG;
703
		} else {
704
			$level = TLogger::INFO;
705
		}
706
		self::log($msg, $level, $category, $ctl);
707
	}
708
709
	/**
710
	 * Logs a message.
711
	 * Messages logged by this method may be retrieved via {@link TLogger::getLogs}
712
	 * and may be recorded in different media, such as file, email, database, using
713
	 * {@link TLogRouter}.
714
	 * @param string $msg message to be logged
715
	 * @param int $level level of the message. Valid values include
716
	 * TLogger::DEBUG, TLogger::INFO, TLogger::NOTICE, TLogger::WARNING,
717
	 * TLogger::ERROR, TLogger::ALERT, TLogger::FATAL.
718
	 * @param string $category category of the message
719
	 * @param null|\Prado\Web\UI\TControl|string $ctl control of the message
720
	 */
721
	public static function log($msg, $level = TLogger::INFO, $category = 'Uncategorized', $ctl = null): void
722
	{
723
		if (self::$_logger === null) {
724
			self::$_logger = new TLogger();
725
		}
726
		self::$_logger->log($msg, $level, $category, $ctl);
727
	}
728
729
	/**
730
	 * @return TLogger message logger
731
	 */
732
	public static function getLogger(): TLogger
733
	{
734
		if (self::$_logger === null) {
735
			self::$_logger = new TLogger();
736
		}
737
		return self::$_logger;
738
	}
739
740
	/**
741
	 * Converts a variable into a string representation.
742
	 * This method achieves the similar functionality as var_dump and print_r
743
	 * but is more robust when handling complex objects such as PRADO controls.
744
	 * @param mixed $var variable to be dumped
745
	 * @param int $depth maximum depth that the dumper should go into the variable. Defaults to 10.
746
	 * @param bool $highlight whether to syntax highlight the output. Defaults to false.
747
	 * @return string the string representation of the variable
748
	 */
749
	public static function varDump($var, $depth = 10, $highlight = false): string
750
	{
751
		return TVarDumper::dump($var, $depth, $highlight);
752
	}
753
754
	/**
755
	 * Localize a text to the locale/culture specified in the globalization handler.
756
	 * @param string $text text to be localized.
757
	 * @param array<string, string> $parameters a set of parameters to substitute.
758
	 * @param string $catalogue a different catalogue to find the localize text.
759
	 * @param string $charset the input AND output charset.
760
	 * @return string localized text.
761
	 * @see TTranslate::formatter()
762
	 * @see TTranslate::init()
763
	 */
764
	public static function localize($text, $parameters = [], $catalogue = null, $charset = null): string
765
	{
766
		$params = [];
767
		foreach ($parameters as $key => $value) {
768
			$params['{' . $key . '}'] = $value;
769
		}
770
771
		// no translation handler provided
772
		if (self::$_application === null
773
			|| ($app = self::$_application->getGlobalization(false)) === null
774
			|| ($config = $app->getTranslationConfiguration()) === null) {
775
			return strtr($text, $params);
776
		}
777
778
		if ($catalogue === null) {
779
			$catalogue = $config['catalogue'] ?? 'messages';
780
		}
781
782
		Translation::init($catalogue);
783
784
		//globalization charset
785
		if (empty($charset)) {
786
			$charset = $app->getCharset();
787
		}
788
789
		//default charset
790
		if (empty($charset)) {
791
			$charset = $app->getDefaultCharset();
792
		}
793
794
		return Translation::formatter($catalogue)->format($text, $params, $catalogue, $charset);
795
	}
796
}
797
798
/**
799
 * Initialize Prado autoloader and error handler
800
 */
801
Prado::init();
802
803
/**
804
 * Defines Prado in global namespace
805
 */
806
class_alias(\Prado\Prado::class, 'Prado');
807