onetableDocLister::getDocs()   B
last analyzed

Complexity

Conditions 7
Paths 32

Size

Total Lines 32
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 13
c 1
b 1
f 0
dl 0
loc 32
ccs 0
cts 20
cp 0
rs 8.8333
cc 7
nc 32
nop 1
crap 56
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
     * @abstract
41
     */
42
    public function getDocs($tvlist = '')
43
    {
44
        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...
45
            $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

45
            $this->extPaginate->/** @scrutinizer ignore-call */ 
46
                                init($this);
Loading history...
46
        }
47
48
        /**
49
         * @var $extCommentsCount commentscount_DL_Extender
50
         */
51
        $extCommentsCount = $this->getCFGdef('commentsCount', 0) ? $this->getExtender('commentscount', true) : null;
52
53
        if ($extCommentsCount) {
0 ignored issues
show
introduced by
$extCommentsCount is of type commentscount_DL_Extender, thus it always evaluated to true.
Loading history...
54
            $extCommentsCount->init($this);
55
        }
56
57
        $this->getExtender($this->getCFGDef('extender', ""), false, true)->init($this);
58
59
        $type = $this->getCFGDef('idType', 'parents');
60
        $this->_docs = ($type == 'parents') ? $this->getChildrenList() : $this->getDocList();
61
62
        /**
63
         * @var $extUser user_DL_Extender
64
         */
65
        if ($extUser = $this->getExtender('user')) {
66
            $extUser->init($this, array('fields' => $this->getCFGDef("userFields", "")));
67
            foreach ($this->_docs as &$item) {
68
                $item = $extUser->setUserData($item);
69
            }
70
            //[+user.id.createdby+], [+user.fullname.publishedby+], [+dl.user.publishedby+]....
71
        }
72
73
        return $this->_docs;
74
    }
75
76
    /**
77
     * Очистка массива $IDs по которому потом будет производиться выборка документов
78
     *
79
     * @param mixed $IDs список id документов по которым необходима выборка
80
     * @return array очищенный массив
81
     */
82
    public function setIDs($IDs)
0 ignored issues
show
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...
83
    {
84
        $this->masterAlias = $this->getCFGDef('masterAlias', $this->masterAlias);
85
        $this->masterIdField = $this->getCFGDef('masterIdField', $this->masterIdField);
86
        $this->masterParentField = $this->getCFGDef('masterParentField', $this->masterParentField);
87
        if ($masterTable = $this->getCFGDef('masterTable', $this->masterTable)) {
88
            $this->masterTable = $this->getTable($masterTable, $this->masterAlias);
89
        }
90
91
        return parent::setIDs($IDs); // TODO: Change the autogenerated stub
92
    }
93
94
    /**
95
     * @param string $tpl
96
     * @return string
97
     */
98
    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...
99
    {
100
        $out = '';
101
        $separator = $this->getCFGDef('outputSeparator', '');
102
        if ($tpl == '') {
103
            $tpl = $this->getCFGDef('tpl', '');
104
        }
105
        if ($tpl != '') {
106
            $this->toPlaceholders(count($this->_docs), 1, "display"); // [+display+] - сколько показано на странице.
107
            $i = 1;
108
            $sysPlh = $this->renameKeyArr($this->_plh, $this->getCFGDef("sysKey", "dl"));
109
            $noneTPL = $this->getCFGDef('noneTpl', $this->getCFGDef('noneTPL', ''));
110
            if (count($this->_docs) == 0 && $noneTPL != '') {
111
                $out = $this->parseChunk($noneTPL, $sysPlh);
112
            } else {
113
                /**
114
                 * @var $extSummary summary_DL_Extender
115
                 */
116
                $extSummary = $this->getExtender('summary');
117
118
                /**
119
                 * @var $extPrepare prepare_DL_Extender
120
                 */
121
                $extPrepare = $this->getExtender('prepare');
122
                $this->skippedDocs = 0;
123
                foreach ($this->_docs as $item) {
124
                    $this->renderTPL = $tpl;
125
126
                    $item[$this->getCFGDef("sysKey", "dl") . '.summary'] = $extSummary ? $this->getSummary(
127
                        $item,
128
                        $extSummary
129
                    ) : '';
130
131
                    $item = array_merge(
132
                        $item,
133
                        $sysPlh
134
                    ); //inside the chunks available all placeholders set via $modx->toPlaceholders with prefix id, and with prefix sysKey
135
                    $item[$this->getCFGDef(
136
                        "sysKey",
137
                        "dl"
138
                    ) . '.iteration'] = $i; //[+iteration+] - Number element. Starting from zero
139
140
                    $date = $this->getCFGDef('dateSource', 'pub_date');
141
                    if (isset($item[$date])) {
142
                        $_date = is_numeric($item[$date]) && $item[$date] == (int) $item[$date] ? $item[$date] : strtotime($item[$date]);
143
                        if ($_date !== false) {
144
                            $_date = $_date + $this->modx->config['server_offset_time'];
145
                            $dateFormat = $this->getCFGDef('dateFormat', 'd.m.Y H:i');
146
                            if ($dateFormat) {
147
                                $item['date'] = date($dateFormat, $_date);
148
                            }
149
                        }
150
                    }
151
152
                    $findTpl = $this->renderTPL;
153
                    $tmp = $this->uniformPrepare($item, $i);
154
                    extract($tmp, EXTR_SKIP);
155
                    if ($this->renderTPL == '') {
156
                        $this->renderTPL = $findTpl;
157
                    }
158
159
                    if ($extPrepare) {
160
                        $item = $extPrepare->init($this, array(
161
                            'data' => $item,
162
                            'nameParam' => 'prepare',
163
                        ));
164
                        if ($item === false) {
165
                            $this->skippedDocs++;
166
                            continue;
167
                        }
168
                    }
169
                    $tmp = $this->parseChunk($this->renderTPL, $item);
170
                    if ($this->getCFGDef('contentPlaceholder', 0) !== 0) {
171
                        $this->toPlaceholders(
172
                            $tmp,
173
                            1,
174
                            "item[" . $i . "]"
175
                        ); // [+item[x]+] – individual placeholder for each iteration documents on this page
176
                    }
177
                    $out .= $tmp;
178
                    if (next($this->_docs) !== false) {
179
                        $out .= $separator;
180
                    }
181
                    $i++;
182
                }
183
            }
184
            $out = $this->renderWrap($out);
185
        }
186
187
        return $this->toPlaceholders($out);
188
    }
189
190
    /**
191
     * @param array $data
192
     * @param mixed $fields
193
     * @param array $array
194
     * @return string
195
     */
196
    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...
197
    {
198
        $out = array();
199
        $fields = is_array($fields) ? $fields : explode(",", $fields);
200
        $date = $this->getCFGDef('dateSource', 'pub_date');
201
202
        /**
203
         * @var $extSummary summary_DL_Extender
204
         */
205
        $extSummary = $this->getExtender('summary');
206
207
        /**
208
         * @var $extPrepare prepare_DL_Extender
209
         */
210
        $extPrepare = $this->getExtender('prepare');
211
212
        /**
213
         * @var $extE e_DL_Extender
214
         */
215
        $extE = $this->getExtender('e', true, true);
216
        foreach ($data as $num => $row) {
217
            switch (true) {
218
                case ((array('1') == $fields || in_array('summary', $fields)) && $extSummary):
219
                    $row['summary'] = $this->getSummary($row, $extSummary, 'introtext');
220
                //without break
221
                case ((array('1') == $fields || in_array('date', $fields)) && $date != 'date'):
222
                    if (isset($row[$date])) {
223
                        $_date = is_numeric($row[$date]) && $row[$date] == (int) $row[$date] ? $row[$date] : strtotime($row[$date]);
224
                        if ($_date !== false) {
225
                            $_date = $_date + $this->modx->config['server_offset_time'];
226
                            $dateFormat = $this->getCFGDef('dateFormat', 'd.m.Y H:i');
227
                            if ($dateFormat) {
228
                                $row['date'] = date($dateFormat, $_date);
229
                            }
230
                        }
231
                    }
232
                    //nobreak
233
            }
234
235
            if ($extE && $tmp = $extE->init($this, array('data' => $row))) {
236
                if (is_array($tmp)) {
237
                    $row = $tmp;
238
                }
239
            }
240
241
            if ($extPrepare) {
242
                $row = $extPrepare->init($this, array('data' => $row));
243
                if ($row === false) {
244
                    continue;
245
                }
246
            }
247
            $out[$num] = $row;
248
        }
249
250
        return parent::getJSON($out, $fields, $out);
251
    }
252
253
    /**
254
     * @return array
255
     */
256
    protected function getDocList()
257
    {
258
        $out = array();
259
        $sanitarInIDs = $this->sanitarIn($this->IDs);
260
        if ($sanitarInIDs != "''" || $this->getCFGDef('ignoreEmpty', '0')) {
261
            $from = $this->table . " " . $this->_filters['join'];
262
            $where = $this->getCFGDef('addWhereList', '');
263
264
            //====== block added by Dreamer to enable filters ======
265
            $where = ($where ? $where . ' AND ' : '') . $this->_filters['where'];
266
            $where = sqlHelper::trimLogicalOp($where);
267
            //------- end of block -------
268
269 9
            if ($where != '') {
270
                $where = array($where);
271 9
            } else {
272 9
                $where = array();
273 9
            }
274 9
            if ($sanitarInIDs != "''") {
275 9
                $where[] = "{$this->getPK()} IN ({$sanitarInIDs})";
276
            }
277
278 9
            if (!empty($where)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
279 9
                $where = "WHERE " . implode(" AND ", $where);
280
            } else {
281
                $where = '';
282
            }
283 9
284 3
            $limit = $this->LimitSQL($this->getCFGDef('queryLimit', 0));
285 3
            $fields = $this->getCFGDef('selectFields', '*');
286 9
            $group = $this->getGroupSQL($this->getCFGDef('groupBy', $this->getPK()));
287
            $sort = $this->SortOrderSQL($this->getPK());
288 9
            $rs = $this->dbQuery("SELECT {$fields} FROM {$from} {$where} {$group} {$sort} {$limit}");
289 9
290 9
            $pk = $this->getPK(false);
291 9
            while ($item = $this->modx->db->getRow($rs)) {
292 9
                $out[$item[$pk]] = $item;
293 3
            }
294 3
        }
295 6
296 3
        return $out;
297 3
    }
298 3
299 3
    /**
300 3
     * @return array
301 3
     */
302 9
    protected function getChildrenList()
303 9
    {
304 9
        $where = array();
305 6
        $out = array();
306 6
        $from = $this->table . " " . $this->_filters['join'];
307
        $tmpWhere = $this->getCFGDef('addWhereList', '');
308
        $tmpWhere = sqlHelper::trimLogicalOp($tmpWhere);
309 6
310
        //====== block added by Dreamer to enable filters ======
311 6
        $tmpWhere = ($tmpWhere ? $tmpWhere . ' AND ' : '') . $this->_filters['where'];
312 9
        $tmpWhere = sqlHelper::trimLogicalOp($tmpWhere);
313 9
        //------- end of block -------
314 9
315 9
        if (!empty($tmpWhere)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
316 9
            $where[] = $tmpWhere;
317 9
        }
318
        $sanitarInIDs = $this->sanitarIn($this->IDs);
319
        $tmpWhere = null;
320 9
        if ($sanitarInIDs != "''") {
321 9
            $tmpWhere = "({$this->getParentField()} IN (" . $sanitarInIDs . ")";
322 9
            switch ($this->getCFGDef('showParent', '0')) {
323 9
                case -1:
324 9
                    $tmpWhere .= ")";
325 9
                    break;
326
                case 0:
327 9
                    $tmpWhere .= " AND {$this->getPK()} NOT IN(" . $sanitarInIDs . "))";
328
                    break;
329 9
                case 1:
330
                default:
331
                    $tmpWhere .= " OR {$this->getPK()} IN({$sanitarInIDs}))";
332 9
                    break;
333
            }
334 9
        }
335
        if (($addDocs = $this->getCFGDef('documents', '')) != '') {
336
            $addDocs = $this->sanitarIn($this->cleanIDs($addDocs));
337
            if (empty($tmpWhere)) {
338
                $tmpWhere = $this->getPK() . " IN({$addDocs})";
339
            } else {
340 9
                $tmpWhere = "((" . $tmpWhere . ") OR {$this->getPK()} IN({$addDocs}))";
341
            }
342 9
        }
343 9
        if (!empty($tmpWhere)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
344 9
            $where[] = $tmpWhere;
345 9
        }
346 9
        if (!empty($where)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
347
            $where = "WHERE " . implode(" AND ", $where);
348
        } else {
349 9
            $where = '';
350 9
        }
351
        $fields = $this->getCFGDef('selectFields', '*');
352
        $group = $this->getGroupSQL($this->getCFGDef('groupBy', $this->getPK()));
353 9
        $sort = $this->SortOrderSQL($this->getPK());
354 3
        $limit = $this->LimitSQL($this->getCFGDef('queryLimit', 0));
355 3
        if ($sanitarInIDs != "''" || $this->getCFGDef('ignoreEmpty', '0')) {
356 6
            $rs = $this->dbQuery("SELECT {$fields} FROM {$from} {$where} {$group} {$sort} {$limit}");
357
358 9
            $pk = $this->getPK(false);
359 9
360 9
            while ($item = $this->modx->db->getRow($rs)) {
361 9
                $out[$item[$pk]] = $item;
362 9
            }
363 3
        }
364 3
365 6
        return $out;
366 3
    }
367 3
368 3
    /**
369 3
     * @absctract
370 3
     */
371 3
    public function getChildrenCount()
0 ignored issues
show
Coding Style introduced by
Function's nesting level (6) exceeds 3; consider refactoring the function
Loading history...
372 9
    {
373 9
        $out = 0;
374 6
        $sanitarInIDs = $this->sanitarIn($this->IDs);
375 6
        if ($sanitarInIDs != "''" || $this->getCFGDef('ignoreEmpty', '0')) {
376 6
            $from = $this->table . " " . $this->_filters['join'];
377 3
            $where = $this->getCFGDef('addWhereList', '');
378
379 9
            //====== block added by Dreamer ======
380
            $where = ($where ? $where . ' AND ' : '') . $this->_filters['where'];
381
            $where = sqlHelper::trimLogicalOp($where);
382
            //------- end of block -------
383 9
384 9
            if ($where != '') {
385 9
                $where = array($where);
386 9
            } else {
387 9
                $where = array();
388
            }
389
            if ($sanitarInIDs != "''") {
390
                switch ($this->getCFGDef('idType', 'parents')) {
391 9
                    case 'parents':
392 9
                        switch ($this->getCFGDef('showParent', '0')) {
393 9
                            case '-1':
394 9
                                $tmpWhere = "{$this->getParentField()} IN ({$sanitarInIDs})";
395 9
                                break;
396 9
                            case 0:
397
                                $tmpWhere = "{$this->getParentField()} IN ({$sanitarInIDs}) AND {$this->getPK()} NOT IN({$sanitarInIDs})";
398 9
                                break;
399
                            case 1:
400
                            default:
401
                                $tmpWhere = "({$this->getParentField()} IN ({$sanitarInIDs}) OR {$this->getPK()} IN({$sanitarInIDs}))";
402
                                break;
403
                        }
404
                        if (($addDocs = $this->getCFGDef('documents', '')) != '') {
405
                            $addDocs = $this->sanitarIn($this->cleanIDs($addDocs));
406
                            $where[] = "((" . $tmpWhere . ") OR {$this->getPK()} IN({$addDocs}))";
407
                        } else {
408
                            $where[] = $tmpWhere;
409
                        }
410
                        break;
411
                    case 'documents':
412
                        $where[] = "{$this->getPK()} IN({$sanitarInIDs})";
413
                        break;
414
                }
415
            }
416
            if (!empty($where)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
417
                $where = "WHERE " . implode(" AND ", $where);
418
            } else {
419
                $where = '';
420
            }
421
422
            $group = $this->getGroupSQL($this->getCFGDef('groupBy', $this->getPK()));
423
            $maxDocs = $this->getCFGDef('maxDocs', 0);
424
            $limit = $maxDocs > 0 ? $this->LimitSQL($this->getCFGDef('maxDocs', 0)) : '';
425
            $rs = $this->dbQuery("SELECT count(*) FROM (SELECT count(*) FROM {$from} {$where} {$group} {$limit}) as `tmp`");
426
            $out = $this->modx->db->getValue($rs);
427
        }
428
429
        return $out;
430
    }
431
432
    /**
433
     * @param string|array $id
434
     * @return array
435
     */
436
    public function getChildrenFolder($id)
437
    {
438
        $out = array();
439
        $sanitarInIDs = $this->sanitarIn($id);
440
        $tmp = $this->getCFGDef('addWhereFolder', '');
441
        if (!empty($this->masterTable)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
442
            $table = $this->masterTable;
443
            $parentField = $this->getMasterParentField();
444
            $pk = $this->getMasterPK();
445
        } else {
446
            $table = $this->table;
447
            $parentField = $this->getParentField();
448
            $pk = $this->getPK();
449
        }
450
        $where = "{$parentField} IN ({$sanitarInIDs})";
451
        if (!empty($tmp)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
452
            $where .= " AND " . $tmp;
453
        }
454
455
        $rs = $this->dbQuery("SELECT {$pk} as `id` FROM {$table} WHERE {$where}");
456
        while ($item = $this->modx->db->getRow($rs)) {
457
            $out[] = $item['id'];
458
        }
459
460
        return $out;
461
    }
462
463
    /**
464
     * @param bool $full
465
     * @return string
466
     */
467
    public function getMasterParentField($full = true)
468
    {
469
        $parentField = isset($this->masterParentField) ? $this->masterParentField : '';
470
        if ($full && !empty($parentField)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space 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 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
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...
485
    {
486
        $idField = !empty($this->masterIdField) ? $this->masterIdField : 'id';
0 ignored issues
show
Coding Style introduced by
Expected 1 space 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 after NOT operator; 0 found
Loading history...
490
                $idField = '`' . $this->masterAlias . '`.' . $idField;
491
            }
492
        }
493
494
        return $idField;
495
    }
496
497
}
498