Passed
Push — master ( 3f9dde...47232d )
by Dāvis
04:45
created

QuickInsertRepository::update()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 8
nop 5
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
1
<?php
2
3
namespace Sludio\HelperBundle\Script\Repository;
4
5
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
6
use Sludio\HelperBundle\Script\Utils\Helper;
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 get($object, $one = false, array $where = [], array $fields = [], $manager = null, array $extra = [])
27
    {
28
        self::getTable($object, $tableName, $columns, $type, $manager);
29
30
        $select = sprintf('SELECT %s ', isset($extra['MODE']) ? $extra['MODE'] : '');
31
        $fields = $fields ?: ['id'];
0 ignored issues
show
introduced by
The condition $fields can never be true.
Loading history...
32
        $sql = $select.implode(', ', $fields).' FROM '.$tableName.self::buildWhere($tableName, $where).self::buildExtra($extra);
33
34
        $result = self::runSQL($sql) ?: null;
35
36
        if ($result) {
37
            $field = null;
38
            if (\count($fields) === 1 && $fields[0] !== '*') {
39
                $field = $fields[0];
40
            }
41
            if ($field !== null) {
42
                if (!$one) {
43
                    /** @var $result array */
44
                    foreach ($result as &$res) {
45
                        $res = $res[$field];
46
                    }
47
                } else {
48
                    $result = $result[0][$field];
49
                }
50
            } elseif ($one) {
51
                $result = $result[0];
52
            }
53
        }
54
55
        return $result;
56
    }
57
58
    public static function runSQL($sql, $noFkCheck = true, $manager = null, $skip = false)
59
    {
60
        $sql = trim(preg_replace('/\s+/', ' ', $sql));
61
        self::init($manager);
62
        if (!$skip) {
63
            self::setFK(0, $noFkCheck);
64
        }
65
66
        $sth = self::$connection->prepare($sql);
67
        $sth->execute();
68
69
        if (!$skip) {
70
            self::setFK(1, $noFkCheck);
71
        }
72
        if (0 === strpos($sql, 'SELECT')) {
73
            return $sth->fetchAll();
74
        }
75
76
        return true;
77
    }
78
79
    public static function setFK($fkCheck = 0, $noFkCheck = false)
80
    {
81
        if (!$noFkCheck) {
82
            self::runSQL("SET FOREIGN_KEY_CHECKS = $fkCheck", false, null, true);
83
        }
84
    }
85
86
    public static function update($id, $object, array $extraFields = [], $noFkCheck = false, $manager = null)
87
    {
88
        self::getTable($object, $tableName, $columns, $type, $manager, $extraFields);
89
90
        $result = self::get(['table_name' => $tableName], true, ['id' => $id], ['*']) ?: [];
91
        if (isset($result['id'])) {
92
            unset($result['id']);
93
        }
94
        $data = self::parseUpdateResult($object, $type, $id, $tableName, $result);
95
96
        if (!empty($data)) {
97
            $sql = sprintf('UPDATE %s SET ', $tableName);
98
            foreach ($data as $key => $value) {
99
                if (self::numeric($tableName, $key, $value)) {
100
                    $value = (int)$value;
101
                } else {
102
                    $value = "'".addslashes(trim($value))."'";
103
                }
104
                $sql .= ' '.$key.' = '.$value.',';
105
            }
106
            $sql = substr($sql, 0, -1).' WHERE id = '.$id;
107
108
            self::runSQL($sql, $noFkCheck);
109
        }
110
    }
111
112
    public static function delete($object, array $where = [], $noFkCheck = false, $manager = null)
113
    {
114
        self::getTable($object, $tableName, $columns, $type, $manager);
115
116
        $sql = sprintf('DELETE FROM %s%s', $tableName, self::buildWhere($tableName, $where));
117
        self::runSQL($sql, $noFkCheck);
118
    }
119
120
    public static function link($object, $data, $noFkCheck = false, $manager = null)
121
    {
122
        self::getTable($object, $tableName, $columns, $type, $manager);
123
124
        $data['table_name'] = $tableName;
125
        self::persist($data, true, [], $noFkCheck, $manager);
126
    }
127
128
    public static function persist($object, $full = false, array $extraFields = [], $noFkCheck = false, $manager = null)
129
    {
130
        self::getTable($object, $tableName, $columns, $type, $manager, $extraFields);
131
132
        $id = self::findNextId($tableName);
133
        $data = [];
134
135
        $idd = null;
136
        /** @var $columns array */
137
        foreach ($columns as $value => $key) {
138
            $keys = [
139
                $key,
140
                $value,
141
            ];
142
            if (!Helper::multiple($keys)) {
143
                $value = self::value($object, $value, $type, $tableName);
144
                if ($value !== null) {
145
                    $data[$key] = $value;
146
                    if ($key === self::$identifier) {
147
                        $idd = $value;
148
                    }
149
                }
150
            }
151
        }
152
153
        if (!$full) {
154
            $data[self::$identifier] = $id;
155
        } else {
156
            $id = $idd;
157
        }
158
159
        if ($id !== null && Helper::isEmpty($data)) {
160
            return null;
161
        }
162
163
        $sql = '
164
            INSERT INTO
165
                '.$tableName.'
166
                    ('.implode(',', array_keys($data)).')
167
            VALUES
168
                ('.implode(',', array_values($data)).')
169
        ';
170
171
        self::runSQL($sql, $noFkCheck);
172
173
        return $id;
174
    }
175
}
176