Conditions | 32 |
Paths | > 20000 |
Total Lines | 239 |
Code Lines | 136 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
115 | public function createUpdateDbTableByAnnotations(string $modelClassName): bool |
||
116 | { |
||
117 | $result = true; |
||
118 | |||
119 | // Check if the model class exists and has properties |
||
120 | if ( |
||
121 | ! class_exists($modelClassName) |
||
122 | || count(get_class_vars($modelClassName)) === 0 |
||
123 | ) { |
||
124 | return true; |
||
125 | } |
||
126 | |||
127 | |||
128 | // Test if the model class is abstract |
||
129 | try { |
||
130 | $reflection = new ReflectionClass($modelClassName); |
||
131 | if ($reflection->isAbstract()) { |
||
132 | return true; |
||
133 | } |
||
134 | } catch (Throwable $exception) { |
||
135 | return false; |
||
136 | } |
||
137 | |||
138 | // Get the model instance |
||
139 | $model = new $modelClassName(); |
||
140 | |||
141 | // Get the connection service name |
||
142 | $connectionServiceName = $model->getReadConnectionService(); |
||
143 | |||
144 | // Check if the connection service name is empty |
||
145 | if (empty($connectionServiceName)) { |
||
146 | return false; |
||
147 | } |
||
148 | |||
149 | // Get the connection service and metadata provider |
||
150 | $connectionService = $this->di->getShared($connectionServiceName); |
||
151 | $metaData = $this->di->get(ModelsMetadataProvider::SERVICE_NAME); |
||
152 | $metaData->reset(); |
||
153 | |||
154 | // Get the model annotations |
||
155 | //https://docs.phalcon.io/4.0/ru-ru/annotations |
||
156 | $modelAnnotation = $this->di->get(ModelsAnnotationsProvider::SERVICE_NAME)->get($model); |
||
157 | |||
158 | // Initialize table name, structure and indexes |
||
159 | $tableName = $model->getSource(); |
||
160 | $table_structure = []; |
||
161 | $indexes = []; |
||
162 | |||
163 | // Create columns list by code annotations |
||
164 | $newColNames = $metaData->getAttributes($model); |
||
165 | $previousAttribute = ''; |
||
166 | foreach ($newColNames as $attribute) { |
||
167 | $table_structure[$attribute] = [ |
||
168 | 'type' => Column::TYPE_VARCHAR, |
||
169 | 'after' => $previousAttribute, |
||
170 | 'notNull' => false, |
||
171 | 'isNumeric' => false, |
||
172 | 'primary' => false, |
||
173 | ]; |
||
174 | $previousAttribute = $attribute; |
||
175 | } |
||
176 | |||
177 | // Set data types |
||
178 | $propertiesAnnotations = $modelAnnotation->getPropertiesAnnotations(); |
||
179 | if ($propertiesAnnotations !== false) { |
||
180 | $attributeTypes = $metaData->getDataTypes($model); |
||
181 | foreach ($attributeTypes as $attribute => $type) { |
||
182 | $table_structure[$attribute]['type'] = $type; |
||
183 | // Try to find size of field |
||
184 | if (array_key_exists($attribute, $propertiesAnnotations)) { |
||
185 | $propertyDescription = $propertiesAnnotations[$attribute]; |
||
186 | if ( |
||
187 | $propertyDescription->has('Column') |
||
188 | && $propertyDescription->get('Column')->hasArgument('length') |
||
189 | ) { |
||
190 | $table_structure[$attribute]['size'] = $propertyDescription->get('Column')->getArgument( |
||
191 | 'length' |
||
192 | ); |
||
193 | } |
||
194 | } |
||
195 | } |
||
196 | } |
||
197 | |||
198 | // Change type for numeric columns |
||
199 | $numericAttributes = $metaData->getDataTypesNumeric($model); |
||
200 | foreach ($numericAttributes as $attribute => $value) { |
||
201 | $table_structure[$attribute]['type'] = Column::TYPE_INTEGER; |
||
202 | $table_structure[$attribute]['isNumeric'] = true; |
||
203 | } |
||
204 | |||
205 | // Set not null for columns |
||
206 | $notNull = $metaData->getNotNullAttributes($model); |
||
207 | foreach ($notNull as $attribute) { |
||
208 | $table_structure[$attribute]['notNull'] = true; |
||
209 | } |
||
210 | |||
211 | // Set default values for initial save, later it fill at Models\ModelBase\beforeValidationOnCreate |
||
212 | $defaultValues = $metaData->getDefaultValues($model); |
||
213 | foreach ($defaultValues as $key => $value) { |
||
214 | if ($value !== null) { |
||
215 | $table_structure[$key]['default'] = $value; |
||
216 | } |
||
217 | } |
||
218 | |||
219 | // Set primary keys |
||
220 | // $primaryKeys = $metaData->getPrimaryKeyAttributes($model); |
||
221 | // foreach ($primaryKeys as $attribute) { |
||
222 | // $indexes[$attribute] = new Index($attribute, [$attribute], 'UNIQUE'); |
||
223 | // } |
||
224 | |||
225 | // Set bind types |
||
226 | $bindTypes = $metaData->getBindTypes($model); |
||
227 | foreach ($bindTypes as $attribute => $value) { |
||
228 | $table_structure[$attribute]['bindType'] = $value; |
||
229 | } |
||
230 | |||
231 | // Find auto incremental column, usually it is ID column |
||
232 | $keyFiled = $metaData->getIdentityField($model); |
||
233 | if ($keyFiled) { |
||
234 | unset($indexes[$keyFiled]); |
||
235 | $table_structure[$keyFiled] = [ |
||
236 | 'type' => Column::TYPE_INTEGER, |
||
237 | 'notNull' => true, |
||
238 | 'autoIncrement' => true, |
||
239 | 'primary' => true, |
||
240 | 'isNumeric' => true, |
||
241 | 'first' => true, |
||
242 | ]; |
||
243 | } |
||
244 | |||
245 | // Some exceptions |
||
246 | if ($modelClassName === PbxSettings::class) { |
||
247 | $keyFiled = 'key'; |
||
248 | unset($indexes[$keyFiled]); |
||
249 | $table_structure[$keyFiled] = [ |
||
250 | 'type' => Column::TYPE_VARCHAR, |
||
251 | 'notNull' => true, |
||
252 | 'autoIncrement' => false, |
||
253 | 'primary' => true, |
||
254 | 'isNumeric' => false, |
||
255 | 'first' => true, |
||
256 | ]; |
||
257 | } |
||
258 | |||
259 | // Create additional indexes |
||
260 | $modelClassAnnotation = $modelAnnotation->getClassAnnotations(); |
||
261 | if ( |
||
262 | $modelClassAnnotation !== null |
||
263 | && $modelClassAnnotation->has('Indexes') |
||
264 | ) { |
||
265 | $additionalIndexes = $modelClassAnnotation->get('Indexes')->getArguments(); |
||
266 | foreach ($additionalIndexes as $index) { |
||
267 | $indexName = "i_{$tableName}_{$index['name']}"; |
||
268 | $indexes[$indexName] = new Index($indexName, $index['columns'], $index['type']); |
||
269 | } |
||
270 | } |
||
271 | |||
272 | // Create new table structure |
||
273 | $columns = []; |
||
274 | foreach ($table_structure as $colName => $colType) { |
||
275 | $columns[] = new Column($colName, $colType); |
||
276 | } |
||
277 | |||
278 | $columnsNew = [ |
||
279 | 'columns' => $columns, |
||
280 | 'indexes' => $indexes, |
||
281 | ]; |
||
282 | |||
283 | // Let's describe the directory for storing temporary tables and data |
||
284 | $tempDir = $this->di->getShared('config')->path('core.tempDir'); |
||
285 | $sqliteTempStore = $connectionService->fetchColumn('PRAGMA temp_store'); |
||
286 | $sqliteTempDir = $connectionService->fetchColumn('PRAGMA temp_store_directory'); |
||
287 | $connectionService->execute('PRAGMA temp_store = FILE;'); |
||
288 | $connectionService->execute("PRAGMA temp_store_directory = '$tempDir';"); |
||
289 | |||
290 | // Starting the transaction |
||
291 | $connectionService->begin(); |
||
292 | |||
293 | if (! $connectionService->tableExists($tableName)) { |
||
294 | $msg = ' - UpdateDatabase: Create new table: ' . $tableName . ' '; |
||
295 | SystemMessages::echoWithSyslog($msg); |
||
296 | $result = $connectionService->createTable($tableName, '', $columnsNew); |
||
297 | SystemMessages::echoResult($msg); |
||
298 | } else { |
||
299 | // Table exists, we have to check/upgrade its structure |
||
300 | $currentColumnsArr = $connectionService->describeColumns($tableName, ''); |
||
301 | |||
302 | if ($this->isTableStructureNotEqual($currentColumnsArr, $columns)) { |
||
303 | $msg = ' - UpdateDatabase: Upgrade table: ' . $tableName . ' '; |
||
304 | SystemMessages::echoWithSyslog($msg); |
||
305 | // Create new table and copy all data |
||
306 | $currentStateColumnList = []; |
||
307 | $oldColNames = []; // Old columns names |
||
308 | $countColumnsTemp = count($currentColumnsArr); |
||
309 | for ($k = 0; $k < $countColumnsTemp; $k++) { |
||
310 | $currentStateColumnList[$k] = $currentColumnsArr[$k]->getName(); |
||
311 | $oldColNames[] = $currentColumnsArr[$k]->getName(); |
||
312 | } |
||
313 | |||
314 | // Create temporary clone on current table with all columns and date |
||
315 | // Delete original table |
||
316 | $gluedColumns = implode(',', $currentStateColumnList); |
||
317 | $query = "CREATE TEMPORARY TABLE {$tableName}_backup($gluedColumns); |
||
318 | INSERT INTO {$tableName}_backup SELECT $gluedColumns FROM $tableName; |
||
319 | DROP TABLE $tableName"; |
||
320 | $result = $result && $connectionService->execute($query); |
||
321 | |||
322 | // Create new table with new columns structure |
||
323 | $result = $result && $connectionService->createTable($tableName, '', $columnsNew); |
||
324 | |||
325 | // Copy data from temporary table to newly created |
||
326 | $newColumnNames = array_intersect($newColNames, $oldColNames); |
||
327 | $gluedNewColumns = implode(',', $newColumnNames); |
||
328 | $result = $result && $connectionService->execute( |
||
329 | "INSERT INTO $tableName ( $gluedNewColumns) SELECT $gluedNewColumns FROM {$tableName}_backup;" |
||
330 | ); |
||
331 | |||
332 | // Drop temporary table |
||
333 | $result = $result && $connectionService->execute("DROP TABLE {$tableName}_backup;"); |
||
334 | SystemMessages::echoResult($msg); |
||
335 | } |
||
336 | } |
||
337 | |||
338 | |||
339 | if ($result) { |
||
340 | $result = $this->updateIndexes($tableName, $connectionService, $indexes); |
||
341 | } |
||
342 | |||
343 | if ($result) { |
||
344 | $result = $connectionService->commit(); |
||
345 | } else { |
||
346 | SystemMessages::sysLogMsg('createUpdateDbTableByAnnotations', "Error: Failed on create/update table {$tableName}", LOG_ERR); |
||
347 | $connectionService->rollback(); |
||
348 | } |
||
349 | |||
350 | // Restoring PRAGMA values |
||
351 | $connectionService->execute("PRAGMA temp_store = $sqliteTempStore;"); |
||
352 | $connectionService->execute("PRAGMA temp_store_directory = '$sqliteTempDir';"); |
||
353 | return $result; |
||
354 | } |
||
469 |