GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( ecf3ef...78a151 )
by Robert
11:40
created

BaseYii::createObject()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 8.8571
c 0
b 0
f 0
ccs 12
cts 12
cp 1
cc 6
eloc 12
nc 5
nop 2
crap 6
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 the application is running in production environment.
35
 */
36
defined('YII_ENV_PROD') or define('YII_ENV_PROD', YII_ENV === 'prod');
37
/**
38
 * Whether the the application is running in development environment.
39
 */
40
defined('YII_ENV_DEV') or define('YII_ENV_DEV', YII_ENV === 'dev');
41
/**
42
 * Whether the the application is running in 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 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 66
    public static function getVersion()
95
    {
96 66
        return '2.0.14-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|bool 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 3350
    public static function getAlias($alias, $throwException = true)
132
    {
133 3350
        if (strncmp($alias, '@', 1)) {
134
            // not an alias
135 3210
            return $alias;
136
        }
137
138 3271
        $pos = strpos($alias, '/');
139 3271
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
140
141 3271
        if (isset(static::$aliases[$root])) {
142 3270
            if (is_string(static::$aliases[$root])) {
143 3270
                return $pos === false ? static::$aliases[$root] : static::$aliases[$root] . substr($alias, $pos);
144
            }
145
146 1
            foreach (static::$aliases[$root] as $name => $path) {
147 1
                if (strpos($alias . '/', $name . '/') === 0) {
148 1
                    return $path . substr($alias, strlen($name));
149
                }
150
            }
151
        }
152
153 16
        if ($throwException) {
154
            throw new InvalidArgumentException("Invalid path alias: $alias");
155
        }
156
157 16
        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|bool 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 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 3119
    public static function setAlias($alias, $path)
218
    {
219 3119
        if (strncmp($alias, '@', 1)) {
220
            $alias = '@' . $alias;
221
        }
222 3119
        $pos = strpos($alias, '/');
223 3119
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
224 3119
        if ($path !== null) {
225 3119
            $path = strncmp($path, '@', 1) ? rtrim($path, '\\/') : static::getAlias($path);
226 3119
            if (!isset(static::$aliases[$root])) {
227 8
                if ($pos === false) {
228 8
                    static::$aliases[$root] = $path;
229
                } else {
230 8
                    static::$aliases[$root] = [$alias => $path];
231
                }
232 3118
            } elseif (is_string(static::$aliases[$root])) {
233 3118
                if ($pos === false) {
234 3117
                    static::$aliases[$root] = $path;
235
                } else {
236 1
                    static::$aliases[$root] = [
237 1
                        $alias => $path,
238 3118
                        $root => static::$aliases[$root],
239
                    ];
240
                }
241
            } else {
242
                static::$aliases[$root][$alias] = $path;
243 3119
                krsort(static::$aliases[$root]);
244
            }
245 3
        } elseif (isset(static::$aliases[$root])) {
246 3
            if (is_array(static::$aliases[$root])) {
247 1
                unset(static::$aliases[$root][$alias]);
248 2
            } elseif ($pos === false) {
249 2
                unset(static::$aliases[$root]);
250
            }
251
        }
252 3119
    }
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 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 219
    public static function autoload($className)
278
    {
279 219
        if (isset(static::$classMap[$className])) {
280 122
            $classFile = static::$classMap[$className];
281 122
            if ($classFile[0] === '@') {
282 122
                $classFile = static::getAlias($classFile);
283
            }
284 125
        } elseif (strpos($className, '\\') !== false) {
285 105
            $classFile = static::getAlias('@' . str_replace('\\', '/', $className) . '.php', false);
286 105
            if ($classFile === false || !is_file($classFile)) {
287 105
                return;
288
            }
289
        } else {
290 24
            return;
291
        }
292
293 181
        include $classFile;
294
295 181
        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 181
    }
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 2965
    public static function createObject($type, array $params = [])
343
    {
344 2965
        if (is_string($type)) {
345 1028
            return static::$container->get($type, $params);
346 2933
        } elseif (is_array($type) && isset($type['class'])) {
347 2929
            $class = $type['class'];
348 2929
            unset($type['class']);
349 2929
            return static::$container->get($class, $params, $type);
350 8
        } elseif (is_callable($type, true)) {
351 6
            return static::$container->invoke($type, $params);
352 2
        } elseif (is_array($type)) {
353 1
            throw new InvalidConfigException('Object configuration must be an array containing a "class" element.');
354
        }
355
356 1
        throw new InvalidConfigException('Unsupported configuration type: ' . gettype($type));
357
    }
358
359
    private static $_logger;
360
361
    /**
362
     * @return Logger message logger
363
     */
364 1800
    public static function getLogger()
365
    {
366 1800
        if (self::$_logger !== null) {
367 1800
            return self::$_logger;
368
        }
369
370 1
        return self::$_logger = static::createObject('yii\log\Logger');
371
    }
372
373
    /**
374
     * Sets the logger object.
375
     * @param Logger $logger the logger object.
376
     */
377 12
    public static function setLogger($logger)
378
    {
379 12
        self::$_logger = $logger;
380 12
    }
381
382
    /**
383
     * Logs a debug message.
384
     * Trace messages are logged mainly for development purpose to see
385
     * the execution work flow of some code. This method will only log
386
     * a message when the application is in debug mode.
387
     * @param string|array $message the message to be logged. This can be a simple string or a more
388
     * complex data structure, such as array.
389
     * @param string $category the category of the message.
390
     * @since 2.0.14
391
     */
392 1664
    public static function debug($message, $category = 'application')
393
    {
394 1664
        if (YII_DEBUG) {
395 1664
            static::getLogger()->log($message, Logger::LEVEL_TRACE, $category);
396
        }
397 1664
    }
398
399
    /**
400
     * Alias of [[debug()]].
401
     * @param string|array $message the message to be logged. This can be a simple string or a more
402
     * complex data structure, such as array.
403
     * @param string $category the category of the message.
404
     * @deprecated 2.0.14 Use [[debug()]]
405
     */
406
    public static function trace($message, $category = 'application')
407
    {
408
        static::debug($message, $category);
409
    }
410
411
    /**
412
     * Logs an error message.
413
     * An error message is typically logged when an unrecoverable error occurs
414
     * during the execution of an application.
415
     * @param string|array $message the message to be logged. This can be a simple string or a more
416
     * complex data structure, such as array.
417
     * @param string $category the category of the message.
418
     */
419 5
    public static function error($message, $category = 'application')
420
    {
421 5
        static::getLogger()->log($message, Logger::LEVEL_ERROR, $category);
422 5
    }
423
424
    /**
425
     * Logs a warning message.
426
     * A warning message is typically logged when an error occurs while the execution
427
     * can still continue.
428
     * @param string|array $message the message to be logged. This can be a simple string or a more
429
     * complex data structure, such as array.
430
     * @param string $category the category of the message.
431
     */
432 14
    public static function warning($message, $category = 'application')
433
    {
434 14
        static::getLogger()->log($message, Logger::LEVEL_WARNING, $category);
435 14
    }
436
437
    /**
438
     * Logs an informative message.
439
     * An informative message is typically logged by an application to keep record of
440
     * something important (e.g. an administrator logs in).
441
     * @param string|array $message the message to be logged. This can be a simple string or a more
442
     * complex data structure, such as array.
443
     * @param string $category the category of the message.
444
     */
445 1596
    public static function info($message, $category = 'application')
446
    {
447 1596
        static::getLogger()->log($message, Logger::LEVEL_INFO, $category);
448 1596
    }
449
450
    /**
451
     * Marks the beginning of a code block for profiling.
452
     *
453
     * This has to be matched with a call to [[endProfile]] with the same category name.
454
     * The begin- and end- calls must also be properly nested. For example,
455
     *
456
     * ```php
457
     * \Yii::beginProfile('block1');
458
     * // some code to be profiled
459
     *     \Yii::beginProfile('block2');
460
     *     // some other code to be profiled
461
     *     \Yii::endProfile('block2');
462
     * \Yii::endProfile('block1');
463
     * ```
464
     * @param string $token token for the code block
465
     * @param string $category the category of this log message
466
     * @see endProfile()
467
     */
468 1540
    public static function beginProfile($token, $category = 'application')
469
    {
470 1540
        static::getLogger()->log($token, Logger::LEVEL_PROFILE_BEGIN, $category);
471 1540
    }
472
473
    /**
474
     * Marks the end of a code block for profiling.
475
     * This has to be matched with a previous call to [[beginProfile]] with the same category name.
476
     * @param string $token token for the code block
477
     * @param string $category the category of this log message
478
     * @see beginProfile()
479
     */
480 1540
    public static function endProfile($token, $category = 'application')
481
    {
482 1540
        static::getLogger()->log($token, Logger::LEVEL_PROFILE_END, $category);
483 1540
    }
484
485
    /**
486
     * Returns an HTML hyperlink that can be displayed on your Web page showing "Powered by Yii Framework" information.
487
     * @return string an HTML hyperlink that can be displayed on your Web page showing "Powered by Yii Framework" information
488
     * @deprecated 2.0.14
489
     */
490
    public static function powered()
491
    {
492
        return \Yii::t('yii', 'Powered by {yii}', [
493
            'yii' => '<a href="http://www.yiiframework.com/" rel="external">' . \Yii::t('yii',
494
                    'Yii Framework') . '</a>',
495
        ]);
496
    }
497
498
    /**
499
     * Translates a message to the specified language.
500
     *
501
     * This is a shortcut method of [[\yii\i18n\I18N::translate()]].
502
     *
503
     * The translation will be conducted according to the message category and the target language will be used.
504
     *
505
     * You can add parameters to a translation message that will be substituted with the corresponding value after
506
     * translation. The format for this is to use curly brackets around the parameter name as you can see in the following example:
507
     *
508
     * ```php
509
     * $username = 'Alexander';
510
     * echo \Yii::t('app', 'Hello, {username}!', ['username' => $username]);
511
     * ```
512
     *
513
     * Further formatting of message parameters is supported using the [PHP intl extensions](http://www.php.net/manual/en/intro.intl.php)
514
     * message formatter. See [[\yii\i18n\I18N::translate()]] for more details.
515
     *
516
     * @param string $category the message category.
517
     * @param string $message the message to be translated.
518
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
519
     * @param string $language the language code (e.g. `en-US`, `en`). If this is null, the current
520
     * [[\yii\base\Application::language|application language]] will be used.
521
     * @return string the translated message.
522
     */
523 761
    public static function t($category, $message, $params = [], $language = null)
524
    {
525 761
        if (static::$app !== null) {
526 527
            return static::$app->getI18n()->translate($category, $message, $params, $language ?: static::$app->language);
527
        }
528
529 234
        $placeholders = [];
530 234
        foreach ((array) $params as $name => $value) {
531 4
            $placeholders['{' . $name . '}'] = $value;
532
        }
533
534 234
        return ($placeholders === []) ? $message : strtr($message, $placeholders);
535
    }
536
537
    /**
538
     * Configures an object with the initial property values.
539
     * @param object $object the object to be configured
540
     * @param array $properties the property initial values given in terms of name-value pairs.
541
     * @return object the object itself
542
     */
543 3610
    public static function configure($object, $properties)
544
    {
545 3610
        foreach ($properties as $name => $value) {
546 3610
            $object->$name = $value;
547
        }
548
549 3610
        return $object;
550
    }
551
552
    /**
553
     * Returns the public member variables of an object.
554
     * This method is provided such that we can get the public member variables of an object.
555
     * It is different from "get_object_vars()" because the latter will return private
556
     * and protected variables if it is called within the object itself.
557
     * @param object $object the object to be handled
558
     * @return array the public member variables of the object
559
     */
560 3
    public static function getObjectVars($object)
561
    {
562 3
        return get_object_vars($object);
563
    }
564
}
565