Passed
Push — master ( e643a0...1f75e2 )
by Michael
03:19
created

Oledrion_XoopsPersistableObjectHandler::getCount()   B

Complexity

Conditions 10
Paths 36

Size

Total Lines 47
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 47
rs 7.6666
c 0
b 0
f 0
cc 10
nc 36
nop 1

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
2
/*
3
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
*/
11
12
/**
13
 * oledrion
14
 *
15
 * @copyright   {@link https://xoops.org/ XOOPS Project}
16
 * @license     {@link http://www.fsf.org/copyleft/gpl.html GNU public license}
17
 * @author      Hervé Thouzard (http://www.herve-thouzard.com/)
18
 */
19
// defined('XOOPS_ROOT_PATH') || die('Restricted access');
20
21
class OledrionObject extends \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...
22
{
23
    /**
24
     * @param  string $format
25
     * @return array
26
     */
27
    public function toArray($format = 's')
28
    {
29
        $ret = [];
30
        foreach ($this->vars as $k => $v) {
0 ignored issues
show
Bug Best Practice introduced by
The property vars does not exist on OledrionObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
31
            $ret[$k] = $this->getVar($k, $format);
32
        }
33
34
        return $ret;
35
    }
36
37
    // TODO: Rajouter une méthode intsert() et delete()
38
39
    /**
40
     * Permet de valoriser un champ de la table comme si c'était une propriété de la classe
41
     *
42
     * @example $enregistrement->nom_du_champ = 'ma chaine'
43
     *
44
     * @param  string $key   Le nom du champ à traiter
45
     * @param  mixed  $value La valeur à lui attribuer
46
     */
47
    public function __set($key, $value)
48
    {
49
        return $this->setVar($key, $value);
50
    }
51
52
    /**
53
     * Permet d'accéder aux champs de la table comme à des propriétés de la classe
54
     *
55
     * @example echo $enregistrement->nom_du_champ;
56
     *
57
     * @param  string $key Le nom du champ que l'on souhaite récupérer
58
     * @return mixed
59
     */
60
    public function __get($key)
61
    {
62
        return $this->getVar($key);
63
    }
64
}
65
66
/**
67
 * Persistable Object Handler class.
68
 * This class is responsible for providing data access mechanisms to the data source
69
 * of derived class objects. Original Author : Mithrandir
70
 */
71
class Oledrion_XoopsPersistableObjectHandler extends \XoopsObjectHandler
0 ignored issues
show
Bug introduced by
The type XoopsObjectHandler 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...
72
{
73
    /**#@+
74
     * Information about the class, the handler is managing
75
     *
76
     * @var string
77
     */
78
    public    $table;
79
    protected $keyName;
80
    protected $className;
81
    protected $identifierName;
82
    protected $cacheOptions = [];
83
84
    /**#@-*/
85
86
    /**
87
     * Constructor - called from child classes
88
     * @param null|\XoopsDatabase $db            {@link XoopsDatabase}
89
     *                                           object
90
     * @param string              $tablename     Name of database table
91
     * @param string              $classname     Name of Class, this handler is managing
92
     * @param string              $keyname       Name of the property, holding the key
93
     * @param string              $idenfierName  Name of the property, holding the label
94
     * @param array               $cacheOptions  Optional, options for the cache
95
     */
96
    public function __construct(\XoopsDatabase $db, $tablename, $classname, $keyname, $idenfierName = '', $cacheOptions = null)
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...
97
    {
98
        //require_once  dirname(__DIR__) . '/include/common.php';
99
        require_once XOOPS_ROOT_PATH . '/modules/oledrion/include/common.php';
0 ignored issues
show
Bug introduced by
The constant XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
100
        //        $this->XoopsObjectHandler($db);
101
        parent::__construct($db);
102
        $this->table     = $db->prefix($tablename);
103
        $this->keyName   = $keyname;
104
        $this->className = $classname;
105
        if ('' !== trim($idenfierName)) {
106
            $this->identifierName = $idenfierName;
107
        }
108
        // To diable cache, add this line after the first one : 'caching' => false,
109
        if (null === $cacheOptions) {
110
            $this->setCachingOptions([
111
                                         'cacheDir'               => OLEDRION_CACHE_PATH,
112
                                         'lifeTime'               => null,
113
                                         'automaticSerialization' => true,
114
                                         'fileNameProtection'     => false,
115
                                     ]);
116
        } else {
117
            $this->setCachingOptions($cacheOptions);
118
        }
119
    }
120
121
    /**
122
     * @param $cacheOptions
123
     */
124
    public function setCachingOptions($cacheOptions)
125
    {
126
        $this->cacheOptions = $cacheOptions;
127
    }
128
129
    /**
130
     * Generates a unique ID for a Sql Query
131
     *
132
     * @param  string $query The SQL query for which we want a unidque ID
133
     * @param int     $start Which record to start at
134
     * @param int     $limit Max number of objects to fetch
135
     * @return string  An MD5 of the query
136
     */
137
    protected function _getIdForCache($query, $start, $limit)
138
    {
139
        $id = md5($query . '-' . (string)$start . '-' . (string)$limit);
140
141
        return $id;
142
    }
143
144
    /**
145
     * create a new object
146
     *
147
     * @param bool $isNew Flag the new objects as "new"?
148
     *
149
     * @return Oledrion_XoopsPersistableObjectHandler
150
     */
151
    public function create($isNew = true)
152
    {
153
        $obj = new $this->className();
154
        if (true === $isNew) {
155
            $obj->setNew();
156
        }
157
158
        return $obj;
159
    }
160
161
    /**
162
     * retrieve an object
163
     *
164
     * @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
165
     * @param  bool  $as_object whether to return an object or an array
166
     * @return mixed reference to the object, FALSE if failed
167
     */
168
    public function get($id, $as_object = true)
169
    {
170
        if (is_array($this->keyName)) {
0 ignored issues
show
introduced by
The condition is_array($this->keyName) is always false.
Loading history...
171
            $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...
172
            $vnb      = count($this->keyName);
173
            for ($i = 0; $i < $vnb; ++$i) {
174
                $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...
175
            }
176
        } else {
177
            $criteria = new \Criteria($this->keyName, (int)$id);
178
        }
179
        $criteria->setLimit(1);
180
        $obj_array = $this->getObjects($criteria, false, $as_object);
181
        if (1 != count($obj_array)) {
182
            $ret = null;
183
        } else {
184
            $ret = $obj_array[0];
185
        }
186
187
        return $ret;
188
    }
189
190
    /**
191
     * retrieve objects from the database
192
     *
193
     * @param \CriteriaElement|\CriteriaCompo $criteria  conditions to be met
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...
194
     * @param bool             $id_as_key use the ID as key for the array?
195
     * @param bool             $as_object return an array of objects?
196
     *
197
     * @param  string          $fields
198
     * @param  bool            $autoSort
199
     * @return array
200
     */
201
    public function getObjects(
202
        $criteria = null,
203
        $id_as_key = false,
204
        $as_object = true,
205
        $fields = '*',
206
        $autoSort = true)
207
    {
208
        //require_once __DIR__ . '/lite.php';
209
        $ret   = [];
210
        $limit = $start = 0;
211
        $sql   = 'SELECT ' . $fields . ' FROM ' . $this->table;
212
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
213
            $sql .= ' ' . $criteria->renderWhere();
214
            if ('' != $criteria->groupby) {
215
                $sql .= $criteria->getGroupby();
216
            }
217
            if ('' != $criteria->getSort()) {
218
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
219
            } elseif ('' !== $this->identifierName && $autoSort) {
220
                $sql .= ' ORDER BY ' . $this->identifierName;
221
            }
222
            $limit = $criteria->getLimit();
223
            $start = $criteria->getStart();
224
        }
225
        //$Cache_Lite = new oledrion_Cache_Lite($this->cacheOptions);
226
        $id = $this->_getIdForCache($sql, $start, $limit);
0 ignored issues
show
Unused Code introduced by
The assignment to $id is dead and can be removed.
Loading history...
227
        //$cacheData = $Cache_Lite->get($id);
228
        //if ($cacheData === false) {
229
        $result = $this->db->query($sql, $limit, $start);
230
        if (!$result) {
231
            return $ret;
232
        }
233
        $ret = $this->convertResultSet($result, $id_as_key, $as_object, $fields);
234
235
        //$Cache_Lite->save($ret);
236
        return $ret;
237
        //} else {
238
        //return $cacheData;
239
        //}
240
    }
241
242
    /**
243
     * Convert a database resultset to a returnable array
244
     *
245
     * @param mysqli_result $result    database resultset
246
     * @param bool          $id_as_key - should NOT be used with joint keys
247
     * @param bool          $as_object
248
     * @param string        $fields    Requested fields from the query
249
     *
250
     * @return array
251
     */
252
    protected function convertResultSet($result, $id_as_key = false, $as_object = true, $fields = '*')
253
    {
254
        $ret = [];
255
        while (false !== ($myrow = $this->db->fetchArray($result))) {
256
            $obj = $this->create(false);
257
            $obj->assignVars($myrow);
258
            if (!$id_as_key) {
259
                if ($as_object) {
260
                    $ret[] = $obj;
261
                } else {
262
                    $row     = [];
263
                    $vars    = $obj->getVars();
264
                    $tbl_tmp = array_keys($vars);
265
                    foreach ($tbl_tmp as $i) {
266
                        $row[$i] = $obj->getVar($i);
267
                    }
268
                    $ret[] = $row;
269
                }
270
            } else {
271
                if ($as_object) {
272
                    if ('*' === $fields) {
273
                        $ret[$myrow[$this->keyName]] = $obj;
274
                    } else {
275
                        $ret[] = $obj;
276
                    }
277
                } else {
278
                    $row     = [];
279
                    $vars    = $obj->getVars();
280
                    $tbl_tmp = array_keys($vars);
281
                    foreach ($tbl_tmp as $i) {
282
                        $row[$i] = $obj->getVar($i);
283
                    }
284
                    $ret[$myrow[$this->keyName]] = $row;
285
                }
286
            }
287
            unset($obj);
288
        }
289
290
        return $ret;
291
    }
292
293
    /**
294
     * get IDs of objects matching a condition
295
     *
296
     * @param  \CriteriaElement|\CriteriaCompo $criteria to match
297
     * @return array  of object IDs
298
     */
299
    public function getIds($criteria = null)
300
    {
301
        //require_once __DIR__ . '/lite.php';
302
        $limit = $start = 0;
303
304
        //$Cache_Lite = new oledrion_Cache_Lite($this->cacheOptions);
305
        $sql = 'SELECT ' . $this->keyName . ' FROM ' . $this->table;
306
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
307
            $sql .= ' ' . $criteria->renderWhere();
308
            if ('' !== $criteria->groupby) {
309
                $sql .= $criteria->getGroupby();
310
            }
311
            if ('' !== $criteria->getSort()) {
312
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
313
            } elseif ('' !== $this->identifierName) {
314
                $sql .= ' ORDER BY ' . $this->identifierName;
315
            }
316
            $limit = $criteria->getLimit();
317
            $start = $criteria->getStart();
318
        }
319
320
        $id = $this->_getIdForCache($sql, $start, $limit);
0 ignored issues
show
Unused Code introduced by
The assignment to $id is dead and can be removed.
Loading history...
321
        //$cacheData = $Cache_Lite->get($id);
322
        //if ($cacheData === false) {
323
        $result = $this->db->query($sql, $limit, $start);
324
        $ret    = [];
325
        while (false !== ($myrow = $this->db->fetchArray($result))) {
326
            $ret[] = $myrow[$this->keyName];
327
        }
328
329
        //$Cache_Lite->save($ret);
330
        return $ret;
331
        //} else {
332
        //  return $cacheData;
333
        //}
334
    }
335
336
    /**
337
     * Retrieve a list of objects as arrays - DON'T USE WITH JOINT KEYS
338
     *
339
     * @param  \CriteriaElement|\CriteriaCompo $criteria conditions to be met
340
     * @return array
341
     */
342
    public function getList($criteria = null)
343
    {
344
        //require_once __DIR__ . '/lite.php';
345
        $limit = $start = 0;
346
        //$Cache_Lite = new oledrion_Cache_Lite($this->cacheOptions);
347
348
        $ret = [];
349
350
        $sql = 'SELECT ' . $this->keyName;
351
        if (!empty($this->identifierName)) {
352
            $sql .= ', ' . $this->identifierName;
353
        }
354
        $sql .= ' FROM ' . $this->table;
355
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
356
            $sql .= ' ' . $criteria->renderWhere();
357
            if ('' !== $criteria->groupby) {
358
                $sql .= $criteria->getGroupby();
359
            }
360
            if ('' !== $criteria->getSort()) {
361
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
362
            } elseif ('' !== $this->identifierName) {
363
                $sql .= ' ORDER BY ' . $this->identifierName;
364
            }
365
            $limit = $criteria->getLimit();
366
            $start = $criteria->getStart();
367
        }
368
369
        $id = $this->_getIdForCache($sql, $start, $limit);
0 ignored issues
show
Unused Code introduced by
The assignment to $id is dead and can be removed.
Loading history...
370
        // $cacheData = $Cache_Lite->get($id);
371
        //if ($cacheData === false) {
372
        $result = $this->db->query($sql, $limit, $start);
373
        if (!$result) {
374
            //$Cache_Lite->save($ret);
375
            return $ret;
376
        }
377
378
        $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...
379
        while (false !== ($myrow = $this->db->fetchArray($result))) {
380
            // identifiers should be textboxes, so sanitize them like that
381
            $ret[$myrow[$this->keyName]] = empty($this->identifierName) ? 1 : $myts->htmlSpecialChars($myrow[$this->identifierName]);
382
        }
383
384
        //$Cache_Lite->save($ret);
385
        return $ret;
386
        //} else {
387
        //return $cacheData;
388
        // }
389
    }
390
391
    /**
392
     * Retourne des éléments selon leur ID
393
     *
394
     * @param  array $ids Les ID des éléments à retrouver
395
     * @return array Tableau d'objets (clé = id key name)
396
     */
397
    public function getItemsFromIds($ids)
398
    {
399
        $ret = [];
400
        if (is_array($ids) && count($ids) > 0) {
401
            $criteria = new \Criteria($this->keyName, '(' . implode(',', $ids) . ')', 'IN');
402
            $ret      = $this->getObjects($criteria, true);
403
        }
404
405
        return $ret;
406
    }
407
408
    /**
409
     * count objects matching a condition
410
     *
411
     * @param  \CriteriaElement|\CriteriaCompo $criteria to match
412
     * @return int    count of objects
413
     */
414
    public function getCount($criteria = null)
415
    {
416
        $field   = '';
417
        $groupby = false;
418
        $limit   = $start = 0;
419
        //require_once __DIR__ . '/lite.php';
420
421
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
422
            if ('' !== $criteria->groupby) {
423
                $groupby = true;
424
                $field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
425
            }
426
        }
427
        $sql = 'SELECT ' . $field . 'COUNT(*) FROM ' . $this->table;
428
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
429
            $sql .= ' ' . $criteria->renderWhere();
430
            if ('' !== $criteria->groupby) {
431
                $sql .= $criteria->getGroupby();
432
            }
433
            $limit = $criteria->getLimit();
434
            $start = $criteria->getStart();
435
        }
436
        //$Cache_Lite = new oledrion_Cache_Lite($this->cacheOptions);
437
        $id = $this->_getIdForCache($sql, $start, $limit);
0 ignored issues
show
Unused Code introduced by
The assignment to $id is dead and can be removed.
Loading history...
438
        //$cacheData = $Cache_Lite->get($id);
439
        //if ($cacheData === false) {
440
        $result = $this->db->query($sql, $limit, $start);
441
        if (!$result) {
442
            $ret = 0;
443
            $Cache_Lite->save($ret);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $Cache_Lite seems to be never defined.
Loading history...
444
445
            return $ret;
446
        }
447
        if (false === $groupby) {
448
            list($count) = $this->db->fetchRow($result);
449
450
            //$Cache_Lite->save($count);
451
            return $count;
452
        }
453
454
        $ret = [];
455
        while (false !== ([$id, $count] = $this->db->fetchRow($result))) {
456
            $ret[$id] = $count;
457
        }
458
459
        //  $Cache_Lite->save($ret);
460
        return $ret;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $ret returns the type array which is incompatible with the documented return type integer.
Loading history...
461
        //} else {
462
        //return $cacheData;
463
        //}
464
    }
465
466
    /**
467
     * Retourne le total d'un champ
468
     *
469
     * @param  string           $field    Le champ dont on veut calculer le total
470
     * @param  \CriteriaElement|\CriteriaCompo $criteria to match
471
     * @return int le total
472
     */
473
    public function getSum($field, $criteria = null)
474
    {
475
        $limit = $start = 0;
476
        //require_once __DIR__ . '/lite.php';
477
478
        $sql = 'SELECT Sum(' . $field . ') as cpt FROM ' . $this->table;
479
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
480
            $sql .= ' ' . $criteria->renderWhere();
481
            if ('' !== $criteria->groupby) {
482
                $sql .= $criteria->getGroupby();
483
            }
484
            $limit = $criteria->getLimit();
485
            $start = $criteria->getStart();
486
        }
487
        //$Cache_Lite = new oledrion_Cache_Lite($this->cacheOptions);
488
        $id = $this->_getIdForCache($sql, $start, $limit);
0 ignored issues
show
Unused Code introduced by
The assignment to $id is dead and can be removed.
Loading history...
489
        //$cacheData = $Cache_Lite->get($id);
490
        //if ($cacheData === false) {
491
        $result = $this->db->query($sql, $limit, $start);
492
        if (!$result) {
493
            $ret = 0;
494
495
            //$Cache_Lite->save($ret);
496
            return $ret;
497
        }
498
        $row   = $this->db->fetchArray($result);
499
        $count = $row['cpt'];
500
501
        //$Cache_Lite->save($count);
502
        return $count;
503
        //} else {
504
        //  return $cacheData;
505
        // }
506
    }
507
508
    /**
509
     * delete an object from the database
510
     *
511
     * @param  \XoopsObject $obj reference to the object to delete
512
     * @param  bool         $force
513
     * @return bool   FALSE if failed.
514
     */
515
    public function delete(\XoopsObject $obj, $force = false)
516
    {
517
        if (is_array($this->keyName)) {
0 ignored issues
show
introduced by
The condition is_array($this->keyName) is always false.
Loading history...
518
            $clause = [];
519
            $vnb    = count($this->keyName);
520
            for ($i = 0; $i < $vnb; ++$i) {
521
                $clause[] = $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
522
            }
523
            $whereclause = implode(' AND ', $clause);
524
        } else {
525
            $whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
526
        }
527
        $sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $whereclause;
528
        if (false !== $force) {
529
            $result = $this->db->queryF($sql);
530
        } else {
531
            $result = $this->db->query($sql);
532
        }
533
        // Clear cache
534
        $this->forceCacheClean();
535
536
        if (!$result) {
537
            return false;
538
        }
539
540
        return true;
541
    }
542
543
    /**
544
     * Quickly insert a record like this $myobjectHandler->quickInsert('field1' => field1value, 'field2' => $field2value)
545
     *
546
     * @param  array $vars  Array containing the fields name and value
547
     * @param  bool  $force whether to force the query execution despite security settings
548
     * @return bool  @link insert's value
549
     */
550
    public function quickInsert($vars = null, $force = true)
551
    {
552
        $object = $this->create(true);
553
        $object->setVars($vars);
554
        $retval = $this->insert($object, $force);
555
        unset($object);
556
557
        // Clear cache
558
        $this->forceCacheClean();
559
560
        return $retval;
561
    }
562
563
    /**
564
     * insert a new object in the database
565
     *
566
     * @param  \XoopsObject $obj         reference to the object
567
     * @param  bool         $force       whether to force the query execution despite security settings
568
     * @param  bool         $checkObject check if the object is dirty and clean the attributes
569
     * @return bool   FALSE if failed, TRUE if already present and unchanged or successful
570
     */
571
    public function insert(\XoopsObject $obj, $force = false, $checkObject = true)
572
    {
573
        if (false !== $checkObject) {
574
            if (!is_object($obj)) {
575
                trigger_error('Error, not object');
576
577
                return false;
578
            }
579
            /**
580
             * @TODO: Change to if (!(class_exists($this->className) && $obj instanceof $this->className)) when going fully PHP5
581
             */
582
            if (!is_a($obj, $this->className)) {
583
                $obj->setErrors(get_class($obj) . ' Differs from ' . $this->className);
584
585
                return false;
586
            }
587
            if (!$obj->isDirty()) {
588
                $obj->setErrors('Not dirty'); //will usually not be outputted as errors are not displayed when the method returns true, but it can be helpful when troubleshooting code - Mith
589
590
                return true;
591
            }
592
        }
593
        if (!$obj->cleanVars()) {
594
            foreach ($obj->getErrors() as $oneerror) {
595
                trigger_error($oneerror);
596
            }
597
598
            return false;
599
        }
600
        foreach ($obj->cleanVars as $k => $v) {
601
            if (XOBJ_DTYPE_INT == $obj->vars[$k]['data_type']) {
0 ignored issues
show
Bug introduced by
The constant XOBJ_DTYPE_INT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
602
                $cleanvars[$k] = (int)$v;
603
            } elseif (is_array($v)) {
604
                $cleanvars[$k] = $this->db->quoteString(implode(',', $v));
605
            } else {
606
                $cleanvars[$k] = $this->db->quoteString($v);
607
            }
608
        }
609
        if (isset($cleanvars['dohtml'])) {
610
            // Modification Hervé to be able to use dohtml
611
            unset($cleanvars['dohtml']);
612
        }
613
        if ($obj->isNew()) {
614
            if (!is_array($this->keyName)) {
0 ignored issues
show
introduced by
The condition is_array($this->keyName) is always false.
Loading history...
615
                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 600. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
616
                    $cleanvars[$this->keyName] = $this->db->genId($this->table . '_' . $this->keyName . '_seq');
617
                }
618
            }
619
            $sql = 'INSERT INTO ' . $this->table . ' (' . implode(',', array_keys($cleanvars)) . ') VALUES (' . implode(',', array_values($cleanvars)) . ')';
620
        } else {
621
            $sql = 'UPDATE ' . $this->table . ' SET';
622
            foreach ($cleanvars as $key => $value) {
623
                if ((!is_array($this->keyName) && $key == $this->keyName) || (is_array($this->keyName) && in_array($key, $this->keyName, true))) {
624
                    continue;
625
                }
626
                if (null !== $notfirst) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $notfirst does not seem to be defined for all execution paths leading up to this point.
Loading history...
627
                    $sql .= ',';
628
                }
629
                $sql      .= ' ' . $key . ' = ' . $value;
630
                $notfirst = true;
631
            }
632
            if (is_array($this->keyName)) {
0 ignored issues
show
introduced by
The condition is_array($this->keyName) is always false.
Loading history...
633
                $whereclause = '';
634
                $vnb         = count($this->keyName);
635
                for ($i = 0; $i < $vnb; ++$i) {
636
                    if ($i > 0) {
637
                        $whereclause .= ' AND ';
638
                    }
639
                    $whereclause .= $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
640
                }
641
            } else {
642
                $whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
643
            }
644
            $sql .= ' WHERE ' . $whereclause;
645
        }
646
647
        if (false !== $force) {
648
            $result = $this->db->queryF($sql);
649
        } else {
650
            $result = $this->db->query($sql);
651
        }
652
653
        // Clear cache
654
        $this->forceCacheClean();
655
656
        if (!$result) {
657
            return false;
658
        }
659
        if ($obj->isNew() && !is_array($this->keyName)) {
660
            $obj->assignVar($this->keyName, $this->db->getInsertId());
661
        }
662
663
        return true;
664
    }
665
666
    /**
667
     * Change a value for objects with a certain criteria
668
     *
669
     * @param string           $fieldname  Name of the field
670
     * @param string           $fieldvalue Value to write
671
     * @param \CriteriaElement|\CriteriaCompo $criteria
672
     *
673
     * @param  bool            $force
674
     * @return bool
675
     */
676
    public function updateAll($fieldname, $fieldvalue, $criteria = null, $force = false)
677
    {
678
        $set_clause = $fieldname . ' = ';
679
        if (is_numeric($fieldvalue)) {
680
            $set_clause .= $fieldvalue;
681
        } elseif (is_array($fieldvalue)) {
0 ignored issues
show
introduced by
The condition is_array($fieldvalue) is always false.
Loading history...
682
            $set_clause .= $this->db->quoteString(implode(',', $fieldvalue));
683
        } else {
684
            $set_clause .= $this->db->quoteString($fieldvalue);
685
        }
686
        $sql = 'UPDATE ' . $this->table . ' SET ' . $set_clause;
687
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
688
            $sql .= ' ' . $criteria->renderWhere();
689
        }
690
        if ($force) {
691
            $result = $this->db->queryF($sql);
692
        } else {
693
            $result = $this->db->query($sql);
694
        }
695
696
        // Clear cache
697
        $this->forceCacheClean();
698
699
        if (!$result) {
700
            return false;
701
        }
702
703
        return true;
704
    }
705
706
    //  check if target object is attempting to use duplicated info
707
708
    /**
709
     * @param         $obj
710
     * @param  string $field
711
     * @param  string $error
712
     * @return bool
713
     */
714
    public function isDuplicated($obj, $field = '', $error = '')
715
    {
716
        if (empty($field)) {
717
            return false;
718
        }
719
        $criteria = new \CriteriaCompo();
720
        $criteria->add(new \Criteria($field, $obj->getVar($field)));
721
        //  one more condition if target object exisits in database
722
        if (!$obj->isNew()) {
723
            $criteria->add(new \Criteria($this->_key, $obj->getVar($this->_key), '!='));
724
        }
725
        if ($this->getCount($criteria)) {
726
            $obj->setErrors($error);
727
728
            return true;
729
        }
730
731
        return false;
732
    }
733
734
    /**
735
     * delete all objects meeting the conditions
736
     *
737
     * @param  \CriteriaElement|\CriteriaCompo $criteria with conditions to meet
738
     * @return bool
739
     */
740
    public function deleteAll($criteria = null)
741
    {
742
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
743
            $sql = 'DELETE FROM ' . $this->table;
744
            $sql .= ' ' . $criteria->renderWhere();
745
            if (!$this->db->queryF($sql)) {
746
                return false;
747
            }
748
            $rows = $this->db->getAffectedRows();
749
750
            // Clear cache
751
            $this->forceCacheClean();
752
753
            return $rows > 0 ? $rows : true;
754
        }
755
756
        return false;
757
    }
758
759
    /**
760
     * Compare two objects and returns, in an array, the differences
761
     *
762
     * @param  \XoopsObject $old_object The first object to compare
763
     * @param  \XoopsObject $new_object The new object
764
     * @return array       differences    key = fieldname, value = array('old_value', 'new_value')
765
     */
766
    public function compareObjects($old_object, $new_object)
767
    {
768
        $ret       = [];
769
        $vars_name = array_keys($old_object->getVars());
770
        foreach ($vars_name as $one_var) {
771
            if ($old_object->getVar($one_var, 'f') == $new_object->getVar($one_var, 'f')) {
772
            } else {
773
                $ret[$one_var] = [$old_object->getVar($one_var), $new_object->getVar($one_var)];
774
            }
775
        }
776
777
        return $ret;
778
    }
779
780
    /**
781
     * Get distincted values of a field in the table
782
     *
783
     * @param  string           $field    Field's name
784
     * @param  \CriteriaElement|\CriteriaCompo $criteria {@link CriteriaElement} conditions to be met
785
     * @param  string           $format   Format in wich we want the datas
786
     * @return array  containing the distinct values
787
     */
788
    public function getDistincts($field, $criteria = null, $format = 's')
789
    {
790
        //require_once __DIR__ . '/lite.php';
791
        $limit = $start = 0;
792
        $sql   = 'SELECT ' . $this->keyName . ', ' . $field . ' FROM ' . $this->table;
793
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
794
            $sql   .= ' ' . $criteria->renderWhere();
795
            $limit = $criteria->getLimit();
796
            $start = $criteria->getStart();
797
        }
798
        $sql .= ' GROUP BY ' . $field . ' ORDER BY ' . $field;
799
800
        //$Cache_Lite = new oledrion_Cache_Lite($this->cacheOptions);
801
        $id = $this->_getIdForCache($sql, $start, $limit);
0 ignored issues
show
Unused Code introduced by
The assignment to $id is dead and can be removed.
Loading history...
802
        //$cacheData = $Cache_Lite->get($id);
803
        //if ($cacheData === false) {
804
        $result = $this->db->query($sql, $limit, $start);
805
        $ret    = [];
806
        $obj    = new $this->className();
807
        while (false !== ($myrow = $this->db->fetchArray($result))) {
808
            $obj->setVar($field, $myrow[$field]);
809
            $ret[$myrow[$this->keyName]] = $obj->getVar($field, $format);
810
        }
811
812
        //$Cache_Lite->save($ret);
813
        return $ret;
814
        //} else {
815
        //return $cacheData;
816
        // }
817
    }
818
819
    /**
820
     * A generic shortcut to getObjects
821
     *
822
     * @author Herve Thouzard - Instant Zero
823
     *
824
     * @param int     $start   Starting position
825
     * @param int     $limit   Maximum count of elements to return
826
     * @param  string $sort    Field to use for the sort
827
     * @param  string $order   Sort order
828
     * @param  bool   $idAsKey Do we have to return an array whoses keys are the record's ID ?
829
     * @return array   Array of current objects
830
     */
831
    public function getItems($start = 0, $limit = 0, $sort = '', $order = 'ASC', $idAsKey = true)
832
    {
833
        if ('' === trim($order)) {
834
            if (isset($this->identifierName) && '' !== trim($this->identifierName)) {
835
                $order = $this->identifierName;
836
            } else {
837
                $order = $this->keyName;
838
            }
839
        }
840
        $items   = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $items is dead and can be removed.
Loading history...
841
        $critere = new \Criteria($this->keyName, 0, '<>');
842
        $critere->setLimit($limit);
843
        $critere->setStart($start);
844
        $critere->setSort($sort);
845
        $critere->setOrder($order);
846
        $items = $this->getObjects($critere, $idAsKey);
847
848
        return $items;
849
    }
850
851
    /**
852
     * Forces the cache to be cleaned
853
     */
854
    public function forceCacheClean()
855
    {
856
        //require_once __DIR__ . '/lite.php';
857
        //$Cache_Lite = new oledrion_Cache_Lite($this->cacheOptions);
858
        //$Cache_Lite->clean();
859
    }
860
}
861