Completed
Push — master ( bcded9...57d427 )
by Daniel
11:33
created

FKchange::createChangeColumn()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
c 6
b 0
f 1
dl 0
loc 9
rs 9.6667
cc 3
eloc 7
nc 4
nop 2
1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\fk_scale_mysql;
30
31
/**
32
 * Description of FKchange
33
 *
34
 * @author Daniel Popiniuc <[email protected]>
35
 */
36
class FKchange
37
{
38
39
    use ConfigurationMySQL,
40
        ConfigurationForAction,
41
        FKinterface,
42
        \danielgp\common_lib\MySQLiAdvancedOutput;
43
44
    private $applicationSpecificArray;
45
46
    public function __construct()
47
    {
48
        $rqst = new \Symfony\Component\HttpFoundation\Request;
49
        echo $this->setApplicationHeader()
50
        . $this->buildApplicationInterface($rqst->createFromGlobals())
51
        . $this->setApplicationFooter();
52
    }
53
54
    private function buildApplicationInterface($sGb)
55
    {
56
        $mysqlConfig          = $this->configuredMySqlServer();
57
        $elToModify           = $this->targetElementsToModify($sGb);
58
        $transmitedParameters = $this->countTransmitedParameters(['db', 'tbl', 'fld', 'dt']);
59
        $mConnection          = $this->connectToMySql($mysqlConfig);
60
        $sReturn              = [];
61
        $sReturn[]            = $this->buildInputFormTab($mysqlConfig, $transmitedParameters, $sGb);
62
        $sReturn[]            = $this->buildResultsTab($mConnection, $elToModify, $transmitedParameters);
63
        return implode('', $sReturn);
64
    }
65
66
    private function buildResultsTab($mConnection, $elToModify, $tParams)
67
    {
68
        $sReturn             = [];
69
        $targetTableTextFlds = $this->getForeignKeys($elToModify);
70
        $sReturn[]           = '<div class="tabbertab' . ($tParams ? ' tabbertabdefault' : '')
71
                . '" id="FKscaleMySQLresults" title="Results">';
72
        if (is_array($targetTableTextFlds)) {
73
            $sReturn[]    = $this->createDropForeignKeysAndGetTargetColumnDefinition($targetTableTextFlds);
74
            $mainColArray = $this->packParameteresForMainChangeColumn($elToModify, $targetTableTextFlds);
75
            $sReturn[]    = $this->createChangeColumn($mainColArray, [
76
                'style'                => 'color:blue;font-weight:bold;',
77
                'includeOldColumnType' => true,
78
            ]);
79
            $sReturn[]    = $this->recreateFKs($elToModify, $targetTableTextFlds);
80
        } else {
81
            $sReturn[] = $this->returnMessagesInCaseOfNoResults($mConnection);
82
        }
83
        $sReturn[] = '</div><!-- end of FKscaleMySQLresults tab -->'
84
                . '</div><!-- tabberFKscaleMySQL -->';
85
        return implode('', $sReturn);
86
    }
87
88
    private function createChangeColumn($params, $adtnlFeatures = null)
89
    {
90
        return '<div style="' . (isset($adtnlFeatures['style']) ? $adtnlFeatures['style'] : 'color:blue;') . '">'
91
                . 'ALTER TABLE `' . $params['Database'] . '`.`' . $params['Table'] . '` '
92
                . 'CHANGE `' . $params['Column'] . '` `' . $params['Column'] . '` ' . $params['NewDataType'] . ' '
93
                . $this->setColumnDefinition($params) . ';'
94
                . (isset($adtnlFeatures['includeOldColumnType']) ? ' /* from ' . $params['OldDataType'] . ' */' : '')
95
                . '</div>';
96
    }
97
98
    private function createDropForeignKey($parameters)
99
    {
100
        return '<div style="color:red;">'
101
                . 'ALTER TABLE `' . $parameters['Database'] . '`.`' . $parameters['Table']
102
                . '` DROP FOREIGN KEY `' . $parameters['ForeignKeyName'] . '`;'
103
                . '</div>';
104
    }
105
106
    private function createDropForeignKeysAndGetTargetColumnDefinition($targetTableTextFlds)
107
    {
108
        $sReturn = [];
109
        foreach ($targetTableTextFlds as $key => $value) {
110
            $sReturn[]                                    = $this->createDropForeignKey([
111
                'Database'       => $value['TABLE_SCHEMA'],
112
                'Table'          => $value['TABLE_NAME'],
113
                'ForeignKeyName' => $value['CONSTRAINT_NAME'],
114
            ]);
115
            $this->applicationSpecificArray['Cols'][$key] = $this->getMySQLlistColumns([
116
                'TABLE_SCHEMA' => $value['TABLE_SCHEMA'],
117
                'TABLE_NAME'   => $value['TABLE_NAME'],
118
                'COLUMN_NAME'  => $value['COLUMN_NAME'],
119
            ]);
120
        }
121
        return implode('', $sReturn);
122
    }
123
124
    private function createForeignKey($params)
125
    {
126
        return '<div style="color:green;">'
127
                . 'ALTER TABLE `' . $params['Database'] . '`.`' . $params['Table'] . '` '
128
                . 'ADD CONSTRAINT `' . $params['ForeignKeyName'] . '` '
129
                . 'FOREIGN KEY (`' . $params['Column'] . '`) REFERENCES `' . $params['ReferencedDatabase'] . '`.`'
130
                . $params['ReferencedTable'] . '` (`' . $params['ReferencedColumn'] . '`) '
131
                . 'ON DELETE ' . ($params['RuleDelete'] == 'NULL' ? 'SET NULL' : $params['RuleDelete']) . ' '
132
                . 'ON UPDATE ' . ($params['RuleUpdate'] == 'NULL' ? 'SET NULL' : $params['RuleUpdate']) . ';'
133
                . '</div>';
134
    }
135
136
    private function getForeignKeys($elToModify)
137
    {
138
        $additionalFeatures = [
139
            'REFERENCED_TABLE_SCHEMA' => $elToModify['Database'],
140
            'REFERENCED_TABLE_NAME'   => $elToModify['Table'],
141
            'REFERENCED_COLUMN_NAME'  => $elToModify['Column'],
142
            'REFERENCED_TABLE_NAME'   => 'NOT NULL',
143
        ];
144
        $query              = $this->sQueryMySqlIndexes($additionalFeatures);
145
        return $this->setMySQLquery2Server($query, 'full_array_key_numbered')['result'];
146
    }
147
148
    private function packParameteresForMainChangeColumn($elToModify, $targetTableTextFlds)
149
    {
150
        $colToIdentify = [
151
            'TABLE_SCHEMA' => $elToModify['Database'],
152
            'TABLE_NAME'   => $elToModify['Table'],
153
            'COLUMN_NAME'  => $elToModify['Column'],
154
        ];
155
        $col           = $this->getMySQLlistColumns($colToIdentify);
156
        return [
157
            'Database'       => $targetTableTextFlds[0]['REFERENCED_TABLE_SCHEMA'],
158
            'Table'          => $targetTableTextFlds[0]['REFERENCED_TABLE_NAME'],
159
            'Column'         => $targetTableTextFlds[0]['REFERENCED_COLUMN_NAME'],
160
            'OldDataType'    => strtoupper($col[0]['COLUMN_TYPE']) . ' ' . $this->setColumnDefinition($col[0]),
161
            'NewDataType'    => $elToModify['NewDataType'],
162
            'IS_NULLABLE'    => $col[0]['IS_NULLABLE'],
163
            'COLUMN_DEFAULT' => $col[0]['COLUMN_DEFAULT'],
164
            'EXTRA'          => $col[0]['EXTRA'],
165
            'COLUMN_COMMENT' => $col[0]['COLUMN_COMMENT'],
166
        ];
167
    }
168
169
    private function recreateFKs($elToModify, $targetTableTextFlds)
170
    {
171
        $sReturn = [];
172
        foreach ($targetTableTextFlds as $key => $value) {
173
            $sReturn[] = $this->createChangeColumn([
174
                'Database'       => $value['TABLE_SCHEMA'],
175
                'Table'          => $value['TABLE_NAME'],
176
                'Column'         => $value['COLUMN_NAME'],
177
                'NewDataType'    => $elToModify['NewDataType'],
178
                'IS_NULLABLE'    => $this->applicationSpecificArray['Cols'][$key][0]['IS_NULLABLE'],
179
                'COLUMN_DEFAULT' => $this->applicationSpecificArray['Cols'][$key][0]['COLUMN_DEFAULT'],
180
                'EXTRA'          => $this->applicationSpecificArray['Cols'][$key][0]['EXTRA'],
181
                'COLUMN_COMMENT' => $this->applicationSpecificArray['Cols'][$key][0]['COLUMN_COMMENT'],
182
            ]);
183
            $sReturn[] = $this->createForeignKey([
184
                'Database'           => $value['TABLE_SCHEMA'],
185
                'Table'              => $value['TABLE_NAME'],
186
                'Column'             => $value['COLUMN_NAME'],
187
                'ForeignKeyName'     => $value['CONSTRAINT_NAME'],
188
                'ReferencedDatabase' => $value['REFERENCED_TABLE_SCHEMA'],
189
                'ReferencedTable'    => $value['REFERENCED_TABLE_NAME'],
190
                'ReferencedColumn'   => $value['REFERENCED_COLUMN_NAME'],
191
                'RuleDelete'         => $value['DELETE_RULE'],
192
                'RuleUpdate'         => $value['UPDATE_RULE'],
193
            ]);
194
        }
195
        return implode('', $sReturn);
196
    }
197
198
    private function setColumnDefinition($inArray)
199
    {
200
        $colDefinition = $this->setColumnDefinitionPrefix($inArray['IS_NULLABLE'], $inArray['COLUMN_DEFAULT']);
201
        if ($inArray['EXTRA'] == 'auto_increment') {
202
            $colDefinition .= ' AUTO_INCREMENT';
203
        }
204
        if (strlen($inArray['COLUMN_COMMENT']) > 0) {
205
            $colDefinition .= ' COMMENT "' . $inArray['COLUMN_COMMENT'] . '"';
206
        }
207
        return $colDefinition;
208
    }
209
210
    private function setColumnDefinitionPrefix($nullableYesNo, $defaultValue)
211
    {
212
        $colDefinition = 'NOT NULL DEFAULT "' . $defaultValue . '"';
213
        if ($nullableYesNo == 'NO') {
214
            if (is_null($defaultValue)) {
215
                $colDefinition = 'NOT NULL';
216
            }
217
        } elseif ($nullableYesNo == 'YES') {
218
            $colDefinition = 'DEFAULT "' . $defaultValue . '"';
219
            if ($defaultValue === null) {
220
                $colDefinition = 'DEFAULT NULL';
221
            }
222
        }
223
        return $colDefinition;
224
    }
225
}
226