Completed
Pull Request — master (#2)
by Rougin
01:55
created

CreateMigrationCommand::defineColumns()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 15
cts 15
cp 1
rs 7.551
c 0
b 0
f 0
cc 7
eloc 12
nc 6
nop 3
crap 7
1
<?php
2
3
namespace Rougin\Refinery\Commands;
4
5
use Symfony\Component\Console\Input\InputOption;
6
use Symfony\Component\Console\Input\InputArgument;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Output\OutputInterface;
9
10
/**
11
 * Create Migration Command
12
 *
13
 * Creates a new migration file based on its file name.
14
 *
15
 * @package Refinery
16
 * @author  Rougin Royce Gutib <[email protected]>
17
 */
18
class CreateMigrationCommand extends AbstractCommand
19
{
20
    /**
21
     * Checks whether the command is enabled or not in the current environment.
22
     *
23
     * @return boolean
24
     */
25 3
    public function isEnabled()
26
    {
27 3
        return true;
28
    }
29
30
    /**
31
     * Sets the configurations of the specified command.
32
     *
33
     * @return void
34
     */
35 33
    protected function configure()
36
    {
37 33
        $this->setName('create')
38 33
            ->setDescription('Creates a new migration file')
39 33
            ->addArgument('name', InputArgument::REQUIRED, 'Name of the migration file')
40 33
            ->addOption('from-database', null, InputOption::VALUE_NONE, 'Generates a migration based from the database')
41 33
            ->addOption('sequential', null, InputOption::VALUE_NONE, 'Generates a migration file with a sequential identifier')
42 33
            ->addOption('type', null, InputOption::VALUE_OPTIONAL, 'Data type of the column', 'varchar')
43 33
            ->addOption('length', null, InputOption::VALUE_OPTIONAL, 'Length of the column', 50)
44 33
            ->addOption('auto_increment', null, InputOption::VALUE_OPTIONAL, 'Generates an "AUTO_INCREMENT" flag on the column', false)
45 33
            ->addOption('default', null, InputOption::VALUE_OPTIONAL, 'Generates a default value in the column definition', '')
46 33
            ->addOption('null', null, InputOption::VALUE_OPTIONAL, 'Generates a "NULL" value in the column definition', false)
47 33
            ->addOption('primary', null, InputOption::VALUE_OPTIONAL, 'Generates a "PRIMARY" value in the column definition', false)
48 33
            ->addOption('unsigned', null, InputOption::VALUE_OPTIONAL, 'Generates an "UNSIGNED" value in the column definition', false);
49 33
    }
50
51
    /**
52
     * Executes the command.
53
     *
54
     * @param  \Symfony\Component\Console\Input\InputInterface   $input
55
     * @param  \Symfony\Component\Console\Output\OutputInterface $output
56
     * @return object|\Symfony\Component\Console\Output\OutputInterface
57
     */
58 27
    protected function execute(InputInterface $input, OutputInterface $output)
59
    {
60 27
        $config = $this->filesystem->read('application/config/migration.php');
61
62 27
        $name = underscore($input->getArgument('name'));
63 27
        $path = APPPATH . 'migrations';
64
65 27
        $fileName = date('YmdHis') . '_' . $name;
66
67
        // Returns the migration type to be used
68 27
        preg_match('/\$config\[\'migration_type\'\] = \'(.*?)\';/i', $config, $match);
69
70 27
        if ($match[1] == 'sequential' || $input->getOption('sequential')) {
71 27
            $number = 1;
72
73 27
            $files = new \FilesystemIterator($path, \FilesystemIterator::SKIP_DOTS);
74
75 27
            $number += iterator_count($files);
76
77 27
            $sequence = sprintf('%03d', $number);
78 27
            $fileName = $sequence . '_' . $name;
79 27
        }
80
81 27
        $keywords = [ '', '', '', '' ];
82 27
        $keywords = array_replace($keywords, explode('_', $name));
83
84 27
        $data = $this->prepareData($input, $keywords);
85 24
        $data = $this->defineColumns($input, $keywords, $data);
86
87 24
        $rendered = $this->renderer->render('Migration.twig', $data);
88
89 24
        $this->filesystem->write('application/migrations/' . $fileName . '.php', $rendered);
90
91 24
        return $output->writeln('<info>"' . $fileName . '" has been created.</info>');
92
    }
93
94
    /**
95
     * Defines the columns to be included in the migration.
96
     *
97
     * @param  \Symfony\Component\Console\Input\InputInterface $input
98
     * @param  array                                           $keywords
99
     * @param  array                                           $data
100
     * @return array
101
     */
102 24
    protected function defineColumns(InputInterface $input, array $keywords, array $data)
103
    {
104 24
        $data['columns']  = [];
105 24
        $data['defaults'] = [];
106
107 24
        if ($data['command_name'] == 'create' && $input->getOption('from-database') === true) {
108 3
            $data['columns'] = $this->describe->getTable($data['table_name']);
109 24
        } elseif ($data['command_name'] != 'create') {
110 6
            $data['table_name'] = $keywords[3];
111
112 6
            array_push($data['columns'], $this->setColumn($input, $keywords[1]));
113 6
        }
114
115 24
        if ($data['command_name'] == 'modify') {
116 3
            foreach ($this->describe->getTable($data['table_name']) as $column) {
117 3
                $column->getField() != $keywords[1] || array_push($data['defaults'], $column);
118 3
            }
119 3
        }
120
121 24
        return $data;
122
    }
123
124
    /**
125
     * Prepares the data to be inserted in the template.
126
     *
127
     * @param  \Symfony\Component\Console\Input\InputInterface $input
128
     * @param  array                                           $keywords
129
     * @return array
130
     */
131 27
    protected function prepareData(InputInterface $input, array $keywords)
132
    {
133 27
        if ($input->getOption('from-database') && $keywords[0] != 'create') {
134 3
            $message = '--from-database is only available to create_*table*_table keyword';
135
136 3
            throw new \InvalidArgumentException($message);
137
        }
138
139 24
        $data = [];
140
141 24
        $data['command_name'] = $keywords[0];
142 24
        $data['data_types']   = [ 'string' => 'VARCHAR', 'integer' => 'INT' ];
143 24
        $data['class_name']   = underscore($input->getArgument('name'));
144 24
        $data['table_name']   = $keywords[1];
145
146 24
        return $data;
147
    }
148
149
    /**
150
     * Sets properties for a specified column
151
     *
152
     * @param  \Symfony\Component\Console\Input\InputInterface $input
153
     * @param  string                                          $fieldName
154
     * @return \Rougin\Describe\Column
155
     */
156 6
    protected function setColumn(InputInterface $input, $fieldName)
157
    {
158 6
        $column = new \Rougin\Describe\Column;
159
160 6
        $column->setField($fieldName);
161 6
        $column->setNull($input->getOption('null'));
162 6
        $column->setDataType($input->getOption('type'));
163 6
        $column->setLength($input->getOption('length'));
164 6
        $column->setPrimary($input->getOption('primary'));
165 6
        $column->setUnsigned($input->getOption('unsigned'));
166 6
        $column->setDefaultValue($input->getOption('default'));
167 6
        $column->setAutoIncrement($input->getOption('auto_increment'));
168
169 6
        return $column;
170
    }
171
}
172