Commit cb616956 authored by Roman S. Borschel's avatar Roman S. Borschel

Merge commit 'upstream/master'

parents 7cc56c45 b67e1f86
......@@ -2,12 +2,15 @@
require_once 'Doctrine/Common/ClassLoader.php';
$classLoader = new \Doctrine\Common\ClassLoader('Doctrine');
$classLoader = new \Doctrine\Common\ClassLoader('Doctrine', __DIR__ . '/../lib');
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader('Symfony', __DIR__ . '/../lib/vendor');
$classLoader->register();
$configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php';
$configuration = null;
$helperSet = null;
if (file_exists($configFile)) {
if ( ! is_readable($configFile)) {
trigger_error(
......@@ -17,15 +20,38 @@ if (file_exists($configFile)) {
require $configFile;
foreach ($GLOBALS as $configCandidate) {
if ($configCandidate instanceof \Doctrine\Common\CLI\Configuration) {
$configuration = $configCandidate;
foreach ($GLOBALS as $helperSetCandidate) {
if ($helperSetCandidate instanceof \Symfony\Components\Console\Helper\HelperSet) {
$helperSet = $helperSetCandidate;
break;
}
}
}
$configuration = ($configuration) ?: new \Doctrine\Common\CLI\Configuration();
$helperSet = ($helperSet) ?: new \Symfony\Components\Console\Helper\HelperSet();
$cli = new \Symfony\Components\Console\Application('Doctrine Command Line Interface', Doctrine\Common\Version::VERSION);
$cli->setCatchExceptions(true);
$cli->setHelperSet($helperSet);
$cli->addCommands(array(
// DBAL Commands
new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
// ORM Commands
new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
$cli = new \Doctrine\Common\CLI\CLIController($configuration);
$cli->run($_SERVER['argv']);
\ No newline at end of file
));
$cli->run();
\ No newline at end of file
<?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;
use Doctrine\Common\Util\Inflector;
/**
* Abstract CLI Namespace class
*
* @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>
*/
abstract class AbstractNamespace
{
/**
* @var Configuration CLI Configuration instance
*/
private $_configuration = null;
/**
* @var AbstractPrinter CLI Printer instance
*/
private $_printer = null;
/**
* @var AbstractNamespace CLI Namespace instance
*/
private $_parentNamespace = null;
/**
* @var array Available namespaces
*/
private $_namespaces = array();
/**
* Add a single namespace to CLI.
* Example of inclusion support to a single namespace:
*
* [php]
* $cliOrmNamespace->addNamespace('my-custom-namespace');
*
* @param string $name CLI Namespace name
*
* @return CliController This object instance
*/
public function addNamespace($name)
{
$name = self::formatName($name);
if ($this->hasNamespace($name)) {
throw CLIException::cannotOverrideNamespace($name);
}
return $this->overrideNamespace($name);
}
/**
* Overrides a namespace to CLI.
* Example of inclusion support to a single namespace:
*
* [php]
* $cli->overrideNamespace('orm');
*
* @param string $name CLI Namespace name
*
* @return AbstractNamespace Newly created CLI Namespace
*/
public function overrideNamespace($name)
{
$taskNamespace = new TaskNamespace($name);
$taskNamespace->setParentNamespace($this);
$taskNamespace->setPrinter($this->_printer);
$taskNamespace->setConfiguration($this->_configuration);
$this->_namespaces[$taskNamespace->getName()] = $taskNamespace;
return $taskNamespace;
}
/**
* Retrieve CLI Namespace.
* Example of usage:
*
* [php]
* $cliOrmNamespace = $cli->getNamespace('ORM');
*
* @param string $name CLI Namespace name
*
* @return TaskNamespace CLI Namespace
*/
public function getNamespace($name)
{
$name = self::formatName($name);
return isset($this->_namespaces[$name])
? $this->_namespaces[$name] : null;
}
/**
* Check existance of a CLI Namespace
*
* @param string CLI Namespace name
*
* @return boolean TRUE if namespace if defined, false otherwise
*/
public function hasNamespace($name)
{
return ($this->getNamespace($name) !== null);
}
/**
* Defines the parent CLI Namespace
*
* @return AbstractNamespace
*/
public function setParentNamespace(AbstractNamespace $namespace)
{
$this->_parentNamespace = $namespace;
return $this;
}
/**
* Retrieves currently parent CLI Namespace
*
* @return AbstractNamespace
*/
public function getParentNamespace()
{
return $this->_parentNamespace;
}
/**
* Retrieve all defined CLI Tasks
*
* @return array
*/
public function getAvailableTasks()
{
$tasks = array();
foreach ($this->_namespaces as $namespace) {
$tasks = array_merge($tasks, $namespace->getAvailableTasks());
}
return $tasks;
}
/**
* Defines the CLI Output Printer
*
* @param AbstractPrinter $printer CLI Output Printer
*
* @return AbstractNamespace
*/
public function setPrinter(Printers\AbstractPrinter $printer = null)
{
$this->_printer = $printer ?: new Printers\AnsiColorPrinter;
return $this;
}
/**
* Retrieves currently used CLI Output Printer
*
* @return AbstractPrinter
*/
public function getPrinter()
{
return $this->_printer;
}
/**
* Defines the CLI Configuration
*
* #param Configuration $configuration CLI Configuration
*
* @return AbstractNamespace
*/
public function setConfiguration(Configuration $config)
{
$this->_configuration = $config;
return $this;
}
/**
* Retrieves currently used CLI Configuration
*
* @return Configuration
*/
public function getConfiguration()
{
return $this->_configuration;
}
/**
* Formats the CLI Namespace name into a camel-cased name
*
* @param string $name CLI Namespace name
*
* @return string Formatted CLI Namespace name
*/
public static function formatName($name)
{
return Inflector::classify($name);
}
}
\ No newline at end of file
This diff is collapsed.
<?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;
/**
* CLI Exception class
*
* @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 CLIException extends \Exception
{
public static function namespaceDoesNotExist($namespaceName, $namespacePath = '')
{
return new self(
"Namespace '{$namespaceName}' does not exist" .
(( ! empty($namespacePath)) ? " in '{$namespacePath}'." : '.')
);
}
public static function taskDoesNotExist($taskName, $namespacePath)
{
return new self("Task '{$taskName}' does not exist in '{$namespacePath}'.");
}
public static function cannotOverrideTask($taskName)
{
return new self("Task '{$taskName}' cannot be overriden.");
}
public static function cannotOverrideNamespace($namespace) {
return new self("Namespace '$namespace' cannot be overriden. Call overrideNamespace() directly.");
}
}
\ No newline at end of file
<?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;
/**
* CLI Option definition
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class Option
{
/** @var string Option name */
private $_name;
/** @var string Option default value */
private $_defaultValue;
/** @var string Option description */
private $description;
/**
* Constructs a CLI Option
*
* @param string Option name
* @param integer Option type
* @param string Option description
*/
public function __construct($name, $defaultValue, $description)
{
$this->_name = $name;
$this->_defaultValue = $defaultValue;
$this->_description = $description;
}
/**
* Retrieves the CLI Option name
*
* @return string Option name
*/
public function getName()
{
return $this->_name;
}
/**
* Retrieves the CLI Option default value
*
* @return mixed Option default value
*/
public function getDefaultValue()
{
return $this->_defaultValue;
}
/**
* Retrieves the CLI Option description
*
* @return string Option description
*/
public function getDescription()
{
return $this->_description;
}
/**
* Converts the Option instance into a string representation
*
* @return string CLI Option representation in string
*/
public function __toString()
{
$defaultValue = ( ! is_null($this->_defaultValue))
? '=' . (is_array($this->_defaultValue) ? implode(',', $this->_defaultValue) : $this->_defaultValue)
: '';
return '--' . $this->_name . $defaultValue;
}
}
\ No newline at end of file
This diff is collapsed.
<?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\Printers;
use Doctrine\Common\CLI\Style;
/**
* CLI Output Printer.
* Abstract class responsable to provide basic methods to support output
* styling and excerpt limited by output margin.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
abstract class AbstractPrinter
{
/**
* @var resource Output Stream
*/
protected $_stream;
/**
* @var integer Maximum column size
*/
protected $_maxColumnSize;
/**
* @var array Array of Styles
*/
protected $_styles;
/**
* Creates an instance of Printer
*
* @param resource $stream Output Stream
*/
public function __construct($stream = STDOUT)
{
$this->_stream = $stream;
$this->_maxColumnSize = 80;
$this->_initStyles();
}
/**
* Initializes Printer Styles
*
*/
protected function _initStyles()
{
// Defines base styles
$this->addStyles(array(
'ERROR' => new Style(),
'INFO' => new Style(),
'COMMENT' => new Style(),
'HEADER' => new Style(),
'NONE' => new Style(),
));
}
/**
* Add a collection of styles to the Printer.
* To include them, just call the method with the following structure:
*
* [php]
* $printer->addStyles(array(
* 'ERROR' => new Style('BLACK', 'DEFAULT', array('BOLD' => true)),
* ...
* ));
*
* @param array $tasks CLI Tasks to be included
*/
public function addStyles($styles)
{
foreach ($styles as $name => $style) {
$this->addStyle($name, $style);
}
}
/**
* Add a single Style to Printer.
* Example of inclusion to support a new Style:
*
* [php]
* $printer->addStyle('ERROR', new Style('BLACK', 'DEFAULT', array('BOLD' => true)));
*
* @param string $name Style name
* @param Style $style Style instance
*/
public function addStyle($name, Style $style)
{
$this->_styles[strtoupper($name)] = $style;
}
/**
* Retrieves a defined Style.
*
* @return Style
*/
public function getStyle($name)
{
if (is_string($name)) {
$name = strtoupper($name);
return isset($this->_styles[$name]) ? $this->_styles[$name] : null;
}
return $name;
}
/**
* Sets the maximum column size (defines the CLI margin).
*
* @param integer $maxColumnSize The maximum column size for a message
*/
public function setMaxColumnSize($maxColumnSize)
{
$this->_maxColumnSize = $maxColumnSize;
}
/**
* Writes to the output stream.
*
* @param string $message Message to be outputted
*/
public function output($message)
{
fwrite($this->_stream, $message);
return $this;
}
/**
* Formats message applying the defined style and writes to the output stream.
*
* @param string $message Message to be outputted
* @param mixed $style Optional style to be applied in message
*/
public function write($message, $style = 'NONE')
{
$this->output($this->format($message, $style));
return $this;
}
/**
* Writes a line to the output stream, formatting it by applying the defined style.
*
* @param string $message Message to be outputted
* @param mixed $style Optional style to be applied in message
*/
public function writeln($message, $style = 'NONE')
{
$this->output($this->format($message, $style) . PHP_EOL);
return $this;
}
/**
* Formats the given message with the defined style.
*
* @param string $message Message to be formatted
* @param mixed $style Style to be applied in message
* @return string Formatted message
*/
abstract public function format($message, $style);
}
\ No newline at end of file
<?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\Printers;
use Doctrine\Common\CLI\Style;
/**
* CLI Output Printer for ANSI Color terminal
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class AnsiColorPrinter extends AbstractPrinter
{
/**
* @inheritdoc
*/
protected function _initStyles()
{
$this->addStyles(array(
'HEADER' => new Style('DEFAULT', 'DEFAULT', array('BOLD' => true)),
'ERROR' => new Style('WHITE', 'RED', array('BOLD' => true)),
'WARNING' => new Style('DEFAULT', 'YELLOW'),
'KEYWORD' => new Style('BLUE', 'DEFAULT', array('BOLD' => true)),
'REQ_ARG' => new Style('MAGENTA', 'DEFAULT', array('BOLD' => true)),
'OPT_ARG' => new Style('CYAN', 'DEFAULT', array('BOLD' => true)),
'INFO' => new Style('GREEN', 'DEFAULT', array('BOLD' => true)),
'COMMENT' => new Style('DEFAULT', 'MAGENTA'),
'NONE' => new Style(),
));
}
/**
* @inheritdoc
*/
public function format($message, $style = 'NONE')
{
if ( ! $this->_supportsColor()) {
return $message;
}
$style = $this->getStyle($style);
$str = $this->_getForegroundString($style)
. $this->_getBackgroundString($style);
$styleSet = ($str != '');
return $str . $message . ($styleSet ? chr(27) . '[0m' : '');
}
/**
* Retrieves the ANSI string representation of requested color name
*
* @param Style $style Style
* @return string
*/
protected function _getBackgroundString(Style $style)
{
$background = $style->getBackground();
if (empty($background)) {
return '';
}
$esc = chr(27);
switch (strtoupper($background)) {
case 'BLACK':
return $esc . '[40m';
case 'RED':
return $esc . '[41m';
case 'GREEN':
return $esc . '[42m';
case 'YELLOW':
return $esc . '[43m';
case 'BLUE':
return $esc . '[44m';
case 'MAGENTA':
return $esc . '[45m';
case 'CYAN':
return $esc . '[46m';
case 'WHITE':
return $esc . '[47m';
case 'DEFAULT':
default:
return $esc . '[48m';
}
}
/**
* Retrieves the ANSI string representation of requested color name
*
* @param Style $style Style
* @return string
*/
protected function _getForegroundString(Style $style)
{
$foreground = $style->getForeground();
if (empty($foreground)) {
return '';
}
$str = chr(27) . '[' . $this->_getOptionsString($style);
switch (strtoupper($foreground)) {
case 'BLACK':
return $str . '30m';
case 'RED':
return $str . '31m';
case 'GREEN':
return $str . '32m';
case 'YELLOW':
return $str . '33m';
case 'BLUE':
return $str . '34m';
case 'MAGENTA':
return $str . '35m';
case 'CYAN':
return $str . '36m';
case 'WHITE':
return $str . '37m';
case 'DEFAULT_FGU':
return $str . '38m';
case 'DEFAULT':
default:
return $str . '39m';
}
}
/**
* Retrieves the ANSI string representation of requested options
*
* @param Style $style Style
* @return string
*/
protected function _getOptionsString(Style $style)
{
$options = $style->getOptions();
if (empty($options)) {
return '';
}
$str = '';
foreach ($options as $name => $value) {
if ($value) {
$name = strtoupper($name);
switch ($name) {
case 'BOLD':
$str .= '1;';
break;
case 'HALF':
$str .= '2;';
break;
case 'UNDERLINE':
$str .= '4;';
break;
case 'BLINK':
$str .= '5;';
break;
case 'REVERSE':
$str .= '7;';
break;
case 'CONCEAL':
$str .= '8;';
break;
default:
// Ignore unknown option
break;
}
}
}
return $str;
}
/**
* Checks if the current Output Stream supports ANSI Colors
*
* @return boolean
*/
private function _supportsColor()
{
return DIRECTORY_SEPARATOR != '\\' &&
function_exists('posix_isatty') &&
@posix_isatty($this->_stream);
}
}
\ No newline at end of file
<?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\Printers;
use Doctrine\Common\CLI\Style;
/**
* CLI Output Printer for Normal terminal
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class NormalPrinter extends AbstractPrinter
{
/**
* @inheritdoc
*/
public function format($message, $style)
{
return $message;
}
}
\ No newline at end of file
<?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;
/**
* CLI Output Style
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class Style
{
/**
* @var string Background color
*/
private $_background;
/**
* @var string Foreground color
*/
private $_foreground;
/**
* @var array Formatting options
*/
private $_options = array();
/**
* @param string $foreground Foreground color name
* @param string $background Background color name
* @param array $options Formatting options
*/
public function __construct($foreground = null, $background = null, $options = array())
{
$this->_foreground = strtoupper($foreground);
$this->_background = strtoupper($background);
$this->_options = $options;
}
/**
* Retrieves the foreground color name
*
* @return string
*/
public function getForeground()
{
return $this->_foreground;
}
/**
* Retrieves the background color name
*
* @return string
*/
public function getBackground()
{
return $this->_background;
}
/**
* Retrieves the formatting options
*
* @return string
*/
public function getOptions()
{
return $this->_options;
}
}
\ No newline at end of file
<?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;
use Doctrine\Common\CLI\Printers\AbstractPrinter,
Doctrine\Common\CLI\OptionGroup,
Doctrine\Common\CLI\Option;
/**
* CLI Task documentation
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class TaskDocumentation
{
/** @var AbstractPrinter CLI Printer */
private $_printer;
/** @var AbstractNamespace CLI Namespace */
private $_namespace;
/** @var string CLI Task name */
private $_name;
/** @var string CLI Task description */
private $_description;
/** @var array CLI Task Option Group */
private $_optionGroup;
/**
* Constructs a new CLI Task Documentation
*
* @param AbstractNamespace CLI Namespace
*/
public function __construct(AbstractNamespace $namespace)
{
$this->_namespace = $namespace;
$this->_printer = $namespace->getPrinter();
$this->_optionGroup = new OptionGroup(OptionGroup::CARDINALITY_M_N);
}
/**
* Retrieves the CLI Namespace
*
* @return AbstractNamespace
*/
public function getNamespace()
{
return $this->_namespace;
}
/**
* Defines the CLI Task name
*
* @param string Task name
* @return TaskDocumentation This object instance
*/
public function setName($name)
{
$this->_name = $name;
return $this;
}
/**
* Retrieves the CLI Task name
*
* @return string Task name
*/
public function getName()
{
return $this->_name;
}
/**
* Retrieves the full CLI Task name
*
* @return string Task full name
*/
public function getFullName()
{
return $this->getNamespace()->getFullName() . ':' . $this->_name;
}
/**
* Defines the CLI Task description
*
* @param string Task description
* @return TaskDocumentation This object instance
*/
public function setDescription($description)
{
$this->_description = $description;
return $this;
}
/**
* Retrieves the CLI Task description
*
* @var string Task description
*/
public function getDescription()
{
return $this->_description;
}
/**
* Retrieves the CLI Task Option Group
*
* @return OptionGroup CLI Task Option Group
*/
public function getOptionGroup()
{
return $this->_optionGroup;
}
/**
* Includes a new CLI Option Group to the CLI Task documentation
*
* @param OptionGroup CLI Option Group
* @return TaskDocumentation This object instance
*/
public function addOption($option)
{
if ($option instanceof OptionGroup) {
$this->_optionGroup->addOption($option);
}
return $this;
}
/**
* Retrieves the synopsis of associated CLI Task
*
* @return string CLI Task synopsis
*/
public function getSynopsis()
{
return $this->_printer->format($this->getFullName(), 'KEYWORD') . ' '
. trim($this->_optionGroup->formatPlain($this->_printer));
}
/**
* Retrieve the complete documentation of associated CLI Task
*
* @return string CLI Task complete documentation
*/
public function getCompleteDocumentation()
{
$printer = $this->_printer;
return $printer->format('Task: ')
. $printer->format($this->getFullName(), 'KEYWORD')
. $printer->format(PHP_EOL)
. $printer->format('Synopsis: ')
. $this->getSynopsis()
. $printer->format(PHP_EOL)
. $printer->format('Description: ')
. $printer->format($this->_description)
. $printer->format(PHP_EOL)
. $printer->format('Options: ')
. $printer->format(PHP_EOL)
. $this->_optionGroup->formatWithDescription($printer);
}
}
<?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;
/**
* CLI Namespace class
*
* @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 TaskNamespace extends AbstractNamespace
{
/**
* @var boolean CLI Tasks flag to check if they are already initialized
*/
private $_initialized = false;
/**
* @var string CLI Namespace full name
*/
private $_fullName = null;
/**
* @var string CLI Namespace name
*/
private $_name = null;
/**
* @var array Available tasks
*/
private $_tasks = array();
/**
* The CLI namespace
*
* @param string $name CLI Namespace name
*/
public function __construct($name)
{
$this->_name = self::formatName($name);
}
/**
* Retrieve an instantiated CLI Task by given its name.
*
* @param string $name CLI Task name
*
* @return AbstractTask
*/
public function getTask($name)
{
// Check if task exists in namespace
if ($this->hasTask($name)) {
$taskClass = $this->_tasks[self::formatName($name)];
return new $taskClass($this);
}
throw CLIException::taskDoesNotExist($name, $this->getFullName());
}
/**
* Retrieve all CLI Task in this Namespace.
*
* @return array
*/
public function getTasks()
{
return $this->_tasks;
}
/**
* Retrieve all defined CLI Tasks
*
* @return array
*/
public function getAvailableTasks()
{
$tasks = parent::getAvailableTasks();
foreach ($this->_tasks as $taskName => $taskClass) {
$fullName = $this->getFullName() . ':' . $taskName;
$tasks[$fullName] = $taskClass;
}
return $tasks;
}
/**
* Add a single task to CLI Namespace.
* Example of inclusion support to a single task:
*
* [php]
* $cliOrmNamespace->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 TaskNamespace This object instance
*/
public function addTask($name, $class)
{
$name = self::formatName($name);
if ($this->hasTask($name)) {
throw CLIException::cannotOverrideTask($name);
}
return $this->overrideTask($name, $class);
}
/**
* Overrides task on CLI Namespace.
* Example of inclusion support to a single task:
*
* [php]
* $cliOrmNamespace->overrideTask('schema-tool', 'MyProject\Cli\Tasks\MyCustomTask');
*
* @param string $name CLI Task name
* @param string $class CLI Task class (FQCN - Fully Qualified Class Name)
*
* @return TaskNamespace This object instance
*/
public function overrideTask($name, $class)
{
$name = self::formatName($name);
$this->_tasks[$name] = $class;
return $this;
}
/**
* Check existance of a CLI Task
*
* @param string CLI Task name
*
* @return boolean TRUE if CLI Task if defined, false otherwise
*/
public function hasTask($name)
{
$name = self::formatName($name);
return isset($this->_tasks[$name]);
}
/**
* Retrieves the CLI Namespace name
*
* @return string CLI Namespace name
*/
public function getName()
{
return $this->_name;
}
/**
* Retrieves the full CLI Namespace name
*
* @return string CLI Namespace full name
*/
public function getFullName()
{
if ($this->_fullName === null) {
$str = $this->_name;
while (
($parentNamespace = $this->getParentNamespace()) !== null &&
! ($parentNamespace instanceof CliController)
) {
$str = $parentNamespace->getFullName() . ':' . $str;
}
$this->_fullName = $str;
}
return $this->_fullName;
}
/**
* Effectively instantiate and execute a given CLI Task
*
* @param string $name CLI Task name
* @param array $arguments CLI Task arguments
*/
public function runTask($name, $arguments = array())
{
try {
$task = $this->getTask($name);
// Merge global configuration if it exists
if (($globalArgs = $this->getConfiguration()->getAttribute('globalArguments')) !== null) {
$arguments = array_merge($globalArgs, $arguments);
}
$task->setArguments($arguments);
if ((isset($arguments['help']) && $arguments['help']) || (isset($arguments['h']) && $arguments['h'])) {
$task->extendedHelp(); // User explicitly asked for help option
} else if (isset($arguments['basic-help']) && $arguments['basic-help']) {
$task->basicHelp(); // User explicitly asked for basic help option
} else if ($task->validate()) {
$task->run();
}
} catch (CLIException $e) {
$message = $this->getFullName() . ':' . $name . ' => ' . $e->getMessage();
$printer = $this->getPrinter();
// If we want the trace of calls, append to error message
if (isset($arguments['trace']) && $arguments['trace']) {
$message .= PHP_EOL . PHP_EOL . $e->getTraceAsString();
}
$printer->writeln($message, 'ERROR');
// Unable instantiate task or task is not valid
if (isset($task) && $task !== null) {
$printer->write(PHP_EOL);
$task->basicHelp(); // Fallback of not-valid task arguments
}
$printer->write(PHP_EOL);
}
}
}
\ No newline at end of file
<?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\Tasks;
use Doctrine\Common\CLI\AbstractNamespace,
Doctrine\Common\CLI\TaskDocumentation;
/**
* Base class for CLI Tasks.
* Provides basic methods and requires implementation of methods that
* each task should implement in order to correctly work.
*
* @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>
*/
abstract class AbstractTask
{
/**
* @var AbstractNamespace CLI Namespace
*/
protected $_printer;
/**
* @var TaskDocumentation CLI Task Documentation
*/
protected $_documentation;
/**
* @var array CLI Task arguments
*/
protected $_arguments = array();
/**
* Constructor of CLI Task
*
* @param AbstractNamespace CLI Namespace
*/
public function __construct(AbstractNamespace $namespace)
{
$this->_namespace = $namespace;
$this->_documentation = new TaskDocumentation($namespace);
// Complete the CLI Task Documentation creation
$this->buildDocumentation();
}
/**
* Retrieves the CLI Namespace
*
* @return AbstractNamespace
*/
public function getNamespace()
{
return $this->_namespace;
}
/**
* Retrieves the CLI Task Documentation
*
* @return TaskDocumentation
*/
public function getDocumentation()
{
return $this->_documentation;
}
/**
* Defines the CLI Task arguments
*
* @param array $arguments CLI Task arguments
*
* @return AbstractTask
*/
public function setArguments(array $arguments = array())
{
$this->_arguments = $arguments;
return $this;
}
/**
* Retrieves the CLI Task arguments
*
* @return array
*/
public function getArguments()
{
return $this->_arguments;
}
/**
* Retrieves currently used CLI Output Printer
*
* @return AbstractPrinter
*/
public function getPrinter()
{
return $this->_namespace->getPrinter();
}
/**
* Retrieves current used CLI Configuration
*
* @return Configuration
*/
public function getConfiguration()
{
return $this->_namespace->getConfiguration();
}
/**
* Expose to CLI Output Printer the extended help of the given task.
* This means it should detail all parameters, options and the meaning
* of each one.
* This method is executed when user types in CLI the following command:
*
* [bash]
* ./doctrine task --help
*
*/
public function extendedHelp()
{
$this->getPrinter()->output($this->_documentation->getCompleteDocumentation());
}
/**
* Expose to CLI Output Printer the basic help of the given task.
* This means it should only expose the basic task call. It is also
* executed when user calls the global help; so this means it should
* not pollute the Printer.
* Basic help exposure is displayed when task does not pass the validate
* (which means when user does not type the required options or when given
* options are invalid, ie: invalid option), or when user requests to have
* description of all available tasks.
* This method is executed when user uses the following commands:
*
* [bash]
* ./doctrine task --invalid-option
* ./doctrine --help
*
*/
public function basicHelp()
{
$this->getPrinter()
->output($this->_documentation->getSynopsis())
->output(PHP_EOL)
->output(' ' . $this->_documentation->getDescription())
->output(PHP_EOL . PHP_EOL);
}
/**
* Assures the given arguments matches with required/optional ones.
* This method should be used to introspect arguments to check for
* missing required arguments and also for invalid defined options.
*
* @return boolean
*/
public function validate()
{
// TODO implement DAG here!
return true;
}
/**
* Safely execution of task.
* Each CLI task should implement this as normal flow execution of
* what is supposed to do.
*/
abstract public function run();
/**
* Generate the CLI Task Documentation
*/
abstract public function buildDocumentation();
}
......@@ -38,7 +38,7 @@ class Version
/**
* Current Doctrine Version
*/
const VERSION = '2.0 ALPHA 4';
const VERSION = '2.0-DEV';
/**
* Compares a Doctrine version with the current one.
......
......@@ -19,100 +19,67 @@
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Tools\CLI\Tasks;
namespace Doctrine\DBAL\Tools\Console\Command;
use Doctrine\Common\CLI\Tasks\AbstractTask,
Doctrine\Common\CLI\CLIException,
Doctrine\Common\Util\Debug,
Doctrine\Common\CLI\Option,
Doctrine\Common\CLI\OptionGroup;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console;
/**
* Task for executing arbitrary SQL that can come from a file or directly from
* the command line.
*
*
* @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 RunSqlTask extends AbstractTask
class ImportCommand extends Console\Command\Command
{
/**
* @inheritdoc
* @see Console\Command\Command
*/
public function buildDocumentation()
protected function configure()
{
$dqlAndFile = new OptionGroup(OptionGroup::CARDINALITY_1_1, array(
new Option(
'sql', '<SQL>', 'The SQL to execute.' . PHP_EOL .
'If defined, --file can not be requested on same task.'
),
new Option(
'file', '<PATH>', 'The path to the file with the SQL to execute.' . PHP_EOL .
'If defined, --sql can not be requested on same task.'
$this
->setName('dbal:import')
->setDescription('Import SQL file(s) directly to Database.')
->setDefinition(array(
new InputArgument(
'file', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'File path(s) of SQL to be executed.'
)
));
$depth = new OptionGroup(OptionGroup::CARDINALITY_0_1, array(
new Option('depth', '<DEPTH>', 'Dumping depth of Entities graph.')
));
$doc = $this->getDocumentation();
$doc->setName('run-sql')
->setDescription('Executes arbitrary SQL from a file or directly from the command line.')
->getOptionGroup()
->addOption($dqlAndFile)
->addOption($depth);
}
/**
* @inheritdoc
*/
public function validate()
{
$arguments = $this->getArguments();
$em = $this->getConfiguration()->getAttribute('em');
if ($em === null) {
throw new CLIException(
"Attribute 'em' of CLI Configuration is not defined or it is not a valid EntityManager."
);
}
if ( ! (isset($arguments['sql']) ^ isset($arguments['file']))) {
throw new CLIException('One of --sql or --file required, and only one.');
}
return true;
))
->setHelp(<<<EOT
Import SQL file(s) directly to Database.
EOT
);
}
/**
* Executes the task.
* @see Console\Command\Command
*/
public function run()
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$arguments = $this->getArguments();
if (isset($arguments['file'])) {
$em = $this->getConfiguration()->getAttribute('em');
$conn = $em->getConnection();
$printer = $this->getPrinter();
$fileNames = (array) $arguments['file'];
foreach ($fileNames as $fileName) {
$conn = $this->getHelper('db')->getConnection();
if (($fileNames = $input->getArgument('file')) !== null) {
foreach ((array) $fileNames as $fileName) {
$fileName = realpath($fileName);
if ( ! file_exists($fileName)) {
throw new CLIException(sprintf('The SQL file [%s] does not exist.', $fileName));
throw new \InvalidArgumentException(
sprintf("SQL file '<info>%s</info>' does not exist.", $fileName)
);
} else if ( ! is_readable($fileName)) {
throw new CLIException(sprintf('The SQL file [%s] does not have read permissions.', $fileName));
throw new \InvalidArgumentException(
sprintf("SQL file '<info>%s</info>' does not have read permissions.", $fileName)
);
}
$printer->write('Processing file [' . $fileName . ']... ');
$output->write(sprintf("Processing file '<info>%s</info>'... ", $fileName));
$sql = file_get_contents($fileName);
if ($conn instanceof \Doctrine\DBAL\Driver\PDOConnection) {
......@@ -123,49 +90,38 @@ class RunSqlTask extends AbstractTask
$stmt = $conn->prepare($sql);
$stmt->execute();
do {
do {
// Required due to "MySQL has gone away!" issue
$stmt->fetch();
$stmt->fetch();
$stmt->closeCursor();
$lines++;
$lines++;
} while ($stmt->nextRowset());
$printer->writeln(sprintf('%d statements executed!', $lines));
$output->write(sprintf('%d statements executed!', $lines) . PHP_EOL);
} catch (\PDOException $e) {
$printer->writeln('error!')
->writeln($e->getMessage());
$output->write('error!' . PHP_EOL);
throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);
}
} else {
// Non-PDO Drivers (ie. OCI8 driver)
$stmt = $conn->prepare($sql);
$rs = $stmt->execute();
if ($rs) {
$printer->writeln('OK!');
} else {
$error = $stmt->errorInfo();
$printer->writeln('error!')
->writeln($error['message']);
$output->write('error!' . PHP_EOL);
throw new \RuntimeException($error[2], $error[0]);
}
$stmt->closeCursor();
}
}
} else if (isset($arguments['sql'])) {
$em = $this->getConfiguration()->getAttribute('em');
if (preg_match('/^select/i', $arguments['sql'])) {
$stmt = $em->getConnection()->executeQuery($arguments['sql']);
$resultSet = $stmt->fetchAll(\Doctrine\DBAL\Connection::FETCH_ASSOC);
} else {
$resultSet = $em->getConnection()->executeUpdate($arguments['sql']);
}
$maxDepth = isset($arguments['depth']) ? $arguments['depth'] : 7;
Debug::dump($resultSet, $maxDepth);
}
}
}
\ No newline at end of file
......@@ -18,15 +18,17 @@
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Tools\CLI\Tasks;
use Doctrine\Common\CLI\Tasks\AbstractTask,
Doctrine\Common\Version;
namespace Doctrine\DBAL\Tools\Console\Command;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* CLI Task to display the doctrine version
*
* Task for executing arbitrary SQL that can come from a file or directly from
* the command line.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
......@@ -36,27 +38,49 @@ use Doctrine\Common\CLI\Tasks\AbstractTask,
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class VersionTask extends AbstractTask
class RunSqlCommand extends Console\Command\Command
{
/**
* @inheritdoc
* @see Console\Command\Command
*/
public function buildDocumentation()
protected function configure()
{
// There're no options on this task
$this->getDocumentation()->getOptionGroup()->clear();
$doc = $this->getDocumentation();
$doc->setName('version')
->setDescription('Displays the current installed Doctrine version.');
$this
->setName('dbal:run-sql')
->setDescription('Executes arbitrary SQL directly from the command line.')
->setDefinition(array(
new InputArgument('sql', InputArgument::REQUIRED, 'The SQL statement to execute.'),
new InputOption('depth', null, InputOption::PARAMETER_REQUIRED, 'Dumping depth of result set.', 7)
))
->setHelp(<<<EOT
Executes arbitrary SQL directly from the command line.
EOT
);
}
/**
* Displays the current version of Doctrine
*
* @see Console\Command\Command
*/
public function run()
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$this->getPrinter()->writeln('You are currently running Doctrine ' . Version::VERSION, 'INFO');
$conn = $this->getHelper('db')->getConnection();
if (($sql = $input->getArgument('sql')) === null) {
throw new \RuntimeException("Argument 'SQL' is required in order to execute this command correctly.");
}
$depth = $input->getOption('depth');
if ( ! is_numeric($depth)) {
throw new \LogicException("Option 'depth' must contains an integer value");
}
if (preg_match('/^select/i', $sql)) {
$resultSet = $conn->fetchAll($sql);
} else {
$resultSet = $em->getConnection()->executeUpdate($sql);
}
\Doctrine\Common\Util\Debug::dump($resultSet, (int) $depth);
}
}
\ No newline at end of file
......@@ -18,13 +18,14 @@
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\CLI\Tasks;
use Doctrine\Common\Version;
namespace Doctrine\DBAL\Tools\Console\Helper;
use Symfony\Components\Console\Helper\Helper,
Doctrine\DBAL\Connection;
/**
* CLI Task to display the doctrine version
* Doctrine CLI Connection Helper.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
......@@ -35,27 +36,39 @@ use Doctrine\Common\Version;
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class VersionTask extends AbstractTask
class ConnectionHelper extends Helper
{
/**
* @inheritdoc
* Doctrine Database Connection
* @var Connection
*/
protected $_connection;
/**
* Constructor
*
* @param Connection $connection Doctrine Database Connection
*/
public function buildDocumentation()
public function __construct(Connection $connection)
{
// There're no options on this task
$this->getDocumentation()->getOptionGroup()->clear();
$doc = $this->getDocumentation();
$doc->setName('version')
->setDescription('Displays the current installed Doctrine version.');
$this->_connection = $connection;
}
/**
* Displays the current version of Doctrine
* Retrieves Doctrine Database Connection
*
* @return Connection
*/
public function getConnection()
{
return $this->_connection;
}
/**
* @see Helper
*/
public function run()
public function getName()
{
$this->getPrinter()->writeln('You are currently running Doctrine ' . Version::VERSION, 'INFO');
return 'connection';
}
}
\ No newline at end of file
<?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\ORM\Tools\CLI\Tasks;
use Doctrine\Common\CLI\Tasks\AbstractTask,
Doctrine\Common\CLI\CliException,
Doctrine\Common\CLI\Option,
Doctrine\Common\CLI\OptionGroup,
Doctrine\Common\Cache\AbstractDriver;
/**
* CLI Task to clear the cache of the various cache drivers
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class ClearCacheTask extends AbstractTask
{
/**
* @inheritdoc
*/
public function buildDocumentation()
{
$cacheOptions = new OptionGroup(OptionGroup::CARDINALITY_1_1, array(
new Option('query', null, 'Clear the query cache.'),
new Option('metadata', null, 'Clear the metadata cache.'),
new OptionGroup(OptionGroup::CARDINALITY_M_N, array(
new OptionGroup(OptionGroup::CARDINALITY_1_1, array(
new Option('result', null, 'Clear the result cache.')
)),
new OptionGroup(OptionGroup::CARDINALITY_0_N, array(
new Option('id', '<ID>', 'The id of the cache entry to delete (accepts * wildcards).'),
new Option('regex', '<REGEX>', 'Delete cache entries that match the given regular expression.'),
new Option('prefix', '<PREFIX>', 'Delete cache entries that have the given prefix.'),
new Option('suffix', '<SUFFIX>', 'Delete cache entries that have the given suffix.')
))
))
));
$doc = $this->getDocumentation();
$doc->setName('clear-cache')
->setDescription('Clear cache from configured query, result and metadata drivers.')
->getOptionGroup()
->addOption($cacheOptions);
}
/**
* @inheritdoc
*/
public function validate()
{
$arguments = $this->getArguments();
// Check if we have an active EntityManager
$em = $this->getConfiguration()->getAttribute('em');
if ($em === null) {
throw new CLIException(
"Attribute 'em' of CLI Configuration is not defined or it is not a valid EntityManager."
);
}
// When clearing the query cache no need to specify
// id, regex, prefix or suffix.
if (
(isset($arguments['query']) || isset($arguments['metadata'])) && (isset($arguments['id']) ||
isset($arguments['regex']) || isset($arguments['prefix']) || isset($arguments['suffix']))
) {
throw new CLIException(
'When clearing the query or metadata cache do not ' .
'specify any --id, --regex, --prefix or --suffix.'
);
}
return true;
}
/**
* @inheritdoc
*/
public function run()
{
$arguments = $this->getArguments();
$printer = $this->getPrinter();
$query = isset($arguments['query']);
$result = isset($arguments['result']);
$metadata = isset($arguments['metadata']);
$id = isset($arguments['id']) ? $arguments['id'] : null;
$regex = isset($arguments['regex']) ? $arguments['regex'] : null;
$prefix = isset($arguments['prefix']) ? $arguments['prefix'] : null;
$suffix = isset($arguments['suffix']) ? $arguments['suffix'] : null;
$all = false;
if ( ! $query && ! $result && ! $metadata) {
$all = true;
}
$em = $this->getConfiguration()->getAttribute('em');
$configuration = $em->getConfiguration();
if ($query || $all) {
$this->_doDelete(
'query', $configuration->getQueryCacheImpl(), $id, $regex, $prefix, $suffix
);
}
if ($result || $all) {
$this->_doDelete(
'result', $configuration->getResultCacheImpl(), $id, $regex, $prefix, $suffix
);
}
if ($metadata || $all) {
$this->_doDelete(
'metadata', $configuration->getMetadataCacheImpl(), $id, $regex, $prefix, $suffix
);
}
}
private function _doDelete($type, $cacheDriver, $id, $regex, $prefix, $suffix)
{
$printer = $this->getPrinter();
if ( ! $cacheDriver) {
throw new CLIException('No driver has been configured for the ' . $type . ' cache.');
}
if ($id) {
$printer->writeln('Clearing ' . $type . ' cache entries that match the id "' . $id . '".', 'INFO');
$deleted = $cacheDriver->delete($id);
if (is_array($deleted)) {
$this->_printDeleted($type, $deleted);
} else if (is_bool($deleted) && $deleted) {
$this->_printDeleted($type, array($id));
}
}
if ($regex) {
$printer->writeln('Clearing ' . $type . ' cache entries that match the regular expression ".' . $regex . '"', 'INFO');
$this->_printDeleted($type, $cacheDriver->deleteByRegex('/' . $regex. '/'));
}
if ($prefix) {
$printer->writeln('Clearing ' . $type . ' cache entries that have the prefix "' . $prefix . '".', 'INFO');
$this->_printDeleted($type, $cacheDriver->deleteByPrefix($prefix));
}
if ($suffix) {
$printer->writeln('Clearing ' . $type . ' cache entries that have the suffix "' . $suffix . '".', 'INFO');
$this->_printDeleted($type, $cacheDriver->deleteBySuffix($suffix));
}
if ( ! $id && ! $regex && ! $prefix && ! $suffix) {
$printer->writeln('Clearing all ' . $type . ' cache entries.', 'INFO');
$this->_printDeleted($type, $cacheDriver->deleteAll());
}
}
private function _printDeleted($type, array $ids)
{
$printer = $this->getPrinter();
if ( ! empty($ids)) {
foreach ($ids as $id) {
$printer->writeln(' - ' . $id);
}
} else {
throw new CLIException('No ' . $type . ' cache entries found.');
}
$printer->write(PHP_EOL);
}
}
\ No newline at end of file
<?php
namespace Doctrine\ORM\Tools\CLI\Tasks;
use Doctrine\Common\CLI\Tasks\AbstractTask,
Doctrine\Common\CLI\CLIException,
Doctrine\Common\CLI\Option,
Doctrine\Common\CLI\OptionGroup;
/**
* Task to (re)generate the proxy classes used by doctrine.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision: 3938 $
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class GenerateProxiesTask extends AbstractTask
{
/**
* @inheritdoc
*/
public function buildDocumentation()
{
$classDir = new OptionGroup(OptionGroup::CARDINALITY_1_1, array(
new Option('class-dir', '<PATH>', 'Specified directory where mapping classes are located.')
));
$toDir = new OptionGroup(OptionGroup::CARDINALITY_0_1, array(
new Option('to-dir', '<PATH>', 'Generates the classes in the specified directory.')
));
$doc = $this->getDocumentation();
$doc->setName('generate-proxies')
->setDescription('Generates proxy classes for entity classes.')
->getOptionGroup()
->addOption($classDir)
->addOption($toDir);
}
/**
* @inheritdoc
*/
public function validate()
{
$arguments = $this->getArguments();
$em = $this->getConfiguration()->getAttribute('em');
if ($em === null) {
throw new CLIException(
"Attribute 'em' of CLI Configuration is not defined or it is not a valid EntityManager."
);
}
$metadataDriver = $em->getConfiguration()->getMetadataDriverImpl();
if ($metadataDriver instanceof \Doctrine\ORM\Mapping\Driver\AnnotationDriver) {
if (isset($arguments['class-dir'])) {
$metadataDriver->addPaths((array) $arguments['class-dir']);
} else {
throw new CLIException(
'The supplied configuration uses the annotation metadata driver. ' .
"The 'class-dir' argument is required for this driver."
);
}
}
return true;
}
/**
* @inheritdoc
*/
public function run()
{
$arguments = $this->getArguments();
$printer = $this->getPrinter();
$em = $this->getConfiguration()->getAttribute('em');
$cmf = $em->getMetadataFactory();
$classes = $cmf->getAllMetadata();
$factory = $em->getProxyFactory();
if (empty($classes)) {
$printer->writeln('No classes to process.', 'INFO');
} else {
foreach ($classes as $class) {
$printer->writeln(
sprintf('Processing entity "%s"', $printer->format($class->name, 'KEYWORD'))
);
}
$factory->generateProxyClasses(
$classes, isset($arguments['to-dir']) ? $arguments['to-dir'] : null
);
$printer->writeln('');
$printer->writeln(
sprintf('Proxy classes generated to "%s"',
$printer->format(isset($arguments['to-dir']) ? $arguments['to-dir'] : $em->getConfiguration()->getProxyDir(), 'KEYWORD'))
);
}
}
}
\ No newline at end of file
<?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\ORM\Tools\CLI\Tasks;
use Doctrine\Common\CLI\Tasks\AbstractTask,
Doctrine\Common\CLI\CLIException,
Doctrine\Common\Util\Debug,
Doctrine\Common\CLI\Option,
Doctrine\Common\CLI\OptionGroup,
Doctrine\ORM\Query;
/**
* Task for executing DQL in passed EntityManager.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class RunDqlTask extends AbstractTask
{
/**
* @inheritdoc
*/
public function buildDocumentation()
{
$dql = new OptionGroup(OptionGroup::CARDINALITY_1_1, array(
new Option('dql', '<DQL>', 'The DQL to execute.')
));
$hydrate = new OptionGroup(OptionGroup::CARDINALITY_0_1, array(
new Option(
'hydrate', '<HYDRATION_MODE>',
'Hydration mode of result set.' . PHP_EOL .
'Should be either: object, array, scalar or single-scalar.'
)
));
$firstResult = new OptionGroup(OptionGroup::CARDINALITY_0_1, array(
new Option('first-result', '<INTEGER>', 'The first result in the result set.')
));
$maxResults = new OptionGroup(OptionGroup::CARDINALITY_0_1, array(
new Option('max-results', '<INTEGER>', 'The maximum number of results in the result set.')
));
$depth = new OptionGroup(OptionGroup::CARDINALITY_0_1, array(
new Option('depth', '<DEPTH>', 'Dumping depth of Entities graph.')
));
$doc = $this->getDocumentation();
$doc->setName('run-dql')
->setDescription('Executes arbitrary DQL directly from the command line.')
->getOptionGroup()
->addOption($dql)
->addOption($hydrate)
->addOption($firstResult)
->addOption($maxResults)
->addOption($depth);
}
/**
* @inheritdoc
*/
public function validate()
{
$arguments = $this->getArguments();
$em = $this->getConfiguration()->getAttribute('em');
if ($em === null) {
throw new CLIException(
"Attribute 'em' of CLI Configuration is not defined or it is not a valid EntityManager."
);
}
if ( ! isset($arguments['dql'])) {
throw new CLIException('Argument --dql must be defined.');
}
if (isset($arguments['hydrate'])) {
$hydrationModeName = 'Doctrine\ORM\Query::HYDRATE_' . strtoupper(str_replace('-', '_', $arguments['hydrate']));
if ( ! defined($hydrationModeName)) {
throw new CLIException("Argument --hydrate must be either 'object', 'array', 'scalar' or 'single-scalar'.");
}
}
if (isset($arguments['first-result']) && ! ctype_digit($arguments['first-result'])) {
throw new CLIException('Argument --first-result must be an integer value.');
}
if (isset($arguments['max-results']) && ! ctype_digit($arguments['max-results'])) {
throw new CLIException('Argument --max-results must be an integer value.');
}
return true;
}
/**
* @inheritdoc
*/
public function run()
{
$arguments = $this->getArguments();
$em = $this->getConfiguration()->getAttribute('em');
$query = $em->createQuery($arguments['dql']);
$hydrationMode = isset($arguments['hydrate'])
? constant('Doctrine\ORM\Query::HYDRATE_' . strtoupper(str_replace('-', '_', $arguments['hydrate'])))
: Query::HYDRATE_OBJECT;
if (isset($arguments['first-result'])) {
$query->setFirstResult($arguments['first-result']);
}
if (isset($arguments['max-results'])) {
$query->setMaxResults($arguments['max-results']);
}
$resultSet = $query->getResult($hydrationMode);
$maxDepth = isset($arguments['depth']) ? $arguments['depth'] : 7;
Debug::dump($resultSet, $maxDepth);
}
}
\ No newline at end of file
<?php
namespace Doctrine\ORM\Tools\CLI\Tasks;
use Doctrine\Common\CLI\Tasks\AbstractTask,
Doctrine\Common\CLI\CLIException,
Doctrine\Common\CLI\Option,
Doctrine\Common\CLI\OptionGroup,
Doctrine\ORM\Tools\SchemaTool,
Doctrine\Common\Annotations\AnnotationReader,
Doctrine\ORM\Mapping\Driver\AnnotationDriver,
Doctrine\ORM\Mapping\Driver\XmlDriver,
Doctrine\ORM\Mapping\Driver\YamlDriver;
/**
* Task to create the database schema for a set of classes based on their mappings.
*
* This task has the following arguments:
*
* <tt>--class-dir=<path></tt>
* Specifies the directory where to start looking for mapped classes.
* This argument is required when the annotation metadata driver is used,
* otherwise it has no effect.
*
* <tt>--dump-sql</tt>
* Specifies that instead of directly executing the SQL statements,
* they should be printed to the standard output.
*
* <tt>--create</tt>
* Specifies that the schema of the classes should be created.
*
* <tt>--drop</tt>
* Specifies that the schema of the classes should be dropped.
*
* <tt>--update</tt>
* Specifies that the schema of the classes should be updated.
*
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision: 3938 $
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class SchemaToolTask extends AbstractTask
{
/**
* @inheritdoc
*/
public function buildDocumentation()
{
$schemaOption = new OptionGroup(OptionGroup::CARDINALITY_1_1, array(
new Option(
'create', null,
'Creates the schema in EntityManager (create tables on Database).' . PHP_EOL .
'If defined, --drop, --update and --re-create can not be requested on same task.'
),
new Option(
'drop', null,
'Drops the schema of EntityManager (drop tables on Database).' . PHP_EOL .
'Beware that the complete database is dropped by this command, '.PHP_EOL.
'even tables that are not relevant to your metadata model.' . PHP_EOL .
'If defined, --create, --update and --re-create can not be requested on same task.'
),
new Option(
'update', null,
'Updates the schema in EntityManager (update tables on Database).' . PHP_EOL .
'This command does a save update, which does not delete any tables, sequences or affected foreign keys.' . PHP_EOL .
'If defined, --create, --drop and --complete-update --re-create can not be requested on same task.'
),
new Option(
'complete-update', null,
'Updates the schema in EntityManager (update tables on Database).' . PHP_EOL .
'Beware that all assets of the database which are not relevant to the current metadata are dropped by this command.'.PHP_EOL.
'If defined, --create, --drop and --update --re-create can not be requested on same task.'
),
new Option(
're-create', null,
'Runs --drop then --create to re-create the database.' . PHP_EOL .
'If defined, --create, --update and --drop can not be requested on same task.'
)
));
$optionalOptions = new OptionGroup(OptionGroup::CARDINALITY_0_N, array(
new Option('dump-sql', null, 'Instead of try to apply generated SQLs into EntityManager, output them.'),
new Option('class-dir', '<PATH>', 'Optional class directory to fetch for Entities.')
));
$doc = $this->getDocumentation();
$doc->setName('schema-tool')
->setDescription('Processes the schema and either apply it directly on EntityManager or generate the SQL output.')
->getOptionGroup()
->addOption($schemaOption)
->addOption($optionalOptions);
}
/**
* @inheritdoc
*/
public function validate()
{
$arguments = $this->getArguments();
$em = $this->getConfiguration()->getAttribute('em');
if ($em === null) {
throw new CLIException(
"Attribute 'em' of CLI Configuration is not defined or it is not a valid EntityManager."
);
}
if (isset($arguments['re-create'])) {
$arguments['drop'] = true;
$arguments['create'] = true;
unset($arguments['re-create']);
$this->setArguments($arguments);
}
$isCreate = isset($arguments['create']) && $arguments['create'];
$isDrop = isset($arguments['drop']) && $arguments['drop'];
$isUpdate = isset($arguments['update']) && $arguments['update'];
$isCompleteUpdate = isset($arguments['complete-update']) && $arguments['complete-update'];
if ($isUpdate && ($isCreate || $isDrop || $isCompleteUpdate)) {
throw new CLIException(
'You cannot use --update with --create, --drop or --complete-update.'
);
}
if ($isCompleteUpdate && ($isCreate || $isDrop || $isUpdate)) {
throw new CLIException('You cannot use --complete-update with --create, --drop or --update.');
}
if ( ! ($isCreate || $isDrop || $isUpdate || $isCompleteUpdate)) {
throw new CLIException(
'You must specify at a minimum one of the options: ' .
'--create, --drop, --update, --re-create or --complete-update.'
);
}
$metadataDriver = $em->getConfiguration()->getMetadataDriverImpl();
if ($metadataDriver instanceof \Doctrine\ORM\Mapping\Driver\AnnotationDriver) {
if (isset($arguments['class-dir'])) {
$metadataDriver->addPaths((array) $arguments['class-dir']);
} else {
throw new CLIException(
'The supplied configuration uses the annotation metadata driver. ' .
"The 'class-dir' argument is required for this driver."
);
}
}
return true;
}
/**
* @inheritdoc
*/
public function run()
{
$arguments = $this->getArguments();
$printer = $this->getPrinter();
$isCreate = isset($arguments['create']) && $arguments['create'];
$isDrop = isset($arguments['drop']) && $arguments['drop'];
$isUpdate = isset($arguments['update']) && $arguments['update'];
$isCompleteUpdate = isset($arguments['complete-update']) && $arguments['complete-update'];
$em = $this->getConfiguration()->getAttribute('em');
$cmf = $em->getMetadataFactory();
$classes = $cmf->getAllMetadata();
if (empty($classes)) {
$printer->writeln('No classes to process.', 'INFO');
return;
}
$tool = new SchemaTool($em);
if ($isDrop) {
if (isset($arguments['dump-sql'])) {
foreach ($tool->getDropSchemaSql($classes) as $sql) {
$printer->writeln($sql . ";");
}
} else {
$printer->writeln('Dropping database schema...', 'INFO');
$tool->dropSchema($classes);
$printer->writeln('Database schema dropped successfully.', 'INFO');
}
}
if ($isCreate) {
if (isset($arguments['dump-sql'])) {
foreach ($tool->getCreateSchemaSql($classes) as $sql) {
$printer->writeln($sql . ";");
}
} else {
$printer->writeln('Creating database schema...', 'INFO');
$tool->createSchema($classes);
$printer->writeln('Database schema created successfully.', 'INFO');
}
}
if ($isUpdate || $isCompleteUpdate) {
$saveMode = $isUpdate ? true : false;
if (isset($arguments['dump-sql'])) {
foreach ($tool->getUpdateSchemaSql($classes, $saveMode) as $sql) {
$printer->writeln($sql . ";");
}
} else {
$printer->writeln('Updating database schema...', 'INFO');
$tool->updateSchema($classes, $saveMode);
$printer->writeln('Database schema updated successfully.', 'INFO');
}
}
}
}
\ No newline at end of file
......@@ -18,11 +18,15 @@
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\CLI;
namespace Doctrine\ORM\Tools\Console\Command\ClearCache;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* CLI Configuration class
* Command to clear the metadata cache of the various cache drivers.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
......@@ -33,54 +37,45 @@ namespace Doctrine\Common\CLI;
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class Configuration
class MetadataCommand extends Console\Command\Command
{
/**
* @var array Configuration attributes
*/
private $_attributes = array();
/**
* Defines a new configuration attribute
*
* @param string $name Attribute name
* @param mixed $value Attribute value
*
* @return Configuration This object instance
* @see Console\Command\Command
*/
public function setAttribute($name, $value = null)
protected function configure()
{
$this->_attributes[$name] = $value;
if ($value === null) {
unset($this->_attributes[$name]);
}
return $this;
$this
->setName('orm:clear-cache:metadata')
->setDescription('Clear all metadata cache of the various cache drivers.')
->setDefinition(array())
->setHelp(<<<EOT
Clear all metadata cache of the various cache drivers.
EOT
);
}
/**
* Retrieves a configuration attribute
*
* @param string $name Attribute name
*
* @return mixed Attribute value
*/
public function getAttribute($name)
{
return isset($this->_attributes[$name])
? $this->_attributes[$name] : null;
}
/**
* Checks if configuration attribute is defined
*
* @param string $name Attribute name
*
* @return boolean TRUE if attribute exists, FALSE otherwise
* @see Console\Command\Command
*/
public function hasAttribute($name)
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
return isset($this->_attributes[$name]);
$em = $this->getHelper('em')->getEntityManager();
$cacheDriver = $em->getConfiguration()->getMetadataCacheImpl();
if ( ! $cacheDriver) {
throw new \InvalidArgumentException('No Metadata cache driver is configured on given EntityManager.');
}
$output->write('Clearing ALL Metadata cache entries' . PHP_EOL);
$cacheIds = $cacheDriver->deleteAll();
if ($cacheIds) {
foreach ($cacheIds as $cacheId) {
$output->write(' - ' . $cacheId . PHP_EOL);
}
} else {
$output->write('No entries to be deleted.' . PHP_EOL);
}
}
}
\ No newline at end of file
......@@ -18,13 +18,15 @@
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\CLI\Tasks;
use Doctrine\Common\CLI\CLIException;
namespace Doctrine\ORM\Tools\Console\Command\ClearCache;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* CLI Task to display available commands help
* Command to clear the query cache of the various cache drivers.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
......@@ -35,45 +37,45 @@ use Doctrine\Common\CLI\CLIException;
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class HelpTask extends AbstractTask
class QueryCommand extends Console\Command\Command
{
/**
* @inheritdoc
*/
public function buildDocumentation()
{
$doc = $this->getDocumentation();
$doc->setName('help')
->setDescription('Exposes helpful information about all available tasks.');
}
/**
* @inheritdoc
* @see Console\Command\Command
*/
public function extendedHelp()
protected function configure()
{
$this->run();
$this
->setName('orm:clear-cache:query')
->setDescription('Clear all query cache of the various cache drivers.')
->setDefinition(array())
->setHelp(<<<EOT
Clear all query cache of the various cache drivers.
EOT
);
}
/**
* Exposes the available tasks
*
* @see Console\Command\Command
*/
public function run()
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$this->getPrinter()->writeln('Available Tasks:', 'HEADER')->write(PHP_EOL);
// Find the CLI Controller
$cliController = $this->getNamespace()->getParentNamespace();
// Switch between ALL available tasks and display the basic Help of each one
$availableTasks = $cliController->getAvailableTasks();
//unset($availableTasks['Core:Help']);
ksort($availableTasks);
foreach (array_keys($availableTasks) as $taskName) {
$cliController->runTask($taskName, array('basic-help' => true));
$em = $this->getHelper('em')->getEntityManager();
$cacheDriver = $em->getConfiguration()->getQueryCacheImpl();
if ( ! $cacheDriver) {
throw new \InvalidArgumentException('No Query cache driver is configured on given EntityManager.');
}
$output->write('Clearing ALL Query cache entries' . PHP_EOL);
$cacheIds = $cacheDriver->deleteAll();
if ($cacheIds) {
foreach ($cacheIds as $cacheId) {
$output->write(' - ' . $cacheId . PHP_EOL);
}
} else {
$output->write('No entries to be deleted.' . PHP_EOL);
}
}
}
\ No newline at end of file
<?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\ORM\Tools\Console\Command\ClearCache;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* Command to clear the result cache of the various cache drivers.
*
* @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 ResultCommand extends Console\Command\Command
{
/**
* @see Console\Command\Command
*/
protected function configure()
{
$this
->setName('orm:clear-cache:result')
->setDescription('Clear result cache of the various cache drivers.')
->setDefinition(array(
new InputOption(
'id', null, InputOption::PARAMETER_REQUIRED | InputOption::PARAMETER_IS_ARRAY,
'ID(s) of the cache entry to delete (accepts * wildcards).', array()
),
new InputOption(
'regex', null, InputOption::PARAMETER_REQUIRED | InputOption::PARAMETER_IS_ARRAY,
'Delete cache entries that match the given regular expression(s).', array()
),
new InputOption(
'prefix', null, InputOption::PARAMETER_REQUIRED | InputOption::PARAMETER_IS_ARRAY,
'Delete cache entries that have the given prefix(es).', array()
),
new InputOption(
'suffix', null, InputOption::PARAMETER_REQUIRED | InputOption::PARAMETER_IS_ARRAY,
'Delete cache entries that have the given suffix(es).', array()
),
))
->setHelp(<<<EOT
Clear result cache of the various cache drivers.
If none of the options are defined, all cache entries will be removed.
EOT
);
}
/**
* @see Console\Command\Command
*/
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$em = $this->getHelper('em')->getEntityManager();
$cacheDriver = $em->getConfiguration()->getResultCacheImpl();
if ( ! $cacheDriver) {
throw new \InvalidArgumentException('No Result cache driver is configured on given EntityManager.');
}
$outputed = false;
// Removing based on --id
if (($ids = $input->getOption('id')) !== null && $ids) {
foreach ($ids as $id) {
$output->write($outputed ? PHP_EOL : '');
$output->write(sprintf('Clearing Result cache entries that match the id "<info>%s</info>"', $id) . PHP_EOL);
$deleted = $cacheDriver->delete($id);
if (is_array($deleted)) {
$this->_printDeleted($deleted);
} else if (is_bool($deleted) && $deleted) {
$this->_printDeleted(array($id));
}
$outputed = true;
}
}
// Removing based on --regex
if (($regex = $input->getOption('regex')) !== null && $regexps) {
foreach($regexps as $regex) {
$output->write($outputed ? PHP_EOL : '');
$output->write(sprintf('Clearing Result cache entries that match the regular expression "<info>%s</info>"', $regex) . PHP_EOL);
$this->_printDeleted($cacheDriver->deleteByRegex('/' . $regex. '/'));
$outputed = true;
}
}
// Removing based on --prefix
if (($prefixes = $input->getOption('prefix')) !== null & $prefixes) {
foreach ($prefixes as $prefix) {
$output->write($outputed ? PHP_EOL : '');
$output->write(sprintf('Clearing Result cache entries that have the prefix "<info>%s</info>"', $prefix) . PHP_EOL);
$this->_printDeleted($cacheDriver->deleteByPrefix($prefix));
$outputed = true;
}
}
// Removing based on --suffix
if (($suffixes = $input->getOption('suffix')) !== null && $suffixes) {
foreach ($suffixes as $suffix) {
$output->write($outputed ? PHP_EOL : '');
$output->write(sprintf('Clearing Result cache entries that have the suffix "<info>%s</info>"', $suffix) . PHP_EOL);
$this->_printDeleted($cacheDriver->deleteBySuffix($suffix));
$outputed = true;
}
}
// Removing ALL entries
if ( ! $ids && ! $regexps && ! $prefixes && ! $suffixes) {
$output->write($outputed ? PHP_EOL : '');
$output->write('Clearing ALL Result cache entries');
$this->_printDeleted($cacheDriver->deleteAll());
$outputed = true;
}
}
private function _printDeleted(Console\Output\OutputInterface $output, array $items)
{
if ($items) {
foreach ($items as $item) {
$output->write(' - ' . $item . PHP_EOL);
}
} else {
$output->write('No entries to be deleted.' . PHP_EOL);
}
}
}
\ No newline at end of file
<?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\ORM\Tools\Console\Command;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* Command to convert a Doctrine 1 schema to a Doctrine 2 mapping file.
*
* @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 ConvertDoctrine1SchemaCommand extends Console\Command\Command
{
/**
* @see Console\Command\Command
*/
protected function configure()
{
$this
->setName('orm:convert-d1-schema')
->setDescription('Converts Doctrine 1.X schema into a Doctrine 2.X schema.')
->setDefinition(array(
new InputArgument(
'from-path', InputArgument::REQUIRED, 'The path of Doctrine 1.X schema information.'
),
new InputArgument(
'to-type', InputArgument::REQUIRED, 'The destination Doctrine 2.X mapping type.'
),
new InputArgument(
'dest-path', InputArgument::REQUIRED,
'The path to generate your Doctrine 2.X mapping information.'
),
new InputOption(
'from', null, InputOption::PARAMETER_REQUIRED | InputOption::PARAMETER_IS_ARRAY,
'Optional paths of Doctrine 1.X schema information.',
array()
),
new InputOption(
'extend', null, InputOption::PARAMETER_OPTIONAL,
'Defines a base class to be extended by generated entity classes.'
),
new InputOption(
'num-spaces', null, InputOption::PARAMETER_OPTIONAL,
'Defines the number of indentation spaces', 4
)
))
->setHelp(<<<EOT
Converts Doctrine 1.X schema into a Doctrine 2.X schema.
EOT
);
}
/**
* @see Console\Command\Command
*/
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$em = $this->getHelper('em')->getEntityManager();
// Process source directories
$fromPaths = array_merge(array($input->getArgument('from-path')), $input->getOption('from'));
foreach ($fromPaths as &$dirName) {
$dirName = realpath($dirName);
if ( ! file_exists($dirName)) {
throw new \InvalidArgumentException(
sprintf("Doctrine 1.X schema directory '<info>%s</info>' does not exist.", $dirName)
);
} else if ( ! is_readable($dirName)) {
throw new \InvalidArgumentException(
sprintf("Doctrine 1.X schema directory '<info>%s</info>' does not have read permissions.", $dirName)
);
}
}
// Process destination directory
$destPath = realpath($input->getArgument('dest-path'));
if ( ! file_exists($destPath)) {
throw new \InvalidArgumentException(
sprintf("Doctrine 2.X mapping destination directory '<info>%s</info>' does not exist.", $destPath)
);
} else if ( ! is_writable($destPath)) {
throw new \InvalidArgumentException(
sprintf("Doctrine 2.X mapping destination directory '<info>%s</info>' does not have write permissions.", $destPath)
);
}
$toType = $input->getArgument('to-type');
$cme = new ClassMetadataExporter();
$exporter = $cme->getExporter($toType, $destPath);
if (strtolower($toType) === 'annotation') {
$entityGenerator = new EntityGenerator();
$exporter->setEntityGenerator($entityGenerator);
$entityGenerator->setNumSpaces($input->getOption('num-spaces'));
if (($extend = $input->getOption('extend')) !== null) {
$entityGenerator->setClassToExtend($extend);
}
}
$converter = new ConvertDoctrine1Schema($fromPaths);
$metadatas = $converter->getMetadatas();
if ($metadatas) {
$output->write(PHP_EOL);
foreach ($metadatas as $metadata) {
$output->write(sprintf('Processing entity "<info>%s</info>"', $metadata->name) . PHP_EOL);
}
$exporter->setMetadatas($metadatas);
$exporter->export();
$output->write(PHP_EOL . sprintf(
'Converting Doctrine 1.X schema to "<info>%s</info>" mapping type in "<info>%s</info>"', $toType, $destPath
));
} else {
$output->write('No Metadata Classes to process.' . PHP_EOL);
}
}
}
\ No newline at end of file
......@@ -18,146 +18,148 @@
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Tools\CLI\Tasks;
use Doctrine\Common\CLI\Tasks\AbstractTask,
Doctrine\Common\CLI\CliException,
Doctrine\Common\CLI\Option,
Doctrine\Common\CLI\OptionGroup,
Doctrine\ORM\Tools\EntityGenerator,
Doctrine\ORM\Tools\Export\ClassMetadataExporter,
Doctrine\ORM\Mapping\Driver\DriverChain,
Doctrine\ORM\Mapping\Driver\AnnotationDriver,
Doctrine\ORM\Mapping\Driver\Driver;
namespace Doctrine\ORM\Tools\Console\Command;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* CLI Task to convert your mapping information between the various formats
* Command to convert your mapping information between the various formats.
*
* @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 ConvertMappingTask extends AbstractTask
class ConvertMappingCommand extends Console\Command\Command
{
/**
* @inheritdoc
* @see Console\Command\Command
*/
public function buildDocumentation()
protected function configure()
{
$convertOptions = new OptionGroup(OptionGroup::CARDINALITY_N_N, array(
new OptionGroup(OptionGroup::CARDINALITY_1_1, array(
new Option('from', '<SOURCE>', 'The path to the mapping information to convert from (yml, xml, php, annotation).'),
new Option('from-database', null, 'Use this option if you wish to reverse engineer your database to a set of Doctrine mapping files.')
)),
new Option('to', '<TYPE>', 'The format to convert to (yml, xml, php, annotation).'),
new Option('dest', '<PATH>', 'The path to write the converted mapping information.')
));
$doc = $this->getDocumentation();
$doc->setName('convert-mapping')
->setDescription('Convert mapping information between supported formats.')
->getOptionGroup()
->addOption($convertOptions);
$this
->setName('orm:convert-mapping')
->setDescription('Convert mapping information between supported formats.')
->setDefinition(array(
new InputArgument(
'from-path', InputArgument::REQUIRED, 'The path of mapping information.'
),
new InputArgument(
'to-type', InputArgument::REQUIRED, 'The mapping type to be converted.'
),
new InputArgument(
'dest-path', InputArgument::REQUIRED,
'The path to generate your entities classes.'
),
new InputOption(
'from', null, InputOption::PARAMETER_REQUIRED | InputOption::PARAMETER_IS_ARRAY,
'Optional paths of mapping information.',
array()
),
new InputOption(
'extend', null, InputOption::PARAMETER_OPTIONAL,
'Defines a base class to be extended by generated entity classes.'
),
new InputOption(
'num-spaces', null, InputOption::PARAMETER_OPTIONAL,
'Defines the number of indentation spaces', 4
)
))
->setHelp(<<<EOT
Convert mapping information between supported formats.
EOT
);
}
/**
* @inheritdoc
*/
public function validate()
* @see Console\Command\Command
*/
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$arguments = $this->getArguments();
if (isset($arguments['from-database']) && $arguments['from-database']) {
$arguments['from'] = 'database';
$this->setArguments($arguments);
}
$em = $this->getHelper('em')->getEntityManager();
$cme = new ClassMetadataExporter();
if (!(isset($arguments['from']) && isset($arguments['to']) && isset($arguments['dest']))) {
throw new CLIException(
'You must include a value for all three options: --from, --to and --dest.'
);
}
if (strtolower($arguments['to']) != 'annotation' && isset($arguments['extend'])) {
throw new CLIException(
'You can only use the --extend argument when converting to annotations.'
);
}
if (strtolower($arguments['from']) == 'database') {
// Check if we have an active EntityManager
$em = $this->getConfiguration()->getAttribute('em');
if ($em === null) {
throw new CLIException(
"Attribute 'em' of CLI Configuration is not defined or it is not a valid EntityManager."
);
// Process source directories
$fromPath = $input->getArgument('from-path');
if (strtolower($fromPath) !== 'database') {
$fromPaths = array_merge(array($fromPath), $input->getOption('from'));
foreach ($fromPaths as &$dirName) {
$dirName = realpath($dirName);
if ( ! file_exists($dirName)) {
throw new \InvalidArgumentException(
sprintf("Mapping directory '<info>%s</info>' does not exist.", $dirName)
);
} else if ( ! is_readable($dirName)) {
throw new \InvalidArgumentException(
sprintf("Mapping directory '<info>%s</info>' does not have read permissions.", $dirName)
);
}
$cme->addMappingSource($dirName);
}
$config = $em->getConfiguration();
$config->setMetadataDriverImpl(
} else {
$em->getConfiguration()->setMetadataDriverImpl(
new \Doctrine\ORM\Mapping\Driver\DatabaseDriver(
$em->getConnection()->getSchemaManager()
)
);
$cme->addMappingSource($fromPath);
}
return true;
}
public function run()
{
$arguments = $this->getArguments();
$cme = new ClassMetadataExporter();
$cme->setEntityManager($this->getConfiguration()->getAttribute('em'));
$printer = $this->getPrinter();
// Get exporter and configure it
$exporter = $cme->getExporter($arguments['to'], $arguments['dest']);
// Process destination directory
$destPath = realpath($input->getArgument('dest-path'));
if ($arguments['to'] === 'annotation') {
if ( ! file_exists($destPath)) {
throw new \InvalidArgumentException(
sprintf("Mapping destination directory '<info>%s</info>' does not exist.", $destPath)
);
} else if ( ! is_writable($destPath)) {
throw new \InvalidArgumentException(
sprintf("Mapping destination directory '<info>%s</info>' does not have write permissions.", $destPath)
);
}
$toType = strtolower($input->getArgument('to-type'));
$exporter = $cme->getExporter($toType, $destPath);
if ($toType == 'annotation') {
$entityGenerator = new EntityGenerator();
$exporter->setEntityGenerator($entityGenerator);
if (isset($arguments['extend']) && $arguments['extend']) {
$entityGenerator->setClassToExtend($arguments['extend']);
}
$entityGenerator->setNumSpaces($input->getOption('num-spaces'));
if (isset($arguments['num-spaces']) && $arguments['extend']) {
$entityGenerator->setNumSpaces($arguments['num-spaces']);
if (($extend = $input->getOption('extend')) !== null) {
$entityGenerator->setClassToExtend($extend);
}
}
$from = (array) $arguments['from'];
foreach ($from as $source) {
$cme->addMappingSource($source);
}
$metadatas = $cme->getMetadatas();
foreach ($metadatas as $metadata) {
$printer->writeln(
sprintf('Processing entity "%s"', $printer->format($metadata->name, 'KEYWORD'))
);
}
if ($metadatas) {
foreach ($metadatas as $metadata) {
$output->write(sprintf('Processing entity "<info>%s</info>"', $metadata->name) . PHP_EOL);
}
$printer->writeln('');
$printer->writeln(
sprintf(
'Exporting "%s" mapping information to "%s"',
$printer->format($arguments['to'], 'KEYWORD'),
$printer->format($arguments['dest'], 'KEYWORD')
)
);
$exporter->setMetadatas($metadatas);
$exporter->export();
$exporter->setMetadatas($metadatas);
$exporter->export();
$output->write(PHP_EOL . sprintf(
'Exporting "<info>%s</info>" mapping information to "<info>%s</info>"', $toType, $destPath
));
} else {
$output->write('No Metadata Classes to process.' . PHP_EOL);
}
}
}
\ No newline at end of file
......@@ -18,14 +18,15 @@
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Tools\CLI\Tasks;
use Doctrine\Common\CLI\Tasks\AbstractTask,
Doctrine\Common\CLI\CLIException;
namespace Doctrine\ORM\Tools\Console\Command;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* CLI Task to ensure that Doctrine is properly configured for a production environment.
* Command to ensure that Doctrine is properly configured for a production environment.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
......@@ -36,43 +37,40 @@ use Doctrine\Common\CLI\Tasks\AbstractTask,
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class EnsureProductionSettingsTask extends AbstractTask
class EnsureProductionSettingsCommand extends Console\Command\Command
{
/**
* @inheritdoc
*/
public function buildDocumentation()
{
$doc = $this->getDocumentation();
$doc->setName('ensure-production-settings')
->setDescription('Verify that Doctrine is properly configured for a production environment.');
}
/**
* @inheritdoc
* @see Console\Command\Command
*/
public function validate()
protected function configure()
{
// Check if we have an active EntityManager
$em = $this->getConfiguration()->getAttribute('em');
if ($em === null) {
throw new CLIException(
"Attribute 'em' of CLI Configuration is not defined or it is not a valid EntityManager."
);
}
return true;
$this
->setName('orm:ensure-production-settings')
->setDescription('Verify that Doctrine is properly configured for a production environment.')
->setDefinition(array(
new InputOption(
'complete', null, InputOption::PARAMETER_NONE,
'Flag to also inspect database connection existance.'
)
))
->setHelp(<<<EOT
Verify that Doctrine is properly configured for a production environment.
EOT
);
}
/**
* @inheritdoc
* @see Console\Command\Command
*/
public function run()
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$em = $this->getConfiguration()->getAttribute('em');
$em = $this->getHelper('em')->getEntityManager();
$em->getConfiguration()->ensureProductionSettings();
$this->getPrinter()->writeln('Environment is correctly configured for production.');
if ($input->getOption('complete') !== null) {
$em->getConnection()->connect();
}
$output->write('Environment is correctly configured for production.');
}
}
\ No newline at end of file
<?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\ORM\Tools\Console\Command;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* Command to generate entity classes and method stubs from your mapping information.
*
* @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 GenerateEntitiesCommand extends Console\Command\Command
{
/**
* @see Console\Command\Command
*/
protected function configure()
{
$this
->setName('orm:generate-entities')
->setDescription('Generate entity classes and method stubs from your mapping information.')
->setDefinition(array(
new InputArgument(
'from-path', InputArgument::REQUIRED, 'The path of mapping information.'
),
new InputArgument(
'dest-path', InputArgument::REQUIRED, 'The path to generate your entity classes.'
),
new InputOption(
'from', null, InputOption::PARAMETER_REQUIRED | InputOption::PARAMETER_IS_ARRAY,
'Optional paths of mapping information.',
array()
),
new InputOption(
'generate-annotations', null, InputOption::PARAMETER_OPTIONAL,
'Flag to define if generator should generate annotation metadata on entities.', false
),
new InputOption(
'generate-methods', null, InputOption::PARAMETER_OPTIONAL,
'Flag to define if generator should generate stub methods on entities.', true
),
new InputOption(
'regenerate-entities', null, InputOption::PARAMETER_OPTIONAL,
'Flag to define if generator should regenerate entity if it exists.', false
),
new InputOption(
'update-entities', null, InputOption::PARAMETER_OPTIONAL,
'Flag to define if generator should only update entity if it exists.', true
),
new InputOption(
'extend', null, InputOption::PARAMETER_OPTIONAL,
'Defines a base class to be extended by generated entity classes.'
),
new InputOption(
'num-spaces', null, InputOption::PARAMETER_OPTIONAL,
'Defines the number of indentation spaces', 4
)
))
->setHelp(<<<EOT
Generate entity classes and method stubs from your mapping information.
EOT
);
}
/**
* @see Console\Command\Command
*/
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$em = $this->getHelper('em')->getEntityManager();
$reader = new ClassMetadataReader();
$reader->setEntityManager($em);
// Process source directories
$fromPaths = array_merge(array($input->getArgument('from-path')), $input->getOption('from'));
foreach ($fromPaths as $dirName) {
$dirName = realpath($dirName);
if ( ! file_exists($dirName)) {
throw new \InvalidArgumentException(
sprintf("Mapping directory '<info>%s</info>' does not exist.", $dirName)
);
} else if ( ! is_readable($dirName)) {
throw new \InvalidArgumentException(
sprintf("Mapping directory '<info>%s</info>' does not have read permissions.", $dirName)
);
}
$reader->addMappingSource($dirName);
}
// Process destination directory
$destPath = realpath($input->getArgument('dest-path'));
if ( ! file_exists($destPath)) {
throw new \InvalidArgumentException(
sprintf("Entities destination directory '<info>%s</info>' does not exist.", $destPath)
);
} else if ( ! is_writable($destPath)) {
throw new \InvalidArgumentException(
sprintf("Entities destination directory '<info>%s</info>' does not have write permissions.", $destPath)
);
}
// Create EntityGenerator
$entityGenerator = new EntityGenerator();
$entityGenerator->setGenerateAnnotations($input->getOption('generate-annotations'));
$entityGenerator->setGenerateStubMethods($input->getOption('generate-methods'));
$entityGenerator->setRegenerateEntityIfExists($input->getOption('regenerate-entities'));
$entityGenerator->setUpdateEntityIfExists($input->getOption('update-entities'));
$entityGenerator->setNumSpaces($input->getOption('num-spaces'));
if (($extend = $input->getOption('extend')) !== null) {
$entityGenerator->setClassToExtend($extend);
}
// Retrieving ClassMetadatas
$metadatas = $reader->getMetadatas();
if ( ! empty($metadatas)) {
foreach ($metadatas as $metadata) {
$output->write(
sprintf('Processing entity "<info>%s</info>"', $metadata->name) . PHP_EOL
);
}
// Generating Entities
$entityGenerator->generate($metadatas, $destPath);
// Outputting information message
$output->write(PHP_EOL . sprintf('Entity classes generated to "<info>%s</INFO>"', $destPath) . PHP_EOL);
} else {
$output->write('No Metadata Classes to process.' . PHP_EOL);
}
}
}
\ No newline at end of file
<?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\ORM\Tools\Console\Command;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* Command to (re)generate the proxy classes used by doctrine.
*
* @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 GenerateProxiesCommand extends Console\Command\Command
{
/**
* @see Console\Command\Command
*/
protected function configure()
{
$this
->setName('orm:generate-proxies')
->setDescription('Generates proxy classes for entity classes.')
->setDefinition(array(
new InputArgument(
'from-path', InputArgument::REQUIRED, 'The path of mapping information.'
),
new InputArgument(
'dest-path', InputArgument::OPTIONAL,
'The path to generate your proxy classes. If none is provided, it will attempt to grab from configuration.'
),
new InputOption(
'from', null, InputOption::PARAMETER_REQUIRED | InputOption::PARAMETER_IS_ARRAY,
'Optional paths of mapping information.',
array()
)
))
->setHelp(<<<EOT
Generates proxy classes for entity classes.
EOT
);
}
/**
* @see Console\Command\Command
*/
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$em = $this->getHelper('em')->getEntityManager();
$reader = new ClassMetadataReader();
$reader->setEntityManager($em);
// Process source directories
$fromPaths = array_merge(array($input->getArgument('from-path')), $input->getOption('from'));
foreach ($fromPaths as $dirName) {
$dirName = realpath($dirName);
if ( ! file_exists($dirName)) {
throw new \InvalidArgumentException(
sprintf("Mapping directory '<info>%s</info>' does not exist.", $dirName)
);
} else if ( ! is_readable($dirName)) {
throw new \InvalidArgumentException(
sprintf("Mapping directory '<info>%s</info>' does not have read permissions.", $dirName)
);
}
$reader->addMappingSource($dirName);
}
// Process destination directory
if (($destPath = $input->getArgument('dest-path')) === null) {
$destPath = $em->getConfiguration()->getProxyDir();
}
$destPath = realpath($destPath);
if ( ! file_exists($destPath)) {
throw new \InvalidArgumentException(
sprintf("Proxies destination directory '<info>%s</info>' does not exist.", $destPath)
);
} else if ( ! is_writable($destPath)) {
throw new \InvalidArgumentException(
sprintf("Proxies destination directory '<info>%s</info>' does not have write permissions.", $destPath)
);
}
// Retrieving ClassMetadatas
$metadatas = $reader->getMetadatas();
if ( ! empty($metadatas)) {
foreach ($metadatas as $metadata) {
$output->write(
sprintf('Processing entity "<info>%s</info>"', $metadata->name) . PHP_EOL
);
}
// Generating Proxies
$em->getProxyFactory()->generateProxyClasses($metadatas, $destPath);
// Outputting information message
$output->write(PHP_EOL . sprintf('Proxy classes generated to "<info>%s</INFO>"', $destPath) . PHP_EOL);
} else {
$output->write('No Metadata Classes to process.' . PHP_EOL);
}
}
}
\ No newline at end of file
......@@ -18,17 +18,15 @@
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Tools\CLI\Tasks;
use Doctrine\Common\CLI\Tasks\AbstractTask,
Doctrine\Common\CLI\Option,
Doctrine\Common\CLI\OptionGroup,
Doctrine\Common\CLI\CLIException,
Doctrine\ORM\Tools\ClassMetadataReader;
namespace Doctrine\ORM\Tools\Console\Command;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* CLI Task to generate repository classes for some mapping information
* Command to generate repository classes for mapping information.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
......@@ -39,7 +37,7 @@ use Doctrine\Common\CLI\Tasks\AbstractTask,
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class GenerateRepositoriesTask extends ConvertMappingTask
class GenerateRepositoriesCommand extends Console\Command\Command
{
private static $_template =
'<?php
......@@ -59,88 +57,115 @@ class <className> extends EntityRepository
}';
/**
* @inheritdoc
* @see Console\Command\Command
*/
public function buildDocumentation()
protected function configure()
{
$options = new OptionGroup(OptionGroup::CARDINALITY_N_N, array(
new Option('from', '<FROM>', 'The path to mapping information.'),
new Option('dest', '<DEST>', 'The path to generate your repository classes.')
));
$doc = $this->getDocumentation();
$doc->setName('generate-repositories')
->setDescription('Generate repository classes for some mapping information.')
->getOptionGroup()
->addOption($options);
$this
->setName('orm:generate-repositories')
->setDescription('Generate repository classes from your mapping information.')
->setDefinition(array(
new InputArgument(
'from-path', InputArgument::REQUIRED, 'The path of mapping information.'
),
new InputArgument(
'dest-path', InputArgument::REQUIRED, 'The path to generate your repository classes.'
),
new InputOption(
'from', null, InputOption::PARAMETER_REQUIRED | InputOption::PARAMETER_IS_ARRAY,
'Optional paths of mapping information.',
array()
)
))
->setHelp(<<<EOT
Generate repository classes from your mapping information.
EOT
);
}
/**
* @inheritdoc
* @see Console\Command\Command
*/
public function validate()
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$arguments = $this->getArguments();
$em = $this->getConfiguration()->getAttribute('em');
$em = $this->getHelper('em')->getEntityManager();
if ( ! isset($arguments['from']) || ! isset($arguments['dest'])) {
throw new CLIException('You must specify a value for --from and --dest');
}
$reader = new ClassMetadataReader();
$reader->setEntityManager($em);
return true;
}
// Process source directories
$fromPaths = array_merge(array($input->getArgument('from-path')), $input->getOption('from'));
public function run()
{
$printer = $this->getPrinter();
$arguments = $this->getArguments();
$dest = realpath($arguments['dest']);
foreach ($fromPaths as $dirName) {
$dirName = realpath($dirName);
$reader = new ClassMetadataReader();
$reader->setEntityManager($this->getConfiguration()->getAttribute('em'));
$reader->addMappingSource($arguments['from']);
if ( ! file_exists($dirName)) {
throw new \InvalidArgumentException(
sprintf("Mapping directory '<info>%s</info>' does not exist.", $dirName)
);
} else if ( ! is_readable($dirName)) {
throw new \InvalidArgumentException(
sprintf("Mapping directory '<info>%s</info>' does not have read permissions.", $dirName)
);
}
$reader->addMappingSource($dirName);
}
// Process destination directory
$destPath = realpath($input->getArgument('dest-path'));
if ( ! file_exists($destPath)) {
throw new \InvalidArgumentException(
sprintf("Entities destination directory '<info>%s</info>' does not exist.", $destPath)
);
} else if ( ! is_writable($destPath)) {
throw new \InvalidArgumentException(
sprintf("Entities destination directory '<info>%s</info>' does not have write permissions.", $destPath)
);
}
// Retrieving ClassMetadatas
$metadatas = $reader->getMetadatas();
foreach ($metadatas as $metadata) {
if ($metadata->customRepositoryClassName) {
$code = $this->_generateRepositoryClass($metadata->customRepositoryClassName);
$path = $dest . '/' . str_replace('\\', '/', $metadata->customRepositoryClassName) . '.php';
$dir = dirname($path);
if ( ! is_dir($dir)) {
mkdir($dir, 0777, true);
if ( ! empty($metadatas)) {
$numRepositories = 0;
foreach ($metadatas as $metadata) {
if ($metadata->customRepositoryClassName) {
$output->write(
sprintf('Processing repository "<info>%s</info>"', $metadata->customRepositoryClassName) . PHP_EOL
);
$this->_generateRepositoryClass($metadata, $destPath);
$numRepositories++;
}
$printer->writeln(
sprintf('Processing entity "%s"',
$printer->format($metadata->customRepositoryClassName, 'KEYWORD')
)
);
file_put_contents($path, $code);
}
if ($numRepositories) {
// Outputting information message
$output->write(PHP_EOL . sprintf('Repository classes generated to "<info>%s</INFO>"', $destPath) . PHP_EOL);
} else {
$output->write('No Repository classes were found to be processed.' . PHP_EOL);
}
} else {
$output->write('No Metadata Classes to process.' . PHP_EOL);
}
$printer->writeln('');
$printer->writeln(
sprintf('Entity repository classes generated to "%s"',
$printer->format($dest, 'KEYWORD')
)
);
}
private function _generateRepositoryClass($fullyQualifiedClassName)
private function _generateRepositoryClass($metadata, $destPath)
{
$namespace = substr($fullyQualifiedClassName, 0, strrpos($fullyQualifiedClassName, '\\'));
$code = $this->_generateRepositoryClass($metadata->customRepositoryClassName);
$pos = strrpos($fullyQualifiedClassName, '\\');
$className = substr($fullyQualifiedClassName, $pos + 1, strlen($fullyQualifiedClassName));
$path = $destPath . DIRECTORY_SEPARATOR
. str_replace('\\', \DIRECTORY_SEPARATOR, $metadata->customRepositoryClassName) . '.php';
$dir = dirname($path);
$placeHolders = array(
'<namespace>',
'<className>'
);
$replacements = array(
$namespace,
$className
);
$code = str_replace($placeHolders, $replacements, self::$_template);
return $code;
if ( ! is_dir($dir)) {
mkdir($dir, 0777, true);
}
file_put_contents($path, $code);
}
}
\ No newline at end of file
<?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\ORM\Tools\Console\Command\SchemaTool;
use Symfony\Components\Console\Input\InputArgument,
Symfony\Components\Console\Input\InputOption,
Symfony\Components\Console;
/**
* Command to drop the database schema for a set of classes based on their mappings.
*
* @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 DropCommand extends Console\Command\Command
{
/**
* @see Console\Command\Command
*/
protected function configure()
{
$this
->setName('orm:schema-tool:drop')
->setDescription(
'Processes the schema and either drop the database schema of EntityManager Storage Connection or generate the SQL output.'
)
->setDefinition(array(
new InputArgument(
'from-path', InputArgument::REQUIRED, 'The path of mapping information.'
),
new InputOption(
'from', null, InputOption::PARAMETER_REQUIRED | InputOption::PARAMETER_IS_ARRAY,
'Optional paths of mapping information.',
array()
),
new InputOption(
'dump-sql', null, InputOption::PARAMETER_NONE,
'Instead of try to apply generated SQLs into EntityManager Storage Connection, output them.'
)
))
->setHelp(<<<EOT
Processes the schema and either drop the database schema of EntityManager Storage Connection or generate the SQL output.
Beware that the complete database is dropped by this command, even tables that are not relevant to your metadata model.
EOT
);
}
/**
* @see Console\Command\Command
*/
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
{
$em = $this->getHelper('em')->getEntityManager();
$reader = new \Doctrine\ORM\Tools\ClassMetadataReader();
$reader->setEntityManager($em);
// Process source directories
$fromPaths = array_merge(array($input->getArgument('from-path')), $input->getOption('from'));
foreach ($fromPaths as $dirName) {
$dirName = realpath($dirName);
if ( ! file_exists($dirName)) {
throw new \InvalidArgumentException(
sprintf("Mapping directory '<info>%s</info>' does not exist.", $dirName)
);
} else if ( ! is_readable($dirName)) {
throw new \InvalidArgumentException(
sprintf("Mapping directory '<info>%s</info>' does not have read permissions.", $dirName)
);
}
$reader->addMappingSource($dirName);
}
// Retrieving ClassMetadatas
$metadatas = $reader->getMetadatas();
if ( ! empty($metadatas)) {
// Create SchemaTool
$tool = new \Doctrine\ORM\Tools\SchemaTool($em);
if ($input->getOption('dump-sql') === null) {
$sqls = $tool->getDropSchemaSql($metadatas);
$output->write(implode(';' . PHP_EOL, $sqls));
} else {
$output->write('Dropping database schema...' . PHP_EOL);
$tool->dropSchema($metadatas);
$output->write('Database schema dropped successfully!' . PHP_EOL);
}
} else {
$output->write('No Metadata Classes to process.' . PHP_EOL);
}
}
}
\ No newline at end of file
......@@ -48,7 +48,7 @@ class ConvertDoctrine1Schema
* Constructor passes the directory or array of directories
* to convert the Doctrine 1 schema files from
*
* @param string $from
* @param array $from
* @author Jonathan Wage
*/
public function __construct($from)
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment