TruncateCommand::configure()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 9
nc 1
nop 0
1
<?php
2
3
namespace LimeSoda\Database;
4
5
use N98\Magento\Command\Database\AbstractDatabaseCommand;
6
use N98\Util\Console\Helper\DatabaseHelper;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Input\InputOption;
10
use Symfony\Component\Console\Output\OutputInterface;
11
12
class TruncateCommand extends AbstractDatabaseCommand
13
{
14
    protected function configure()
15
    {
16
        $this
17
            ->setName('db:truncate')
18
            ->addOption('force', 'f', InputOption::VALUE_NONE, 'Force')
19
            ->setDescription('Truncate database tables');
20
21
        $help = <<<HELP
22
The command prompts before truncating the tables in the database. If --force option is specified it
23
directly truncates the tables.
24
The configured user in app/etc/local.xml must have "TRUNCATE" privileges.
25
HELP;
26
        $this->setHelp($help);
27
    }
28
29
    /**
30
     * @param \Symfony\Component\Console\Input\InputInterface $input
31
     * @param \Symfony\Component\Console\Output\OutputInterface $output
32
     * @return int|void
33
     */
34
    protected function execute(InputInterface $input, OutputInterface $output)
35
    {
36
        $this->detectDbSettings($output);
37
        $dialog = $this->getHelperSet()->get('dialog');
38
        $dbHelper = $this->getHelper('database');
39
40
        if ($input->getOption('force')) {
41
            $shouldDrop = true;
42
        } else {
43
            $question = '<question>Really truncate tables in ' . $this->dbSettings['dbname'] . ' ?</question> ' .
44
                        '<comment>[n]</comment>: ';
45
            $shouldDrop = $dialog->askConfirmation($output, $question, false);
46
        }
47
48
        if ($shouldDrop) {
49
            $result = $dbHelper->getTables();
50
            $query = 'SET FOREIGN_KEY_CHECKS = 0; ';
51
            $count = 0;
52
            foreach ($result as $tableName) {
53
                $query .= 'TRUNCATE TABLE `'.$tableName.'`; ';
54
                $count++;
55
            }
56
            $query .= 'SET FOREIGN_KEY_CHECKS = 1;';
57
            $dbHelper->getConnection()->query($query);
58
            $output->writeln('<info>Truncated database tables</info> <comment>' . $count . ' tables truncated</comment>');
59
        }
60
    }
61
}
62