Passed
Push — 2.2 ( d2c397...e7be9e )
by Paweł
06:27 queued 17s
created

BaseYii   F

Complexity

Total Complexity 62

Size/Duplication

Total Lines 490
Duplicated Lines 0 %

Test Coverage

Coverage 86.61%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 104
dl 0
loc 490
ccs 97
cts 112
cp 0.8661
rs 3.44
c 1
b 1
f 0
wmc 62

17 Methods

Rating   Name   Duplication   Size   Complexity  
A beginProfile() 0 3 1
A warning() 0 3 1
A error() 0 3 1
A info() 0 3 1
B autoload() 0 20 10
A endProfile() 0 3 1
A getRootAlias() 0 18 6
B getAlias() 0 27 9
A getVersion() 0 3 1
A getLogger() 0 7 2
A setLogger() 0 3 1
A debug() 0 4 2
A createObject() 0 27 6
C setAlias() 0 33 12
A getObjectVars() 0 3 1
A t() 0 12 5
A configure() 0 7 2

How to fix   Complexity   

Complex Class

Complex classes like BaseYii often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BaseYii, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://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 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 16
    public static function getVersion()
95
    {
96 16
        return '2.2-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 2374
    public static function getAlias($alias, $throwException = true)
132
    {
133 2374
        if (strncmp((string)$alias, '@', 1) !== 0) {
134
            // not an alias
135 2277
            return $alias;
136
        }
137
138 2295
        $pos = strpos($alias, '/');
139 2295
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
140
141 2295
        if (isset(static::$aliases[$root])) {
142 2286
            if (is_string(static::$aliases[$root])) {
143 2286
                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 27
        if ($throwException) {
154
            throw new InvalidArgumentException("Invalid path alias: $alias");
155
        }
156
157 27
        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|null $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. `https://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 2197
    public static function setAlias($alias, $path)
218
    {
219 2197
        if (strncmp($alias, '@', 1)) {
220
            $alias = '@' . $alias;
221
        }
222 2197
        $pos = strpos($alias, '/');
223 2197
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
224 2197
        if ($path !== null) {
225 2197
            $path = strncmp($path, '@', 1) ? rtrim($path, '\\/') : static::getAlias($path);
226 2197
            if (!isset(static::$aliases[$root])) {
227 10
                if ($pos === false) {
228 10
                    static::$aliases[$root] = $path;
229
                } else {
230 10
                    static::$aliases[$root] = [$alias => $path];
231
                }
232 2196
            } elseif (is_string(static::$aliases[$root])) {
233 2196
                if ($pos === false) {
234 2195
                    static::$aliases[$root] = $path;
235
                } else {
236 2196
                    static::$aliases[$root] = [
237 2196
                        $alias => $path,
238 2196
                        $root => static::$aliases[$root],
239 2196
                    ];
240
                }
241
            } else {
242
                static::$aliases[$root][$alias] = $path;
243 2197
                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
    }
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](https://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 2265
    public static function autoload($className)
278
    {
279 2265
        if (isset(static::$classMap[$className])) {
280 127
            $classFile = static::$classMap[$className];
281 127
            if (strncmp($classFile, '@', 1) === 0) {
282 127
                $classFile = static::getAlias($classFile);
283
            }
284 2242
        } elseif (strpos($className, '\\') !== false) {
285 2238
            $classFile = static::getAlias('@' . str_replace('\\', '/', $className) . '.php', false);
286 2238
            if ($classFile === false || !is_file($classFile)) {
287 2238
                return;
288
            }
289
        } else {
290 8
            return;
291
        }
292
293 182
        include $classFile;
294
295 182
        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 1540
    public static function createObject($type, array $params = [])
343
    {
344 1540
        if (is_string($type)) {
345 250
            return static::$container->get($type, $params);
346
        }
347
348 1530
        if (is_callable($type, true)) {
349 3
            return static::$container->invoke($type, $params);
350
        }
351
352 1528
        if (!is_array($type)) {
353 1
            throw new InvalidConfigException('Unsupported configuration type: ' . gettype($type));
354
        }
355
356 1527
        if (isset($type['__class'])) {
357 3
            $class = $type['__class'];
358 3
            unset($type['__class'], $type['class']);
359 3
            return static::$container->get($class, $params, $type);
360
        }
361
362 1525
        if (isset($type['class'])) {
363 1524
            $class = $type['class'];
364 1524
            unset($type['class']);
365 1524
            return static::$container->get($class, $params, $type);
366
        }
367
368 1
        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 425
    public static function getLogger()
377
    {
378 425
        if (self::$_logger !== null) {
379 425
            return self::$_logger;
380
        }
381
382 1
        return self::$_logger = static::createObject('yii\log\Logger');
383
    }
384
385
    /**
386
     * Sets the logger object.
387
     * @param Logger|null $logger the logger object.
388
     */
389 13
    public static function setLogger($logger)
390
    {
391 13
        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 349
    public static function debug($message, $category = 'application')
405
    {
406 349
        if (YII_DEBUG) {
407 349
            static::getLogger()->log($message, Logger::LEVEL_TRACE, $category);
408
        }
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 an array.
417
     * @param string $category the category of the message.
418
     */
419 4
    public static function error($message, $category = 'application')
420
    {
421 4
        static::getLogger()->log($message, Logger::LEVEL_ERROR, $category);
422
    }
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 an array.
430
     * @param string $category the category of the message.
431
     */
432 21
    public static function warning($message, $category = 'application')
433
    {
434 21
        static::getLogger()->log($message, Logger::LEVEL_WARNING, $category);
435
    }
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 an array.
443
     * @param string $category the category of the message.
444
     */
445 167
    public static function info($message, $category = 'application')
446
    {
447 167
        static::getLogger()->log($message, Logger::LEVEL_INFO, $category);
448
    }
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 90
    public static function beginProfile($token, $category = 'application')
469
    {
470 90
        static::getLogger()->log($token, Logger::LEVEL_PROFILE_BEGIN, $category);
471
    }
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 90
    public static function endProfile($token, $category = 'application')
481
    {
482 90
        static::getLogger()->log($token, Logger::LEVEL_PROFILE_END, $category);
483
    }
484
485
    /**
486
     * Translates a message to the specified language.
487
     *
488
     * This is a shortcut method of [[\yii\i18n\I18N::translate()]].
489
     *
490
     * The translation will be conducted according to the message category and the target language will be used.
491
     *
492
     * You can add parameters to a translation message that will be substituted with the corresponding value after
493
     * translation. The format for this is to use curly brackets around the parameter name as you can see in the following example:
494
     *
495
     * ```php
496
     * $username = 'Alexander';
497
     * echo \Yii::t('app', 'Hello, {username}!', ['username' => $username]);
498
     * ```
499
     *
500
     * Further formatting of message parameters is supported using the [PHP intl extensions](https://www.php.net/manual/en/intro.intl.php)
501
     * message formatter. See [[\yii\i18n\I18N::translate()]] for more details.
502
     *
503
     * @param string $category the message category.
504
     * @param string $message the message to be translated.
505
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
506
     * @param string|null $language the language code (e.g. `en-US`, `en`). If this is null, the current
507
     * [[\yii\base\Application::language|application language]] will be used.
508
     * @return string the translated message.
509
     */
510 974
    public static function t($category, $message, $params = [], $language = null)
511
    {
512 974
        if (static::$app !== null) {
513 755
            return static::$app->getI18n()->translate($category, $message, $params, $language ?: static::$app->language);
514
        }
515
516 219
        $placeholders = [];
517 219
        foreach ((array) $params as $name => $value) {
518
            $placeholders['{' . $name . '}'] = $value;
519
        }
520
521 219
        return ($placeholders === []) ? $message : strtr($message, $placeholders);
522
    }
523
524
    /**
525
     * Configures an object with the initial property values.
526
     * @param object $object the object to be configured
527
     * @param array $properties the property initial values given in terms of name-value pairs.
528
     * @return object the object itself
529
     */
530 2531
    public static function configure($object, $properties)
531
    {
532 2531
        foreach ($properties as $name => $value) {
533 2531
            $object->$name = $value;
534
        }
535
536 2531
        return $object;
537
    }
538
539
    /**
540
     * Returns the public member variables of an object.
541
     * This method is provided such that we can get the public member variables of an object.
542
     * It is different from "get_object_vars()" because the latter will return private
543
     * and protected variables if it is called within the object itself.
544
     * @param object $object the object to be handled
545
     * @return array the public member variables of the object
546
     */
547 3
    public static function getObjectVars($object)
548
    {
549 3
        return get_object_vars($object);
550
    }
551
}
552