Passed
Push — master ( eb2b9c...2ce42f )
by Dāvis
05:18 queued 02:31
created

QuickInsertRepository::update()   D

Complexity

Conditions 9
Paths 8

Size

Total Lines 39
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 26
nc 8
nop 5
dl 0
loc 39
rs 4.909
c 0
b 0
f 0
1
<?php
2
3
namespace Sludio\HelperBundle\Script\Repository;
4
5
use Sludio\HelperBundle\Script\Utils\Helper;
6
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
7
8
class QuickInsertRepository extends QuickInsertFunctions
9
{
10
    public static function findNextIdExt(ClassMetadata $metadata, $manager = null)
11
    {
12
        self::init($manager);
13
        $data = self::extractExt($metadata);
14
15
        return self::findNextId($data['table']);
16
    }
17
18
    public static function findNextId($tableName)
19
    {
20
        return self::get(['table_name' => 'information_schema.tables'], true, [
21
            'table_name' => $tableName,
22
            ['table_schema = DATABASE()'],
23
        ], ['AUTO_INCREMENT']) ?: 1;
24
    }
25
26
    public static function setFK($fkCheck = 0, $noFkCheck = false)
27
    {
28
        if (!$noFkCheck) {
29
            self::runSQL("SET FOREIGN_KEY_CHECKS = $fkCheck", false, null, true);
30
        }
31
    }
32
33
    public static function runSQL($sql, $noFkCheck = true, $manager = null, $skip = false)
34
    {
35
        $sql = trim(preg_replace('/\s+/', ' ', $sql));
36
        self::init($manager);
37
        if (!$skip) {
38
            self::setFK(0, $noFkCheck);
39
        }
40
41
        $sth = self::$connection->prepare($sql);
42
        $sth->execute();
43
44
        if (!$skip) {
45
            self::setFK(1, $noFkCheck);
46
        }
47
        if (0 === strpos($sql, "SELECT")) {
48
            return $sth->fetchAll();
49
        }
50
51
        return true;
52
    }
53
54
    public static function get($object, $one = false, $where = [], $fields = [], $manager = null, $extra = [])
55
    {
56
        self::getTable($object, $tableName, $columns, $type, $manager);
57
58
        $select = sprintf('SELECT %s ', isset($extra['MODE']) ? $extra['MODE'] : '');
59
        $fields = $fields ?: ['id'];
60
        $sql = $select.implode(', ', $fields).' FROM '.$tableName.self::buildWhere($tableName, $where).self::buildExtra($extra);
61
62
        $result = self::runSQL($sql) ?: null;
63
64
        if ($result) {
65
            $field = null;
66
            if (count($fields) === 1 && $fields[0] !== '*') {
67
                $field = $fields[0];
68
            }
69
            if ($field) {
70
                if (!$one) {
71
                    foreach ($result as &$res) {
72
                        $res = $res[$field];
73
                    }
74
                } else {
75
                    $result = $result[0][$field];
76
                }
77
            } elseif ($one) {
78
                $result = $result[0];
79
            }
80
        }
81
82
        return $result;
83
    }
84
85
    public static function persist($object, $full = false, $extraFields = [], $noFkCheck = false, $manager = null)
86
    {
87
        self::getTable($object, $tableName, $columns, $type, $manager, $extraFields);
88
89
        $id = self::findNextId($tableName);
90
        $data = [];
91
92
        $idd = null;
93
        foreach ($columns as $value => $key) {
94
            $keys = [
95
                $key,
96
                $value,
97
            ];
98
            if (!Helper::multiple($keys)) {
99
                $value = self::value($object, $value, $type);
100
                if ($value !== null) {
101
                    $data[$key] = $value;
102
                    if ($key === self::$identifier) {
103
                        $idd = $value;
104
                    }
105
                }
106
            }
107
        }
108
109
        if (!$full) {
110
            $data[self::$identifier] = $id;
111
        } else {
112
            $id = $idd;
113
        }
114
115
        if ($id !== null && Helper::isEmpty($data)) {
116
            return null;
117
        }
118
119
        $sql = '
120
            INSERT INTO
121
                '.$tableName.'
122
                    ('.implode(',', array_keys($data)).')
123
            VALUES
124
                ('.implode(',', array_values($data)).')
125
        ';
126
127
        self::runSQL($sql, $noFkCheck);
128
129
        return $id;
130
    }
131
132
    public static function update($id, $object, $extraFields = [], $noFkCheck = false, $manager = null)
133
    {
134
        self::getTable($object, $tableName, $columns, $type, $manager, $extraFields);
135
136
        $result = self::get(['table_name' => $tableName], true, ['id' => $id], ['*']);
137
        unset($result['id']);
138
        $data = [];
139
140
        $flip = array_flip($columns);
141
        if(!empty($result)) {
142
            foreach ($result as $key => $value) {
143
                $content = self::value($object, $key, $type, false);
144
                if ($content !== $value) {
145
                    $data[$key] = $content;
146
                }
147
                if (!$id && $content === null) {
148
                    unset($data[$key]);
149
                }
150
            }
151
        }
152
153
        if ($data) {
154
            $sql = sprintf('UPDATE %s SET ', $tableName);
155
            foreach ($data as $key => $value) {
156
                $intTypes = [
157
                    'boolean',
158
                    'integer',
159
                    'longint',
160
                ];
161
                if (in_array(self::$metadata[$tableName]->getFieldMapping($flip[$key])['type'], $intTypes)) {
162
                    $value = (int)$value;
163
                } else {
164
                    $value = "'".addslashes(trim($value))."'";
165
                }
166
                $sql .= ' '.$key.' = '.$value.',';
167
            }
168
            $sql = substr($sql, 0, -1).' WHERE id = '.$id;
169
170
            self::runSQL($sql, $noFkCheck);
171
        }
172
    }
173
174
    public static function delete($object, $where = [], $noFkCheck = false, $manager = null)
175
    {
176
        self::getTable($object, $tableName, $columns, $type, $manager);
177
178
        $sql = sprintf('DELETE FROM %s%s', $tableName, self::buildWhere($tableName, $where));
179
        self::runSQL($sql, $noFkCheck);
180
    }
181
182
    public static function link($object, $data, $noFkCheck = false, $manager = null)
183
    {
184
        self::getTable($object, $tableName, $columns, $type, $manager);
185
186
        $data['table_name'] = $tableName;
187
        self::persist($data, true, [], $noFkCheck, $manager);
188
    }
189
}
190