Completed
Push — 2.1 ( 732d0a...b04e0e )
by
unknown
11:44
created

BaseYii::configure()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
crap 2
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 Psr\Log\LoggerInterface;
11
use Psr\Log\LogLevel;
12
use yii\base\InvalidArgumentException;
13
use yii\base\InvalidConfigException;
14
use yii\base\UnknownClassException;
15
use yii\di\Container;
16
use yii\di\Instance;
17
use yii\helpers\VarDumper;
18
use yii\log\Logger;
19
use yii\profile\Profiler;
20
use yii\profile\ProfilerInterface;
21
22
/**
23
 * Gets the application start timestamp.
24
 */
25
defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME', microtime(true));
26
/**
27
 * This constant defines the framework installation directory.
28
 */
29
defined('YII2_PATH') or define('YII2_PATH', __DIR__);
30
/**
31
 * This constant defines whether the application should be in debug mode or not. Defaults to false.
32
 */
33
defined('YII_DEBUG') or define('YII_DEBUG', false);
34
/**
35
 * This constant defines in which environment the application is running. Defaults to 'prod', meaning production environment.
36
 * You may define this constant in the bootstrap script. The value could be 'prod' (production), 'dev' (development), 'test', 'staging', etc.
37
 */
38
defined('YII_ENV') or define('YII_ENV', 'prod');
39
/**
40
 * Whether the the application is running in production environment
41
 */
42
defined('YII_ENV_PROD') or define('YII_ENV_PROD', YII_ENV === 'prod');
43
/**
44
 * Whether the the application is running in development environment
45
 */
46
defined('YII_ENV_DEV') or define('YII_ENV_DEV', YII_ENV === 'dev');
47
/**
48
 * Whether the the application is running in testing environment
49
 */
50
defined('YII_ENV_TEST') or define('YII_ENV_TEST', YII_ENV === 'test');
51
52
/**
53
 * This constant defines whether error handling should be enabled. Defaults to true.
54
 */
55
defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER', true);
56
57
/**
58
 * BaseYii is the core helper class for the Yii framework.
59
 *
60
 * Do not use BaseYii directly. Instead, use its child class [[\Yii]] which you can replace to
61
 * customize methods of BaseYii.
62
 *
63
 * @author Qiang Xue <[email protected]>
64
 * @since 2.0
65
 */
66
class BaseYii
67
{
68
    /**
69
     * @var \yii\console\Application|\yii\web\Application the application instance
70
     */
71
    public static $app;
72
    /**
73
     * @var array registered path aliases
74
     * @see getAlias()
75
     * @see setAlias()
76
     */
77
    public static $aliases = ['@yii' => __DIR__];
78
    /**
79
     * @var Container the dependency injection (DI) container used by [[createObject()]].
80
     * You may use [[Container::set()]] to set up the needed dependencies of classes and
81
     * their initial property values.
82
     * @see createObject()
83
     * @see Container
84
     */
85
    public static $container;
86
87
88
    /**
89
     * Returns a string representing the current version of the Yii framework.
90
     * @return string the version of Yii framework
91
     */
92 65
    public static function getVersion()
93
    {
94 65
        return '2.0.15-dev';
95
    }
96
97
    /**
98
     * Translates a path alias into an actual path.
99
     *
100
     * The translation is done according to the following procedure:
101
     *
102
     * 1. If the given alias does not start with '@', it is returned back without change;
103
     * 2. Otherwise, look for the longest registered alias that matches the beginning part
104
     *    of the given alias. If it exists, replace the matching part of the given alias with
105
     *    the corresponding registered path.
106
     * 3. Throw an exception or return false, depending on the `$throwException` parameter.
107
     *
108
     * For example, by default '@yii' is registered as the alias to the Yii framework directory,
109
     * say '/path/to/yii'. The alias '@yii/web' would then be translated into '/path/to/yii/web'.
110
     *
111
     * If you have registered two aliases '@foo' and '@foo/bar'. Then translating '@foo/bar/config'
112
     * would replace the part '@foo/bar' (instead of '@foo') with the corresponding registered path.
113
     * This is because the longest alias takes precedence.
114
     *
115
     * However, if the alias to be translated is '@foo/barbar/config', then '@foo' will be replaced
116
     * instead of '@foo/bar', because '/' serves as the boundary character.
117
     *
118
     * Note, this method does not check if the returned path exists or not.
119
     *
120
     * See the [guide article on aliases](guide:concept-aliases) for more information.
121
     *
122
     * @param string $alias the alias to be translated.
123
     * @param bool $throwException whether to throw an exception if the given alias is invalid.
124
     * If this is false and an invalid alias is given, false will be returned by this method.
125
     * @return string|bool the path corresponding to the alias, false if the root alias is not previously registered.
126
     * @throws InvalidArgumentException if the alias is invalid while $throwException is true.
127
     * @see setAlias()
128
     */
129 3474
    public static function getAlias($alias, $throwException = true)
130
    {
131 3474
        if (strncmp($alias, '@', 1)) {
132
            // not an alias
133 3259
            return $alias;
134
        }
135
136 3393
        $result = static::findAlias($alias);
137
138 3393
        if (is_array($result)) {
139 3393
            return $result['path'];
140
        }
141
142 1
        if ($throwException) {
143 1
            throw new InvalidArgumentException("Invalid path alias: $alias");
144
        }
145
146 1
        return false;
147
    }
148
149
    /**
150
     * Returns the root alias part of a given alias.
151
     * A root alias is an alias that has been registered via [[setAlias()]] previously.
152
     * If a given alias matches multiple root aliases, the longest one will be returned.
153
     * @param string $alias the alias
154
     * @return string|bool the root alias, or false if no root alias is found
155
     */
156 1
    public static function getRootAlias($alias)
157
    {
158 1
        $result = static::findAlias($alias);
159 1
        if (is_array($result)) {
160 1
            $result = $result['root'];
161
        }
162 1
        return $result;
163
    }
164
165
    /**
166
     * @param string $alias
167
     * @return array|bool
168
     */
169 3394
    protected static function findAlias(string $alias)
170
    {
171 3394
        $pos = strpos($alias, '/');
172 3394
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
173
174 3394
        if (isset(static::$aliases[$root])) {
175 3394
            if (is_string(static::$aliases[$root])) {
176 3393
                return ['root' => $root, 'path' => $pos === false ? static::$aliases[$root] : static::$aliases[$root] . substr($alias, $pos)];
177
            }
178
179 3
            foreach (static::$aliases[$root] as $name => $path) {
180 3
                if (strpos($alias . '/', $name . '/') === 0) {
181 3
                    return ['root' => $name, 'path' => $path . substr($alias, strlen($name))];
182
                }
183
            }
184
        }
185
186 1
        return false;
187
    }
188
189
    /**
190
     * Registers a path alias.
191
     *
192
     * A path alias is a short name representing a long path (a file path, a URL, etc.)
193
     * For example, we use '@yii' as the alias of the path to the Yii framework directory.
194
     *
195
     * A path alias must start with the character '@' so that it can be easily differentiated
196
     * from non-alias paths.
197
     *
198
     * Note that this method does not check if the given path exists or not. All it does is
199
     * to associate the alias with the path.
200
     *
201
     * Any trailing '/' and '\' characters in the given path will be trimmed.
202
     *
203
     * See the [guide article on aliases](guide:concept-aliases) for more information.
204
     *
205
     * @param string $alias the alias name (e.g. "@yii"). It must start with a '@' character.
206
     * It may contain the forward slash '/' which serves as boundary character when performing
207
     * alias translation by [[getAlias()]].
208
     * @param string $path the path corresponding to the alias. If this is null, the alias will
209
     * be removed. Trailing '/' and '\' characters will be trimmed. This can be
210
     *
211
     * - a directory or a file path (e.g. `/tmp`, `/tmp/main.txt`)
212
     * - a URL (e.g. `http://www.yiiframework.com`)
213
     * - a path alias (e.g. `@yii/base`). In this case, the path alias will be converted into the
214
     *   actual path first by calling [[getAlias()]].
215
     *
216
     * @throws InvalidArgumentException if $path is an invalid alias.
217
     * @see getAlias()
218
     */
219 3161
    public static function setAlias($alias, $path)
220
    {
221 3161
        if (strncmp($alias, '@', 1)) {
222 1
            $alias = '@' . $alias;
223
        }
224 3161
        $pos = strpos($alias, '/');
225 3161
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
226 3161
        if ($path !== null) {
227 3161
            $path = strncmp($path, '@', 1) ? rtrim($path, '\\/') : static::getAlias($path);
228 3161
            if (!isset(static::$aliases[$root])) {
229 10
                if ($pos === false) {
230 9
                    static::$aliases[$root] = $path;
231
                } else {
232 10
                    static::$aliases[$root] = [$alias => $path];
233
                }
234 3160
            } elseif (is_string(static::$aliases[$root])) {
235 3159
                if ($pos === false) {
236 3157
                    static::$aliases[$root] = $path;
237
                } else {
238 2
                    static::$aliases[$root] = [
239 2
                        $alias => $path,
240 3159
                        $root => static::$aliases[$root],
241
                    ];
242
                }
243
            } else {
244 1
                static::$aliases[$root][$alias] = $path;
245 3161
                krsort(static::$aliases[$root]);
246
            }
247 3
        } elseif (isset(static::$aliases[$root])) {
248 3
            if (is_array(static::$aliases[$root])) {
249 1
                unset(static::$aliases[$root][$alias]);
250 2
            } elseif ($pos === false) {
251 2
                unset(static::$aliases[$root]);
252
            }
253
        }
254 3161
    }
255
256
    /**
257
     * Creates a new object using the given configuration.
258
     *
259
     * You may view this method as an enhanced version of the `new` operator.
260
     * The method supports creating an object based on a class name, a configuration array or
261
     * an anonymous function.
262
     *
263
     * Below are some usage examples:
264
     *
265
     * ```php
266
     * // create an object using a class name
267
     * $object = Yii::createObject(\yii\db\Connection::class);
268
     *
269
     * // create an object using a configuration array
270
     * $object = Yii::createObject([
271
     *     'class' => \yii\db\Connection::class,
272
     *     'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
273
     *     'username' => 'root',
274
     *     'password' => '',
275
     *     'charset' => 'utf8',
276
     * ]);
277
     *
278
     * // create an object with two constructor parameters
279
     * $object = \Yii::createObject('MyClass', [$param1, $param2]);
280
     * ```
281
     *
282
     * Using [[\yii\di\Container|dependency injection container]], this method can also identify
283
     * dependent objects, instantiate them and inject them into the newly created object.
284
     *
285
     * @param string|array|callable $type the object type. This can be specified in one of the following forms:
286
     *
287
     * - a string: representing the class name of the object to be created
288
     * - a configuration array: the array must contain a `class` element which is treated as the object class,
289
     *   and the rest of the name-value pairs will be used to initialize the corresponding object properties
290
     * - a PHP callable: either an anonymous function or an array representing a class method (`[$class or $object, $method]`).
291
     *   The callable should return a new instance of the object being created.
292
     *
293
     * @param array $params the constructor parameters
294
     * @return object the created object
295
     * @throws InvalidConfigException if the configuration is invalid.
296
     * @see \yii\di\Container
297
     */
298 3050
    public static function createObject($type, array $params = [])
299
    {
300 3050
        if (is_string($type)) {
301 1043
            return static::$container->get($type, $params);
302 3013
        } elseif (is_array($type) && (isset($type['__class']) || isset($type['class']))) {
303 3009
            if (isset($type['__class'])) {
304 3
                $class = $type['__class'];
305 3
                unset($type['__class']);
306
            } else {
307
                // @todo remove fallback
308 3008
                $class = $type['class'];
309 3008
                unset($type['class']);
310
            }
311 3009
            return static::$container->get($class, $params, $type);
312 9
        } elseif (is_callable($type, true)) {
313 6
            return static::$container->invoke($type, $params);
314 3
        } elseif (is_array($type)) {
315 2
            throw new InvalidConfigException('Object configuration must be an array containing a "__class" element.');
316
        }
317
318 1
        throw new InvalidConfigException('Unsupported configuration type: ' . gettype($type));
319
    }
320
321
    /**
322
     * @var LoggerInterface logger instance.
323
     */
324
    private static $_logger;
325
326
    /**
327
     * @return LoggerInterface message logger
328
     */
329 1822
    public static function getLogger()
330
    {
331 1822
        if (self::$_logger !== null) {
332 1736
            return self::$_logger;
333
        }
334
335 544
        return self::$_logger = Instance::ensure(['class' => Logger::class], LoggerInterface::class);
336
    }
337
338
    /**
339
     * Sets the logger object.
340
     * @param LoggerInterface|\Closure|array|null $logger the logger object or its DI compatible configuration.
341
     */
342 3137
    public static function setLogger($logger)
343
    {
344 3137
        if ($logger === null) {
345 3137
            self::$_logger = null;
346 3137
            return;
347
        }
348
349 19
        if (is_array($logger)) {
350 7
            if (!isset($logger['class']) && is_object(self::$_logger)) {
351 2
                static::configure(self::$_logger, $logger);
352 2
                return;
353
            }
354 6
            $logger = array_merge(['class' => Logger::class], $logger);
355 13
        } elseif ($logger instanceof \Closure) {
356 1
            $logger = call_user_func($logger);
357
        }
358
359 18
        self::$_logger = Instance::ensure($logger, LoggerInterface::class);
360 18
    }
361
362
    /**
363
     * @var ProfilerInterface profiler instance.
364
     * @since 2.1
365
     */
366
    private static $_profiler;
367
368
    /**
369
     * @return ProfilerInterface profiler instance.
370
     * @since 2.1
371
     */
372 1585
    public static function getProfiler()
373
    {
374 1585
        if (self::$_profiler !== null) {
375 1585
            return self::$_profiler;
376
        }
377 2
        return self::$_profiler = Instance::ensure(['class' => Profiler::class], ProfilerInterface::class);
378
    }
379
380
    /**
381
     * @param ProfilerInterface|\Closure|array|null $profiler profiler instance or its DI compatible configuration.
382
     * @since 2.1
383
     */
384 10
    public static function setProfiler($profiler)
385
    {
386 10
        if ($profiler === null) {
387 10
            self::$_profiler = null;
388 10
            return;
389
        }
390
391 1
        if (is_array($profiler)) {
392 1
            if (!isset($profiler['class']) && is_object(self::$_profiler)) {
393 1
                static::configure(self::$_profiler, $profiler);
394 1
                return;
395
            }
396 1
            $profiler = array_merge(['class' => Profiler::class], $profiler);
397 1
        } elseif ($profiler instanceof \Closure) {
398 1
            $profiler = call_user_func($profiler);
399
        }
400
401 1
        self::$_profiler = Instance::ensure($profiler, ProfilerInterface::class);
402 1
    }
403
404
    /**
405
     * Logs a message with category.
406
     * @param string $level log level.
407
     * @param mixed $message the message to be logged. This can be a simple string or a more
408
     * complex data structure, such as array.
409
     * @param string $category the category of the message.
410
     * @since 2.1.0
411
     */
412 1821
    public static function log($level, $message, $category = 'application')
413
    {
414 1821
        $context = ['category' => $category];
415 1821
        if (!is_string($message)) {
416 11
            if ($message instanceof \Throwable) {
417
                // exceptions are string-convertable, thus should be passed as it is to the logger
418
                // if exception instance is given to produce a stack trace, it MUST be in a key named "exception".
419 1
                $context['exception'] = $message;
420
            } else {
421
                // exceptions may not be serializable if in the call stack somewhere is a Closure
422 10
                $message = VarDumper::export($message);
423
            }
424
        }
425 1821
        static::getLogger()->log($level, $message, $context);
0 ignored issues
show
Bug introduced by
It seems like $message defined by parameter $message on line 412 can also be of type object<Throwable>; however, Psr\Log\LoggerInterface::log() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
426 1821
    }
427
428
    /**
429
     * Logs a debug message.
430
     * Trace messages are logged mainly for development purpose to see
431
     * the execution work flow of some code.
432
     * @param string|array $message the message to be logged. This can be a simple string or a more
433
     * complex data structure, such as array.
434
     * @param string $category the category of the message.
435
     * @since 2.0.14
436
     */
437 1680
    public static function debug($message, $category = 'application')
438
    {
439 1680
        if (YII_DEBUG) {
440 1680
            static::log(LogLevel::DEBUG, $message, $category);
441
        }
442 1680
    }
443
444
    /**
445
     * Logs an error message.
446
     * An error message is typically logged when an unrecoverable error occurs
447
     * during the execution of an application.
448
     * @param string|array $message the message to be logged. This can be a simple string or a more
449
     * complex data structure, such as array.
450
     * @param string $category the category of the message.
451
     */
452 6
    public static function error($message, $category = 'application')
453
    {
454 6
        static::log(LogLevel::ERROR, $message, $category);
455 6
    }
456
457
    /**
458
     * Logs a warning message.
459
     * A warning message is typically logged when an error occurs while the execution
460
     * can still continue.
461
     * @param string|array $message the message to be logged. This can be a simple string or a more
462
     * complex data structure, such as array.
463
     * @param string $category the category of the message.
464
     */
465 14
    public static function warning($message, $category = 'application')
466
    {
467 14
        static::log(LogLevel::WARNING, $message, $category);
468 14
    }
469
470
    /**
471
     * Logs an informative message.
472
     * An informative message is typically logged by an application to keep record of
473
     * something important (e.g. an administrator logs in).
474
     * @param string|array $message the message to be logged. This can be a simple string or a more
475
     * complex data structure, such as array.
476
     * @param string $category the category of the message.
477
     */
478 1628
    public static function info($message, $category = 'application')
479
    {
480 1628
        static::log(LogLevel::INFO, $message, $category);
481 1628
    }
482
483
    /**
484
     * Marks the beginning of a code block for profiling.
485
     *
486
     * This has to be matched with a call to [[endProfile]] with the same category name.
487
     * The begin- and end- calls must also be properly nested. For example,
488
     *
489
     * ```php
490
     * \Yii::beginProfile('block1');
491
     * // some code to be profiled
492
     *     \Yii::beginProfile('block2');
493
     *     // some other code to be profiled
494
     *     \Yii::endProfile('block2');
495
     * \Yii::endProfile('block1');
496
     * ```
497
     * @param string $token token for the code block
498
     * @param string $category the category of this log message
499
     * @see endProfile()
500
     */
501 1585
    public static function beginProfile($token, $category = 'application')
502
    {
503 1585
        static::getProfiler()->begin($token, ['category' => $category]);
504 1585
    }
505
506
    /**
507
     * Marks the end of a code block for profiling.
508
     * This has to be matched with a previous call to [[beginProfile]] with the same category name.
509
     * @param string $token token for the code block
510
     * @param string $category the category of this log message
511
     * @see beginProfile()
512
     */
513 1585
    public static function endProfile($token, $category = 'application')
514
    {
515 1585
        static::getProfiler()->end($token, ['category' => $category]);
516 1585
    }
517
518
    /**
519
     * Translates a message to the specified language.
520
     *
521
     * This is a shortcut method of [[\yii\i18n\I18N::translate()]].
522
     *
523
     * The translation will be conducted according to the message category and the target language will be used.
524
     *
525
     * You can add parameters to a translation message that will be substituted with the corresponding value after
526
     * translation. The format for this is to use curly brackets around the parameter name as you can see in the following example:
527
     *
528
     * ```php
529
     * $username = 'Alexander';
530
     * echo \Yii::t('app', 'Hello, {username}!', ['username' => $username]);
531
     * ```
532
     *
533
     * Further formatting of message parameters is supported using the [PHP intl extensions](http://www.php.net/manual/en/intro.intl.php)
534
     * message formatter. See [[\yii\i18n\I18N::translate()]] for more details.
535
     *
536
     * @param string $category the message category.
537
     * @param string $message the message to be translated.
538
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
539
     * @param string $language the language code (e.g. `en-US`, `en`). If this is null, the current
540
     * [[\yii\base\Application::language|application language]] will be used.
541
     * @return string the translated message.
542
     */
543 780
    public static function t($category, $message, $params = [], $language = null)
544
    {
545 780
        if (static::$app !== null) {
546 535
            return static::$app->getI18n()->translate($category, $message, $params, $language ?: static::$app->language);
547
        }
548
549 245
        $placeholders = [];
550 245
        foreach ((array) $params as $name => $value) {
551 3
            $placeholders['{' . $name . '}'] = $value;
552
        }
553
554 245
        return ($placeholders === []) ? $message : strtr($message, $placeholders);
555
    }
556
557
    /**
558
     * Configures an object with the initial property values.
559
     * @param object $object the object to be configured
560
     * @param array $properties the property initial values given in terms of name-value pairs.
561
     * @return object the object itself
562
     */
563 3684
    public static function configure($object, $properties)
564
    {
565 3684
        foreach ($properties as $name => $value) {
566 3684
            $object->$name = $value;
567
        }
568
569 3684
        return $object;
570
    }
571
572
    /**
573
     * Returns the public member variables of an object.
574
     * This method is provided such that we can get the public member variables of an object.
575
     * It is different from "get_object_vars()" because the latter will return private
576
     * and protected variables if it is called within the object itself.
577
     * @param object $object the object to be handled
578
     * @return array the public member variables of the object
579
     */
580 3
    public static function getObjectVars($object)
581
    {
582 3
        return get_object_vars($object);
583
    }
584
}
585