Passed
Pull Request — php81 (#19140)
by
unknown
39:25
created

BaseYii::createObject()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 6
nop 2
dl 0
loc 27
rs 9.2222
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii;
9
10
use yii\base\InvalidArgumentException;
11
use yii\base\InvalidConfigException;
12
use yii\base\UnknownClassException;
13
use yii\di\Container;
14
use yii\log\Logger;
15
16
/**
17
 * Gets the application start timestamp.
18
 */
19
defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME', microtime(true));
20
/**
21
 * This constant defines the framework installation directory.
22
 */
23
defined('YII2_PATH') or define('YII2_PATH', __DIR__);
24
/**
25
 * This constant defines whether the application should be in debug mode or not. Defaults to false.
26
 */
27
defined('YII_DEBUG') or define('YII_DEBUG', false);
28
/**
29
 * This constant defines in which environment the application is running. Defaults to 'prod', meaning production environment.
30
 * You may define this constant in the bootstrap script. The value could be 'prod' (production), 'dev' (development), 'test', 'staging', etc.
31
 */
32
defined('YII_ENV') or define('YII_ENV', 'prod');
33
/**
34
 * Whether the application is running in the production environment.
35
 */
36
defined('YII_ENV_PROD') or define('YII_ENV_PROD', YII_ENV === 'prod');
37
/**
38
 * Whether the application is running in the development environment.
39
 */
40
defined('YII_ENV_DEV') or define('YII_ENV_DEV', YII_ENV === 'dev');
41
/**
42
 * Whether the application is running in the testing environment.
43
 */
44
defined('YII_ENV_TEST') or define('YII_ENV_TEST', YII_ENV === 'test');
45
46
/**
47
 * This constant defines whether error handling should be enabled. Defaults to true.
48
 */
49
defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER', true);
50
51
/**
52
 * BaseYii is the core helper class for the Yii framework.
53
 *
54
 * Do not use BaseYii directly. Instead, use its child class [[\Yii]] which you can replace to
55
 * customize methods of BaseYii.
56
 *
57
 * @author Qiang Xue <[email protected]>
58
 * @since 2.0
59
 */
60
class BaseYii
61
{
62
    /**
63
     * @var array class map used by the Yii autoloading mechanism.
64
     * The array keys are the class names (without leading backslashes), and the array values
65
     * are the corresponding class file paths (or [path aliases](guide:concept-aliases)). This property mainly affects
66
     * how [[autoload()]] works.
67
     * @see autoload()
68
     */
69
    public static $classMap = [];
70
    /**
71
     * @var \yii\console\Application|\yii\web\Application|\yii\base\Application the application instance
72
     */
73
    public static $app;
74
    /**
75
     * @var array registered path aliases
76
     * @see getAlias()
77
     * @see setAlias()
78
     */
79
    public static $aliases = ['@yii' => __DIR__];
80
    /**
81
     * @var Container the dependency injection (DI) container used by [[createObject()]].
82
     * You may use [[Container::set()]] to set up the needed dependencies of classes and
83
     * their initial property values.
84
     * @see createObject()
85
     * @see Container
86
     */
87
    public static $container;
88
89
90
    /**
91
     * Returns a string representing the current version of the Yii framework.
92
     * @return string the version of Yii framework
93
     */
94
    public static function getVersion()
95
    {
96
        return '2.0.44-dev';
97
    }
98
99
    /**
100
     * Translates a path alias into an actual path.
101
     *
102
     * The translation is done according to the following procedure:
103
     *
104
     * 1. If the given alias does not start with '@', it is returned back without change;
105
     * 2. Otherwise, look for the longest registered alias that matches the beginning part
106
     *    of the given alias. If it exists, replace the matching part of the given alias with
107
     *    the corresponding registered path.
108
     * 3. Throw an exception or return false, depending on the `$throwException` parameter.
109
     *
110
     * For example, by default '@yii' is registered as the alias to the Yii framework directory,
111
     * say '/path/to/yii'. The alias '@yii/web' would then be translated into '/path/to/yii/web'.
112
     *
113
     * If you have registered two aliases '@foo' and '@foo/bar'. Then translating '@foo/bar/config'
114
     * would replace the part '@foo/bar' (instead of '@foo') with the corresponding registered path.
115
     * This is because the longest alias takes precedence.
116
     *
117
     * However, if the alias to be translated is '@foo/barbar/config', then '@foo' will be replaced
118
     * instead of '@foo/bar', because '/' serves as the boundary character.
119
     *
120
     * Note, this method does not check if the returned path exists or not.
121
     *
122
     * See the [guide article on aliases](guide:concept-aliases) for more information.
123
     *
124
     * @param string $alias the alias to be translated.
125
     * @param bool $throwException whether to throw an exception if the given alias is invalid.
126
     * If this is false and an invalid alias is given, false will be returned by this method.
127
     * @return string|false the path corresponding to the alias, false if the root alias is not previously registered.
128
     * @throws InvalidArgumentException if the alias is invalid while $throwException is true.
129
     * @see setAlias()
130
     */
131
    public static function getAlias($alias, $throwException = true)
132
    {
133
        if (strncmp((string)$alias), '@', 1) !== 0) {
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected ',' on line 133 at column 35
Loading history...
134
            // not an alias
135
            return $alias;
136
        }
137
138
        $pos = strpos($alias, '/');
139
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
140
141
        if (isset(static::$aliases[$root])) {
142
            if (is_string(static::$aliases[$root])) {
143
                return $pos === false ? static::$aliases[$root] : static::$aliases[$root] . substr($alias, $pos);
144
            }
145
146
            foreach (static::$aliases[$root] as $name => $path) {
147
                if (strpos($alias . '/', $name . '/') === 0) {
148
                    return $path . substr($alias, strlen($name));
149
                }
150
            }
151
        }
152
153
        if ($throwException) {
154
            throw new InvalidArgumentException("Invalid path alias: $alias");
155
        }
156
157
        return false;
158
    }
159
160
    /**
161
     * Returns the root alias part of a given alias.
162
     * A root alias is an alias that has been registered via [[setAlias()]] previously.
163
     * If a given alias matches multiple root aliases, the longest one will be returned.
164
     * @param string $alias the alias
165
     * @return string|false the root alias, or false if no root alias is found
166
     */
167
    public static function getRootAlias($alias)
168
    {
169
        $pos = strpos($alias, '/');
170
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
171
172
        if (isset(static::$aliases[$root])) {
173
            if (is_string(static::$aliases[$root])) {
174
                return $root;
175
            }
176
177
            foreach (static::$aliases[$root] as $name => $path) {
178
                if (strpos($alias . '/', $name . '/') === 0) {
179
                    return $name;
180
                }
181
            }
182
        }
183
184
        return false;
185
    }
186
187
    /**
188
     * Registers a path alias.
189
     *
190
     * A path alias is a short name representing a long path (a file path, a URL, etc.)
191
     * For example, we use '@yii' as the alias of the path to the Yii framework directory.
192
     *
193
     * A path alias must start with the character '@' so that it can be easily differentiated
194
     * from non-alias paths.
195
     *
196
     * Note that this method does not check if the given path exists or not. All it does is
197
     * to associate the alias with the path.
198
     *
199
     * Any trailing '/' and '\' characters in the given path will be trimmed.
200
     *
201
     * See the [guide article on aliases](guide:concept-aliases) for more information.
202
     *
203
     * @param string $alias the alias name (e.g. "@yii"). It must start with a '@' character.
204
     * It may contain the forward-slash '/' which serves as a boundary character when performing
205
     * alias translation by [[getAlias()]].
206
     * @param string $path the path corresponding to the alias. If this is null, the alias will
207
     * be removed. Trailing '/' and '\' characters will be trimmed. This can be
208
     *
209
     * - a directory or a file path (e.g. `/tmp`, `/tmp/main.txt`)
210
     * - a URL (e.g. `http://www.yiiframework.com`)
211
     * - a path alias (e.g. `@yii/base`). In this case, the path alias will be converted into the
212
     *   actual path first by calling [[getAlias()]].
213
     *
214
     * @throws InvalidArgumentException if $path is an invalid alias.
215
     * @see getAlias()
216
     */
217
    public static function setAlias($alias, $path)
218
    {
219
        if (strncmp($alias, '@', 1)) {
220
            $alias = '@' . $alias;
221
        }
222
        $pos = strpos($alias, '/');
223
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
224
        if ($path !== null) {
225
            $path = strncmp($path, '@', 1) ? rtrim($path, '\\/') : static::getAlias($path);
226
            if (!isset(static::$aliases[$root])) {
227
                if ($pos === false) {
228
                    static::$aliases[$root] = $path;
229
                } else {
230
                    static::$aliases[$root] = [$alias => $path];
231
                }
232
            } elseif (is_string(static::$aliases[$root])) {
233
                if ($pos === false) {
234
                    static::$aliases[$root] = $path;
235
                } else {
236
                    static::$aliases[$root] = [
237
                        $alias => $path,
238
                        $root => static::$aliases[$root],
239
                    ];
240
                }
241
            } else {
242
                static::$aliases[$root][$alias] = $path;
243
                krsort(static::$aliases[$root]);
244
            }
245
        } elseif (isset(static::$aliases[$root])) {
246
            if (is_array(static::$aliases[$root])) {
247
                unset(static::$aliases[$root][$alias]);
248
            } elseif ($pos === false) {
249
                unset(static::$aliases[$root]);
250
            }
251
        }
252
    }
253
254
    /**
255
     * Class autoload loader.
256
     *
257
     * This method is invoked automatically when PHP sees an unknown class.
258
     * The method will attempt to include the class file according to the following procedure:
259
     *
260
     * 1. Search in [[classMap]];
261
     * 2. If the class is namespaced (e.g. `yii\base\Component`), it will attempt
262
     *    to include the file associated with the corresponding path alias
263
     *    (e.g. `@yii/base/Component.php`);
264
     *
265
     * This autoloader allows loading classes that follow the [PSR-4 standard](http://www.php-fig.org/psr/psr-4/)
266
     * and have its top-level namespace or sub-namespaces defined as path aliases.
267
     *
268
     * Example: When aliases `@yii` and `@yii/bootstrap` are defined, classes in the `yii\bootstrap` namespace
269
     * will be loaded using the `@yii/bootstrap` alias which points to the directory where the bootstrap extension
270
     * files are installed and all classes from other `yii` namespaces will be loaded from the yii framework directory.
271
     *
272
     * Also the [guide section on autoloading](guide:concept-autoloading).
273
     *
274
     * @param string $className the fully qualified class name without a leading backslash "\"
275
     * @throws UnknownClassException if the class does not exist in the class file
276
     */
277
    public static function autoload($className)
278
    {
279
        if (isset(static::$classMap[$className])) {
280
            $classFile = static::$classMap[$className];
281
            if (strncmp($classFile, '@', 1) === 0) {
282
                $classFile = static::getAlias($classFile);
283
            }
284
        } elseif (strpos($className, '\\') !== false) {
285
            $classFile = static::getAlias('@' . str_replace('\\', '/', $className) . '.php', false);
286
            if ($classFile === false || !is_file($classFile)) {
287
                return;
288
            }
289
        } else {
290
            return;
291
        }
292
293
        include $classFile;
294
295
        if (YII_DEBUG && !class_exists($className, false) && !interface_exists($className, false) && !trait_exists($className, false)) {
296
            throw new UnknownClassException("Unable to find '$className' in file: $classFile. Namespace missing?");
297
        }
298
    }
299
300
    /**
301
     * Creates a new object using the given configuration.
302
     *
303
     * You may view this method as an enhanced version of the `new` operator.
304
     * The method supports creating an object based on a class name, a configuration array or
305
     * an anonymous function.
306
     *
307
     * Below are some usage examples:
308
     *
309
     * ```php
310
     * // create an object using a class name
311
     * $object = Yii::createObject('yii\db\Connection');
312
     *
313
     * // create an object using a configuration array
314
     * $object = Yii::createObject([
315
     *     'class' => 'yii\db\Connection',
316
     *     'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
317
     *     'username' => 'root',
318
     *     'password' => '',
319
     *     'charset' => 'utf8',
320
     * ]);
321
     *
322
     * // create an object with two constructor parameters
323
     * $object = \Yii::createObject('MyClass', [$param1, $param2]);
324
     * ```
325
     *
326
     * Using [[\yii\di\Container|dependency injection container]], this method can also identify
327
     * dependent objects, instantiate them and inject them into the newly created object.
328
     *
329
     * @param string|array|callable $type the object type. This can be specified in one of the following forms:
330
     *
331
     * - a string: representing the class name of the object to be created
332
     * - a configuration array: the array must contain a `class` element which is treated as the object class,
333
     *   and the rest of the name-value pairs will be used to initialize the corresponding object properties
334
     * - a PHP callable: either an anonymous function or an array representing a class method (`[$class or $object, $method]`).
335
     *   The callable should return a new instance of the object being created.
336
     *
337
     * @param array $params the constructor parameters
338
     * @return object the created object
339
     * @throws InvalidConfigException if the configuration is invalid.
340
     * @see \yii\di\Container
341
     */
342
    public static function createObject($type, array $params = [])
343
    {
344
        if (is_string($type)) {
345
            return static::$container->get($type, $params);
346
        }
347
348
        if (is_callable($type, true)) {
349
            return static::$container->invoke($type, $params);
350
        }
351
352
        if (!is_array($type)) {
353
            throw new InvalidConfigException('Unsupported configuration type: ' . gettype($type));
354
        }
355
356
        if (isset($type['__class'])) {
357
            $class = $type['__class'];
358
            unset($type['__class'], $type['class']);
359
            return static::$container->get($class, $params, $type);
360
        }
361
362
        if (isset($type['class'])) {
363
            $class = $type['class'];
364
            unset($type['class']);
365
            return static::$container->get($class, $params, $type);
366
        }
367
368
        throw new InvalidConfigException('Object configuration must be an array containing a "class" or "__class" element.');
369
    }
370
371
    private static $_logger;
372
373
    /**
374
     * @return Logger message logger
375
     */
376
    public static function getLogger()
377
    {
378
        if (self::$_logger !== null) {
379
            return self::$_logger;
380
        }
381
382
        return self::$_logger = static::createObject('yii\log\Logger');
383
    }
384
385
    /**
386
     * Sets the logger object.
387
     * @param Logger $logger the logger object.
388
     */
389
    public static function setLogger($logger)
390
    {
391
        self::$_logger = $logger;
392
    }
393
394
    /**
395
     * Logs a debug message.
396
     * Trace messages are logged mainly for development purposes to see
397
     * the execution workflow of some code. This method will only log
398
     * a message when the application is in debug mode.
399
     * @param string|array $message the message to be logged. This can be a simple string or a more
400
     * complex data structure, such as an array.
401
     * @param string $category the category of the message.
402
     * @since 2.0.14
403
     */
404
    public static function debug($message, $category = 'application')
405
    {
406
        if (YII_DEBUG) {
407
            static::getLogger()->log($message, Logger::LEVEL_TRACE, $category);
408
        }
409
    }
410
411
    /**
412
     * Alias of [[debug()]].
413
     * @param string|array $message the message to be logged. This can be a simple string or a more
414
     * complex data structure, such as an array.
415
     * @param string $category the category of the message.
416
     * @deprecated since 2.0.14. Use [[debug()]] instead.
417
     */
418
    public static function trace($message, $category = 'application')
419
    {
420
        static::debug($message, $category);
421
    }
422
423
    /**
424
     * Logs an error message.
425
     * An error message is typically logged when an unrecoverable error occurs
426
     * during the execution of an application.
427
     * @param string|array $message the message to be logged. This can be a simple string or a more
428
     * complex data structure, such as an array.
429
     * @param string $category the category of the message.
430
     */
431
    public static function error($message, $category = 'application')
432
    {
433
        static::getLogger()->log($message, Logger::LEVEL_ERROR, $category);
434
    }
435
436
    /**
437
     * Logs a warning message.
438
     * A warning message is typically logged when an error occurs while the execution
439
     * can still continue.
440
     * @param string|array $message the message to be logged. This can be a simple string or a more
441
     * complex data structure, such as an array.
442
     * @param string $category the category of the message.
443
     */
444
    public static function warning($message, $category = 'application')
445
    {
446
        static::getLogger()->log($message, Logger::LEVEL_WARNING, $category);
447
    }
448
449
    /**
450
     * Logs an informative message.
451
     * An informative message is typically logged by an application to keep record of
452
     * something important (e.g. an administrator logs in).
453
     * @param string|array $message the message to be logged. This can be a simple string or a more
454
     * complex data structure, such as an array.
455
     * @param string $category the category of the message.
456
     */
457
    public static function info($message, $category = 'application')
458
    {
459
        static::getLogger()->log($message, Logger::LEVEL_INFO, $category);
460
    }
461
462
    /**
463
     * Marks the beginning of a code block for profiling.
464
     *
465
     * This has to be matched with a call to [[endProfile]] with the same category name.
466
     * The begin- and end- calls must also be properly nested. For example,
467
     *
468
     * ```php
469
     * \Yii::beginProfile('block1');
470
     * // some code to be profiled
471
     *     \Yii::beginProfile('block2');
472
     *     // some other code to be profiled
473
     *     \Yii::endProfile('block2');
474
     * \Yii::endProfile('block1');
475
     * ```
476
     * @param string $token token for the code block
477
     * @param string $category the category of this log message
478
     * @see endProfile()
479
     */
480
    public static function beginProfile($token, $category = 'application')
481
    {
482
        static::getLogger()->log($token, Logger::LEVEL_PROFILE_BEGIN, $category);
483
    }
484
485
    /**
486
     * Marks the end of a code block for profiling.
487
     * This has to be matched with a previous call to [[beginProfile]] with the same category name.
488
     * @param string $token token for the code block
489
     * @param string $category the category of this log message
490
     * @see beginProfile()
491
     */
492
    public static function endProfile($token, $category = 'application')
493
    {
494
        static::getLogger()->log($token, Logger::LEVEL_PROFILE_END, $category);
495
    }
496
497
    /**
498
     * Returns an HTML hyperlink that can be displayed on your Web page showing "Powered by Yii Framework" information.
499
     * @return string an HTML hyperlink that can be displayed on your Web page showing "Powered by Yii Framework" information
500
     * @deprecated since 2.0.14, this method will be removed in 2.1.0.
501
     */
502
    public static function powered()
503
    {
504
        return \Yii::t('yii', 'Powered by {yii}', [
505
            'yii' => '<a href="http://www.yiiframework.com/" rel="external">' . \Yii::t('yii',
506
                    'Yii Framework') . '</a>',
507
        ]);
508
    }
509
510
    /**
511
     * Translates a message to the specified language.
512
     *
513
     * This is a shortcut method of [[\yii\i18n\I18N::translate()]].
514
     *
515
     * The translation will be conducted according to the message category and the target language will be used.
516
     *
517
     * You can add parameters to a translation message that will be substituted with the corresponding value after
518
     * translation. The format for this is to use curly brackets around the parameter name as you can see in the following example:
519
     *
520
     * ```php
521
     * $username = 'Alexander';
522
     * echo \Yii::t('app', 'Hello, {username}!', ['username' => $username]);
523
     * ```
524
     *
525
     * Further formatting of message parameters is supported using the [PHP intl extensions](https://www.php.net/manual/en/intro.intl.php)
526
     * message formatter. See [[\yii\i18n\I18N::translate()]] for more details.
527
     *
528
     * @param string $category the message category.
529
     * @param string $message the message to be translated.
530
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
531
     * @param string $language the language code (e.g. `en-US`, `en`). If this is null, the current
532
     * [[\yii\base\Application::language|application language]] will be used.
533
     * @return string the translated message.
534
     */
535
    public static function t($category, $message, $params = [], $language = null)
536
    {
537
        if (static::$app !== null) {
538
            return static::$app->getI18n()->translate($category, $message, $params, $language ?: static::$app->language);
539
        }
540
541
        $placeholders = [];
542
        foreach ((array) $params as $name => $value) {
543
            $placeholders['{' . $name . '}'] = $value;
544
        }
545
546
        return ($placeholders === []) ? $message : strtr($message, $placeholders);
547
    }
548
549
    /**
550
     * Configures an object with the initial property values.
551
     * @param object $object the object to be configured
552
     * @param array $properties the property initial values given in terms of name-value pairs.
553
     * @return object the object itself
554
     */
555
    public static function configure($object, $properties)
556
    {
557
        foreach ($properties as $name => $value) {
558
            $object->$name = $value;
559
        }
560
561
        return $object;
562
    }
563
564
    /**
565
     * Returns the public member variables of an object.
566
     * This method is provided such that we can get the public member variables of an object.
567
     * It is different from "get_object_vars()" because the latter will return private
568
     * and protected variables if it is called within the object itself.
569
     * @param object $object the object to be handled
570
     * @return array the public member variables of the object
571
     */
572
    public static function getObjectVars($object)
573
    {
574
        return get_object_vars($object);
575
    }
576
}
577