Completed
Push — master ( 84202a...feaa3c )
by Andreas
09:23
created

schema::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 7
rs 9.4285
c 1
b 0
f 0
1
<?php
2
/**
3
 * @author CONTENT CONTROL http://www.contentcontrol-berlin.de/
4
 * @copyright CONTENT CONTROL http://www.contentcontrol-berlin.de/
5
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
6
 */
7
8
namespace midgard\portable\command;
9
10
use midgard\portable\storage\connection;
11
use midgard\portable\classgenerator;
12
use Symfony\Component\Console\Command\Command;
13
use Symfony\Component\Console\Input\InputInterface;
14
use Symfony\Component\Console\Input\InputArgument;
15
use Symfony\Component\Console\Output\OutputInterface;
16
use Symfony\Component\Console\Helper\ProgressBar;
17
use Symfony\Component\Console\Question\Question;
18
use midgard_storage;
19
use midgard_connection;
20
use Doctrine\ORM\Tools\SchemaTool;
21
use Doctrine\DBAL\Schema\Comparator;
22
use Symfony\Component\Console\Input\InputOption;
23
use Doctrine\Common\Proxy\ProxyGenerator;
24
25
/**
26
 * (Re)generate mapping information from MgdSchema XMLs
27
 */
28
class schema extends Command
29
{
30
    public $connected = false;
31
32
    protected function configure()
33
    {
34
        $this->setName('schema')
35
            ->setDescription('(Re)generate mapping information from MgdSchema XMLs')
36
            ->addArgument('config', InputArgument::OPTIONAL, 'Full path to midgard-portable config file')
37
            ->addOption('force', null, InputOption::VALUE_NONE, 'Ignore errors from DB');
38
    }
39
40
    protected function execute(InputInterface $input, OutputInterface $output)
41
    {
42
        if (!$this->connected) {
43
            $path = $input->getArgument('config');
44
            if (empty($path)) {
45
                if (file_exists(OPENPSA_PROJECT_BASEDIR . 'config/midgard-portable.inc.php')) {
46
                    $path = OPENPSA_PROJECT_BASEDIR . 'config/midgard-portable.inc.php';
47
                } else {
48
                    $dialog = $this->getHelper('question');
49
                    $path = $dialog->ask($input, $output, new Question('<question>Enter path to config file</question>'));
50
                }
51
            }
52
            if (!file_exists($path)) {
53
                throw new \RuntimeException('Config file ' . $path . ' not found');
54
            }
55
            //we have to delay startup so that we can delete the entity class file before it gets included
56
            connection::set_autostart(false);
57
            require $path;
58
        }
59
60
        $mgd_config = midgard_connection::get_instance()->config;
61
        $mgdschema_file = $mgd_config->vardir . '/mgdschema_classes.php';
62
        if (   file_exists($mgdschema_file)
63
            && !unlink($mgdschema_file)) {
64
            throw new \RuntimeException('Could not unlink ' . $mgdschema_file);
65
        }
66
        if (connection::get_parameter('dev_mode') !== true) {
67
            $driver = connection::get_parameter('driver');
68
            $classgenerator = new classgenerator($driver->get_manager(), $mgdschema_file);
69
            $classgenerator->write($driver->get_namespace());
70
        }
71
        if (!file_exists($mgd_config->blobdir . '/0/0')) {
72
            $mgd_config->create_blobdir();
73
        }
74
        connection::startup();
75
        $em = connection::get_em();
76
        connection::invalidate_cache();
77
        $cms = $em->getMetadataFactory()->getAllMetadata();
78
79
        // create storage
80
        if (    !midgard_storage::create_base_storage()
81
             && midgard_connection::get_instance()->get_error_string() != 'MGD_ERR_OK') {
82
            throw new \Exception("Failed to create base database structures" . midgard_connection::get_instance()->get_error_string());
83
        }
84
        $force = $input->getOption('force');
85
        $to_update = array();
86
        $to_create = array();
87
88
        foreach ($cms as $cm) {
89
            if (!$em->getConnection()->getSchemaManager()->tablesExist(array($cm->getTableName()))) {
90
                $to_create[] = $cm;
91
            } else {
92
                $to_update[] = $cm;
93
            }
94
        }
95
96
        if (!empty($to_create)) {
97
            $output->writeln('Creating <info>' . count($to_create) . '</info> new tables');
98
            $tool = new SchemaTool($em);
99
            try {
100
                $tool->createSchema($to_create);
101
            } catch (\Exception $e) {
102
                if (!$force) {
103
                    throw $e;
104
                } else {
105
                    $output->writeln('<error>' . $e->getMessage() . '</error>');
106
                }
107
            }
108
        }
109
        if (!empty($to_update)) {
110
            $this->process_updates($to_update, $output, $force);
111
        }
112
        $output->writeln('Generating proxies');
113
        $this->generate_proxyfiles($cms);
114
115
        $output->writeln('Done');
116
    }
117
118 View Code Duplication
    private function generate_proxyfiles(array $cms)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
    {
120
        $em = connection::get_em();
121
        $generator = new ProxyGenerator($em->getConfiguration()->getProxyDir(), $em->getConfiguration()->getProxyNamespace());
122
        $generator->setPlaceholder('baseProxyInterface', 'Doctrine\ORM\Proxy\Proxy');
123
124
        foreach ($cms as $cm) {
125
            $filename = $generator->getProxyFileName($cm->getName());
126
            if (file_exists($filename)) {
127
                unlink($filename);
128
            }
129
            $generator->generateProxyClass($cm, $filename);
130
        }
131
    }
132
133
    private function process_updates(array $to_update, OutputInterface $output, $force)
134
    {
135
        $em = connection::get_em();
136
        $conn = $em->getConnection();
137
        $tool = new SchemaTool($em);
138
        $from = $conn->getSchemaManager()->createSchema();
139
        $to = $tool->getSchemaFromMetadata($to_update);
140
141
        $comparator = new Comparator;
142
        $diff = $comparator->compare($from, $to);
143
        foreach ($diff->changedTables as $changed_table) {
144
            if (!empty($changed_table->removedColumns)) {
145
                $changed_table->removedColumns = array();
146
            }
147
        }
148
        $sql = $diff->toSaveSql($conn->getDatabasePlatform());
149
150
        if (count($sql) == 0) {
151
            return;
152
        }
153
154
        $output->writeln('Executing <info>' . count($sql) . '</info> updates');
155
        $progress = new ProgressBar($output);
156
        $progress->start(count($sql));
157
158
        foreach ($sql as $sql_line) {
159
            if ($output->getVerbosity() == OutputInterface::VERBOSITY_VERBOSE) {
160
                $output->writeln(' Executing <info>' . $sql_line . '</info>');
161
            }
162
            try {
163
                $conn->executeQuery($sql_line);
164
            } catch (\Exception $e) {
165
                if (!$force) {
166
                    throw $e;
167
                } else {
168
                    $output->writeln('<error>' . $e->getMessage() . '</error>');
169
                }
170
            }
171
172
            $progress->advance();
173
        }
174
        $progress->finish();
175
        $output->writeln('');
176
    }
177
}
178