OledrionPersistableObjectHandler::isDuplicated()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 18
rs 9.9332
c 0
b 0
f 0
cc 4
nc 5
nop 3
1
<?php
2
3
namespace XoopsModules\Oledrion;
4
5
/*
6
 You may not change or alter any portion of this comment or credits
7
 of supporting developers from this source code or any supporting source code
8
 which is considered copyrighted (c) material of the original comment or credit authors.
9
10
 This program is distributed in the hope that it will be useful,
11
 but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
*/
14
15
use XoopsModules\Oledrion;
16
17
/**
18
 * Persistable Object Handler class.
19
 * This class is responsible for providing data access mechanisms to the data source
20
 * of derived class objects. Original Author : Mithrandir
21
 */
22
class OledrionPersistableObjectHandler extends \XoopsPersistableObjectHandler
23
{
24
    /**#@+
25
     * Information about the class, the handler is managing
26
     *
27
     * @var string
28
     */
29
    //    public $table;
30
    //    public $keyName;
31
    //    public $className;
32
    //    public $identifierName;
33
    public $cacheOptions = [];
34
35
    /**#@-*/
36
37
    /**
38
     * Constructor - called from child classes
39
     * @param null|\XoopsDatabase $db            {@link XoopsDatabase}
40
     *                                           object
41
     * @param string              $tablename     Name of database table
42
     * @param string              $classname     Name of Class, this handler is managing
43
     * @param string              $keyname       Name of the property, holding the key
44
     * @param string              $idenfierName  Name of the property, holding the label
45
     * @param array               $cacheOptions  Optional, options for the cache
46
     */
47
    public function __construct(\XoopsDatabase $db, $tablename, $classname, $keyname, $idenfierName = '', $cacheOptions = null)
48
    {
49
        //require_once  dirname(__DIR__) . '/include/common.php';
50
        require_once XOOPS_ROOT_PATH . '/modules/oledrion/include/common.php';
51
        //        $this->XoopsObjectHandler($db);
52
        parent::__construct($db);
53
        $this->table     = $db->prefix($tablename);
54
        $this->keyName   = $keyname;
55
        $this->className = $classname;
56
        if ('' !== trim($idenfierName)) {
57
            $this->identifierName = $idenfierName;
58
        }
59
        // To diable cache, add this line after the first one : 'caching' => false,
60
        if (null === $cacheOptions) {
61
            $this->setCachingOptions([
62
                                         'cacheDir'               => OLEDRION_CACHE_PATH,
63
                                         'lifeTime'               => null,
64
                                         'automaticSerialization' => true,
65
                                         'fileNameProtection'     => false,
66
                                     ]);
67
        } else {
68
            $this->setCachingOptions($cacheOptions);
69
        }
70
    }
71
72
    /**
73
     * @param $cacheOptions
74
     */
75
    public function setCachingOptions($cacheOptions)
76
    {
77
        $this->cacheOptions = $cacheOptions;
78
    }
79
80
    /**
81
     * Generates a unique ID for a Sql Query
82
     *
83
     * @param  string $query The SQL query for which we want a unidque ID
84
     * @param int     $start Which record to start at
85
     * @param int     $limit Max number of objects to fetch
86
     * @return string  An MD5 of the query
87
     */
88
    protected function _getIdForCache($query, $start, $limit)
89
    {
90
        $id = md5($query . '-' . (string)$start . '-' . (string)$limit);
91
92
        return $id;
93
    }
94
95
    /**
96
     * Convert a database resultset to a returnable array
97
     *
98
     * @param \mysqli_result $result    database resultset
99
     * @param bool           $id_as_key - should NOT be used with joint keys
100
     * @param bool           $as_object
101
     * @param string         $fields    Requested fields from the query
102
     *
103
     * @return array
104
     */
105
    public function convertResultSet($result, $id_as_key = false, $as_object = true, $fields = '*')
106
    {
107
        $ret = [];
108
        while (false !== ($myrow = $this->db->fetchArray($result))) {
109
            $obj = $this->create(false);
110
            $obj->assignVars($myrow);
111
            if (!$id_as_key) {
112
                if ($as_object) {
113
                    $ret[] = $obj;
114
                } else {
115
                    $row     = [];
116
                    $vars    = $obj->getVars();
117
                    $tbl_tmp = array_keys($vars);
118
                    foreach ($tbl_tmp as $i) {
119
                        $row[$i] = $obj->getVar($i);
120
                    }
121
                    $ret[] = $row;
122
                }
123
            } else {
124
                if ($as_object) {
125
                    if ('*' === $fields) {
126
                        $ret[$myrow[$this->keyName]] = $obj;
127
                    } else {
128
                        $ret[] = $obj;
129
                    }
130
                } else {
131
                    $row     = [];
132
                    $vars    = $obj->getVars();
133
                    $tbl_tmp = array_keys($vars);
134
                    foreach ($tbl_tmp as $i) {
135
                        $row[$i] = $obj->getVar($i);
136
                    }
137
                    $ret[$myrow[$this->keyName]] = $row;
138
                }
139
            }
140
            unset($obj);
141
        }
142
143
        return $ret;
144
    }
145
146
    /**
147
     * Retourne des éléments selon leur ID
148
     *
149
     * @param  array $ids Les ID des éléments à retrouver
150
     * @return array Tableau d'objets (clé = id key name)
151
     */
152
    public function getItemsFromIds($ids)
153
    {
154
        $ret = [];
155
        if ($ids && is_array($ids)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ids of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
156
            $criteria = new \Criteria($this->keyName, '(' . implode(',', $ids) . ')', 'IN');
157
            $ret      = $this->getObjects($criteria, true);
158
        }
159
160
        return $ret;
161
    }
162
163
    /**
164
     * Retourne le total d'un champ
165
     *
166
     * @param  string                          $field    Le champ dont on veut calculer le total
167
     * @param  \CriteriaElement|\CriteriaCompo $criteria to match
168
     * @return int le total
169
     */
170
    public function getSum($field, $criteria = null)
171
    {
172
        $limit = $start = 0;
173
        //require_once __DIR__ . '/lite.php';
174
175
        $sql = 'SELECT Sum(' . $field . ') as cpt FROM ' . $this->table;
176
        if (null !== $criteria && $criteria instanceof \CriteriaElement) {
177
            $sql .= ' ' . $criteria->renderWhere();
0 ignored issues
show
Bug introduced by
The method renderWhere() does not exist on CriteriaElement. Did you maybe mean render()? ( Ignorable by Annotation )

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

177
            $sql .= ' ' . $criteria->/** @scrutinizer ignore-call */ renderWhere();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
178
            if ('' !== $criteria->groupby) {
179
                $sql .= $criteria->getGroupby();
180
            }
181
            $limit = $criteria->getLimit();
182
            $start = $criteria->getStart();
183
        }
184
        //$CacheLite = new oledrion_CacheLite($this->cacheOptions);
185
        $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...
186
        //$cacheData = $CacheLite->get($id);
187
        //if ($cacheData === false) {
188
        $result = $this->db->query($sql, $limit, $start);
189
        if (!$result) {
190
            $ret = 0;
191
192
            //$CacheLite->save($ret);
193
            return $ret;
194
        }
195
        $row   = $this->db->fetchArray($result);
196
        $count = $row['cpt'];
197
198
        //$CacheLite->save($count);
199
        return $count;
200
        //} else {
201
        //  return $cacheData;
202
        // }
203
    }
204
205
    /**
206
     * Quickly insert a record like this $myobjectHandler->quickInsert('field1' => field1value, 'field2' => $field2value)
207
     *
208
     * @param  array $vars  Array containing the fields name and value
209
     * @param  bool  $force whether to force the query execution despite security settings
210
     * @return bool  @link insert's value
211
     */
212
    public function quickInsert($vars = null, $force = true)
213
    {
214
        $object = $this->create(true);
215
        $object->setVars($vars);
216
        $retval = $this->insert($object, $force);
217
        unset($object);
218
219
        // Clear cache
220
        $this->forceCacheClean();
221
222
        return $retval;
223
    }
224
225
    //  check if target object is attempting to use duplicated info
226
227
    /**
228
     * @param         $obj
229
     * @param  string $field
230
     * @param  string $error
231
     * @return bool
232
     */
233
    public function isDuplicated($obj, $field = '', $error = '')
234
    {
235
        if (empty($field)) {
236
            return false;
237
        }
238
        $criteria = new \CriteriaCompo();
239
        $criteria->add(new \Criteria($field, $obj->getVar($field)));
240
        //  one more condition if target object exisits in database
241
        if (!$obj->isNew()) {
242
            $criteria->add(new \Criteria($this->_key, $obj->getVar($this->_key), '!='));
0 ignored issues
show
Bug Best Practice introduced by
The property _key does not exist on XoopsModules\Oledrion\Ol...ersistableObjectHandler. Did you maybe forget to declare it?
Loading history...
243
        }
244
        if ($this->getCount($criteria)) {
245
            $obj->setErrors($error);
246
247
            return true;
248
        }
249
250
        return false;
251
    }
252
253
    /**
254
     * Compare two objects and returns, in an array, the differences
255
     *
256
     * @param  \XoopsObject $old_object The first object to compare
257
     * @param  \XoopsObject $new_object The new object
258
     * @return array       differences    key = fieldname, value = array('old_value', 'new_value')
259
     */
260
    public function compareObjects($old_object, $new_object)
261
    {
262
        $ret       = [];
263
        $vars_name = array_keys($old_object->getVars());
264
        foreach ($vars_name as $one_var) {
265
            if ($old_object->getVar($one_var, 'f') == $new_object->getVar($one_var, 'f')) {
266
            } else {
267
                $ret[$one_var] = [$old_object->getVar($one_var), $new_object->getVar($one_var)];
268
            }
269
        }
270
271
        return $ret;
272
    }
273
274
    /**
275
     * Get distincted values of a field in the table
276
     *
277
     * @param  string                          $field    Field's name
278
     * @param  \CriteriaElement|\CriteriaCompo $criteria conditions to be met
279
     * @param  string                          $format   Format in wich we want the datas
280
     * @return array  containing the distinct values
281
     */
282
    public function getDistincts($field, $criteria = null, $format = 's')
283
    {
284
        //require_once __DIR__ . '/lite.php';
285
        $limit = $start = 0;
286
        $sql   = 'SELECT ' . $this->keyName . ', ' . $field . ' FROM ' . $this->table;
287
        if (null !== $criteria && $criteria instanceof \CriteriaElement) {
288
            $sql   .= ' ' . $criteria->renderWhere();
289
            $limit = $criteria->getLimit();
290
            $start = $criteria->getStart();
291
        }
292
        $sql .= ' GROUP BY ' . $field . ' ORDER BY ' . $field;
293
294
        //$CacheLite = new oledrion_CacheLite($this->cacheOptions);
295
        $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...
296
        //$cacheData = $CacheLite->get($id);
297
        //if ($cacheData === false) {
298
        $result = $this->db->query($sql, $limit, $start);
299
        $ret    = [];
300
        $obj    = new $this->className();
301
        while (false !== ($myrow = $this->db->fetchArray($result))) {
302
            $obj->setVar($field, $myrow[$field]);
303
            $ret[$myrow[$this->keyName]] = $obj->getVar($field, $format);
304
        }
305
306
        //$CacheLite->save($ret);
307
        return $ret;
308
        //} else {
309
        //return $cacheData;
310
        // }
311
    }
312
313
    /**
314
     * A generic shortcut to getObjects
315
     *
316
     * @author Herve Thouzard - Instant Zero
317
     *
318
     * @param int     $start   Starting position
319
     * @param int     $limit   Maximum count of elements to return
320
     * @param  string $sort    Field to use for the sort
321
     * @param  string $order   Sort order
322
     * @param  bool   $idAsKey Do we have to return an array whoses keys are the record's ID ?
323
     * @return array   Array of current objects
324
     */
325
    public function getItems($start = 0, $limit = 0, $sort = '', $order = 'ASC', $idAsKey = true)
326
    {
327
        if ('' === trim($order)) {
328
            if (isset($this->identifierName) && '' !== trim($this->identifierName)) {
329
                $order = $this->identifierName;
330
            } else {
331
                $order = $this->keyName;
332
            }
333
        }
334
        $items   = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $items is dead and can be removed.
Loading history...
335
        $critere = new \Criteria($this->keyName, 0, '<>');
336
        $critere->setLimit($limit);
337
        $critere->setStart($start);
338
        $critere->setSort($sort);
339
        $critere->setOrder($order);
340
        $items = $this->getObjects($critere, $idAsKey);
341
342
        return $items;
343
    }
344
345
    /**
346
     * Forces the cache to be cleaned
347
     */
348
    public function forceCacheClean()
349
    {
350
        //require_once __DIR__ . '/lite.php';
351
        //$CacheLite = new oledrion_CacheLite($this->cacheOptions);
352
        //$Cache_Lite->clean();
353
    }
354
}
355