Completed
Push — master ( ec27e4...948d8b )
by smiley
14:17
created

CreateTable   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 113
Duplicated Lines 5.31 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 30
c 0
b 0
f 0
lcom 1
cbo 2
dl 6
loc 113
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B sql() 0 26 6
F fieldspec() 6 81 24

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Class CreateTable
4
 *
5
 * @filesource   CreateTable.php
6
 * @created      03.06.2017
7
 * @package      chillerlan\Database\Query\Dialects\MySQL
8
 * @author       Smiley <[email protected]>
9
 * @copyright    2017 Smiley
10
 * @license      MIT
11
 */
12
13
namespace chillerlan\Database\Query\Dialects\MySQL;
14
15
use chillerlan\Database\Query\CreateTableAbstract;
16
use chillerlan\Database\Query\QueryException;
17
18
/**
19
 * @link https://dev.mysql.com/doc/refman/5.7/en/create-table.html
20
 */
21
class CreateTable extends CreateTableAbstract{
22
23
	public function sql():string{
24
25
		if(empty($this->name)){
26
			throw new QueryException('no name specified');
27
		}
28
29
		$sql = 'CREATE ';
30
		$sql .= $this->temp ? 'TEMPORARY ' : '';
31
		$sql .= 'TABLE ';
32
		$sql .= $this->ifNotExists ? 'IF NOT EXISTS ' : '';
33
		$sql .= $this->quote($this->name);
34
35
		if(!empty($this->cols)){
36
			$sql .= ' ('.PHP_EOL."\t".implode(','.PHP_EOL."\t", $this->cols);
37
38
			if($this->primaryKey){
39
				$sql .=','.PHP_EOL."\t".'PRIMARY KEY ('.$this->quote($this->primaryKey).')';
40
			}
41
42
			$sql .= PHP_EOL.')';
43
		}
44
45
		$sql .= '';
46
47
		return $sql;
48
	}
49
50
	protected function fieldspec(
51
		string $name,
52
		string $type,
53
		$length = null,
54
		string $attribute = null,
55
		string $collation = null,
56
		bool $isNull = false,
57
		string $defaultType = null,
58
		$defaultValue = null,
59
		string $extra = null
60
	){
61
		$name = trim($name);
62
		$type = strtoupper(trim($type));
63
64
		$field = [$this->quote($name)];
65
66
		// @todo: whitelist types?
67
		$nolengthtypes = ['DATE', 'TINYBLOB', 'TINYTEXT', 'BLOB', 'TEXT', 'MEDIUMBLOB',
68
		                  'MEDIUMTEXT', 'LONGBLOB', 'LONGTEXT', 'SERIAL', 'BOOLEAN', 'UUID'];
69
70
		$field[] = (is_int($length) || is_string($length) && count(explode(',', $length)) === 2) && !in_array($type, $nolengthtypes)
71
			? $type.'('. $length . ')'
72
			: $type;
73
74
		if($attribute){
0 ignored issues
show
Bug Best Practice introduced by
The expression $attribute of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
75
			$field[] = strtoupper($attribute);
76
		}
77
78
		$collationtypes = ['TINYTEXT', 'TEXT', 'MEDIUMTEXT', 'LONGTEXT', 'VARCHAR', 'CHAR', 'ENUM', 'SET'];
79
		if($collation && in_array($type, $collationtypes)){
0 ignored issues
show
Bug Best Practice introduced by
The expression $collation of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
80
			list($charset) = explode('_', $collation);
81
82
			$field[] = 'CHARACTER SET '.$charset;
83
84
			if($charset !== $collation){
85
				$field[] = 'COLLATE '.$collation;
86
			}
87
88
		}
89
90
		$field[] = $isNull ? 'NULL' : 'NOT NULL';
91
92
		$defaultType = strtoupper($defaultType);
93
94
		if($defaultType === 'USER_DEFINED'){
95
96
			switch(true){
97
				case $type === 'TIMESTAMP' && intval($defaultValue) === 0:
98
					$field[] = 'DEFAULT 0';
99
					break;
100
				case $type === 'BIT':
101
					$field[] = 'DEFAULT b\''.preg_replace('/[^01]/', '0', $defaultValue).'\'';
102
					break;
103
				case $type === 'BOOLEAN':
104
					$field[] = 'DEFAULT '.preg_match('/^1|T|TRUE|YES$/i', $defaultValue) ? 'TRUE' : 'FALSE';
105
					break;
106
				case $type === 'BINARY' || $type === 'VARBINARY':
107
					$field[] = 'DEFAULT 0x'.$defaultValue;
108
					break;
109
				case strtoupper($defaultValue) === 'NULL' && $isNull:
110
					$field[] = 'DEFAULT NULL';
111
					break;
112
				default:
113
					$field[] = 'DEFAULT \''.$defaultValue.'\'';
114
			}
115
116
		}
117 View Code Duplication
		else if($defaultType === 'CURRENT_TIMESTAMP'){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
			$field[] = 'DEFAULT CURRENT_TIMESTAMP';
119
		}
120
		else if($defaultType === 'NULL' && $isNull){
121
			$field[] = 'DEFAULT NULL';
122
		}
123
124
125
		if($extra){
0 ignored issues
show
Bug Best Practice introduced by
The expression $extra of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
126
			$field[] = $extra;
127
		}
128
129
		return implode(' ', $field);
130
	}
131
132
133
}
134