Completed
Push — master ( c52a21...5ab548 )
by Maxim
02:21
created

onetableDocLister::setIDs()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 10
rs 10
ccs 0
cts 4
cp 0
cc 2
nc 2
nop 1
crap 6
1
<?php
2
/**
3
 * all controller for show info from all table
4
 *
5
 * @category controller
6
 * @license GNU General Public License (GPL), http://www.gnu.org/copyleft/gpl.html
7
 * @author Agel_Nash <[email protected]>
8
 *
9
 * @param introField =`` //introtext
10
 * @param contentField =`description` //content
11
 * @param table =`` //table name
12
 */
13
class onetableDocLister extends DocLister
0 ignored issues
show
Coding Style introduced by
Class name "onetableDocLister" is not in PascalCase format

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
14
{
15
    /**
16
     * @var string
17
     */
18
    protected $table = '';
19
    /**
20
     * @var string
21
     */
22
    protected $idField = 'id';
23
24
    /**
25
     * @var string
26
     */
27
    protected $parentField = 'parent';
28
29
    /**
30
     * Экземпляр экстендера пагинации
31
     * @var null|paginate_DL_Extender
32
     */
33
    protected $extPaginate = null;
34
    protected $masterTable = '';
35
    protected $masterAlias = '';
36
    protected $masterIdField = '';
37
    protected $masterParentField = '';
38
39
40
    /**
41
     * @abstract
42
     */
43
    public function getDocs($tvlist = '')
44
    {
45
        if ($this->extPaginate = $this->getExtender('paginate')) {
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getExtender('paginate') can also be of type xNop. However, the property $extPaginate is declared as type null|paginate_DL_Extender. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
46
            $this->extPaginate->init($this);
0 ignored issues
show
Bug introduced by
The method init() does not exist on xNop. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

46
            $this->extPaginate->/** @scrutinizer ignore-call */ 
47
                                init($this);
Loading history...
47
        }
48
49
        /**
50
         * @var $extCommentsCount commentscount_DL_Extender
51
         */
52
        $extCommentsCount = $this->getCFGdef('commentsCount', 0) ? $this->getExtender('commentscount', true) : null;
53
54
        if ($extCommentsCount) {
0 ignored issues
show
introduced by
$extCommentsCount is of type commentscount_DL_Extender, thus it always evaluated to true.
Loading history...
55
            $extCommentsCount->init($this);
56
        }
57
58
        $type = $this->getCFGDef('idType', 'parents');
59
        $this->_docs = ($type == 'parents') ? $this->getChildrenList() : $this->getDocList();
60
61
        return $this->_docs;
62
    }
63
64
    /**
65
     * Очистка массива $IDs по которому потом будет производиться выборка документов
66
     *
67
     * @param mixed $IDs список id документов по которым необходима выборка
68
     * @return array очищенный массив
69
     */
70
    public function setIDs ($IDs)
0 ignored issues
show
Coding Style introduced by
Expected "function abc(...)"; found "function abc (...)"
Loading history...
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
Coding Style introduced by
Expected 0 spaces before opening parenthesis; 1 found
Loading history...
71
    {
72
        $this->masterAlias = $this->getCFGDef('masterAlias', 'c');
73
        $this->masterIdField = $this->getCFGDef('masterIdField', 'id');
74
        $this->masterParentField = $this->getCFGDef('masterParentField', 'parent');
75
        if ($table = $this->getCFGDef('masterTable')) {
76
            $this->masterTable = $this->getTable($table, $this->masterAlias);
77
        };
78
79
        return parent::setIDs($IDs); // TODO: Change the autogenerated stub
80
    }
81
82
    /**
83
     * @param string $tpl
84
     * @return string
85
     */
86
    public function _render($tpl = '')
0 ignored issues
show
Coding Style introduced by
Function's nesting level (6) exceeds 3; consider refactoring the function
Loading history...
87
    {
88
        $out = '';
89
        $separator = $this->getCFGDef('outputSeparator', '');
90
        if ($tpl == '') {
91
            $tpl = $this->getCFGDef('tpl', '');
92
        }
93
        if ($tpl != '') {
94
            $this->toPlaceholders(count($this->_docs), 1, "display"); // [+display+] - сколько показано на странице.
95
            $i = 1;
96
            $sysPlh = $this->renameKeyArr($this->_plh, $this->getCFGDef("sysKey", "dl"));
97
            $noneTPL = $this->getCFGDef("noneTPL", "");
98
            if (count($this->_docs) == 0 && $noneTPL != '') {
99
                $out = $this->parseChunk($noneTPL, $sysPlh);
100
            } else {
101
                /**
102
                 * @var $extUser user_DL_Extender
103
                 */
104
                if ($extUser = $this->getExtender('user')) {
105
                    $extUser->init($this, array('fields' => $this->getCFGDef("userFields", "")));
106
                }
107
108
                /**
109
                 * @var $extSummary summary_DL_Extender
110
                 */
111
                $extSummary = $this->getExtender('summary');
112
113
                /**
114
                 * @var $extPrepare prepare_DL_Extender
115
                 */
116
                $extPrepare = $this->getExtender('prepare');
117
                $this->skippedDocs = 0;
118
                foreach ($this->_docs as $item) {
119
                    $this->renderTPL = $tpl;
120
                    if ($extUser) {
121
                        $item = $extUser->setUserData($item); //[+user.id.createdby+], [+user.fullname.publishedby+], [+dl.user.publishedby+]....
122
                    }
123
124
                    $item[$this->getCFGDef("sysKey", "dl") . '.summary'] = $extSummary ? $this->getSummary(
125
                        $item,
126
                        $extSummary
127
                    ) : '';
128
129
                    $item = array_merge(
130
                        $item,
131
                        $sysPlh
132
                    ); //inside the chunks available all placeholders set via $modx->toPlaceholders with prefix id, and with prefix sysKey
133
                    $item[$this->getCFGDef(
134
                        "sysKey",
135
                        "dl"
136
                    ) . '.iteration'] = $i; //[+iteration+] - Number element. Starting from zero
137
138
                    $date = $this->getCFGDef('dateSource', 'pub_date');
139
                    if (isset($item[$date])) {
140
                        $_date = is_numeric($item[$date]) && $item[$date] == (int)$item[$date] ? $item[$date] : strtotime($item[$date]);
141
                        if ($_date !== false) {
142
                            $_date = $_date + $this->modx->config['server_offset_time'];
143
                            $dateFormat = $this->getCFGDef('dateFormat', '%d.%b.%y %H:%M');
144
                            if ($dateFormat) {
145
                                $item['date'] = strftime($dateFormat, $_date);
146
                            }
147
                        }
148
                    }
149
150
                    $findTpl = $this->renderTPL;
151
                    $tmp = $this->uniformPrepare($item, $i);
152
                    extract($tmp, EXTR_SKIP);
153
                    if ($this->renderTPL == '') {
154
                        $this->renderTPL = $findTpl;
155
                    }
156
157
                    if ($extPrepare) {
158
                        $item = $extPrepare->init($this, array(
159
                            'data'      => $item,
160
                            'nameParam' => 'prepare'
161
                        ));
162
                        if ($item === false) {
163
                            $this->skippedDocs++;
164
                            continue;
165
                        }
166
                    }
167
                    $tmp = $this->parseChunk($this->renderTPL, $item);
168
                    if ($this->getCFGDef('contentPlaceholder', 0) !== 0) {
169
                        $this->toPlaceholders(
170
                            $tmp,
171
                            1,
172
                            "item[" . $i . "]"
173
                        ); // [+item[x]+] – individual placeholder for each iteration documents on this page
174
                    }
175
                    $out .= $tmp;
176
                    if (next($this->_docs) !== false) {
177
                        $out .= $separator;
178
                    }
179
                    $i++;
180
                }
181
            }
182
            $out = $this->renderWrap($out);
183
        }
184
185
        return $this->toPlaceholders($out);
186
    }
187
188
    /**
189
     * @param array $data
190
     * @param mixed $fields
191
     * @param array $array
192
     * @return string
193
     */
194
    public function getJSON($data, $fields, $array = array())
0 ignored issues
show
Coding Style introduced by
Function's nesting level (6) exceeds 3; consider refactoring the function
Loading history...
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
195
    {
196
        $out = array();
197
        $fields = is_array($fields) ? $fields : explode(",", $fields);
198
        $date = $this->getCFGDef('dateSource', 'pub_date');
199
200
        /**
201
         * @var $extSummary summary_DL_Extender
202
         */
203
        $extSummary = $this->getExtender('summary');
204
205
        /**
206
         * @var $extPrepare prepare_DL_Extender
207
         */
208
        $extPrepare = $this->getExtender('prepare');
209
210
        /**
211
         * @var $extE e_DL_Extender
212
         */
213
        $extE = $this->getExtender('e', true, true);
214
        foreach ($data as $num => $row) {
215
            switch (true) {
216
                case ((array('1') == $fields || in_array('summary', $fields)) && $extSummary):
217
                    $row['summary'] = $this->getSummary($row, $extSummary, 'introtext');
218
                //without break
219
                case ((array('1') == $fields || in_array('date', $fields)) && $date != 'date'):
220
                    if (isset($row[$date])) {
221
                        $_date = is_numeric($row[$date]) && $row[$date] == (int)$row[$date] ? $row[$date] : strtotime($row[$date]);
222
                        if ($_date !== false) {
223
                            $_date = $_date + $this->modx->config['server_offset_time'];
224
                            $dateFormat = $this->getCFGDef('dateFormat', '%d.%b.%y %H:%M');
225
                            if ($dateFormat) {
226
                                $row['date'] = strftime($dateFormat, $_date);
227
                            }
228
                        }
229
                    }
230
                //nobreak
231
            }
232
233
            if ($extE && $tmp = $extE->init($this, array('data' => $row))) {
234
                if (is_array($tmp)) {
235
                    $row = $tmp;
236
                }
237
            }
238
239
            if ($extPrepare) {
240
                $row = $extPrepare->init($this, array('data' => $row));
241
                if ($row === false) {
242
                    continue;
243
                }
244
            }
245
            $out[$num] = $row;
246
        }
247
248
        return parent::getJSON($out, $fields, $out);
249
    }
250
251
    /**
252
     * @return array
253
     */
254
    protected function getDocList()
255
    {
256
        $out = array();
257
        $sanitarInIDs = $this->sanitarIn($this->IDs);
258
        if ($sanitarInIDs != "''" || $this->getCFGDef('ignoreEmpty', '0')) {
259
            $from = $this->table . " " . $this->_filters['join'];
260
            $where = $this->getCFGDef('addWhereList', '');
261
262
            //====== block added by Dreamer to enable filters ======
263
            $where = ($where ? $where . ' AND ' : '') . $this->_filters['where'];
264
            $where = sqlHelper::trimLogicalOp($where);
265
            //------- end of block -------
266
267
268
            if ($where != '') {
269 9
                $where = array($where);
270
            } else {
271 9
                $where = array();
272 9
            }
273 9
            if ($sanitarInIDs != "''") {
274 9
                $where[] = "{$this->getPK()} IN ({$sanitarInIDs})";
275 9
            }
276
277
            if (!empty($where)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
278 9
                $where = "WHERE " . implode(" AND ", $where);
279 9
            } else {
280
                $where = '';
281
            }
282
283 9
            $limit = $this->LimitSQL($this->getCFGDef('queryLimit', 0));
284 3
            $fields = $this->getCFGDef('selectFields', '*');
285 3
            $group = $this->getGroupSQL($this->getCFGDef('groupBy', $this->getPK()));
286 9
            $sort = $this->SortOrderSQL($this->getPK());
287
            $rs = $this->dbQuery("SELECT {$fields} FROM {$from} {$where} {$group} {$sort} {$limit}");
288 9
289 9
            $pk = $this->getPK(false);
290 9
            while ($item = $this->modx->db->getRow($rs)) {
291 9
                $out[$item[$pk]] = $item;
292 9
            }
293 3
        }
294 3
295 6
        return $out;
296 3
    }
297 3
298 3
    /**
299 3
     * @return array
300 3
     */
301 3
    protected function getChildrenList()
302 9
    {
303 9
        $where = array();
304 9
        $out = array();
305 6
        $from = $this->table . " " . $this->_filters['join'];
306 6
        $tmpWhere = $this->getCFGDef('addWhereList', '');
307
        $tmpWhere = sqlHelper::trimLogicalOp($tmpWhere);
308
309 6
        //====== block added by Dreamer to enable filters ======
310
        $tmpWhere = ($tmpWhere ? $tmpWhere . ' AND ' : '') . $this->_filters['where'];
311 6
        $tmpWhere = sqlHelper::trimLogicalOp($tmpWhere);
312 9
        //------- end of block -------
313 9
314 9
315 9
        if (!empty($tmpWhere)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
316 9
            $where[] = $tmpWhere;
317 9
        }
318
        $sanitarInIDs = $this->sanitarIn($this->IDs);
319
320 9
        $tmpWhere = null;
321 9
        if ($sanitarInIDs != "''") {
322 9
            $tmpWhere = "({$this->getParentField()} IN (" . $sanitarInIDs . ")";
323 9
            switch ($this->getCFGDef('showParent', '0')) {
324 9
                case -1:
325 9
                    $tmpWhere .= ")";
326
                    break;
327 9
                case 0:
328
                    $tmpWhere .= " AND {$this->getPK()} NOT IN(" . $sanitarInIDs . "))";
329 9
                    break;
330
                case 1:
331
                default:
332 9
                    $tmpWhere .= " OR {$this->getPK()} IN({$sanitarInIDs}))";
333
                    break;
334 9
            }
335
        }
336
        if (($addDocs = $this->getCFGDef('documents', '')) != '') {
337
            $addDocs = $this->sanitarIn($this->cleanIDs($addDocs));
338
            if (empty($tmpWhere)) {
339
                $tmpWhere = $this->getPK() . " IN({$addDocs})";
340 9
            } else {
341
                $tmpWhere = "((" . $tmpWhere . ") OR {$this->getPK()} IN({$addDocs}))";
342 9
            }
343 9
        }
344 9
        if (!empty($tmpWhere)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
345 9
            $where[] = $tmpWhere;
346 9
        }
347
        if (!empty($where)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
348
            $where = "WHERE " . implode(" AND ", $where);
349 9
        } else {
350 9
            $where = '';
351
        }
352
        $fields = $this->getCFGDef('selectFields', '*');
353 9
        $group = $this->getGroupSQL($this->getCFGDef('groupBy', $this->getPK()));
354 3
        $sort = $this->SortOrderSQL($this->getPK());
355 3
        $limit = $this->LimitSQL($this->getCFGDef('queryLimit', 0));
356 6
        if ($sanitarInIDs != "''" || $this->getCFGDef('ignoreEmpty', '0')) {
357
            $rs = $this->dbQuery("SELECT {$fields} FROM {$from} {$where} {$group} {$sort} {$limit}");
358 9
359 9
            $pk = $this->getPK(false);
360 9
361 9
            while ($item = $this->modx->db->getRow($rs)) {
362 9
                $out[$item[$pk]] = $item;
363 3
            }
364 3
        }
365 6
366 3
        return $out;
367 3
    }
368 3
369 3
    /**
370 3
     * @absctract
371 3
     */
372 9
    public function getChildrenCount()
0 ignored issues
show
Coding Style introduced by
Function's nesting level (6) exceeds 3; consider refactoring the function
Loading history...
373 9
    {
374 6
        $out = 0;
375 6
        $sanitarInIDs = $this->sanitarIn($this->IDs);
376 6
        if ($sanitarInIDs != "''" || $this->getCFGDef('ignoreEmpty', '0')) {
377 3
            $from = $this->table . " " . $this->_filters['join'];
378
            $where = $this->getCFGDef('addWhereList', '');
379 9
380
            //====== block added by Dreamer ======
381
            $where = ($where ? $where . ' AND ' : '') . $this->_filters['where'];
382
            $where = sqlHelper::trimLogicalOp($where);
383 9
            //------- end of block -------
384 9
385 9
            if ($where != '') {
386 9
                $where = array($where);
387 9
            } else {
388
                $where = array();
389
            }
390
            if ($sanitarInIDs != "''") {
391 9
                switch ($this->getCFGDef('idType', 'parents')) {
392 9
                    case 'parents':
393 9
                        switch ($this->getCFGDef('showParent', '0')) {
394 9
                            case '-1':
395 9
                                $tmpWhere = "{$this->getParentField()} IN ({$sanitarInIDs})";
396 9
                                break;
397
                            case 0:
398 9
                                $tmpWhere = "{$this->getParentField()} IN ({$sanitarInIDs}) AND {$this->getPK()} NOT IN({$sanitarInIDs})";
399
                                break;
400
                            case 1:
401
                            default:
402
                                $tmpWhere = "({$this->getParentField()} IN ({$sanitarInIDs}) OR {$this->getPK()} IN({$sanitarInIDs}))";
403
                                break;
404
                        }
405
                        if (($addDocs = $this->getCFGDef('documents', '')) != '') {
406
                            $addDocs = $this->sanitarIn($this->cleanIDs($addDocs));
407
                            $where[] = "((" . $tmpWhere . ") OR {$this->getPK()} IN({$addDocs}))";
408
                        } else {
409
                            $where[] = $tmpWhere;
410
                        }
411
                        break;
412
                    case 'documents':
413
                        $where[] = "{$this->getPK()} IN({$sanitarInIDs})";
414
                        break;
415
                }
416
            }
417
            if (!empty($where)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
418
                $where = "WHERE " . implode(" AND ", $where);
419
            } else {
420
                $where = '';
421
            }
422
423
            $group = $this->getGroupSQL($this->getCFGDef('groupBy', $this->getPK()));
424
            $maxDocs = $this->getCFGDef('maxDocs', 0);
425
            $limit = $maxDocs > 0 ? $this->LimitSQL($this->getCFGDef('maxDocs', 0)) : '';
426
            $rs = $this->dbQuery("SELECT count(*) FROM (SELECT count(*) FROM {$from} {$where} {$group} {$limit}) as `tmp`");
427
            $out = $this->modx->db->getValue($rs);
428
        }
429
430
        return $out;
431
    }
432
433
    /**
434
     * @param string|array $id
435
     * @return array
436
     */
437
    public function getChildrenFolder($id)
438
    {
439
        $out = array();
440
        $sanitarInIDs = $this->sanitarIn($id);
441
        $tmp = $this->getCFGDef('addWhereFolder', '');
442
        if (!empty($this->masterTable)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
443
            $table = $this->masterTable;
444
            $parentField = $this->getMasterParentField();
445
            $pk = $this->getMasterPK();
446
        } else {
447
            $table = $this->table;
448
            $parentField = $this->getParentField();
449
            $pk = $this->getPK();
450
        }
451
        $where = "{$parentField} IN ({$sanitarInIDs})";
452
        if (!empty($tmp)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
453
            $where .= " AND " . $tmp;
454
        }
455
456
        $rs = $this->dbQuery("SELECT {$pk} as `id` FROM {$table} WHERE {$where}");
457
        while ($item = $this->modx->db->getRow($rs)) {
458
            $out[] = $item['id'];
459
        }
460
461
        return $out;
462
    }
463
464
    /**
465
     * @param bool $full
466
     * @return string
467
     */
468
    public function getMasterParentField($full = true) {
469
        $parentField = isset($this->masterParentField) ? $this->masterParentField : '';
470
        if ($full && !empty($parentField)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
471
            $parentField = '`' . $parentField . '`';
472
            if (!empty($this->masterAlias)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
473
                $parentField = '`' . $this->masterAlias . '`.' . $parentField;
474
            }
475
        }
476
477
        return $parentField;
478
    }
479
480
    /**
481
     * @param bool $full
482
     * @return string
483
     */
484
    public function getMasterPK ($full = true)
0 ignored issues
show
Coding Style introduced by
Expected "function abc(...)"; found "function abc (...)"
Loading history...
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
Coding Style introduced by
Expected 0 spaces before opening parenthesis; 1 found
Loading history...
485
    {
486
        $idField = !empty($this->masterIdField) ? $this->masterIdField: 'id';
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
487
        if ($full) {
488
            $idField = '`' . $idField . '`';
489
            if (!empty($this->masterAlias)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after NOT operator; 0 found
Loading history...
490
                $idField = '`' . $this->masterAlias . '`.' . $idField;
491
            }
492
        }
493
494
        return $idField;
495
    }
496
497
498
}
499