Application.php 6.64 KB
Newer Older
Alexander Makarov committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Alexander Makarov committed
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\console;

10
use Yii;
Qiang Xue committed
11
use yii\base\InvalidRouteException;
Qiang Xue committed
12

Alexander Makarov committed
13
/**
Qiang Xue committed
14
 * Application represents a console application.
Alexander Makarov committed
15
 *
Carsten Brandt committed
16
 * Application extends from [[\yii\base\Application]] by providing functionalities that are
Alexander Makarov committed
17 18 19
 * specific to console requests. In particular, it deals with console requests
 * through a command-based approach:
 *
Qiang Xue committed
20
 * - A console application consists of one or several possible user commands;
Qiang Xue committed
21
 * - Each user command is implemented as a class extending [[\yii\console\Controller]];
Qiang Xue committed
22 23 24
 * - User specifies which command to run on the command line;
 * - The command processes the user request with the specified parameters.
 *
25
 * The command classes should be under the namespace specified by [[controllerNamespace]].
Qiang Xue committed
26
 * Their naming should follow the same naming convention as controllers. For example, the `help` command
Qiang Xue committed
27
 * is implemented using the `HelpController` class.
Alexander Makarov committed
28 29 30
 *
 * To run the console application, enter the following on the command line:
 *
Qiang Xue committed
31
 * ~~~
32
 * yii <route> [--param1=value1 --param2 ...]
Qiang Xue committed
33 34
 * ~~~
 *
Qiang Xue committed
35
 * where `<route>` refers to a controller route in the form of `ModuleID/ControllerID/ActionID`
Qiang Xue committed
36 37 38
 * (e.g. `sitemap/create`), and `param1`, `param2` refers to a set of named parameters that
 * will be used to initialize the controller action (e.g. `--since=0` specifies a `since` parameter
 * whose value is 0 and a corresponding `$since` parameter is passed to the action method).
Qiang Xue committed
39
 *
Qiang Xue committed
40
 * A `help` command is provided by default, which lists available commands and shows their usage.
Qiang Xue committed
41
 * To use this command, simply type:
Qiang Xue committed
42 43
 *
 * ~~~
44
 * yii help
Qiang Xue committed
45
 * ~~~
Alexander Makarov committed
46 47 48 49 50 51
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Application extends \yii\base\Application
{
52 53 54 55
    /**
     * The option name for specifying the application configuration file path.
     */
    const OPTION_APPCONFIG = 'appconfig';
56

57 58 59 60 61 62 63 64 65 66 67 68 69 70
    /**
     * @var string the default route of this application. Defaults to 'help',
     * meaning the `help` command.
     */
    public $defaultRoute = 'help';
    /**
     * @var boolean whether to enable the commands provided by the core framework.
     * Defaults to true.
     */
    public $enableCoreCommands = true;
    /**
     * @var Controller the currently active controller instance
     */
    public $controller;
Alexander Makarov committed
71

72

73 74 75 76 77 78 79 80
    /**
     * @inheritdoc
     */
    public function __construct($config = [])
    {
        $config = $this->loadConfig($config);
        parent::__construct($config);
    }
81

82 83 84 85 86
    /**
     * Loads the configuration.
     * This method will check if the command line option [[OPTION_APPCONFIG]] is specified.
     * If so, the corresponding file will be loaded as the application configuration.
     * Otherwise, the configuration provided as the parameter will be returned back.
87
     * @param array $config the configuration provided in the constructor.
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
     * @return array the actual configuration to be used by the application.
     */
    protected function loadConfig($config)
    {
        if (!empty($_SERVER['argv'])) {
            $option = '--' . self::OPTION_APPCONFIG . '=';
            foreach ($_SERVER['argv'] as $param) {
                if (strpos($param, $option) !== false) {
                    $path = substr($param, strlen($option));
                    if (!empty($path) && is_file($file = Yii::getAlias($path))) {
                        return require($file);
                    } else {
                        die("The configuration file does not exist: $path\n");
                    }
                }
            }
        }
105

106 107
        return $config;
    }
108

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    /**
     * Initialize the application.
     */
    public function init()
    {
        parent::init();
        if ($this->enableCoreCommands) {
            foreach ($this->coreCommands() as $id => $command) {
                if (!isset($this->controllerMap[$id])) {
                    $this->controllerMap[$id] = $command;
                }
            }
        }
        // ensure we have the 'help' command so that we can list the available commands
        if (!isset($this->controllerMap['help'])) {
            $this->controllerMap['help'] = 'yii\console\controllers\HelpController';
        }
    }
Alexander Makarov committed
127

128 129
    /**
     * Handles the specified request.
130
     * @param Request $request the request to be handled
131 132 133 134 135 136 137 138 139 140 141
     * @return Response the resulting response
     */
    public function handleRequest($request)
    {
        list ($route, $params) = $request->resolve();
        $this->requestedRoute = $route;
        $result = $this->runAction($route, $params);
        if ($result instanceof Response) {
            return $result;
        } else {
            $response = $this->getResponse();
142
            $response->exitStatus = $result;
143

144 145 146
            return $response;
        }
    }
147

148 149 150 151 152
    /**
     * Runs a controller action specified by a route.
     * This method parses the specified route and creates the corresponding child module(s), controller and action
     * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
     * If the route is empty, the method will use [[defaultRoute]].
153 154 155
     * @param string $route the route that specifies the action.
     * @param array $params the parameters to be passed to the action
     * @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal.
156 157 158 159 160
     * @throws Exception if the route is invalid
     */
    public function runAction($route, $params = [])
    {
        try {
161
            return (int)parent::runAction($route, $params);
162
        } catch (InvalidRouteException $e) {
163
            throw new Exception("Unknown command \"$route\".", 0, $e);
164 165
        }
    }
Qiang Xue committed
166

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    /**
     * Returns the configuration of the built-in commands.
     * @return array the configuration of the built-in commands.
     */
    public function coreCommands()
    {
        return [
            'message' => 'yii\console\controllers\MessageController',
            'help' => 'yii\console\controllers\HelpController',
            'migrate' => 'yii\console\controllers\MigrateController',
            'cache' => 'yii\console\controllers\CacheController',
            'asset' => 'yii\console\controllers\AssetController',
            'fixture' => 'yii\console\controllers\FixtureController',
        ];
    }

    /**
184
     * @inheritdoc
185
     */
186
    public function coreComponents()
187
    {
188
        return array_merge(parent::coreComponents(), [
189 190
            'request' => ['class' => 'yii\console\Request'],
            'response' => ['class' => 'yii\console\Response'],
191
            'errorHandler' => ['class' => 'yii\console\ErrorHandler'],
192
        ]);
193
    }
Alexander Makarov committed
194
}