ConvertMappingTask.php 8.04 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?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;

24 25 26 27
use Doctrine\Common\DoctrineException,
    Doctrine\Common\Cli\Option,
    Doctrine\Common\Cli\OptionGroup,
    Doctrine\ORM\Tools\Export\ClassMetadataExporter;
28

29 30 31 32 33 34 35
if ( ! class_exists('sfYaml', false)) {
    require_once __DIR__ . '/../../../../../vendor/sfYaml/sfYaml.class.php';
    require_once __DIR__ . '/../../../../../vendor/sfYaml/sfYamlDumper.class.php';
    require_once __DIR__ . '/../../../../../vendor/sfYaml/sfYamlInline.class.php';
    require_once __DIR__ . '/../../../../../vendor/sfYaml/sfYamlParser.class.php';
}

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/**
 * CLI Task 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  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
class ConvertMappingTask extends AbstractTask
{
    /**
     * @inheritdoc
     */
52
    public function buildDocumentation()
53
    {
54 55 56 57 58 59 60 61 62 63 64 65 66 67
        $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);
68
    }
69
    
70 71 72 73 74 75 76 77
    /**
     * @inheritdoc
     */    
    public function validate()
    {
        $args = $this->getArguments();
        $printer = $this->getPrinter();

78 79 80 81 82
        if (array_key_exists('from-database', $args)) {
            $args['from'][0] = 'database';
            $this->setArguments($args);
        }

83
        if (!(isset($args['from']) && isset($args['to']) && isset($args['dest']))) {
84
          $printer->writeln('You must include a value for all three options: --from, --to and --dest', 'ERROR');
85 86
          return false;
        }
87
        if ($args['to'] != 'annotation' && isset($args['extend'])) {
88
            $printer->writeln('You can only use the --extend argument when converting to annoations.', 'ERROR');
89 90
            return false;
        }
91
        if ($args['from'][0] == 'database') {
92 93 94
            $em = $this->getEntityManager();
            $config = $em->getConfiguration();
            $config->setMetadataDriverImpl(new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager()));
95
        }
96 97 98 99 100 101 102 103
        return true;
    }

    public function run()
    {
        $printer = $this->getPrinter();
        $args = $this->getArguments();

104
        $cme = new ClassMetadataExporter();
105

106 107
        // Get exporter and configure it
        $exporter = $cme->getExporter($args['to'], $args['dest']);
108

109 110 111 112 113 114
        if (isset($args['extend'])) {
            $exporter->setClassToExtend($args['extend']);
        }
        if (isset($args['num-spaces'])) {
            $exporter->setNumSpaces($args['num-spaces']);
        }
115

116 117 118 119 120 121
        $from = (array) $args['from'];

        if ($this->_isDoctrine1Schema($from)) {
            $printer->writeln('Converting Doctrine 1 schema to Doctrine 2 mapping files', 'INFO');

            $converter = new \Doctrine\ORM\Tools\ConvertDoctrine1Schema($from);
122
            $metadatas = $converter->getMetadatasFromSchema();
123
        } else {
124 125 126 127
            foreach ($from as $source) {
                $sourceArg = $source;

                $type = $this->_determineSourceType($sourceArg);
128 129 130
                if ( ! $type) {
                    throw DoctrineException::invalidMappingSourceType($sourceArg);
                }
131
                $source = $this->_getSourceByType($type, $sourceArg);
132

jwage's avatar
jwage committed
133 134
                $printer->writeln(
                    sprintf(
135 136 137 138
                        'Adding "%s" mapping source which contains the "%s" format', 
                        $printer->format($sourceArg, 'KEYWORD'),
                        $printer->format($type, 'KEYWORD')
                    )
jwage's avatar
jwage committed
139
                );
140

141
                $cme->addMappingSource($source, $type);
142
            }
143 144 145 146
            $metadatas = $cme->getMetadatasForMappingSources();
        }

        foreach ($metadatas as $metadata) {
jwage's avatar
jwage committed
147 148 149 150 151 152
            $printer->writeln(
                sprintf(
                    'Processing entity "%s"',
                    $printer->format($metadata->name, 'KEYWORD')
                )
            );
153 154
        }

jwage's avatar
jwage committed
155 156
        $printer->writeln(
            sprintf(
157
                'Exporting "%s" mapping information to directory "%s"',
jwage's avatar
jwage committed
158 159
                $printer->format($args['to'], 'KEYWORD'),
                $printer->format($args['dest'], 'KEYWORD')
160
            )
jwage's avatar
jwage committed
161
        );
162 163

        $exporter->setMetadatas($metadatas);
164 165 166
        $exporter->export();
    }

167 168
    private function _isDoctrine1Schema(array $from)
    {
169
        $files = glob(current($from) . '/*.yml');
170 171 172
        if ($files) {
            $array = \sfYaml::load($files[0]);
            $first = current($array);
173 174
            // We're dealing with a Doctrine 1 schema if you have
            // a columns index in the first model array
175 176 177 178 179 180
            return isset($first['columns']);
        } else {
            return false;
        }
    }

181 182 183 184 185 186 187 188
    private function _determineSourceType($source)
    {
        // If the --from=<VALUE> is a directory lets determine if it is
        // annotations, yaml, xml, etc.
        if (is_dir($source)) {
            // Find the files in the directory
            $files = glob($source . '/*.*');
            if ( ! $files) {
jwage's avatar
jwage committed
189 190 191
                throw new \InvalidArgumentException(
                    sprintf('No mapping files found in "%s"', $source)
                );
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
            }

            // Get the contents of the first file
            $contents = file_get_contents($files[0]);

            // Check if it has a class definition in it for annotations
            if (preg_match("/class (.*)/", $contents)) {
              return 'annotation';
            // Otherwise lets determine the type based on the extension of the 
            // first file in the directory (yml, xml, etc)
            } else {
              $info = pathinfo($files[0]);
              return $info['extension'];
            }
        // Nothing special for database
        } else if ($source == 'database') {
            return 'database';
        }
    }

    private function _getSourceByType($type, $source)
213
    {
214 215 216 217 218 219 220
        // If --from==database then the source is an instance of SchemaManager
        // for the current EntityMAnager
        if ($type == 'database') {
            return $this->_em->getConnection()->getSchemaManager();
        } else {
            return $source;
        }
221 222
    }
}