Renderer::getColumnWidths()   B
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 16
nc 4
nop 0
1
<?php
2
3
namespace ZfcDatagrid\Renderer\ZendTable;
4
5
use Zend\Console\Adapter\AdapterInterface as ConsoleAdapter;
6
use Zend\Console\Console;
7
use Zend\Console\Request as ConsoleRequest;
8
use Zend\Text\Table;
9
use Zend\Text\Table\Table as TextTable;
10
use ZfcDatagrid\Column;
11
use ZfcDataGrid\Column\Type;
12
use ZfcDatagrid\Renderer\AbstractRenderer;
13
14
/**
15
 * For CLI.
16
 */
17
class Renderer extends AbstractRenderer
18
{
19
    /**
20
     * @var ConsoleAdapter
21
     */
22
    private $consoleAdapter;
23
24
    /**
25
     * @var Column\AbstractColumn[]
26
     */
27
    private $columnsToDisplay;
28
29
    /**
30
     * @return string
31
     */
32
    public function getName()
33
    {
34
        return 'zendTable';
35
    }
36
37
    /**
38
     * @return bool
39
     */
40
    public function isExport()
41
    {
42
        return false;
43
    }
44
45
    /**
46
     * @return bool
47
     */
48
    public function isHtml()
49
    {
50
        return false;
51
    }
52
53
    /**
54
     * @return ConsoleRequest
55
     *
56
     * @throws \Exception
57
     */
58
    public function getRequest()
59
    {
60
        $request = parent::getRequest();
61
        if (!$request instanceof ConsoleRequest) {
62
            throw new \Exception('Request must be an instance of Zend\Console\Request for console rendering');
63
        }
64
65
        return $request;
66
    }
67
68
    /**
69
     * @param ConsoleAdapter $adapter
70
     */
71
    public function setConsoleAdapter(ConsoleAdapter $adapter)
72
    {
73
        $this->consoleAdapter = $adapter;
74
    }
75
76
    /**
77
     * @return ConsoleAdapter
78
     */
79
    public function getConsoleAdapter()
80
    {
81
        if (null === $this->consoleAdapter) {
82
            $this->consoleAdapter = Console::getInstance();
83
        }
84
85
        return $this->consoleAdapter;
86
    }
87
88
    /**
89
     * @todo enable parameters from console
90
     *
91
     * @return array
92
     */
93
    public function getSortConditions()
94
    {
95
        if (is_array($this->sortConditions)) {
96
            return $this->sortConditions;
97
        }
98
99
        $request = $this->getRequest();
100
101
        $optionsRenderer = $this->getOptionsRenderer();
102
        $parameterNames = $optionsRenderer['parameterNames'];
103
104
        $sortConditions = [];
105
106
        $sortColumns = $request->getParam($parameterNames['sortColumns']);
107
        $sortDirections = $request->getParam($parameterNames['sortDirections']);
108
        if ($sortColumns != '') {
109
            $sortColumns = explode(',', $sortColumns);
110
            $sortDirections = explode(',', $sortDirections);
111
112
            foreach ($sortColumns as $key => $sortColumn) {
113
                if (isset($sortDirections[$key])) {
114
                    $sortDirection = strtoupper($sortDirections[$key]);
115
                } else {
116
                    $sortDirection = 'ASC';
117
                }
118
119
                if ($sortDirection != 'ASC' && $sortDirection != 'DESC') {
120
                    $sortDirection = 'ASC';
121
                }
122
123
                foreach ($this->getColumns() as $column) {
124
                    /* @var $column \ZfcDatagrid\Column\AbstractColumn */
125
                    if ($column->getUniqueId() == $sortColumn) {
126
                        $sortConditions[] = [
127
                            'sortDirection' => $sortDirection,
128
                            'column' => $column,
129
                        ];
130
131
                        $column->setSortActive($sortDirection);
132
                    }
133
                }
134
            }
135
        }
136
137
        if (!empty($sortConditions)) {
138
            $this->sortConditions = $sortConditions;
139
        } else {
140
            // No user sorting -> get default sorting
141
            $this->sortConditions = $this->getSortConditionsDefault();
142
        }
143
144
        return $this->sortConditions;
145
    }
146
147
    /**
148
     * @todo enable parameters from console
149
     *
150
     * @return array
151
     */
152
    public function getFilters()
153
    {
154
        return [];
155
    }
156
157
    /**
158
     * Should be implemented for each renderer itself (just default).
159
     *
160
     * @return int
161
     */
162 View Code Duplication
    public function getCurrentPageNumber()
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...
163
    {
164
        $request = $this->getRequest();
165
166
        $optionsRenderer = $this->getOptionsRenderer();
167
        $parameterNames = $optionsRenderer['parameterNames'];
168
        if ($request->getParam($parameterNames['currentPage']) != '') {
169
            return (int) $request->getParam($parameterNames['currentPage']);
170
        }
171
172
        return (int) 1;
173
    }
174
175
    /**
176
     * @param int $defaultItems
177
     *
178
     * @return int
179
     *
180
     * @throws \Exception
181
     */
182 View Code Duplication
    public function getItemsPerPage($defaultItems = 25)
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...
183
    {
184
        $request = $this->getRequest();
185
186
        $optionsRenderer = $this->getOptionsRenderer();
187
        $parameterNames = $optionsRenderer['parameterNames'];
188
        if ($request->getParam($parameterNames['itemsPerPage']) != '') {
189
            return (int) $request->getParam($parameterNames['itemsPerPage']);
190
        }
191
192
        return (int) $defaultItems;
193
    }
194
195
    /**
196
     * @return \Zend\Stdlib\ResponseInterface
197
     */
198
    public function execute()
199
    {
200
        $textTable = clone $this->getTable();
201
202
        $response = $this->getMvcEvent()->getResponse();
203
        $response->setContent($textTable);
204
205
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response; (Zend\Stdlib\ResponseInterface) is incompatible with the return type declared by the interface ZfcDatagrid\Renderer\RendererInterface::execute of type Zend\View\Model\ViewModel.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
206
    }
207
208
    /**
209
     * @return TextTable
210
     */
211
    private function getTable()
212
    {
213
        $paginator = $this->getPaginator();
214
215
        $options = [
216
            'columnWidths' => $this->getColumnWidths(),
217
        ];
218
219
        $table = new TextTable($options);
220
        $table->setDecorator('ascii');
221
222
        /*
223
         * Title
224
         */
225
        $tableRow = new Table\Row();
226
227
        $tableColumn = new Table\Column($this->getTitle());
228
        $tableColumn->setColSpan(count($options['columnWidths']));
229
        $tableColumn->setAlign(Table\Column::ALIGN_CENTER);
230
        $tableRow->appendColumn($tableColumn);
231
232
        $table->appendRow($tableRow);
233
234
        /**
235
         * Header.
236
         */
237
        $tableRow = new Table\Row();
238
        foreach ($this->getColumnsToDisplay() as $column) {
239
            $label = $this->translate($column->getLabel());
240
241
            if (function_exists('mb_strtoupper')) {
242
                $label = mb_strtoupper($label);
243
            } else {
244
                $label = strtoupper($label);
245
            }
246
247
            $tableColumn = new Table\Column($label);
248
            if ($column->getType() instanceof Type\Number) {
249
                $tableColumn->setAlign(Table\Column::ALIGN_RIGHT);
250
            } else {
251
                $tableColumn->setAlign(Table\Column::ALIGN_LEFT);
252
            }
253
254
            $tableRow->appendColumn($tableColumn);
255
        }
256
        $table->appendRow($tableRow);
257
258
        /*
259
         * Data
260
         */
261
        foreach ($this->getData() as $row) {
262
            $tableRow = new Table\Row();
263
264
            foreach ($this->getColumnsToDisplay() as $column) {
265
                $value = '';
266
                if (isset($row[$column->getUniqueId()])) {
267
                    $value = $row[$column->getUniqueId()];
268
                }
269
                if (is_array($value)) {
270
                    $value = implode(', ', $value);
271
                }
272
273
                $tableColumn = new Table\Column($value);
274
                if ($column->getType() instanceof Type\Number) {
275
                    $tableColumn->setAlign(Table\Column::ALIGN_RIGHT);
276
                } else {
277
                    $tableColumn->setAlign(Table\Column::ALIGN_LEFT);
278
                }
279
                $tableRow->appendColumn($tableColumn);
280
            }
281
282
            $table->appendRow($tableRow);
283
        }
284
285
        /*
286
         * Pagination
287
         */
288
        $tableRow = new Table\Row();
289
290
        $footer = $this->translate('Page').' ';
291
        $footer .= sprintf('%s %s %s', $paginator->getCurrentPageNumber(), $this->translate('of'), $paginator->count());
292
293
        $footer .= ' / ';
294
295
        $footer .= sprintf(
296
            '%s %s %s %s %s',
297
            $this->translate('Showing'),
298
            $paginator->getCurrentItemCount(),
299
            $this->translate('of'),
300
            $paginator->getTotalItemCount(),
301
            $this->translate('items')
302
        );
303
304
        $tableColumn = new Table\Column($footer);
305
        $tableColumn->setColSpan(count($options['columnWidths']));
306
        $tableColumn->setAlign(Table\Column::ALIGN_CENTER);
307
        $tableRow->appendColumn($tableColumn);
308
309
        $table->appendRow($tableRow);
310
311
        return $table;
312
    }
313
314
    /**
315
     * Decide which columns we want to display.
316
     *
317
     * @return Column\AbstractColumn[]
318
     *
319
     * @throws \Exception
320
     */
321
    private function getColumnsToDisplay()
322
    {
323
        if (is_array($this->columnsToDisplay)) {
324
            return $this->columnsToDisplay;
325
        }
326
327
        $columnsToDisplay = [];
328
        foreach ($this->getColumns() as $column) {
329
            /* @var $column \ZfcDatagrid\Column\AbstractColumn */
330
331
            if (!$column instanceof Column\Action && $column->isHidden() === false) {
332
                $columnsToDisplay[] = $column;
333
            }
334
        }
335
        if (empty($columnsToDisplay)) {
336
            throw new \Exception('No columns to display available');
337
        }
338
339
        $this->columnsToDisplay = $columnsToDisplay;
340
341
        return $this->columnsToDisplay;
342
    }
343
344
    /**
345
     * @return array
346
     */
347
    private function getColumnWidths()
348
    {
349
        $cols = $this->getColumnsToDisplay();
350
351
        $this->calculateColumnWidthPercent($cols);
352
353
        $border = count($cols) + 1;
354
355
        $widthAvailable = $this->getConsoleAdapter()->getWidth() - $border;
356
        $onePercent = $widthAvailable / 100;
357
358
        $colWidths = [];
359
        foreach ($cols as $col) {
360
            /* @var $column \ZfcDatagrid\Column\AbstractColumn */
361
            $width = $col->getWidth() * $onePercent;
362
            $width = (int) floor($width);
363
364
            $colWidths[] = $width;
365
        }
366
367
        $i = 0;
368
        while (array_sum($colWidths) < $widthAvailable) {
369
            $colWidths[$i] = $colWidths[$i] + 1;
370
371
            ++$i;
372
        }
373
374
        return $colWidths;
375
    }
376
}
377