IndexController::getFilteredData()   B
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
c 2
b 2
f 0
dl 0
loc 25
rs 8.439
cc 5
eloc 13
nc 8
nop 0
1
<?php
2
3
namespace LearnZF2Pagination\Controller;
4
5
use Zend\Mvc\Controller\AbstractActionController;
6
use Zend\Paginator\Adapter\ArrayAdapter;
7
use Zend\Paginator\Paginator;
8
use Zend\View\Model\ViewModel;
9
10
class IndexController extends AbstractActionController
11
{
12
    const ITEM_PER_PAGE = 4;
13
14
    /**
15
     * @var array
16
     */
17
    protected $data;
18
19
    public function __construct(array $data)
20
    {
21
        $this->data = $data;
22
    }
23
24
    public function indexAction()
25
    {
26
        $data = $this->getFilteredData();
27
        $page = $this->params()->fromQuery('page', 1);
28
        // Paginate filtered data
29
        $paginator = new Paginator(new ArrayAdapter($data));
30
        $paginator->setCurrentPageNumber($page)
31
                  ->setItemCountPerPage(self::ITEM_PER_PAGE);
32
33
        return new ViewModel(array_merge($this->params()->fromQuery(), ['paginator' => $paginator]));
34
    }
35
36
    /**
37
     * @return array
38
     */
39
    protected function getFilteredData()
40
    {
41
        // Filter by category
42
        $category = $this->params()->fromQuery('category', '');
43
        $data = array_key_exists($category, $this->data) ? $this->data[$category] : array_merge(
44
            $this->data['movies'],
45
            $this->data['books'],
46
            $this->data['music']
47
        );
48
49
        // Filter by keyword
50
        $keyword = $this->params()->fromQuery('keyword');
51
        if (empty($keyword)) {
52
            return $data;
53
        }
54
55
        // Remove those elements which doesn't accomplish the keyword condition
56
        foreach ($data as $key => $element) {
57
            if (!$this->isKeywordInTitle($keyword, $element['title'])) {
58
                unset($data[$key]);
59
            }
60
        }
61
62
        return $data;
63
    }
64
65
    /**
66
     * Triws to find certain keyword in provided title.
67
     *
68
     * @param $keyword
69
     * @param $title
70
     *
71
     * @return bool
72
     */
73
    protected function isKeywordInTitle($keyword, $title)
74
    {
75
        $pos = strpos(strtolower($title), strtolower($keyword));
76
77
        return is_int($pos);
78
    }
79
}
80