GridViewWidget   B
last analyzed

Complexity

Total Complexity 53

Size/Duplication

Total Lines 321
Duplicated Lines 6.85 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
dl 22
loc 321
c 0
b 0
f 0
wmc 53
lcom 1
cbo 10
rs 7.4757

9 Methods

Rating   Name   Duplication   Size   Complexity  
C __construct() 8 54 13
B init() 0 20 10
A run() 3 15 2
A getCounter() 0 5 1
A getPager() 11 11 2
A getTable() 0 10 1
B renderHeading() 0 19 5
D renderFilters() 0 31 9
D renderRows() 0 33 10

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like GridViewWidget often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use GridViewWidget, and based on these observations, apply Extract Interface, too.

1
<?php /** MicroGridViewWidget */
2
3
namespace Micro\Widget;
4
5
use Micro\Base\Exception;
6
use Micro\Db\Injector;
7
use Micro\File\Type;
8
use Micro\Mvc\Models\IModel;
9
use Micro\Mvc\Models\IQuery;
10
use Micro\Mvc\Models\Query;
11
use Micro\Mvc\Widget;
12
use Micro\Web\Html\Html;
13
use Micro\Web\RequestInjector;
14
15
/**
16
 * GridViewWidget class file.
17
 *
18
 * @author Oleg Lunegov <[email protected]>
19
 * @link https://github.com/linpax/microphp-framework
20
 * @copyright Copyright (c) 2013 Oleg Lunegov
21
 * @license https://github.com/linpax/microphp-framework/blob/master/LICENSE
22
 * @package Micro
23
 * @subpackage Widget
24
 * @version 1.0
25
 * @since 1.0
26
 */
27
class GridViewWidget extends Widget
28
{
29
    /** @var int $page Current page on table */
30
    public $page = 0;
31
    /** @var int $limit Limit current rows */
32
    public $limit = 10;
33
    /** @var bool $filters Usage filters */
34
    public $filters = true;
35
    /** @var string $template Template render */
36
    public $template = '{counter}{table}{pager}';
37
    /** @var string $templateTable Template table render */
38
    public $templateTable = '{headers}{filters}{rows}';
39
    /** @var string $textCounter text for before counter */
40
    public $counterText = 'Sum: ';
41
    /** @var string $emptyText text to render if rows not found */
42
    public $emptyText = 'Elements not found';
43
    /** @var array $attributesEmpty Attributes for empty text */
44
    public $attributesEmpty = [];
45
    /** @var array $attributes attributes for table */
46
    public $attributes = [];
47
    /** @var array $attributesCounter attributes for counter */
48
    public $attributesCounter = [];
49
    /** @var array $attributesHeading attributes for heading */
50
    public $attributesHeading = [];
51
    /** @var array $attributesFilter attributes for filter row */
52
    public $attributesFilter = [];
53
    /** @var array $attributesFilterForm attributes for filter form */
54
    public $attributesFilterForm = [];
55
    /** @var array $tableConfig table configuration */
56
    public $tableConfig = [];
57
    /** @var array $paginationConfig parameters for PaginationWidget */
58
    public $paginationConfig = [];
59
60
    /** @var array $rows Rows from data */
61
    protected $rows;
62
    /** @var array $fields Fields of data */
63
    protected $fields = [];
64
    /** @var int $rowsCount Count rows */
65
    protected $rowsCount = 0;
66
    /** @var int $totalCount Total count data */
67
    protected $totalCount = 0;
68
    /** @var string $filterPrefix prefix for filter name */
69
    protected $filterPrefix;
70
71
72
    /**
73
     * Re-declare widget constructor
74
     *
75
     * @access public
76
     *
77
     * @param array $args arguments
78
     *
79
     * @result void
80
     * @throws Exception
81
     */
82
    public function __construct(array $args = [])
83
    {
84
        parent::__construct($args);
85
86
        if (!array_key_exists('data', $args)) {
87
            throw new Exception('Argument "data" not initialized into GridViewWidget');
88
        }
89
90
        $this->limit = ($this->limit < 10) ? 10 : $this->limit;
91
        $this->page = ($this->page < 0) ? 0 : $this->page;
92
93
        /** @var IQuery|array $data */
94
        $data = $args['data'];
95
96
        if ($data instanceof IQuery) {
97 View Code Duplication
            if ($data->objectName) {
0 ignored issues
show
Bug introduced by
Accessing objectName on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
98
                /** @var IModel $cls */
99
                $cls = $data->objectName;
0 ignored issues
show
Bug introduced by
Accessing objectName on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
100
                /** @noinspection PhpUndefinedFieldInspection */
101
                $data->table = $cls::$tableName;
0 ignored issues
show
Bug introduced by
Accessing table on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
102
            } elseif (!$args['data']->table) {
103
                throw new Exception('Data query not set table or objectName');
104
            }
105
106
            if ($data->having || $data->group) {
0 ignored issues
show
Bug introduced by
Accessing having on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
Bug introduced by
Accessing group on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
107
                $res = new Query((new Injector)->getDriver());
108
                $res->select = 'COUNT(*)';
109
                $res->table = '('.$data->getQuery().') micro_count';
110
                $res->single = true;
111
            } else {
112
                /** @var Query $res */
113
                $res = clone $data;
114
                $res->objectName = null;
115
                $res->select = 'COUNT(*)';
116
                $res->single = true;
117
            }
118
119
            /** @var array $a */
120
            $this->totalCount = ($a = $res->run(\PDO::FETCH_NUM)) ? $a[0] : 0;
121
            $this->filterPrefix = $data->table;
0 ignored issues
show
Bug introduced by
Accessing table on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
122
123
            $data->offset = $this->page * $this->limit;
0 ignored issues
show
Bug introduced by
Accessing offset on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
124
            $data->limit = $this->limit;
0 ignored issues
show
Bug introduced by
Accessing limit on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
125
            $data = $data->run($data->objectName ? \PDO::FETCH_CLASS : \PDO::FETCH_ASSOC);
0 ignored issues
show
Bug introduced by
Accessing objectName on the interface Micro\Mvc\Models\IQuery suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
126
        } else { // array
127
            $this->totalCount = count($data);
128
            $data = array_slice($data, $this->page * $this->limit, $this->limit);
129
        }
130
131
        /** @noinspection ForeachSourceInspection */
132
        foreach ($data AS $model) {
133
            $this->rows[] = is_subclass_of($model, 'Micro\Mvc\Models\Model') ? $model : (object)$model;
134
        }
135
    }
136
137
    /**
138
     * Initialize widget
139
     *
140
     * @access public
141
     *
142
     * @result void
143
     */
144
    public function init()
145
    {
146
        $this->filterPrefix = ucfirst($this->filterPrefix ?: 'data'.$this->totalCount);
147
        $this->fields = (null !== $this->rows) ? array_keys(Type::getVars($this->rows[0])) : [];
148
        $this->rowsCount = count($this->rows);
149
        $this->paginationConfig['countRows'] = $this->totalCount;
150
        $this->paginationConfig['limit'] = $this->limit;
151
        $this->paginationConfig['currentPage'] = $this->page;
152
        $this->tableConfig = $this->tableConfig ?: $this->fields;
153
154
        foreach ($this->tableConfig AS $key => $conf) {
155
            unset($this->tableConfig[$key]);
156
157
            $this->tableConfig[is_string($conf) ? $conf : $key] = array_merge([
158
                'attributesHeader' => !empty($conf['attributesHeader']) ? $conf['attributesHeader'] : [],
159
                'attributesFilter' => !empty($conf['attributesFilter']) ? $conf['attributesFilter'] : [],
160
                'attributes' => !empty($conf['attributes']) ? $conf['attributes'] : []
161
            ], is_array($conf) ? $conf : []);
162
        }
163
    }
164
165
    /**
166
     * Running widget
167
     *
168
     * @access public
169
     *
170
     * @return string
171
     * @throws Exception
172
     */
173
    public function run()
174
    {
175 View Code Duplication
        if (!$this->rows) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->rows 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...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
176
            return Html::openTag('div', $this->attributesEmpty).$this->emptyText.Html::closeTag('div');
177
        }
178
179
        ob_start();
180
        echo str_replace(
181
            ['{counter}', '{pager}', '{table}'],
182
            [$this->getCounter(), $this->getPager(), $this->getTable()],
183
            $this->template
184
        );
185
186
        return ob_get_clean();
187
    }
188
189
    /**
190
     * Get counter
191
     *
192
     * @access protected
193
     *
194
     * @return string
195
     */
196
    protected function getCounter()
197
    {
198
        return Html::openTag('div', $this->attributesCounter).
199
        $this->counterText.$this->totalCount.Html::closeTag('div');
200
    }
201
202
    /**
203
     * Get pager
204
     *
205
     * @access protected
206
     *
207
     * @return string
208
     */
209 View Code Duplication
    protected function getPager()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
210
    {
211
        if (!$this->rows) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->rows 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...
212
            return '';
213
        }
214
215
        $pager = new PaginationWidget($this->paginationConfig);
216
        $pager->init();
217
218
        return $pager->run();
219
    }
220
221
    /**
222
     * Get table
223
     *
224
     * @access protected
225
     *
226
     * @return string
227
     * @throws Exception
228
     */
229
    protected function getTable()
230
    {
231
        $table = str_replace(
232
            ['{headers}', '{filters}', '{rows}'],
233
            [$this->renderHeading(), $this->renderFilters(), $this->renderRows()],
234
            $this->templateTable
235
        );
236
237
        return Html::openTag('table', $this->attributes).$table.Html::closeTag('table');
238
    }
239
240
    /**
241
     * Render heading
242
     *
243
     * @access protected
244
     *
245
     * @return string
246
     */
247
    protected function renderHeading()
248
    {
249
        $result = Html::openTag('tr', $this->attributesHeading);
250
        foreach ($this->tableConfig AS $key => $row) {
251
            $result .= Html::openTag('th', $row['attributesHeader']);
252
            if (!empty($row['header'])) {
253
                $result .= $row['header'];
254
            } else {
255
                if (is_string($key)) {
256
                    /** @noinspection PhpUndefinedMethodInspection */
257
                    $result .= is_subclass_of($this->rows[0],
258
                        'Micro\\Mvc\\Models\\Model') ? $this->rows[0]->getLabel($key) : ucfirst($key);
259
                }
260
            }
261
            $result .= Html::closeTag('th');
262
        }
263
264
        return $result.Html::closeTag('tr');
265
    }
266
267
    /**
268
     * Render filters
269
     *
270
     * @access protected
271
     *
272
     * @return null|string
273
     * @throws Exception
274
     */
275
    protected function renderFilters()
276
    {
277
        if (!$this->filters) {
278
            return null;
279
        }
280
        /** @var array $filtersData */
281
        $query = (new RequestInjector)->build()->getQueryParams();
282
        $filtersData = array_key_exists($this->filterPrefix, $query) ? $query[$this->filterPrefix] : null;
283
284
        $result = Html::beginForm(null, 'get', $this->attributesFilterForm);
285
        $result .= Html::openTag('tr', $this->attributesFilter);
286
287
        foreach ($this->tableConfig AS $key => $row) {
288
            $result .= Html::openTag('td', $row['attributesFilter']);
289
            if (array_key_exists('filter', $row) && $row['filter'] === false) {
290
                continue;
291
            }
292
            if (!empty($row['filter'])) {
293
                $result .= $row['filter'];
294
            } else {
295
                $buffer = is_array($row) ? $key : $row;
296
                $fieldName = $this->filterPrefix.'['.$buffer.']';
297
                $fieldId = $this->filterPrefix.'_'.$buffer;
298
                $val = !empty($filtersData[$buffer]) ? $filtersData[$buffer] : '';
299
                $result .= Html::textField($fieldName, $val, ['id' => $fieldId]);
300
            }
301
            $result .= Html::closeTag('td');
302
        }
303
304
        return $result.Html::closeTag('tr').Html::endForm();
305
    }
306
307
    /**
308
     * Render rows
309
     *
310
     * @access protected
311
     *
312
     * @return null|string
313
     */
314
    protected function renderRows()
315
    {
316
        $result = null;
317
318
        if (0 === count($this->rows)) {
319
            return Html::openTag('tr').
320
            Html::openTag('td', ['cols' => count($this->fields)]).$this->emptyText.Html::closeTag('td').
321
            Html::closeTag('tr');
322
        }
323
324
        foreach ($this->rows AS $data) {
325
            $result .= Html::openTag('tr');
326
327
            foreach ($this->tableConfig AS $key => $row) {
328
                $result .= Html::openTag('td', $row['attributes']);
329
330
                if (!empty($row['class']) && is_subclass_of($row['class'], 'Micro\\Widget\\GridColumn')) {
331
                    $primaryKey = $data->{!empty($row['key']) ? $row['key'] : 'id'};
332
                    $result .= (string)new $row['class'](
333
                        $row + ['str' => (null === $data) ?: $data, 'pKey' => $primaryKey]
334
                    );
335
                } elseif (!empty($row['value'])) {
336
                    $result .= eval('return '.$row['value'].';');
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
337
                } else {
338
                    $result .= property_exists($data, $key) ? $data->$key : null;
339
                }
340
                $result .= Html::closeTag('td');
341
            }
342
            $result .= Html::closeTag('tr');
343
        }
344
345
        return $result;
346
    }
347
}
348