AbstractRenderer::getItemsPerPage()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace ZfcDatagrid\Renderer;
4
5
use Doctrine\Common\Proxy\Exception\InvalidArgumentException;
6
use Zend\Cache;
7
use Zend\I18n\Translator\Translator;
8
use Zend\Mvc\MvcEvent;
9
use Zend\Paginator\Paginator;
10
use Zend\View\Model\ViewModel;
11
use ZfcDatagrid\Datagrid;
12
use ZfcDatagrid\Filter;
13
14
abstract class AbstractRenderer implements RendererInterface
15
{
16
    /**
17
     * @var array
18
     */
19
    protected $options = [];
20
21
    /**
22
     * @var string
23
     */
24
    protected $title;
25
26
    /**
27
     * @var Cache\Storage\StorageInterface
28
     */
29
    protected $cache;
30
31
    /**
32
     * @var string
33
     */
34
    protected $cacheId;
35
36
    /**
37
     * @var Paginator
38
     */
39
    protected $paginator;
40
41
    /**
42
     * @var \ZfcDatagrid\Column\AbstractColumn[]
43
     */
44
    protected $columns = [];
45
46
    /**
47
     * @var \ZfcDataGrid\Column\Style\AbstractStyle[]
48
     */
49
    protected $rowStyles = [];
50
51
    /**
52
     * @var array
53
     */
54
    protected $sortConditions = null;
55
56
    /**
57
     * @var Filter[]
58
     */
59
    protected $filters = null;
60
61
    /**
62
     * @var int
63
     */
64
    protected $currentPageNumber = null;
65
66
    /**
67
     * @var array
68
     */
69
    protected $data = [];
70
71
    /**
72
     * @var MvcEvent
73
     */
74
    protected $mvcEvent;
75
76
    /**
77
     * @var ViewModel
78
     */
79
    protected $viewModel;
80
81
    /**
82
     * @var string
83
     */
84
    protected $template;
85
86
    /**
87
     * @var string
88
     */
89
    protected $templateToolbar;
90
91
    /**
92
     * @var array
93
     */
94
    protected $toolbarTemplateVariables = [];
95
96
    /**
97
     * @var Translator
98
     */
99
    protected $translator;
100
101
    public function setOptions(array $options)
102
    {
103
        $this->options = $options;
104
    }
105
106
    /**
107
     * @return array
108
     */
109
    public function getOptions()
110
    {
111
        return $this->options;
112
    }
113
114
    /**
115
     * @return array
116
     */
117
    public function getOptionsRenderer()
118
    {
119
        $options = $this->getOptions();
120
        if (isset($options['renderer'][$this->getName()])) {
121
            return $options['renderer'][$this->getName()];
122
        } else {
123
            return [];
124
        }
125
    }
126
127
    /**
128
     * @param ViewModel $viewModel
129
     */
130
    public function setViewModel(ViewModel $viewModel)
131
    {
132
        $this->viewModel = $viewModel;
133
    }
134
135
    /**
136
     * @return \Zend\View\Model\ViewModel
137
     */
138
    public function getViewModel()
139
    {
140
        return $this->viewModel;
141
    }
142
143
    /**
144
     * Set the view template.
145
     *
146
     * @param string $name
147
     */
148
    public function setTemplate($name)
149
    {
150
        $this->template = (string) $name;
151
    }
152
153
    /**
154
     * Get the view template name.
155
     *
156
     * @return string
157
     */
158
    public function getTemplate()
159
    {
160
        if (null === $this->template) {
161
            $this->template = $this->getTemplatePathDefault('layout');
162
        }
163
164
        return $this->template;
165
    }
166
167
    /**
168
     * Get the default template path (if there is no own set).
169
     *
170
     * @param string $type layout or toolbar
171
     *
172
     * @return string
173
     *
174
     * @throws \Exception
175
     */
176
    private function getTemplatePathDefault($type = 'layout')
177
    {
178
        $optionsRenderer = $this->getOptionsRenderer();
179
        if (isset($optionsRenderer['templates'][$type])) {
180
            return $optionsRenderer['templates'][$type];
181
        }
182
183
        if ('layout' === $type) {
184
            return 'zfc-datagrid/renderer/'.$this->getName().'/'.$type;
185
        } elseif ('toolbar' === $type) {
186
            return 'zfc-datagrid/toolbar/toolbar';
187
        }
188
189
        throw new \Exception('Unknown type: "'.$type.'"');
190
    }
191
192
    /**
193
     * Set the toolbar view template name.
194
     *
195
     * @param string $name
196
     */
197
    public function setToolbarTemplate($name)
198
    {
199
        $this->templateToolbar = (string) $name;
200
    }
201
202
    /**
203
     * @return string
204
     *
205
     * @throws \Exception
206
     */
207
    public function getToolbarTemplate()
208
    {
209
        if (null === $this->templateToolbar) {
210
            $this->templateToolbar = $this->getTemplatePathDefault('toolbar');
211
        }
212
213
        return $this->templateToolbar;
214
    }
215
216
    /**
217
     * Set the toolbar view template variables.
218
     *
219
     * @param array $variables
220
     */
221
    public function setToolbarTemplateVariables(array $variables)
222
    {
223
        $this->toolbarTemplateVariables = $variables;
224
    }
225
226
    /**
227
     * Get the toolbar template variables.
228
     *
229
     * @return array
230
     */
231
    public function getToolbarTemplateVariables()
232
    {
233
        return $this->toolbarTemplateVariables;
234
    }
235
236
    /**
237
     * Paginator is here to retreive the totalItemCount, count pages, current page
238
     * NOT FOR THE ACTUAL DATA!!!!
239
     *
240
     * @param \Zend\Paginator\Paginator $paginator
241
     */
242
    public function setPaginator(Paginator $paginator)
243
    {
244
        $this->paginator = $paginator;
245
    }
246
247
    /**
248
     * @return \Zend\Paginator\Paginator
249
     */
250
    public function getPaginator()
251
    {
252
        return $this->paginator;
253
    }
254
255
    /**
256
     * Set the columns.
257
     *
258
     * @param array $columns
259
     */
260
    public function setColumns(array $columns)
261
    {
262
        $this->columns = $columns;
263
    }
264
265
    /**
266
     * Get all columns.
267
     *
268
     * @return \ZfcDatagrid\Column\AbstractColumn[]
269
     */
270
    public function getColumns()
271
    {
272
        return $this->columns;
273
    }
274
275
    /**
276
     * @param \ZfcDataGrid\Column\Style\AbstractStyle[] $rowStyles
277
     */
278
    public function setRowStyles($rowStyles = [])
279
    {
280
        $this->rowStyles = $rowStyles;
281
    }
282
283
    /**
284
     * @return \ZfcDataGrid\Column\Style\AbstractStyle[]
285
     */
286
    public function getRowStyles()
287
    {
288
        return $this->rowStyles;
289
    }
290
291
    /**
292
     * Calculate the sum of the displayed column width to 100%.
293
     *
294
     * @param array $columns
295
     */
296
    protected function calculateColumnWidthPercent(array $columns)
297
    {
298
        $widthAllColumn = 0;
299
        foreach ($columns as $column) {
300
            /* @var $column \ZfcDatagrid\Column\AbstractColumn */
301
            $widthAllColumn += $column->getWidth();
302
        }
303
304
        $widthSum = 0;
305
        // How much 1 percent columnd width is really "one" percent...
306
        $relativeOnePercent = $widthAllColumn / 100;
307
308
        foreach ($columns as $column) {
309
            $widthSum += (($column->getWidth() / $relativeOnePercent));
310
            $column->setWidth(($column->getWidth() / $relativeOnePercent));
311
        }
312
    }
313
314
    /**
315
     * The prepared data.
316
     *
317
     * @param array $data
318
     */
319
    public function setData(array $data)
320
    {
321
        $this->data = $data;
322
    }
323
324
    /**
325
     * @return array
326
     */
327
    public function getData()
328
    {
329
        return $this->data;
330
    }
331
332
    /**
333
     * @return array
334
     */
335
    public function getCacheData()
336
    {
337
        return $this->getCache()->getItem($this->getCacheId());
338
    }
339
340
    /**
341
     * @throws \Exception
342
     *
343
     * @return array|false
344
     */
345
    private function getCacheSortConditions()
346
    {
347
        $cacheData = $this->getCacheData();
348
        if (!isset($cacheData['sortConditions'])) {
349
            return false;
350
        }
351
352
        return $cacheData['sortConditions'];
353
    }
354
355
    /**
356
     * @throws \Exception
357
     *
358
     * @return array|false
359
     */
360
    private function getCacheFilters()
361
    {
362
        $cacheData = $this->getCacheData();
363
        if (!isset($cacheData['filters'])) {
364
            return false;
365
        }
366
367
        return $cacheData['filters'];
368
    }
369
370
    /**
371
     * Not used ATM...
372
     *
373
     * @see \ZfcDatagrid\Renderer\RendererInterface::setMvcEvent()
374
     */
375
    public function setMvcEvent(MvcEvent $mvcEvent)
376
    {
377
        $this->mvcEvent = $mvcEvent;
378
    }
379
380
    /**
381
     * Not used ATM...
382
     *
383
     * @return MvcEvent
384
     */
385
    public function getMvcEvent()
386
    {
387
        return $this->mvcEvent;
388
    }
389
390
    /**
391
     * @return \Zend\Stdlib\RequestInterface
392
     */
393
    public function getRequest()
394
    {
395
        return $this->getMvcEvent()->getRequest();
396
    }
397
398
    /**
399
     * @param Translator $translator
400
     *
401
     * @throws \InvalidArgumentException
402
     */
403 View Code Duplication
    public function setTranslator($translator)
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...
404
    {
405
        if (!$translator instanceof Translator && !$translator instanceof \Zend\I18n\Translator\TranslatorInterface) {
406
            throw new \InvalidArgumentException('Translator must be an instanceof "Zend\I18n\Translator\Translator" or "Zend\I18n\Translator\TranslatorInterface"');
407
        }
408
409
        $this->translator = $translator;
410
    }
411
412
    /**
413
     * @return \Zend\I18n\Translator\Translator
414
     */
415
    public function getTranslator()
416
    {
417
        return $this->translator;
418
    }
419
420
    /**
421
     * @param $string
422
     *
423
     * @return string
424
     */
425
    public function translate($string)
426
    {
427
        return $this->getTranslator() ? $this->getTranslator()->translate($string) : $string;
428
    }
429
430
    /**
431
     * Set the title.
432
     *
433
     * @param string $title
434
     */
435
    public function setTitle($title)
436
    {
437
        $this->title = $title;
438
    }
439
440
    /**
441
     * @return string
442
     */
443
    public function getTitle()
444
    {
445
        return $this->title;
446
    }
447
448
    /**
449
     * @param Cache\Storage\StorageInterface $cache
450
     */
451
    public function setCache(Cache\Storage\StorageInterface $cache)
452
    {
453
        $this->cache = $cache;
454
    }
455
456
    /**
457
     * @return Cache\Storage\StorageInterface
458
     */
459
    public function getCache()
460
    {
461
        return $this->cache;
462
    }
463
464
    /**
465
     * @param string $cacheId
466
     */
467
    public function setCacheId($cacheId)
468
    {
469
        $this->cacheId = $cacheId;
470
    }
471
472
    /**
473
     * @return string
474
     */
475
    public function getCacheId()
476
    {
477
        return $this->cacheId;
478
    }
479
480
    /**
481
     * Set the sort conditions explicit (e.g.
482
     * from a custom form).
483
     *
484
     * @param array $sortConditions
485
     */
486
    public function setSortConditions(array $sortConditions)
487
    {
488
        foreach ($sortConditions as $sortCondition) {
489
            if (!is_array($sortCondition)) {
490
                throw new InvalidArgumentException('Sort condition have to be an array');
491
            }
492
493
            if (!array_key_exists('column', $sortCondition)) {
494
                throw new InvalidArgumentException('Sort condition missing array key column');
495
            }
496
        }
497
498
        $this->sortConditions = $sortConditions;
499
    }
500
501
    /**
502
     * @return array
503
     */
504 View Code Duplication
    public function getSortConditions()
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...
505
    {
506
        if (is_array($this->sortConditions)) {
507
            return $this->sortConditions;
508
        }
509
510
        if ($this->isExport() === true && $this->getCacheSortConditions() !== false) {
511
            // Export renderer should always retrieve the sort conditions from cache!
512
            $this->sortConditions = $this->getCacheSortConditions();
513
514
            return $this->sortConditions;
515
        }
516
517
        $this->sortConditions = $this->getSortConditionsDefault();
518
519
        return $this->sortConditions;
520
    }
521
522
    /**
523
     * Get the default sort conditions defined for the columns.
524
     *
525
     * @return array
526
     */
527
    public function getSortConditionsDefault()
528
    {
529
        $sortConditions = [];
530
        foreach ($this->getColumns() as $column) {
531
            /* @var $column \ZfcDatagrid\Column\AbstractColumn */
532
            if ($column->hasSortDefault() === true) {
533
                $sortDefaults = $column->getSortDefault();
534
535
                $sortConditions[$sortDefaults['priority']] = [
536
                    'column' => $column,
537
                    'sortDirection' => $sortDefaults['sortDirection'],
538
                ];
539
540
                $column->setSortActive($sortDefaults['sortDirection']);
541
            }
542
        }
543
544
        ksort($sortConditions);
545
546
        return $sortConditions;
547
    }
548
549
    /**
550
     * Set filters explicit (e.g.
551
     * from a custom form).
552
     *
553
     * @param array $filters
554
     */
555
    public function setFilters(array $filters)
556
    {
557
        foreach ($filters as $filter) {
558
            if (!$filter instanceof Filter) {
559
                throw new InvalidArgumentException('Filter have to be an instanceof ZfcDatagrid\Filter');
560
            }
561
        }
562
563
        $this->filters = $filters;
564
    }
565
566
    /**
567
     * @return Filter[]
568
     */
569 View Code Duplication
    public function getFilters()
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...
570
    {
571
        if (is_array($this->filters)) {
572
            return $this->filters;
573
        }
574
575
        if ($this->isExport() === true && $this->getCacheFilters() !== false) {
576
            // Export renderer should always retrieve the filters from cache!
577
            $this->filters = $this->getCacheFilters();
578
579
            return $this->filters;
580
        }
581
582
        $this->filters = $this->getFiltersDefault();
583
584
        return $this->filters;
585
    }
586
587
    /**
588
     * Get the default filter conditions defined for the columns.
589
     *
590
     * @return Filter[]
591
     */
592
    public function getFiltersDefault()
593
    {
594
        $filters = [];
595
596 View Code Duplication
        foreach ($this->getColumns() as $column) {
0 ignored issues
show
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...
597
            /* @var $column \ZfcDatagrid\Column\AbstractColumn */
598
            if ($column->hasFilterDefaultValue() === true) {
599
                $filter = new Filter();
600
                $filter->setFromColumn($column, $column->getFilterDefaultValue());
601
                $filters[] = $filter;
602
603
                $column->setFilterActive($filter->getDisplayColumnValue());
604
            }
605
        }
606
607
        return $filters;
608
    }
609
610
    /**
611
     * Set the current page number.
612
     *
613
     * @param int $page
614
     */
615
    public function setCurrentPageNumber($page)
616
    {
617
        $this->currentPageNumber = (int) $page;
618
    }
619
620
    /**
621
     * Should be implemented for each renderer itself (just default).
622
     *
623
     * @return int
624
     */
625
    public function getCurrentPageNumber()
626
    {
627
        if (null === $this->currentPageNumber) {
628
            $this->currentPageNumber = 1;
629
        }
630
631
        return (int) $this->currentPageNumber;
632
    }
633
634
    /**
635
     * Should be implemented for each renderer itself (just default).
636
     *
637
     * @return int
638
     */
639
    public function getItemsPerPage($defaultItems = 25)
640
    {
641
        if ($this->isExport() === true) {
642
            return (int) -1;
643
        }
644
645
        return $defaultItems;
646
    }
647
648
    /**
649
     * VERY UGLY DEPENDECY...
650
     *
651
     * @todo Refactor :-)
652
     *
653
     * @see \ZfcDatagrid\Renderer\RendererInterface::prepareViewModel()
654
     */
655
    public function prepareViewModel(Datagrid $grid)
656
    {
657
        $viewModel = $this->getViewModel();
658
659
        $viewModel->setVariable('gridId', $grid->getId());
660
        $viewModel->setVariable('title', $this->getTitle());
661
        $viewModel->setVariable('parameters', $grid->getParameters());
662
        $viewModel->setVariable('overwriteUrl', $grid->getUrl());
663
664
        $viewModel->setVariable('templateToolbar', $this->getToolbarTemplate());
665
        foreach ($this->getToolbarTemplateVariables() as $key => $value) {
666
            $viewModel->setVariable($key, $value);
667
        }
668
        $viewModel->setVariable('rendererName', $this->getName());
669
670
        $options = $this->getOptions();
671
        $generalParameterNames = $options['generalParameterNames'];
672
        $viewModel->setVariable('generalParameterNames', $generalParameterNames);
673
674
        $viewModel->setVariable('columns', $this->getColumns());
675
676
        $viewModel->setVariable('rowStyles', $grid->getRowStyles());
677
678
        $viewModel->setVariable('paginator', $this->getPaginator());
679
        $viewModel->setVariable('data', $this->getData());
680
        $viewModel->setVariable('filters', $this->getFilters());
681
682
        $viewModel->setVariable('rowClickAction', $grid->getRowClickAction());
683
        $viewModel->setVariable('massActions', $grid->getMassActions());
684
685
        $viewModel->setVariable('isUserFilterEnabled', $grid->isUserFilterEnabled());
686
687
        /*
688
         * renderer specific parameter names
689
         */
690
        $optionsRenderer = $this->getOptionsRenderer();
691
        $viewModel->setVariable('optionsRenderer', $optionsRenderer);
692
        if ($this->isExport() === false) {
693
            $parameterNames = $optionsRenderer['parameterNames'];
694
            $viewModel->setVariable('parameterNames', $parameterNames);
695
696
            $activeParameters = [];
697
            $activeParameters[$parameterNames['currentPage']] = $this->getCurrentPageNumber();
698
            {
699
                $sortColumns = [];
700
                $sortDirections = [];
701
                foreach ($this->getSortConditions() as $sortCondition) {
702
                    $sortColumns[] = $sortCondition['column']->getUniqueId();
703
                    $sortDirections[] = $sortCondition['sortDirection'];
704
                }
705
706
                $activeParameters[$parameterNames['sortColumns']] = implode(',', $sortColumns);
707
                $activeParameters[$parameterNames['sortDirections']] = implode(',', $sortDirections);
708
            }
709
            $viewModel->setVariable('activeParameters', $activeParameters);
710
        }
711
712
        $viewModel->setVariable('exportRenderers', $grid->getExportRenderers());
713
    }
714
715
    /**
716
     * Return the name of the renderer.
717
     *
718
     * @return string
719
     */
720
    abstract public function getName();
721
722
    /**
723
     * Determine if the renderer is for export.
724
     *
725
     * @return bool
726
     */
727
    abstract public function isExport();
728
729
    /**
730
     * Determin if the renderer is HTML
731
     * It can be export + html -> f.x.
732
     * printing for HTML.
733
     *
734
     * @return bool
735
     */
736
    abstract public function isHtml();
737
738
    /**
739
     * Execute all...
740
     *
741
     * @return ViewModel Response\Stream
742
     */
743
    abstract public function execute();
744
}
745