CliController.php 10.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */
 
namespace Doctrine\Common\Cli;

/**
 * Generic CLI Controller of Tasks execution
 *
 * To include a new Task support, create a task:
 *
 *     [php]
 *     class MyProject\Tools\Cli\Tasks\MyTask extends Doctrine\ORM\Tools\Cli\Tasks\AbstractTask
 *     {
 *         public function run();
 *         public function basicHelp();
 *         public function extendedHelp();
 *         public function validate();
 *     }
 *
 * And then, load the namespace assoaicated an include the support to it in your command-line script:
 *
 *     [php]
 *     $cli = new Doctrine\Common\Cli\CliController();
 *     $cliNS = $cli->getNamespace('custom');
 *     $cliNS->addTask('myTask', 'MyProject\Tools\Cli\Tasks\MyTask');
 *
 * To execute, just type any classify-able name:
 *
 *     $ cli.php custom:my-task
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
class CliController extends AbstractNamespace
{
    /**
     * The CLI processor of tasks
     *
63
     * @param Configuration $config
64 65 66 67 68 69 70 71
     * @param AbstractPrinter $printer CLI Output printer
     */
    public function __construct(Configuration $config, AbstractPrinter $printer = null)
    {
        $this->setPrinter($printer);
        $this->setConfiguration($config);
        
        // Include core namespaces of tasks
romanb's avatar
romanb committed
72
        $ns = 'Doctrine\Common\Cli\Tasks';
73 74 75
        $this->addNamespace('Core')
             ->addTask('help', $ns . '\HelpTask');
        
romanb's avatar
romanb committed
76
        $ns = 'Doctrine\ORM\Tools\Cli\Tasks';
77 78 79 80 81 82 83 84 85
        $this->addNamespace('Orm')
             ->addTask('clear-cache', $ns . '\ClearCacheTask')
             ->addTask('convert-mapping', $ns . '\ConvertMappingTask')
             ->addTask('ensure-production-settings', $ns . '\EnsureProductionSettingsTask')
             ->addTask('generate-proxies', $ns . '\GenerateProxiesTask')
             ->addTask('run-dql', $ns . '\RunDqlTask')
             ->addTask('schema-tool', $ns . '\SchemaToolTask')
             ->addTask('version', $ns . '\VersionTask');
        
romanb's avatar
romanb committed
86
        $ns = 'Doctrine\DBAL\Tools\Cli\Tasks';
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
        $this->addNamespace('Dbal')
             ->addTask('run-sql', $ns . '\RunSqlTask');
    }
    
    /**
     * Add a single task to CLI Core Namespace. This method acts as a delegate.
     * Example of inclusion support to a single task:
     *
     *     [php]
     *     $cli->addTask('my-custom-task', 'MyProject\Cli\Tasks\MyCustomTask');
     *
     * @param string $name CLI Task name
     * @param string $class CLI Task class (FQCN - Fully Qualified Class Name)
     *
     * @return CliController This object instance
     */
    public function addTask($name, $class)
    {
        $this->getNamespace('Core')->addTask($name, $class);
        
        return $this;
    }
    
    /**
     * Processor of CLI Tasks. Handles multiple task calls, instantiate
     * respective classes and run them.
     *
     * @param array $args CLI Arguments
     */
    public function run($args = array())
    {
        // Remove script file argument
        $scriptFile = array_shift($args);
        
        // If not arguments are defined, include "help"
        if (empty($args)) {
            array_unshift($args, 'Core:Help');
        }
        
        // Process all sent arguments
        $args = $this->_processArguments($args);

        try {
            $this->getPrinter()->writeln('Doctrine Command Line Interface' . PHP_EOL, 'HEADER');
            
            // Handle possible multiple tasks on a single command
            foreach($args as $taskData) {
                $taskName = $taskData['name'];
                $taskArguments = $taskData['args'];
                
                $this->runTask($taskName, $taskArguments);
            }
        } catch (\Exception $e) {
            $message = $taskName . ' => ' . $e->getMessage();
            
            if (isset($taskArguments['trace']) && $taskArguments['trace']) {
                $message .= PHP_EOL . PHP_EOL . $e->getTraceAsString();
            }
                     
            $this->getPrinter()->writeln($message, 'ERROR');
        }
        
    }
    
    /**
     * Executes a given CLI Task
     *
     * @param atring $name CLI Task name
     * @param array $args CLI Arguments
     */
    public function runTask($name, $args = array())
    {
        // Retrieve namespace name, task name and arguments
        $taskPath = explode(':', $name);
                
        // Find the correct namespace where the task is defined
        $taskName = array_pop($taskPath);
        $taskNamespace = $this->_retrieveTaskNamespace($taskPath);
165
        
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        $taskNamespace->runTask($taskName, $args);
    }
    
    /**
     * Processes arguments and returns a structured hierachy.
     * Example:
     *
     * cli.php foo -abc --option=value bar --option -a=value --optArr=value1,value2
     *
     * Returns:
     *
     * array(
     *     0 => array(
     *         'name' => 'foo',
     *         'args' => array(
     *             'a' => true,
     *             'b' => true,
     *             'c' => true,
     *             'option' => 'value',
     *         ),
     *     ),
     *     1 => array(
     *         'name' => 'bar',
     *         'args' => array(
     *             'option' => true,
     *             'a' => 'value',
     *             'optArr' => array(
     *                 'value1', 'value2'
     *             ),
     *         ),
     *     ),
     * )
     *
     * Based on implementation of Patrick Fisher <patrick@pwfisher.com> available at:
     * http://pwfisher.com/nucleus/index.php?itemid=45
     *
     * @param array $args
     *
     * @return array
     */
    private function _processArguments($args = array())
    {
        $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE;
        $regex = '/\s*[,]?\s*"([^"]*)"|\s*[,]?\s*([^,]*)/i';
        $preparedArgs = array();
        $out = & $preparedArgs;
        
        foreach ($args as $arg){
            // --foo --bar=baz
            if (substr($arg, 0, 2) == '--'){
                $eqPos = strpos($arg, '=');
                
                // --foo
                if ($eqPos === false){
                    $key = substr($arg, 2);
                    $out[$key] = isset($out[$key]) ? $out[$key] : true;
                // --bar=baz
                } else {
                    $key = substr($arg, 2, $eqPos - 2);
                    $value = substr($arg, $eqPos + 1);
                    $value = (strpos($value, ' ') !== false) ? $value : array_values(array_filter(
                        explode(',', $value), function ($v) { return trim($v) != ''; }
                    ));
                    $out[$key] = ( ! is_array($value) || (is_array($value) && count($value) > 1)) 
                        ? $value : $value[0];
                }
            // -k=value -abc
            } else if (substr($arg, 0, 1) == '-'){
                // -k=value
                if (substr($arg, 2, 1) == '='){
                    $key = substr($arg, 1, 1);
                    $value = substr($arg, 3);
                    $value = (strpos($value, ' ') !== false) ? $value : array_values(array_filter(
                        explode(',', $value), function ($v) { return trim($v) != ''; }
                    ));
                    $out[$key] = ( ! is_array($value) || (is_array($value) && count($value) > 1)) 
                        ? $value : $value[0];
                // -abc
                } else {
                    $chars = str_split(substr($arg, 1));
                
                    foreach ($chars as $char){
                        $key = $char;
                        $out[$key] = isset($out[$key]) ? $out[$key] : true;
                    }
                }
            // plain-arg
            } else {
                $key = count($preparedArgs);
                $preparedArgs[$key] = array(
                    'name' => $arg,
                    'args' => array()
                );
                $out = & $preparedArgs[$key]['args'];
            }
        }
        
        return $preparedArgs;
    }

    /**
     * Retrieve the correct namespace given a namespace path
     *
     * @param array $namespacePath CLI Namespace path
     *
     * @return AbstractNamespace
     */
    private function _retrieveTaskNamespace($namespacePath)
    {
        $taskNamespace = $this;
        $currentNamespacePath = '';
        
        // Consider possible missing namespace (ie. "help") and forward to "core"
        if (count($namespacePath) == 0) {
            $namespacePath = array('Core');
        }
        
        // Loop through each namespace
        foreach ($namespacePath as $namespaceName) {
            $taskNamespace = $taskNamespace->getNamespace($namespaceName);
            
            // If the given namespace returned "null", throw exception
            if ($taskNamespace === null) {
                throw CliException::namespaceDoesNotExist($namespaceName, $currentNamespacePath);
            }
            
            $currentNamespacePath = (( ! empty($currentNamespacePath)) ? ':' : '') 
                                  . $taskNamespace->getName();
        }
        
        return $taskNamespace;
    }
}