Completed
Push — master ( ae0103...9b98c5 )
by Joao
04:23 queued 56s
created

SqlHelper::generateSQL()   C

Complexity

Conditions 12
Paths 11

Size

Total Lines 51
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 0
Metric Value
dl 0
loc 51
ccs 0
cts 38
cp 0
rs 5.6668
c 0
b 0
f 0
cc 12
eloc 39
nc 11
nop 6
crap 156

How to fix   Long Method    Complexity   

Long Method

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:

1
<?php
2
3
namespace ByJG\AnyDataset\Store\Helpers;
4
5
use ByJG\AnyDataset\DbDriverInterface;
6
use ByJG\AnyDataset\Enum\SQLFieldType;
7
use ByJG\AnyDataset\Enum\SQLType;
8
use ByJG\AnyDataset\Dataset\Row;
9
use DateTime;
10
use Exception;
11
12
class SqlHelper
13
{
14
15
    /**
16
     * @var DbDriverInterface
17
     */
18
    private $dataset;
19
    protected $fieldDeliLeft = " ";
20
    protected $fieldDeliRight = " ";
21
22
    /**
23
     * @param DbDriverInterface $dataset
24
     */
25
    public function __construct(DbDriverInterface $dataset)
26
    {
27
        $this->dataset = $dataset;
28
    }
29
30
    /**
31
     * Generate and Execute UPDATE and INSERTS
32
     *
33
     * @param string $table
34
     * @param array $fields
35
     * @param $param
36
     * @param SQLType|int $type
37
     * @param string $filter
38
     * @param string $decimalpoint
39
     * @return string
40
     * @throws Exception
41
     */
42
    public function generateSQL(
43
        $table,
44
        $fields,
45
        &$param,
46
        $type = SQLType::SQL_INSERT,
47
        $filter = "",
48
        $decimalpoint = "."
49
    ) {
50
        if ($fields instanceof Row) {
51
            return $this->generateSQL($table, $fields->toArray(), $param, $type, $filter, $decimalpoint);
52
        }
53
54
        if ((is_null($param)) || (!is_array($param))) {
55
            $param = array();
56
        }
57
58
        $sql = "";
59
        if ($type == SQLType::SQL_UPDATE) {
60
            foreach ($fields as $fieldname => $fieldvalue) {
61
                if ($sql != "") {
62
                    $sql .= ", ";
63
                }
64
                $sql .= " "
65
                    . $this->fieldDeliLeft
66
                    . $fieldname
67
                    . $this->fieldDeliRight
68
                    . " = "
69
                    . $this->getValue($fieldname, $fieldvalue, $param, $decimalpoint)
70
                    . " ";
71
            }
72
            $sql = "update $table set $sql where $filter ";
73
        } elseif ($type == SQLType::SQL_INSERT) {
74
            $campos = "";
75
            $valores = "";
76
            foreach ($fields as $fieldname => $fieldvalue) {
77
                if ($campos != "") {
78
                    $campos .= ", ";
79
                    $valores .= ", ";
80
                }
81
                $campos .= $this->fieldDeliLeft . $fieldname . $this->fieldDeliRight;
82
                $valores .= $this->getValue($fieldname, $fieldvalue, $param, $decimalpoint);
83
            }
84
            $sql = "insert into $table ($campos) values ($valores)";
85
        } elseif ($type == SQLType::SQL_DELETE) {
86
            if ($filter == "") {
87
                throw new Exception("I can't generate delete statements without filter");
88
            }
89
            $sql = "delete from $table where $filter";
90
        }
91
        return $sql;
92
    }
93
94
    /**
95
     * Generic Function
96
     *
97
     * @param string $name
98
     * @param string|array $valores
99
     * @param array $param
100
     * @param string $decimalpoint
101
     * @return string
102
     */
103
    protected function getValue($name, $valores, &$param, $decimalpoint)
104
    {
105
        $paramName = "[[" . $name . "]]";
106
        if (!is_array($valores)) {
107
            $valores = array(SQLFieldType::TEXT, $valores);
108
        }
109
110
        if ($valores[0] == SQLFieldType::BOOLEAN) {
111
            $param[$name] = 'N';
112
            if ($valores[1] == "1") {
113
                $param[$name] = 'S';
114
            }
115
            return $paramName;
116
        } elseif (strlen($valores[1]) == 0) { // Zero is Empty!?!?!?!?
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
117
            return "null";
118
        } elseif ($valores[0] == SQLFieldType::TEXT) {
119
            $param[$name] = trim($valores[1]);
120
            return $paramName;
121
        } elseif ($valores[0] == SQLFieldType::DATE) {
122
            $date = ($valores[1] instanceof DateTime ? $valores[1]->format(DbBaseFunctions::YMDH) : $valores[1]);
123
            $param[$name] = $date;
124
            if ($this->getDbDataset()->getUri()->getScheme() == 'oci8') {
125
                return "TO_DATE($paramName, 'YYYY-MM-DD')";
126
            }
127
            return $paramName;
128
129
        } elseif ($valores[0] == SQLFieldType::NUMBER) {
130
            $search = ($decimalpoint == ".") ? "," : ".";
131
            $valores[1] = trim(str_replace($search, $decimalpoint, $valores[1]));
132
            $param[$name] = $valores[1];
133
            return $paramName;
134
        }
135
136
        return $valores[1];
137
    }
138
139
    /**
140
     * Used to create a FILTER in a SQL string.
141
     *
142
     * @param string $fieldName
143
     * @param string $relation
144
     * @param array $value
145
     * @param &string $sql (Full SQL)
0 ignored issues
show
Documentation introduced by
The doc-type &string could not be parsed: Unknown type name "&string" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
146
     * @param &string $param
0 ignored issues
show
Documentation introduced by
The doc-type &string could not be parsed: Unknown type name "&string" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
147
     */
148
    public function getWhereClause($fieldName, $relation, $value, &$sql, &$param)
149
    {
150
        if (strlen($sql) > 4) {
151
            $sql .= ' and ';
152
        }
153
        $sql = " $fieldName " . $relation . " " . $this->getValue($fieldName, $value, $param, '.');
154
    }
155
156
    public function setFieldDelimeters($left, $right)
157
    {
158
        $this->fieldDeliLeft = $left;
159
        $this->fieldDeliRight = $right;
160
    }
161
162 3
    public static function createSafeSQL($sql, $list)
163
    {
164 3
        return str_replace(array_keys($list), array_values($list), $sql);
165
    }
166
167
    /**
168
     * @return DbDriverInterface
169
     */
170
    public function getDbDataset()
171
    {
172
        return $this->dataset;
173
    }
174
}
175