Passed
Push — master ( a51f35...a51f35 )
by Dāvis
05:00
created

QuickInsertRepository::persist()   C

Complexity

Conditions 8
Paths 20

Size

Total Lines 46
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 26
c 2
b 0
f 0
nc 20
nop 5
dl 0
loc 46
rs 5.5555
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 = [];
95
96
        if (!empty($result)) {
97
            foreach ($result as $key => $value) {
98
                $content = self::value($object, $key, $type, false);
99
                if ($id && !\in_array($content, [
100
                        null,
101
                        $value,
102
                    ], true)) {
103
                    $data[$key] = $content;
104
                }
105
            }
106
        }
107
108
        if (!empty($data)) {
109
            $sql = sprintf('UPDATE %s SET ', $tableName);
110
            foreach ($data as $key => $value) {
111
                if (self::numeric($tableName, $key, $value)) {
112
                    $value = (int)$value;
113
                } else {
114
                    $value = "'".addslashes(trim($value))."'";
115
                }
116
                $sql .= ' '.$key.' = '.$value.',';
117
            }
118
            $sql = substr($sql, 0, -1).' WHERE id = '.$id;
119
120
            self::runSQL($sql, $noFkCheck);
121
        }
122
    }
123
124
    public static function delete($object, array $where = [], $noFkCheck = false, $manager = null)
125
    {
126
        self::getTable($object, $tableName, $columns, $type, $manager);
127
128
        $sql = sprintf('DELETE FROM %s%s', $tableName, self::buildWhere($tableName, $where));
129
        self::runSQL($sql, $noFkCheck);
130
    }
131
132
    public static function link($object, $data, $noFkCheck = false, $manager = null)
133
    {
134
        self::getTable($object, $tableName, $columns, $type, $manager);
135
136
        $data['table_name'] = $tableName;
137
        self::persist($data, true, [], $noFkCheck, $manager);
138
    }
139
140
    public static function persist($object, $full = false, array $extraFields = [], $noFkCheck = false, $manager = null)
141
    {
142
        self::getTable($object, $tableName, $columns, $type, $manager, $extraFields);
143
144
        $id = self::findNextId($tableName);
145
        $data = [];
146
147
        $idd = null;
148
        /** @var $columns array */
149
        foreach ($columns as $value => $key) {
150
            $keys = [
151
                $key,
152
                $value,
153
            ];
154
            if (!Helper::multiple($keys)) {
155
                $value = self::value($object, $value, $type);
156
                if ($value !== null) {
157
                    $data[$key] = $value;
158
                    if ($key === self::$identifier) {
159
                        $idd = $value;
160
                    }
161
                }
162
            }
163
        }
164
165
        if (!$full) {
166
            $data[self::$identifier] = $id;
167
        } else {
168
            $id = $idd;
169
        }
170
171
        if ($id !== null && Helper::isEmpty($data)) {
172
            return null;
173
        }
174
175
        $sql = '
176
            INSERT INTO
177
                '.$tableName.'
178
                    ('.implode(',', array_keys($data)).')
179
            VALUES
180
                ('.implode(',', array_values($data)).')
181
        ';
182
183
        self::runSQL($sql, $noFkCheck);
184
185
        return $id;
186
    }
187
}
188