Passed
Push — master ( d2520f...3f8ec2 )
by Michael
02:50
created

ExtcalPersistableObjectHandler::getMax()   D

Complexity

Conditions 10
Paths 36

Size

Total Lines 32
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 22
nc 36
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace XoopsModules\Extcal;
2
3
/*
4
 * You may not change or alter any portion of this comment or credits
5
 * of supporting developers from this source code or any supporting source code
6
 * which is considered copyrighted (c) material of the original comment or credit authors.
7
 *
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
13
/**
14
 * @copyright    {@link https://xoops.org/ XOOPS Project}
15
 * @license      {@link http://www.gnu.org/licenses/gpl-2.0.html GNU GPL 2 or later}
16
 * @package      extcal
17
 * @since
18
 * @author       XOOPS Development Team,
19
 */
20
21
use XoopsModules\Extcal;
22
23
/**
24
 * Persistable Object Handler class.
25
 * This class is responsible for providing data access mechanisms to the data source
26
 * of derived class objects.
27
 *
28
 * @author    Jan Keller Pedersen <[email protected]> - IDG Danmark A/S <www.idg.dk>
29
 * @copyright copyright (c) 2000-2004 XOOPS.org
30
 */
31
class ExtcalPersistableObjectHandler extends \XoopsPersistableObjectHandler //XoopsObjectHandler
0 ignored issues
show
Bug introduced by
The type XoopsPersistableObjectHandler was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
32
{
33
    /**#@+
34
     * Information about the class, the handler is managing
35
     *
36
     * @var string
37
     */
38
    //    public $table;
39
    //    public $keyName;
40
    //    public $className;
41
    //    public $identifierName;
42
43
    /**#@-*/
44
45
    /**
46
     * Constructor - called from child classes.
47
     *
48
     * @param \XoopsDatabase $db        {@link XoopsDatabase}
49
     *                                  object
50
     * @param string         $tablename Name of database table
51
     * @param string         $classname Name of Class, this handler is managing
52
     * @param string         $keyname   Name of the property, holding the key
53
     * @param bool           $idenfierName
54
     */
55
    public function __construct(\XoopsDatabase $db, $tablename, $classname, $keyname, $idenfierName = false)
0 ignored issues
show
Bug introduced by
The type XoopsDatabase was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
56
    {
57
        parent::__construct($db);
58
        $this->table     = $db->prefix($tablename);
0 ignored issues
show
Bug Best Practice introduced by
The property table does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
59
        $this->keyName   = $keyname;
0 ignored issues
show
Bug Best Practice introduced by
The property keyName does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
60
        $this->className = $classname;
0 ignored issues
show
Bug Best Practice introduced by
The property className does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
61
        if (false !== $idenfierName) {
62
            $this->identifierName = $idenfierName;
0 ignored issues
show
Bug Best Practice introduced by
The property identifierName does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
63
        }
64
    }
65
66
    /**
67
     * Constructor.
68
     */
69
    //    public function ExtcalPersistableObjectHandler($db, $tablename, $classname, $keyname, $idenfierName = false)
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% 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...
70
    //    {
71
    //        $this->__construct($db, $tablename, $classname, $keyname, $idenfierName);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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
    //    }
73
74
    /**
75
     * create a new user.
76
     *
77
     * @param bool $isNew Flag the new objects as "new"?
78
     *
79
     * @return \XoopsObject
0 ignored issues
show
Bug introduced by
The type XoopsObject was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
80
     */
81
    public function create($isNew = true)
82
    {
83
        $obj = new $this->className();
84
        if (true === $isNew) {
85
            $obj->setNew();
86
        }
87
88
        return $obj;
89
    }
90
91
    /**
92
     * retrieve an object.
93
     *
94
     * @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
95
     * @param null  $fields
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $fields is correct as it would always require null to be passed?
Loading history...
96
     * @param bool  $as_object
97
     *
98
     * @return mixed reference to the object, FALSE if failed
99
     *
100
     * @internal param bool $asObject whether to return an object or an array
101
     */
102
    public function get($id = null, $fields = null, $as_object = true) //get($id, $as_object = true)
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
103
    {
104
        if (is_array($this->keyName)) {
0 ignored issues
show
introduced by
The condition is_array($this->keyName) is always false.
Loading history...
105
            $criteria = new \CriteriaCompo();
0 ignored issues
show
Bug introduced by
The type CriteriaCompo was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
106
            for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
107
                $criteria->add(new \Criteria($this->keyName[$i], (int)$id[$i]));
0 ignored issues
show
Bug introduced by
The type Criteria was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
108
            }
109
        } else {
110
            $criteria = new \Criteria($this->keyName, (int)$id);
111
        }
112
        $criteria->setLimit(1);
113
        $objectArray =& $this->getObjects($criteria, false, true);
114
        if (1 != count($objectArray)) {
115
            return $this->create();
116
        }
117
118
        return $objectArray[0];
119
    }
120
121
    /**
122
     * retrieve objects from the database.
123
     *
124
     * @param \CriteriaElement $criteria {@link CriteriaElement} conditions to be met
125
     * @param bool             $idAsKey  use the ID as key for the array?
126
     * @param bool             $asObject return an array of objects?
127
     *
128
     * @return array
129
     */
130
    public function &getObjects(\CriteriaElement $criteria = null, $idAsKey = false, $asObject = true)
0 ignored issues
show
Bug introduced by
The type CriteriaElement was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
131
    {
132
        $ret   = [];
133
        $limit = $start = 0;
134
        $sql   = 'SELECT * FROM ' . $this->table;
135
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
136
            $sql .= ' ' . $criteria->renderWhere();
137
            if ('' != $criteria->getSort()) {
138
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
139
            }
140
            $limit = $criteria->getLimit();
141
            $start = $criteria->getStart();
142
        }
143
        $result = $this->db->query($sql, $limit, $start);
144
        if (!$result) {
145
            return $ret;
146
        }
147
148
        $ret = $this->convertResultSet($result, $idAsKey, $asObject);
149
150
        return $ret;
151
    }
152
153
    /**
154
     * Convert a database resultset to a returnable array.
155
     *
156
     * @param \XoopsObject $result  database resultset
157
     * @param bool        $idAsKey - should NOT be used with joint keys
158
     * @param bool        $asObject
159
     *
160
     * @return array
161
     */
162
    public function convertResultSet($result, $idAsKey = false, $asObject = true)
163
    {
164
        $ret = [];
165
       while (false !== ($myrow = $this->db->fetchArray($result))) {
166
            $obj = $this->create(false);
167
            $obj->assignVars($myrow);
168
            if (!$idAsKey) {
169
                if ($asObject) {
170
                    $ret[] = $obj;
171
                } else {
172
                    $row  = [];
173
                    $vars =& $obj->getVars();
174
                    foreach (array_keys($vars) as $i) {
175
                        $row[$i] = $obj->getVar($i);
176
                    }
177
                    $ret[] = $row;
178
                }
179
            } else {
180
                if ($asObject) {
181
                    $ret[$myrow[$this->keyName]] = $obj;
182
                } else {
183
                    $row  = [];
184
                    $vars =& $obj->getVars();
185
                    foreach (array_keys($vars) as $i) {
186
                        $row[$i] = $obj->getVar($i);
187
                    }
188
                    $ret[$myrow[$this->keyName]] = $row;
189
                }
190
            }
191
            unset($obj);
192
        }
193
194
        return $ret;
195
    }
196
197
    /**
198
     * Retrieve a list of objects as arrays - DON'T USE WITH JOINT KEYS.
199
     *
200
     * @param \CriteriaElement $criteria {@link CriteriaElement} conditions to be met
201
     * @param int              $limit    Max number of objects to fetch
202
     * @param int              $start    Which record to start at
203
     *
204
     * @return array
205
     */
206
    public function getList(\CriteriaElement $criteria = null, $limit = 0, $start = 0)
207
    {
208
        $ret = [];
209
        if (null === $criteria) {
210
            $criteria = new \CriteriaCompo();
211
        }
212
213
        if ('' == $criteria->getSort()) {
214
            $criteria->setSort($this->identifierName);
215
        }
216
217
        $sql = 'SELECT ' . $this->keyName;
218
        if (!empty($this->identifierName)) {
219
            $sql .= ', ' . $this->identifierName;
220
        }
221
        $sql .= ' FROM ' . $this->table;
222
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
223
            $sql .= ' ' . $criteria->renderWhere();
224
            if ('' != $criteria->getSort()) {
225
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
226
            }
227
            $limit = $criteria->getLimit();
228
            $start = $criteria->getStart();
229
        }
230
        $result = $this->db->query($sql, $limit, $start);
231
        if (!$result) {
232
            return $ret;
233
        }
234
235
        $myts = \MyTextSanitizer::getInstance();
0 ignored issues
show
Bug introduced by
The type MyTextSanitizer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
236
       while (false !== ($myrow = $this->db->fetchArray($result))) {
237
            //identifiers should be textboxes, so sanitize them like that
238
            $ret[$myrow[$this->keyName]] = empty($this->identifierName) ? 1 : $myts->htmlSpecialChars($myrow[$this->identifierName]);
239
        }
240
241
        return $ret;
242
    }
243
244
    /**
245
     * count objects matching a condition.
246
     *
247
     * @param \CriteriaElement $criteria {@link CriteriaElement} to match
248
     *
249
     * @return int|array count of objects
250
     */
251
    public function getCount(\CriteriaElement $criteria = null)
252
    {
253
        $field   = '';
254
        $groupby = false;
255
        if (isset($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 (isset($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 = [];
278
            while (false !== (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 by id.
288
     *
289
     * @param mixed $id id of the object to delete
290
     * @param bool  $force
291
     *
292
     * @return bool FALSE if failed.
293
     */
294
    public function deleteById($id, $force = false) //delete(\XoopsObject $object, $force = false)
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% 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...
295
    {
296
        if (is_array($this->keyName)) {
0 ignored issues
show
introduced by
The condition is_array($this->keyName) is always false.
Loading history...
297
            $clause = [];
298
            for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
299
                $clause[] = $this->keyName[$i] . ' = ' . $id[$i];
300
            }
301
            $whereclause = implode(' AND ', $clause);
302
        } else {
303
            $whereclause = $this->keyName . ' = ' . $id;
304
        }
305
        $sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $whereclause;
306
        if (false !== $force) {
307
            $result = $this->db->queryF($sql);
308
        } else {
309
            $result = $this->db->query($sql);
310
        }
311
        if (!$result) {
312
            return false;
313
        }
314
315
        return true;
316
    }
317
318
    /**
319
     * insert a new object in the database.
320
     *
321
     * @param \XoopsObject $obj         reference to the object
322
     * @param bool         $force       whether to force the query execution despite security settings
323
     * @param bool         $checkObject check if the object is dirty and clean the attributes
324
     *
325
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
326
     */
327
    public function insert(\XoopsObject $obj, $force = false, $checkObject = true)
328
    {
329
        if (false !== $checkObject) {
330
            if (!is_object($obj)) {
331
                //                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...
332
                return false;
333
            }
334
335
            if (!($obj instanceof $this->className && class_exists($this->className))) {
336
                $obj->setErrors(get_class($obj) . ' Differs from ' . $this->className);
337
338
                return false;
339
            }
340
        }
341
        if (!$obj->cleanVars()) {
342
            return false;
343
        }
344
345
        foreach ($obj->cleanVars as $k => $v) {
346
            if (XOBJ_DTYPE_INT == $obj->vars[$k]['data_type']) {
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Extcal\XOBJ_DTYPE_INT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
347
                $cleanvars[$k] = (int)$v;
348
            } elseif (is_array($v)) {
349
                $cleanvars[$k] = $this->db->quoteString(implode(',', $v));
350
            } else {
351
                $cleanvars[$k] = $this->db->quoteString($v);
352
            }
353
        }
354
        if ($obj->isNew()) {
355
            if (!is_array($this->keyName)) {
0 ignored issues
show
introduced by
The condition is_array($this->keyName) is always false.
Loading history...
356
                if ($cleanvars[$this->keyName] < 1) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $cleanvars seems to be defined by a foreach iteration on line 345. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
357
                    $cleanvars[$this->keyName] = $this->db->genId($this->table . '_' . $this->keyName . '_seq');
358
                }
359
            }
360
            $sql = 'INSERT INTO ' . $this->table . ' (' . implode(',', array_keys($cleanvars)) . ') VALUES (' . implode(',', array_values($cleanvars)) . ')';
361
        } else {
362
            $sql = 'UPDATE ' . $this->table . ' SET';
363
            foreach ($cleanvars as $key => $value) {
364
                if ((!is_array($this->keyName) && $key == $this->keyName)
365
                    || (is_array($this->keyName)
366
                        && in_array($key, $this->keyName))) {
367
                    continue;
368
                }
369
                if (isset($notfirst)) {
370
                    $sql .= ',';
371
                }
372
                $sql      .= ' ' . $key . ' = ' . $value;
373
                $notfirst = true;
374
            }
375
            if (is_array($this->keyName)) {
0 ignored issues
show
introduced by
The condition is_array($this->keyName) is always false.
Loading history...
376
                $whereclause = '';
377
                for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
378
                    if ($i > 0) {
379
                        $whereclause .= ' AND ';
380
                    }
381
                    $whereclause .= $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
382
                }
383
            } else {
384
                $whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
385
            }
386
            $sql .= ' WHERE ' . $whereclause;
387
        }
388
        if (false !== $force) {
389
            $result = $this->db->queryF($sql);
390
        } else {
391
            $result = $this->db->query($sql);
392
        }
393
        if (!$result) {
394
            return false;
395
        }
396
        if (!is_array($this->keyName) && $obj->isNew()) {
0 ignored issues
show
introduced by
The condition is_array($this->keyName) is always false.
Loading history...
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|array     $fieldvalue Value to write
408
     * @param \CriteriaElement $criteria   {@link CriteriaElement}
409
     * @param bool             $force
410
     *
411
     * @return bool
412
     */
413
    public function updateAll($fieldname, $fieldvalue, \CriteriaElement $criteria = null, $force = false)
414
    {
415
        $setClause = $fieldname . ' = ';
416
        if (is_numeric($fieldvalue)) {
417
            $setClause .= $fieldvalue;
418
        } elseif (is_array($fieldvalue)) {
0 ignored issues
show
introduced by
The condition is_array($fieldvalue) is always true.
Loading history...
419
            $setClause .= $this->db->quoteString(implode(',', $fieldvalue));
420
        } else {
421
            $setClause .= $this->db->quoteString($fieldvalue);
422
        }
423
        $sql = 'UPDATE ' . $this->table . ' SET ' . $setClause;
424
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
425
            $sql .= ' ' . $criteria->renderWhere();
426
        }
427
        if (false !== $force) {
428
            $result = $this->db->queryF($sql);
429
        } else {
430
            $result = $this->db->query($sql);
431
        }
432
        if (!$result) {
433
            return false;
434
        }
435
436
        return true;
437
    }
438
439
    /**
440
     * @param      $fieldname
441
     * @param      $fieldvalue
442
     * @param null $criteria
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $criteria is correct as it would always require null to be passed?
Loading history...
443
     * @param bool $force
444
     *
445
     * @return bool
446
     */
447
    public function updateFieldValue($fieldname, $fieldvalue, $criteria = null, $force = true)
448
    {
449
        $sql = 'UPDATE ' . $this->table . ' SET ' . $fieldname . ' = ' . $fieldvalue;
450
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
451
            $sql .= ' ' . $criteria->renderWhere();
452
        }
453
        if (false !== $force) {
454
            $result = $this->db->queryF($sql);
455
        } else {
456
            $result = $this->db->query($sql);
457
        }
458
        if (!$result) {
459
            return false;
460
        }
461
462
        return true;
463
    }
464
465
    /**
466
     * delete all objects meeting the conditions.
467
     *
468
     * @param \CriteriaElement $criteria       {@link CriteriaElement}
469
     *                                         with conditions to meet
470
     * @param bool             $force
471
     * @param bool             $asObject
472
     *
473
     * @return bool
474
     */
475
    public function deleteAll(\CriteriaElement $criteria = null, $force = true, $asObject = false)
476
    {
477
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
478
            $sql = 'DELETE FROM ' . $this->table;
479
            $sql .= ' ' . $criteria->renderWhere();
480
            if (!$this->db->query($sql)) {
481
                return false;
482
            }
483
            $rows = $this->db->getAffectedRows();
484
485
            return $rows > 0 ? $rows : true;
486
        }
487
488
        return false;
489
    }
490
491
    /**
492
     * @param $data
493
     *
494
     * @return array
495
     */
496
    public function _toObject($data)
497
    {
498
        if (is_array($data)) {
499
            $ret = [];
500
            foreach ($data as $v) {
501
                $object = new $this->className();
502
                $object->assignVars($v);
503
                $ret[] = $object;
504
            }
505
506
            return $ret;
507
        } else {
508
            $object = new $this->className();
509
            $object->assignVars($v);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $v seems to be never defined.
Loading history...
510
511
            return $object;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $object returns the type object which is incompatible with the documented return type array.
Loading history...
512
        }
513
    }
514
515
    /**
516
     * @param        $objects
517
     * @param array  $externalKeys
518
     * @param string $format
519
     *
520
     * @return array
521
     */
522
    public function objectToArray($objects, $externalKeys = [], $format = 's')
523
    {
524
        static $cache;
525
        if (!is_array($externalKeys)) {
0 ignored issues
show
introduced by
The condition is_array($externalKeys) is always true.
Loading history...
526
            $externalKeys = [$externalKeys];
527
        } //JJD
528
529
        $ret = [];
530
        if (is_array($objects)) {
531
            $i = 0;
532
            foreach ($objects as $object) {
533
                $vars = $object->getVars();
534
                foreach ($vars as $k => $v) {
535
                    $ret[$i][$k] = $object->getVar($k, $format);
536
                }
537
                foreach ($externalKeys as $key) {
538
                    // Replace external key by corresponding object
539
                    $externalKey = $object->getExternalKey($key);
540
                    if (0 != $ret[$i][$key]) {
541
                        // Retrieving data if isn't cached
542
                        if (!isset($cached[$externalKey['keyName']][$ret[$i][$key]])) {
543
                            if ($externalKey['core']) {
544
                                $handler = xoops_getHandler($externalKey['className']);
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

544
                                $handler = /** @scrutinizer ignore-call */ xoops_getHandler($externalKey['className']);
Loading history...
545
                            } else {
546
                                $handler = Extcal\Helper::getInstance()->getHandler($externalKey['className']);
547
                            }
548
                            $getMethod                                       = $externalKey['getMethodeName'];
549
                            $cached[$externalKey['keyName']][$ret[$i][$key]] = $this->objectToArrayWithoutExternalKey($handler->$getMethod($ret[$i][$key], true), $format);
550
                        }
551
                        $ret[$i][$externalKey['keyName']] = $cached[$externalKey['keyName']][$ret[$i][$key]];
552
                    }
553
                    unset($ret[$i][$key]);
554
                }
555
                ++$i;
556
            }
557
        } else {
558
            $vars = $objects->getVars();
559
            foreach ($vars as $k => $v) {
560
                $ret[$k] = $objects->getVar($k, $format);
561
            }
562
            foreach ($externalKeys as $key) {
563
                // Replace external key by corresponding object
564
                $externalKey = $objects->getExternalKey($key);
565
                if (0 != $ret[$key]) {
566
                    // Retriving data if isn't cached
567
                    if (!isset($cached[$externalKey['keyName']][$ret[$key]])) {
568
                        if ($externalKey['core']) {
569
                            $handler = xoops_getHandler($externalKey['className']);
570
                        } else {
571
                            $handler = Extcal\Helper::getInstance()->getHandler($externalKey['className']);
572
                        }
573
                        $getMethod                                   = $externalKey['getMethodeName'];
574
                        $cached[$externalKey['keyName']][$ret[$key]] = $this->objectToArrayWithoutExternalKey($handler->$getMethod($ret[$key], true), $format);
575
                    }
576
                    $ret[$externalKey['keyName']] = $cached[$externalKey['keyName']][$ret[$key]];
577
                }
578
                unset($ret[$key]);
579
            }
580
        }
581
582
        return $ret;
583
    }
584
585
    /**
586
     * @param        $object
587
     * @param string $format
588
     *
589
     * @return array
590
     */
591
    public function objectToArrayWithoutExternalKey($object, $format = 's')
592
    {
593
        $ret = [];
594
        if (null !== $object) {
595
            $vars = $object->getVars();
596
            foreach ($vars as $k => $v) {
597
                $ret[$k] = $object->getVar($k, $format);
598
            }
599
        }
600
601
        return $ret;
602
    }
603
604
    /**
605
     * @param        $fieldname
606
     * @param        $criteria
607
     * @param string $op
608
     *
609
     * @return bool
610
     */
611
    public function updateCounter($fieldname, $criteria, $op = '+')
612
    {
613
        $sql    = 'UPDATE ' . $this->table . ' SET ' . $fieldname . ' = ' . $fieldname . $op . '1';
614
        $sql    .= ' ' . $criteria->renderWhere();
615
        $result = $this->db->queryF($sql);
616
        if (!$result) {
617
            return false;
618
        }
619
620
        return true;
621
    }
622
623
    /**
624
     * @param \CriteriaElement $criteria
625
     * @param string           $sum
626
     *
627
     * @return array|string
628
     */
629
    public function getSum(\CriteriaElement $criteria = null, $sum = '*')
630
    {
631
        $field   = '';
632
        $groupby = false;
633
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
634
            if ('' != $criteria->groupby) {
635
                $groupby = true;
636
                $field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
637
            }
638
        }
639
        $sql = 'SELECT ' . $field . "SUM($sum) FROM " . $this->table;
640
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
641
            $sql .= ' ' . $criteria->renderWhere();
642
            if ('' != $criteria->groupby) {
643
                $sql .= $criteria->getGroupby();
644
            }
645
        }
646
        $result = $this->db->query($sql);
647
        if (!$result) {
648
            return 0;
649
        }
650
        if (false === $groupby) {
651
            list($sum) = $this->db->fetchRow($result);
652
653
            return $sum;
654
        } else {
655
            $ret = [];
656
            while (false !== (list($id, $sum) = $this->db->fetchRow($result))) {
657
                $ret[$id] = $sum;
658
            }
659
660
            return $ret;
661
        }
662
    }
663
664
    /**
665
     * @param \CriteriaElement $criteria
666
     * @param string           $max
667
     *
668
     * @return array|string
669
     */
670
    public function getMax(\CriteriaElement $criteria = null, $max = '*')
671
    {
672
        $field   = '';
673
        $groupby = false;
674
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
675
            if ('' != $criteria->groupby) {
676
                $groupby = true;
677
                $field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
678
            }
679
        }
680
        $sql = 'SELECT ' . $field . "MAX($max) FROM " . $this->table;
681
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
682
            $sql .= ' ' . $criteria->renderWhere();
683
            if ('' != $criteria->groupby) {
684
                $sql .= $criteria->getGroupby();
685
            }
686
        }
687
        $result = $this->db->query($sql);
688
        if (!$result) {
689
            return 0;
690
        }
691
        if (false === $groupby) {
692
            list($max) = $this->db->fetchRow($result);
693
694
            return $max;
695
        } else {
696
            $ret = [];
697
            while (false !== (list($id, $max) = $this->db->fetchRow($result))) {
698
                $ret[$id] = $max;
699
            }
700
701
            return $ret;
702
        }
703
    }
704
705
    /**
706
     * @param null   $criteria
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $criteria is correct as it would always require null to be passed?
Loading history...
707
     * @param string $avg
708
     *
709
     * @return int
710
     */
711
    public function getAvg($criteria = null, $avg = '*')
712
    {
713
        $field = '';
714
715
        $sql = 'SELECT ' . $field . "AVG($avg) FROM " . $this->table;
716
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
717
            $sql .= ' ' . $criteria->renderWhere();
718
        }
719
        $result = $this->db->query($sql);
720
        if (!$result) {
721
            return 0;
722
        }
723
        list($sum) = $this->db->fetchRow($result);
724
725
        return $sum;
726
    }
727
728
    /**
729
     * @return mixed
730
     */
731
    public function getInsertId()
732
    {
733
        return $this->db->getInsertId();
734
    }
735
}
736