Completed
Push — master ( b659c5...c65770 )
by Michael
10:22
created

AbstractSchemaCommon::addOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 19
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 17
nc 1
nop 1
crap 2
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * Contains AbstractSchemaCommon class.
5
 *
6
 * PHP version 7.0+
7
 *
8
 * LICENSE:
9
 * This file is part of Yet Another Php Eve Api Library also know as Yapeal
10
 * which can be used to access the Eve Online API data and place it into a
11
 * database.
12
 * Copyright (C) 2014-2017 Michael Cummings
13
 *
14
 * This program is free software: you can redistribute it and/or modify it
15
 * under the terms of the GNU Lesser General Public License as published by the
16
 * Free Software Foundation, either version 3 of the License, or (at your
17
 * option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful, but WITHOUT
20
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
21
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
22
 * for more details.
23
 *
24
 * You should have received a copy of the GNU Lesser General Public License
25
 * along with this program. If not, see
26
 * <http://spdx.org/licenses/LGPL-3.0.html>.
27
 *
28
 * You should be able to find a copy of this license in the COPYING-LESSER.md
29
 * file. A copy of the GNU GPL should also be available in the COPYING.md file.
30
 *
31
 * @copyright 2014-2017 Michael Cummings
32
 * @license   LGPL-3.0+
33
 * @author    Michael Cummings <[email protected]>
34
 */
35
namespace Yapeal\Console\Schema;
36
37
use Symfony\Component\Console\Command\Command;
38
use Symfony\Component\Console\Helper\ProgressBar;
39
use Symfony\Component\Console\Input\InputInterface;
40
use Symfony\Component\Console\Input\InputOption;
41
use Symfony\Component\Console\Output\OutputInterface;
42
use Yapeal\Console\ConfigFileTrait;
43
use Yapeal\Console\VerbosityMappingTrait;
44
use Yapeal\CommonToolsTrait;
45
use Yapeal\Container\DicAwareInterface;
46
use Yapeal\Event\YEMAwareInterface;
47
use Yapeal\Event\YEMAwareTrait;
48
use Yapeal\Exception\YapealDatabaseException;
49
use Yapeal\FileSystem\SafeFileHandlingTrait;
50
use Yapeal\Log\Logger;
51
use Yapeal\Sql\SqlCleanupTrait;
52
53
/**
54
 * Class AbstractSchemaCommon
55
 */
56
abstract class AbstractSchemaCommon extends Command implements YEMAwareInterface, DicAwareInterface
57
{
58
    use CommonToolsTrait;
59
    use ConfigFileTrait;
60
    use SafeFileHandlingTrait;
61
    use SqlCleanupTrait;
62
    use VerbosityMappingTrait;
63
    use YEMAwareTrait;
64
    /**
65
     * Sets the help message and all the common options used by the Database:* commands.
66
     *
67
     * @param string $help Command help text.
68
     *
69
     * @throws \Symfony\Component\Console\Exception\LogicException
70
     */
71
    protected function addOptions(string $help)
72
    {
73
        $this->addConfigFileOption();
74
        $this->addOption('schema', 's', InputOption::VALUE_REQUIRED, 'Name of the schema(database).')
75
            ->addOption('hostName', 'o', InputOption::VALUE_REQUIRED, 'Host name for database server.')
76
            ->addOption('password', 'p', InputOption::VALUE_REQUIRED, 'Password used to access schema.')
77
            ->addOption('platform',
78
                'l',
79
                InputOption::VALUE_REQUIRED,
80
                'Platform of PDO driver. Currently only "mysql" support is complete.',
81
                'mysql')
82
            ->addOption('port',
83
                null,
84
                InputOption::VALUE_REQUIRED,
85
                'Port number for remote server. Only needed if using http connection.')
86
            ->addOption('tablePrefix', 't', InputOption::VALUE_REQUIRED, 'Prefix for schema table names.')
87
            ->addOption('userName', 'u', InputOption::VALUE_REQUIRED, 'User name used to access schema.')
88
            ->setHelp($help);
89
    }
90
    /** @noinspection PhpMissingParentCallCommonInspection */
91
    /**
92
     * Executes the current command.
93
     *
94
     * This method is not abstract because you can use this class
95
     * as a concrete class. In this case, instead of defining the
96
     * execute() method, you set the code to execute by passing
97
     * a Closure to the setCode() method.
98
     *
99
     * @param InputInterface  $input  An InputInterface instance
100
     * @param OutputInterface $output An OutputInterface instance
101
     *
102
     * @return int|null null or 0 if everything went fine, or an error code
103
     *
104
     * @throws \DomainException
105
     * @throws \InvalidArgumentException
106
     * @throws \LogicException
107
     * @throws \UnexpectedValueException
108
     * @see    setCode()
109
     */
110
    protected function execute(InputInterface $input, OutputInterface $output): int
111
    {
112
        $this->applyVerbosityMap($output);
113
        $this->processCliOptions($input);
114
        $this->processSql($output);
115
        return 0;
116
    }
117
    /**
118
     * @param string          $sqlStatements
119
     * @param string          $fileName
120
     * @param OutputInterface $output
121
     *
122
     * @throws YapealDatabaseException
123
     * @throws \DomainException
124
     * @throws \InvalidArgumentException
125
     * @throws \LogicException
126
     * @throws \Symfony\Component\Console\Exception\LogicException
127
     * @throws \UnexpectedValueException
128
     */
129
    protected function executeSqlStatements(string $sqlStatements, string $fileName, OutputInterface $output)
130
    {
131
        $pdo = $this->getPdo();
132
        $yem = $this->getYem();
133
        $statements = explode(';', $this->getCleanedUpSql($sqlStatements, $this->getSqlSubs()));
134
        $statements = array_filter($statements,
135
            function ($statement) {
136
                return '' !== trim($statement);
137
            });
138
        $progress = null;
139
        if ($output::VERBOSITY_QUIET !== $output->getVerbosity()) {
140
            if (false === strpos($fileName, '::')) {
141
                $mess = sprintf('<info>Execute %1$s/%2$s</info>',
142
                    basename(dirname($fileName)),
143
                    basename($fileName));
144
            } else {
145
                $mess = sprintf('<info>Execute %s</info>', $fileName);
146
            }
147
            $yem->triggerLogEvent('Yapeal.Log.log', Logger::INFO, strip_tags($mess));
148
            $output->writeln($mess);
149
            $progress = $this->createProgressBar($output, count($statements));
150
        }
151
        foreach ($statements as $statement => $sql) {
152
            try {
153
                // Last minute replacement for procedures that has to be done
154
                // here so as not to break statements.
155
                $sql = str_replace('{semiColon}', ';', trim($sql));
156
                null !== $progress && $progress->clear();
157
                $yem->triggerLogEvent('Yapeal.Log.log', Logger::DEBUG, 'sql - ' . $sql);
158
                $pdo->exec($sql);
159
                if (null !== $progress) {
160
                    $progress->display();
161
                    $progress->setMessage('<comment>executing</comment>');
162
                    $progress->advance();
163
                }
164
            } catch (\PDOException $exc) {
165
                if (null !== $progress) {
166
                    $progress->setMessage('<error>Failed</error>');
167
                    $progress->advance();
168
                    $output->writeln('');
169
                }
170
                $mess = '<error>SQL error in statement ' . $statement . '</error>';
171
                $output->writeln($mess);
172
                throw new YapealDatabaseException(strip_tags($mess), 2, $exc);
173
            }
174
        }
175
        if (null !== $progress) {
176
            $progress->setMessage('<info>Finished</info>');
177
            $progress->finish();
178
            $output->writeln('');
179
        }
180
    }
181
    /**
182
     * @return array
183
     * @throws \LogicException
184
     */
185
    protected function getSqlSubs()
186
    {
187
        return $this->sqlSubs;
188
    }
189
    /**
190
     * @param InputInterface $input
191
     *
192
     * @return static Fluent interface.
193
     * @throws \DomainException
194
     * @throws \LogicException
195
     */
196
    protected function processCliOptions(InputInterface $input)
197
    {
198
        $dic = $this->getDic();
199
        $options = $input->getOptions();
200
        if (!empty($options['configFile'])) {
201
            $this->processConfigFile($options['configFile'], $dic);
0 ignored issues
show
Compatibility introduced by
$dic of type object<ArrayAccess> is not a sub-type of object<Yapeal\Container\ContainerInterface>. It seems like you assume a child interface of the interface ArrayAccess to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
202
        }
203
        // TODO: Needs to be fixed for per platform config settings.
204
        $base = 'Yapeal.Sql.';
205
        foreach (['schema', 'hostName', 'password', 'platform', 'tablePrefix', 'userName'] as $option) {
206
            if (array_key_exists($option, $options) && null !== $options[$option]) {
207
                $dic[$base . $option] = $options[$option];
208
            }
209
        }
210
        return $this;
211
    }
212
    /**
213
     * @param OutputInterface $output
214
     */
215
    abstract protected function processSql(OutputInterface $output);
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
216
    /**
217
     * @var array $sqlSubs Holds a list of Sql section replacement pairs.
218
     */
219
    protected $sqlSubs;
220
    /**
221
     * @param OutputInterface $output
222
     * @param int             $statementCount
223
     *
224
     * @return ProgressBar
225
     */
226
    private function createProgressBar(OutputInterface $output, int $statementCount): ProgressBar
227
    {
228
        $progress = new ProgressBar($output);
229
        $progress->setRedrawFrequency(1);
230
        $progress->setBarWidth(47);
231
        $progress->setFormat('%current:2s%/%max:2s% [%bar%] %percent:3s%% %elapsed:6s% %message%');
232
        $progress->setMessage('<info>starting</info>');
233
        $progress->start($statementCount);
234
        return $progress;
235
    }
236
}
237