Completed
Branch master (48ec27)
by Michael
03:44
created

ExtgalleryPersistableObjectHandler::deleteById()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
c 1
b 0
f 0
nc 8
nop 2
dl 0
loc 23
rs 8.5906
1
<?php
2
/**
3
 * ExtGallery Class Manager
4
 *
5
 * You may not change or alter any portion of this comment or credits
6
 * of supporting developers from this source code or any supporting source code
7
 * which is considered copyrighted (c) material of the original comment or credit authors.
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * @copyright   {@link http://xoops.org/ XOOPS Project}
13
 * @license     GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
14
 * @author      Zoullou (http://www.zoullou.net)
15
 * @package     ExtGallery
16
 */
17
18
/**
19
 * Persistable Object Handler class.
20
 * This class is responsible for providing data access mechanisms to the data source
21
 * of derived class objects.
22
 *
23
 * @author    Jan Keller Pedersen <[email protected]> - IDG Danmark A/S <www.idg.dk>
24
 * @copyright copyright (c) 2000-2004 XOOPS.org
25
 * @package   Kernel
26
 */
27
class ExtgalleryPersistableObjectHandler extends XoopsPersistableObjectHandler //XoopsObjectHandler
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
28
{
29
    /**#@+
30
     * Information about the class, the handler is managing
31
     *
32
     * @var string
33
     */
34
    public $table;
35
    public $keyName;
36
    public $className;
37
    public $identifierName;
38
    /**#@-*/
39
40
    /**
41
     * Constructor - called from child classes
42
     *
43
     * @param XoopsDatabase $db        {@link XoopsDatabase}
44
     *                                 object
45
     * @param string        $tablename Name of database table
46
     * @param string        $classname Name of Class, this handler is managing
47
     * @param string        $keyname   Name of the property, holding the key
48
     *
49
     * @param bool          $idenfierName
50
     *
51
     */
52
53
    public function __construct(XoopsDatabase $db, $tablename, $classname, $keyname, $idenfierName = false)
54
    {
55
        parent::__construct($db);
56
        //        $db = XoopsDatabaseFactory::getDatabaseConnection();
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% 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...
57
        $this->table     = $db->prefix($tablename);
58
        $this->keyName   = $keyname;
59
        $this->className = $classname;
60
        if (false !== $idenfierName) {
61
            $this->identifierName = $idenfierName;
62
        }
63
    }
64
65
    /**
66
     * create a new user
67
     *
68
     * @param bool $isNew Flag the new objects as "new"?
69
     *
70
     * @return XoopsObject
71
     */
72
73
    public function create($isNew = true)
74
    {
75
        $obj = new $this->className();
76
        if (true === $isNew) {
77
            $obj->setNew();
78
        }
79
80
        return $obj;
81
    }
82
83
    /**
84
     * delete an object from the database
85
     *
86
     * @param mixed $id id of the object to delete
87
     * @param  bool $force
88
     * @return bool        FALSE if failed.
89
     */
90
    public function deleteById($id, $force = false)
91
    {
92
        if (is_array($this->keyName)) {
93
            $clause = array();
94
            for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
95
                $clause[] = $this->keyName[$i] . ' = ' . $id[$i];
96
            }
97
            $whereclause = implode(' AND ', $clause);
98
        } else {
99
            $whereclause = $this->keyName . ' = ' . $id;
100
        }
101
        $sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $whereclause;
102
        if (false !== $force) {
103
            $result = $this->db->queryF($sql);
104
        } else {
105
            $result = $this->db->query($sql);
106
        }
107
        if (!$result) {
108
            return false;
109
        }
110
111
        return true;
112
    }
113
114
    /**
115
     * @param      $fieldname
116
     * @param      $fieldvalue
117
     * @param null $criteria
118
     * @param bool $force
119
     *
120
     * @return bool
121
     */
122
    public function updateFieldValue($fieldname, $fieldvalue, $criteria = null, $force = true)
123
    {
124
        $sql = 'UPDATE ' . $this->table . ' SET ' . $fieldname . ' = ' . $fieldvalue;
125 View Code Duplication
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
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...
126
            $sql .= ' ' . $criteria->renderWhere();
0 ignored issues
show
Bug introduced by
The method renderWhere cannot be called on $criteria (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
127
        }
128
        $result = false !== $force ? $this->db->queryF($sql) : $this->db->query($sql);
129
        if (!$result) {
130
            return false;
131
        }
132
133
        return true;
134
    }
135
136
    /**
137
     * @param $data
138
     *
139
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|object?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
140
     */
141
    public function _toObject($data)
142
    {
143
        if (is_array($data)) {
144
            $ret = array();
145
            foreach ($data as $v) {
146
                $object = new $this->className();
147
                $object->assignVars($v);
148
                $ret[] = $object;
149
            }
150
151
            return $ret;
152
        } else {
153
            $object = new $this->className();
154
            $object->assignVars($v);
0 ignored issues
show
Bug introduced by
The variable $v seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
155
156
            return $object;
157
        }
158
    }
159
160
    /**
161
     * @param        $objects
162
     * @param array  $externalKeys
163
     * @param string $format
164
     *
165
     * @return array
166
     */
167
    public function objectToArray($objects, $externalKeys = array(), $format = 's')
168
    {
169
        static $cached;
170
171
        $ret = array();
172
        if (is_array($objects)) {
173
            $i = 0;
174
            foreach ($objects as $object) {
175
                $vars = $object->getVars();
176
                foreach ($vars as $k => $v) {
177
                    $ret[$i][$k] = $object->getVar($k, $format);
178
                }
179
                foreach ($externalKeys as $key) {
180
                    // Replace external key by corresponding object
181
                    $externalKey = $object->getExternalKey($key);
182
                    if ($ret[$i][$key] != 0) {
183
                        // Retriving data if isn't cached
184
                        if (!isset($cached[$externalKey['keyName']][$ret[$i][$key]])) {
185 View Code Duplication
                            if ($externalKey['core']) {
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...
186
                                $handler = xoops_getHandler($externalKey['className']);
187
                            } else {
188
                                $handler = xoops_getModuleHandler($externalKey['className'], 'extgallery');
189
                            }
190
                            $cached[$externalKey['keyName']][$ret[$i][$key]] = $this->objectToArrayWithoutExternalKey($handler->{$externalKey['getMethodeName']}($ret[$i][$key]),
191
                                                                                                                      $format);
192
                        }
193
                        $ret[$i][$externalKey['keyName']] = $cached[$externalKey['keyName']][$ret[$i][$key]];
194
                    }
195
                    unset($ret[$i][$key]);
196
                }
197
                ++$i;
198
            }
199
        } else {
200
            $vars = $objects->getVars();
201
            foreach ($vars as $k => $v) {
202
                $ret[$k] = $objects->getVar($k, $format);
203
            }
204
            foreach ($externalKeys as $key) {
205
                // Replace external key by corresponding object
206
                $externalKey = $objects->getExternalKey($key);
207
                if ($ret[$key] != 0) {
208
                    // Retriving data if isn't cached
209
                    if (!isset($cached[$externalKey['keyName']][$ret[$key]])) {
210 View Code Duplication
                        if ($externalKey['core']) {
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...
211
                            $handler = xoops_getHandler($externalKey['className']);
212
                        } else {
213
                            $handler = xoops_getModuleHandler($externalKey['className'], 'extgallery');
214
                        }
215
                        $cached[$externalKey['keyName']][$ret[$key]] = $this->objectToArrayWithoutExternalKey($handler->{$externalKey['getMethodeName']}($ret[$key]),
216
                                                                                                              $format);
217
                    }
218
                    $ret[$externalKey['keyName']] = $cached[$externalKey['keyName']][$ret[$key]];
219
                }
220
                unset($ret[$key]);
221
            }
222
        }
223
224
        return $ret;
225
    }
226
227
    /**
228
     * @param        $object
229
     * @param string $format
230
     *
231
     * @return array
232
     */
233
    public function objectToArrayWithoutExternalKey($object, $format = 's')
234
    {
235
        $ret = array();
236
        if (null !== $object) {
237
            $vars = $object->getVars();
238
            foreach ($vars as $k => $v) {
239
                $ret[$k] = $object->getVar($k, $format);
240
            }
241
        }
242
243
        return $ret;
244
    }
245
246
    /**
247
     * @param        $fieldname
248
     * @param        $criteria
249
     * @param string $op
250
     *
251
     * @return bool
252
     */
253
    public function updateCounter($fieldname, $criteria, $op = '+')
254
    {
255
        $sql = 'UPDATE ' . $this->table . ' SET ' . $fieldname . ' = ' . $fieldname . $op . '1';
256
        $sql .= ' ' . $criteria->renderWhere();
257
        $result = $this->db->queryF($sql);
258
        if (!$result) {
259
            return false;
260
        }
261
262
        return true;
263
    }
264
265
    /**
266
     * @param null|CriteriaElement $criteria
267
     * @param string               $sum
268
     *
269
     * @return array|int|string
270
     */
271 View Code Duplication
    public function getSum(CriteriaElement $criteria = null, $sum = '*')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
272
    {
273
        $field   = '';
274
        $groupby = false;
275
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
276
            if ($criteria->groupby != '') {
277
                $groupby = true;
278
                $field   = $criteria->groupby
279
                           . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
280
            }
281
        }
282
        $sql = 'SELECT ' . $field . "SUM($sum) FROM " . $this->table;
283
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
284
            $sql .= ' ' . $criteria->renderWhere();
285
            if ($criteria->groupby != '') {
286
                $sql .= $criteria->getGroupby();
287
            }
288
        }
289
        $result = $this->db->query($sql);
290
        if (!$result) {
291
            return 0;
292
        }
293
        if ($groupby === false) {
294
            list($sum) = $this->db->fetchRow($result);
295
296
            return $sum;
297
        } else {
298
            $ret = array();
299
            while (list($id, $sum) = $this->db->fetchRow($result)) {
300
                $ret[$id] = $sum;
301
            }
302
303
            return $ret;
304
        }
305
    }
306
307
    /**
308
     * @param null|CriteriaElement $criteria
309
     * @param string               $max
310
     *
311
     * @return array|int|string
312
     */
313 View Code Duplication
    public function getMax(CriteriaElement $criteria = null, $max = '*')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
314
    {
315
        $field   = '';
316
        $groupby = false;
317
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
318
            if ($criteria->groupby != '') {
319
                $groupby = true;
320
                $field   = $criteria->groupby
321
                           . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
322
            }
323
        }
324
        $sql = 'SELECT ' . $field . "MAX($max) FROM " . $this->table;
325
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
326
            $sql .= ' ' . $criteria->renderWhere();
327
            if ($criteria->groupby != '') {
328
                $sql .= $criteria->getGroupby();
329
            }
330
        }
331
        $result = $this->db->query($sql);
332
        if (!$result) {
333
            return 0;
334
        }
335
        if (false === $groupby) {
336
            list($max) = $this->db->fetchRow($result);
337
338
            return $max;
339
        } else {
340
            $ret = array();
341
            while (list($id, $max) = $this->db->fetchRow($result)) {
342
                $ret[$id] = $max;
343
            }
344
345
            return $ret;
346
        }
347
    }
348
349
    /**
350
     * @param null|CriteriaElement $criteria
351
     * @param string               $avg
352
     *
353
     * @return int
354
     */
355
    public function getAvg(CriteriaElement $criteria = null, $avg = '*')
356
    {
357
        $field = '';
358
359
        $sql = 'SELECT ' . $field . "AVG($avg) FROM " . $this->table;
360 View Code Duplication
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
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...
361
            $sql .= ' ' . $criteria->renderWhere();
362
        }
363
        $result = $this->db->query($sql);
364
        if (!$result) {
365
            return 0;
366
        }
367
        list($sum) = $this->db->fetchRow($result);
368
369
        return $sum;
370
    }
371
372
    /**
373
     * @return mixed
374
     */
375
    public function getInsertId()
376
    {
377
        return $this->db->getInsertId();
378
    }
379
}
380