Completed
Branch master (32b1ca)
by Michael
06:34 queued 03:17
created

ExtgalleryPersistableObjectHandler::getInsertId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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 XoopsObjectHandler //XoopsPersistableObjectHandler
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
    public function __construct(XoopsDatabase $db, $tablename, $classname, $keyname, $idenfierName = false)
53
    {
54
        parent::__construct($db);
55
        //        $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...
56
        $this->table     = $db->prefix($tablename);
57
        $this->keyName   = $keyname;
58
        $this->className = $classname;
59
        if (false !== $idenfierName) {
60
            $this->identifierName = $idenfierName;
61
        }
62
    }
63
64
    /**
65
     * create a new user
66
     *
67
     * @param bool $isNew Flag the new objects as "new"?
68
     *
69
     * @return XoopsObject
70
     */
71
    /* function &create($isNew = true) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
72
        //DNPROSSI - 5.3.0 Assigning the return value of new by reference is deprecated PHP 5.3
73
        //Kept for backward compatability
74
        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
75
            $obj = new $this->className();
76
        } else {
77
            $obj = new $this->className();
78
        }
79
        if ($isNew === true) {
80
            $obj->setNew();
81
        }
82
83
        return $obj;
84
    } */
85
86
    public function create($isNew = true)
87
    {
88
        $obj = new $this->className();
89
        if (true === $isNew) {
90
            $obj->setNew();
91
        }
92
93
        return $obj;
94
    }
95
96
    /**
97
     * retrieve an object
98
     *
99
     * @param  mixed $id        ID of the object - or array of ids for joint keys. Joint keys MUST be given in the same order as in the constructor
100
     * @param  bool  $as_object whether to return an object or an array
101
     * @return mixed reference to the object, FALSE if failed
102
     */
103
    public function get($id, $as_object = true)
104
    {
105
        if (is_array($this->keyName)) {
106
            $criteria = new CriteriaCompo();
107
            for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
108
                $criteria->add(new Criteria($this->keyName[$i], (int)$id[$i]));
109
            }
110
        } else {
111
            $criteria = new Criteria($this->keyName, (int)$id);
112
        }
113
        $criteria->setLimit(1);
114
        $obj_array =& $this->getObjects($criteria, false, $as_object);
115
        if (count($obj_array) != 1) {
116
            return $this->create();
117
        }
118
119
        return $obj_array[0];
120
    }
121
122
    /**
123
     * retrieve objects from the database
124
     *
125
     * @param CriteriaElement $criteria  {@link CriteriaElement} conditions to be met
0 ignored issues
show
Documentation introduced by
Should the type for parameter $criteria not be null|CriteriaElement?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
126
     * @param bool            $id_as_key use the ID as key for the array?
127
     * @param bool            $as_object return an array of objects?
128
     *
129
     * @return array
130
     */
131
    public function &getObjects(CriteriaElement $criteria = null, $id_as_key = false, $as_object = true)
132
    {
133
        $ret   = array();
134
        $limit = $start = 0;
135
        $sql   = 'SELECT * FROM ' . $this->table;
136 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...
137
            $sql .= ' ' . $criteria->renderWhere();
138
            if ($criteria->getSort() != '') {
139
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
140
            }
141
            $limit = $criteria->getLimit();
142
            $start = $criteria->getStart();
143
        }
144
        $result = $this->db->query($sql, $limit, $start);
145
        if (!$result) {
146
            return $ret;
147
        }
148
149
        $ret = $this->convertResultSet($result, $id_as_key, $as_object);
150
151
        return $ret;
152
    }
153
154
    /**
155
     * Convert a database resultset to a returnable array
156
     *
157
     * @param XoopsObject $result    database resultset
158
     * @param bool        $id_as_key - should NOT be used with joint keys
159
     * @param bool        $as_object
160
     *
161
     * @return array
162
     */
163
    public function convertResultSet($result, $id_as_key = false, $as_object = true)
164
    {
165
        $ret = array();
166
        while ($myrow = $this->db->fetchArray($result)) {
167
            $obj = $this->create(false);
168
            $obj->assignVars($myrow);
169
            if (!$id_as_key) {
170
                if ($as_object) {
171
                    $ret[] =& $obj;
172
                } else {
173
                    $row  = array();
174
                    $vars =& $obj->getVars();
175
                    foreach (array_keys($vars) as $i) {
176
                        $row[$i] = $obj->getVar($i);
177
                    }
178
                    $ret[] = $row;
179
                }
180
            } else {
181
                if ($as_object) {
182
                    $ret[$myrow[$this->keyName]] =& $obj;
183
                } else {
184
                    $row  = array();
185
                    $vars =& $obj->getVars();
186
                    foreach (array_keys($vars) as $i) {
187
                        $row[$i] = $obj->getVar($i);
188
                    }
189
                    $ret[$myrow[$this->keyName]] = $row;
190
                }
191
            }
192
            unset($obj);
193
        }
194
195
        return $ret;
196
    }
197
198
    /**
199
     * Retrieve a list of objects as arrays - DON'T USE WITH JOINT KEYS
200
     *
201
     * @param CriteriaElement $criteria {@link CriteriaElement} conditions to be met
0 ignored issues
show
Documentation introduced by
Should the type for parameter $criteria not be null|CriteriaElement?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
202
     * @param int             $limit    Max number of objects to fetch
203
     * @param int             $start    Which record to start at
204
     *
205
     * @return array
206
     */
207
    public function getList(CriteriaElement $criteria = null, $limit = 0, $start = 0)
208
    {
209
        $ret = array();
210
        if (null === $criteria) {
211
            $criteria = new CriteriaCompo();
212
        }
213
214
        if ($criteria->getSort() == '') {
215
            $criteria->setSort($this->identifierName);
216
        }
217
218
        $sql = 'SELECT ' . $this->keyName;
219
        if (!empty($this->identifierName)) {
220
            $sql .= ', ' . $this->identifierName;
221
        }
222
        $sql .= ' FROM ' . $this->table;
223 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...
224
            $sql .= ' ' . $criteria->renderWhere();
225
            if ($criteria->getSort() != '') {
226
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
227
            }
228
            $limit = $criteria->getLimit();
229
            $start = $criteria->getStart();
230
        }
231
        $result = $this->db->query($sql, $limit, $start);
232
        if (!$result) {
233
            return $ret;
234
        }
235
236
        $myts = MyTextSanitizer::getInstance();
237
        while ($myrow = $this->db->fetchArray($result)) {
238
            //identifiers should be textboxes, so sanitize them like that
239
            $ret[$myrow[$this->keyName]] = empty($this->identifierName) ? 1 : $myts->htmlSpecialChars($myrow[$this->identifierName]);
240
        }
241
242
        return $ret;
243
    }
244
245
    /**
246
     * count objects matching a condition
247
     *
248
     * @param  CriteriaElement $criteria {@link CriteriaElement} to match
0 ignored issues
show
Documentation introduced by
Should the type for parameter $criteria not be null|CriteriaElement?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
249
     * @return int|array             count of objects
250
     */
251 View Code Duplication
    public function getCount(CriteriaElement $criteria = null)
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...
252
    {
253
        $field   = '';
254
        $groupby = false;
255
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
256
            if ($criteria->groupby != '') {
257
                $groupby = true;
258
                $field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
259
            }
260
        }
261
        $sql = 'SELECT ' . $field . 'COUNT(*) FROM ' . $this->table;
262
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
263
            $sql .= ' ' . $criteria->renderWhere();
264
            if ($criteria->groupby != '') {
265
                $sql .= $criteria->getGroupby();
266
            }
267
        }
268
        $result = $this->db->query($sql);
269
        if (!$result) {
270
            return 0;
271
        }
272
        if (false === $groupby) {
273
            list($count) = $this->db->fetchRow($result);
274
275
            return $count;
276
        } else {
277
            $ret = array();
278
            while (list($id, $count) = $this->db->fetchRow($result)) {
279
                $ret[$id] = $count;
280
            }
281
282
            return $ret;
283
        }
284
    }
285
286
    /**
287
     * delete an object from the database
288
     *
289
     * @param  int $id id of the object to delete
290
     * @param  bool        $force
291
     * @return bool        FALSE if failed.
292
     */
293
    public function delete($id, $force = false)
294
    {
295
        if (is_array($this->keyName)) {
296
            $clause = array();
297
            for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
298
                $clause[] = $this->keyName[$i] . ' = ' . $id[$i];
299
            }
300
            $whereclause = implode(' AND ', $clause);
301
        } else {
302
            $whereclause = $this->keyName . ' = ' . $id;
303
        }
304
        $sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $whereclause;
305
        if ($force !== false) {
306
            $result = $this->db->queryF($sql);
307
        } else {
308
            $result = $this->db->query($sql);
309
        }
310
        if (!$result) {
311
            return false;
312
        }
313
314
        return true;
315
    }
316
317
    /**
318
     * insert a new object in the database
319
     *
320
     * @param  XoopsObject $obj         reference to the object
321
     * @param  bool        $force       whether to force the query execution despite security settings
322
     * @param  bool        $checkObject check if the object is dirty and clean the attributes
323
     * @return bool        FALSE if failed, TRUE if already present and unchanged or successful
324
     */
325
326
    public function insert(XoopsObject $obj, $force = false, $checkObject = true)
327
    {
328
        if (false !== $checkObject) {
329
            if (!is_object($obj)) {
330
//                var_dump($obj);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
331
332
                return false;
333
            }
334
            //if (!is_a($obj, $this->className)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% 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...
335
            //$obj->setErrors(get_class($obj) . ' Differs from ' . $this->className);
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
336
337
            if (!(class_exists($this->className) && $obj instanceof $this->className)) {
338
                $obj->setErrors(get_class($obj) . ' Differs from ' . $this->className);
339
340
                return false;
341
            }
342
        }
343
        if (!$obj->cleanVars()) {
344
            return false;
345
        }
346
347
        $cleanvars = array();
348
        foreach ($obj->cleanVars as $k => $v) {
349
            if ($obj->vars[$k]['data_type'] == XOBJ_DTYPE_INT) {
350
                $cleanvars[$k] = (int)$v;
351
            } elseif (is_array($v)) {
352
                $cleanvars[$k] = $this->db->quoteString(implode(',', $v));
353
            } else {
354
                $cleanvars[$k] = $this->db->quoteString($v);
355
            }
356
        }
357
        if ($obj->isNew()) {
358
            if (!is_array($this->keyName)) {
359
                if ($cleanvars[$this->keyName] < 1) {
360
                    $cleanvars[$this->keyName] = $this->db->genId($this->table . '_' . $this->keyName . '_seq');
361
                }
362
            }
363
            $sql = 'INSERT INTO ' . $this->table . ' (' . implode(',', array_keys($cleanvars)) . ') VALUES (' . implode(',', array_values($cleanvars)) . ')';
364
        } else {
365
            $sql = 'UPDATE ' . $this->table . ' SET';
366
            foreach ($cleanvars as $key => $value) {
367
                if ((!is_array($this->keyName) && $key == $this->keyName)
368
                    || (is_array($this->keyName)
369
                        && in_array($key, $this->keyName))
370
                ) {
371
                    continue;
372
                }
373
                if (isset($notfirst)) {
374
                    $sql .= ',';
375
                }
376
                $sql .= ' ' . $key . ' = ' . $value;
377
                $notfirst = true;
378
            }
379
            if (is_array($this->keyName)) {
380
                $whereclause = '';
381
                for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
382
                    if ($i > 0) {
383
                        $whereclause .= ' AND ';
384
                    }
385
                    $whereclause .= $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
386
                }
387
            } else {
388
                $whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
389
            }
390
            $sql .= ' WHERE ' . $whereclause;
391
        }
392
        $result = $force !== false ? $this->db->queryF($sql) : $this->db->query($sql);
393
        if (!$result) {
394
            return false;
395
        }
396
        if ($obj->isNew() && !is_array($this->keyName)) {
397
            $obj->assignVar($this->keyName, $this->db->getInsertId());
398
        }
399
400
        return true;
401
    }
402
403
    /**
404
     * Change a value for objects with a certain criteria
405
     *
406
     * @param string          $fieldname  Name of the field
407
     * @param string          $fieldvalue Value to write
408
     * @param CriteriaElement $criteria   {@link CriteriaElement}
0 ignored issues
show
Documentation introduced by
Should the type for parameter $criteria not be CriteriaElement|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
409
     *
410
     * @param  bool           $force
411
     * @return bool
412
     */
413
    public function updateAll($fieldname, $fieldvalue, $criteria = null, $force = false)
414
    {
415
        $set_clause = $fieldname . ' = ';
416
        if (is_numeric($fieldvalue)) {
417
            $set_clause .= $fieldvalue;
418
        } elseif (is_array($fieldvalue)) {
419
            $set_clause .= $this->db->quoteString(implode(',', $fieldvalue));
420
        } else {
421
            $set_clause .= $this->db->quoteString($fieldvalue);
422
        }
423
        $sql = 'UPDATE ' . $this->table . ' SET ' . $set_clause;
424 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...
425
            $sql .= ' ' . $criteria->renderWhere();
426
        }
427
        $result = false !== $force ? $this->db->queryF($sql) : $this->db->query($sql);
428
        if (!$result) {
429
            return false;
430
        }
431
432
        return true;
433
    }
434
435
    /**
436
     * @param      $fieldname
437
     * @param      $fieldvalue
438
     * @param null $criteria
439
     * @param bool $force
440
     *
441
     * @return bool
442
     */
443
    public function updateFieldValue($fieldname, $fieldvalue, $criteria = null, $force = true)
444
    {
445
        $sql = 'UPDATE ' . $this->table . ' SET ' . $fieldname . ' = ' . $fieldvalue;
446 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...
447
            $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...
448
        }
449
        $result = false !== $force ? $this->db->queryF($sql) : $this->db->query($sql);
450
        if (!$result) {
451
            return false;
452
        }
453
454
        return true;
455
    }
456
457
    /**
458
     * delete all objects meeting the conditions
459
     *
460
     * @param  CriteriaElement $criteria {@link CriteriaElement} with conditions to meet
461
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the type for parameter $criteria not be null|CriteriaElement?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
462
     */
463
464
    public function deleteAll(CriteriaElement $criteria = null)
465
    {
466
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
467
            $sql = 'DELETE FROM ' . $this->table;
468
            $sql .= ' ' . $criteria->renderWhere();
469
            if (!$this->db->query($sql)) {
470
                return false;
471
            }
472
            $rows = $this->db->getAffectedRows();
473
474
            return $rows > 0 ? $rows : true;
475
        }
476
477
        return false;
478
    }
479
480
    /**
481
     * @param $data
482
     *
483
     * @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...
484
     */
485
    public function _toObject($data)
486
    {
487
        if (is_array($data)) {
488
            $ret = array();
489
            foreach ($data as $v) {
490
                $object = new $this->className();
491
                $object->assignVars($v);
492
                $ret[] = $object;
493
            }
494
495
            return $ret;
496
        } else {
497
            $object = new $this->className();
498
            $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...
499
500
            return $object;
501
        }
502
    }
503
504
    /**
505
     * @param        $objects
506
     * @param array  $externalKeys
507
     * @param string $format
508
     *
509
     * @return array
510
     */
511
    public function objectToArray($objects, $externalKeys = array(), $format = 's')
512
    {
513
        static $cached;
514
515
        $ret = array();
516
        if (is_array($objects)) {
517
            $i = 0;
518
            foreach ($objects as $object) {
519
                $vars = $object->getVars();
520
                foreach ($vars as $k => $v) {
521
                    $ret[$i][$k] = $object->getVar($k, $format);
522
                }
523
                foreach ($externalKeys as $key) {
524
                    // Replace external key by corresponding object
525
                    $externalKey = $object->getExternalKey($key);
526
                    if ($ret[$i][$key] != 0) {
527
                        // Retriving data if isn't cached
528
                        if (!isset($cached[$externalKey['keyName']][$ret[$i][$key]])) {
529 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...
530
                                $handler = xoops_getHandler($externalKey['className']);
531
                            } else {
532
                                $handler = xoops_getModuleHandler($externalKey['className'], 'extgallery');
533
                            }
534
                            $cached[$externalKey['keyName']][$ret[$i][$key]] = $this->objectToArrayWithoutExternalKey($handler->{$externalKey['getMethodeName']}($ret[$i][$key]), $format);
535
                        }
536
                        $ret[$i][$externalKey['keyName']] = $cached[$externalKey['keyName']][$ret[$i][$key]];
537
                    }
538
                    unset($ret[$i][$key]);
539
                }
540
                ++$i;
541
            }
542
        } else {
543
            $vars = $objects->getVars();
544
            foreach ($vars as $k => $v) {
545
                $ret[$k] = $objects->getVar($k, $format);
546
            }
547
            foreach ($externalKeys as $key) {
548
                // Replace external key by corresponding object
549
                $externalKey = $objects->getExternalKey($key);
550
                if ($ret[$key] != 0) {
551
                    // Retriving data if isn't cached
552
                    if (!isset($cached[$externalKey['keyName']][$ret[$key]])) {
553 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...
554
                            $handler = xoops_getHandler($externalKey['className']);
555
                        } else {
556
                            $handler = xoops_getModuleHandler($externalKey['className'], 'extgallery');
557
                        }
558
                        $cached[$externalKey['keyName']][$ret[$key]] = $this->objectToArrayWithoutExternalKey($handler->{$externalKey['getMethodeName']}($ret[$key]), $format);
559
                    }
560
                    $ret[$externalKey['keyName']] = $cached[$externalKey['keyName']][$ret[$key]];
561
                }
562
                unset($ret[$key]);
563
            }
564
        }
565
566
        return $ret;
567
    }
568
569
    /**
570
     * @param        $object
571
     * @param string $format
572
     *
573
     * @return array
574
     */
575
    public function objectToArrayWithoutExternalKey($object, $format = 's')
576
    {
577
        $ret = array();
578
        if (null !== $object) {
579
            $vars = $object->getVars();
580
            foreach ($vars as $k => $v) {
581
                $ret[$k] = $object->getVar($k, $format);
582
            }
583
        }
584
585
        return $ret;
586
    }
587
588
    /**
589
     * @param        $fieldname
590
     * @param        $criteria
591
     * @param string $op
592
     *
593
     * @return bool
594
     */
595
    public function updateCounter($fieldname, $criteria, $op = '+')
596
    {
597
        $sql = 'UPDATE ' . $this->table . ' SET ' . $fieldname . ' = ' . $fieldname . $op . '1';
598
        $sql .= ' ' . $criteria->renderWhere();
599
        $result = $this->db->queryF($sql);
600
        if (!$result) {
601
            return false;
602
        }
603
604
        return true;
605
    }
606
607
    /**
608
     * @param null|CriteriaElement $criteria
609
     * @param string $sum
610
     *
611
     * @return array|int|string
612
     */
613 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...
614
    {
615
        $field   = '';
616
        $groupby = false;
617
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
618
            if ($criteria->groupby != '') {
619
                $groupby = true;
620
                $field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
621
            }
622
        }
623
        $sql = 'SELECT ' . $field . "SUM($sum) FROM " . $this->table;
624
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
625
            $sql .= ' ' . $criteria->renderWhere();
626
            if ($criteria->groupby != '') {
627
                $sql .= $criteria->getGroupby();
628
            }
629
        }
630
        $result = $this->db->query($sql);
631
        if (!$result) {
632
            return 0;
633
        }
634
        if ($groupby == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
635
            list($sum) = $this->db->fetchRow($result);
636
637
            return $sum;
638
        } else {
639
            $ret = array();
640
            while (list($id, $sum) = $this->db->fetchRow($result)) {
641
                $ret[$id] = $sum;
642
            }
643
644
            return $ret;
645
        }
646
    }
647
648
    /**
649
     * @param null|CriteriaElement $criteria
650
     * @param string $max
651
     *
652
     * @return array|int|string
653
     */
654 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...
655
    {
656
        $field   = '';
657
        $groupby = false;
658
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
659
            if ($criteria->groupby != '') {
660
                $groupby = true;
661
                $field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
662
            }
663
        }
664
        $sql = 'SELECT ' . $field . "MAX($max) FROM " . $this->table;
665
        if (null !== $criteria && is_subclass_of($criteria, 'criteriaelement')) {
666
            $sql .= ' ' . $criteria->renderWhere();
667
            if ($criteria->groupby != '') {
668
                $sql .= $criteria->getGroupby();
669
            }
670
        }
671
        $result = $this->db->query($sql);
672
        if (!$result) {
673
            return 0;
674
        }
675
        if (false === $groupby) {
676
            list($max) = $this->db->fetchRow($result);
677
678
            return $max;
679
        } else {
680
            $ret = array();
681
            while (list($id, $max) = $this->db->fetchRow($result)) {
682
                $ret[$id] = $max;
683
            }
684
685
            return $ret;
686
        }
687
    }
688
689
    /**
690
     * @param null|CriteriaElement $criteria
691
     * @param string $avg
692
     *
693
     * @return int
694
     */
695
    public function getAvg(CriteriaElement $criteria = null, $avg = '*')
696
    {
697
        $field = '';
698
699
        $sql = 'SELECT ' . $field . "AVG($avg) FROM " . $this->table;
700 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...
701
            $sql .= ' ' . $criteria->renderWhere();
702
        }
703
        $result = $this->db->query($sql);
704
        if (!$result) {
705
            return 0;
706
        }
707
        list($sum) = $this->db->fetchRow($result);
708
709
        return $sum;
710
    }
711
712
    /**
713
     * @return mixed
714
     */
715
    public function getInsertId()
716
    {
717
        return $this->db->getInsertId();
718
    }
719
}
720