Completed
Push — master ( 2d0ab0...3edfb6 )
by Adrien
03:09
created

MovieController::indexAction()   C

Complexity

Conditions 14
Paths 145

Size

Total Lines 71
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 18.4

Importance

Changes 0
Metric Value
cc 14
eloc 40
nc 145
nop 0
dl 0
loc 71
rs 5.1254
c 0
b 0
f 0
ccs 28
cts 39
cp 0.7179
crap 18.4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
class MovieController extends Zend_Controller_Action
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
4
{
5 3
    public function init(): void
6
    {
7
        // Init the Context Switch Action helper
8 3
        $contextSwitch = $this->_helper->contextSwitch();
9
10
        // Add the new context
11 3
        $contextSwitch->setContexts([
12 3
            'csv' => ['suffix' => 'csv'],
13
            'rss' => ['suffix' => 'rss'],
14
        ]);
15
16 3
        $contextSwitch->addActionContext('index', 'csv')->addActionContext('index', 'rss')->initContext();
17 3
    }
18
19 1
    public function indexAction(): void
20
    {
21
        // Check there is at least one user, otherwise the whole page will crash
22 1
        if (!\mQueue\Model\User::getCurrent() && !\mQueue\Model\UserMapper::getDbTable()->fetchRow()) {
23
            throw new Exception('At least one user must exist to access this page');
24
        }
25
26 1
        $form = new \mQueue\Form\Filters();
27 1
        $this->view->formFilter = $form;
28
29
        // Detect if at least one filter was submitted
30 1
        $submitted = false;
31 1
        foreach ($this->getRequest()->getParams() as $key => $filter) {
32 1
            if (preg_match('/^filter\d+$/', $key)) {
33 1
                $submitted = true;
34
            }
35
        }
36
37
        // If was submitted, try to validate values
38 1
        if ($submitted) {
39
            if (!$form->isValid($this->getRequest()->getParams())) {
40
                $this->_helper->FlashMessenger(['warning' => _tr('Filter is invalid.')]);
41
                $form->setDefaults([]);
42
            }
43
        }
44
        // If we submitted a quicksearch, set default values to search with any status
45 1
        elseif ($this->_getParam('search')) {
46
            $form->setDefaults([
47
                'filter1' => [
48
                    'user' => \mQueue\Model\User::getCurrent() ? 0 : \mQueue\Model\UserMapper::fetchAll()->current()->id,
49
                    'condition' => 'is',
50
                    'status' => array_merge([0], array_keys(mQueue\Model\Status::$ratings)),
51
                    'title' => $this->_getParam('search'),
52
                ],
53
            ]);
54
        }
55
        // Otherwise clear the filter
56
        else {
57 1
            $form->setDefaults([]);
58
        }
59
60
        // Gather users selected in filters
61 1
        $this->view->users = [];
62 1
        $filters = $form->getValues();
63 1
        foreach ($filters as $key => $filter) {
64 1
            if (!preg_match('/^filter\d+$/', $key)) {
65 1
                continue;
66
            }
67
68 1
            $this->view->users[$filter['user']] = \mQueue\Model\UserMapper::find($filter['user']);
69
        }
70
71
        // If we ouput rss, we force sorting by date
72 1
        if ($this->_helper->contextSwitch()->getCurrentContext() == 'rss') {
73
            $this->getRequest()->setParam('sort', $filters['filter1']['withSource'] ? 'dateSearch' : 'date');
74
            $this->getRequest()->setParam('sortOrder', 'desc');
75
        }
76 1
        $this->view->permanentParams = $form->getValues();
77 1
        $this->view->filterName = $form->getValuesText();
78 1
        unset($this->view->permanentParams['addFilter']);
79
80 1
        $allowedSortingKey = ['title', 'date', 'dateSearch'];
81 1
        $usersCount = count($this->view->users);
82 1
        for ($i = 0; $i < $usersCount; ++$i) {
83 1
            $allowedSortingKey[] = 'status' . $i;
84
        }
85 1
        $sort = $this->_helper->createSorting('sort', $allowedSortingKey);
86
87
        // Set up the paginator: Apply pagination only if there is no special context (so it is normal html rendering)
88 1
        $this->view->paginator = $this->_helper->createPaginator(\mQueue\Model\MovieMapper::getFilteredQuery($filters, $sort));
89 1
    }
90
91 View Code Duplication
    public function viewAction(): void
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...
92
    {
93
        if ($this->getRequest()->getParam('id')) {
94
            $this->view->movie = \mQueue\Model\MovieMapper::find($this->getRequest()->getParam('id'));
95
        }
96
97
        if (!$this->view->movie) {
98
            throw new Exception($this->view->translate('Movie not found'));
99
        }
100
101
        $this->view->users = \mQueue\Model\UserMapper::fetchAll();
102
        $this->view->movieActivity = $this->_helper->createPaginator(\mQueue\Model\StatusMapper::getActivityQuery($this->view->movie));
103
    }
104
105 1
    public function addAction(): void
106
    {
107 1
        $request = $this->getRequest();
108 1
        $form = new \mQueue\Form\Movie();
109
110 1
        if ($this->_getParam('id')) {
111
            if ($form->isValid($request->getParams())) {
112
                $values = $form->getValues();
113
                $movie = \mQueue\Model\MovieMapper::find(\mQueue\Model\Movie::extractId($values['id']));
114
                if (!$movie) {
115
                    $movie = \mQueue\Model\MovieMapper::getDbTable()->createRow();
116
                    $movie->setId($values['id']);
117
                    $movie->save();
118
                    $this->_helper->FlashMessenger(_tr('A movie was added.'));
119
                }
120
121
                $this->view->movies = [$movie];
122
            }
123
        }
124
125 1
        $this->view->form = $form;
126 1
    }
127
128 1
    public function importAction(): void
129
    {
130 1
        $request = $this->getRequest();
131 1
        $form = new \mQueue\Form\Import();
132 1
        $form->setDefaults(['favoriteMinimum' => 9, 'excellentMinimum' => 7, 'okMinimum' => 5]);
133 1
        $this->view->form = $form;
134
135 1
        if ($this->getRequest()->isPost() && $form->isValid($request->getPost())) {
136
            if (\mQueue\Model\User::getCurrent() == null) {
137
                $this->_helper->FlashMessenger(['error' => _tr('You must be logged in.')]);
138
139
                return;
140
            }
141
142
            $values = $form->getValues();
143
            $page = file_get_contents($values['url']);
144
145
            $pattern = '|<a href="/title/tt(\d{7})/">.*</td>\s*<td.*>(\d+(\.\d)*)</td>|U';
146
            preg_match_all($pattern, $page, $matches);
147
148
            $movies = [];
149
            $matchesCount = count($matches[1]);
150
            for ($i = 0; $i < $matchesCount; ++$i) {
151
                $id = $matches[1][$i];
152
                $imdbRating = $matches[2][$i];
153
154
                $movie = \mQueue\Model\MovieMapper::find($id);
155
                if (!$movie) {
156
                    $movie = \mQueue\Model\MovieMapper::getDbTable()->createRow();
157
                    $movie->setId($id);
158
                    $movie->save();
159
                }
160
161
                if ($imdbRating >= $values['favoriteMinimum']) {
162
                    $rating = \mQueue\Model\Status::Favorite;
163
                } elseif ($imdbRating >= $values['excellentMinimum']) {
164
                    $rating = \mQueue\Model\Status::Excellent;
165
                } elseif ($imdbRating >= $values['okMinimum']) {
166
                    $rating = \mQueue\Model\Status::Ok;
167
                } else {
168
                    $rating = \mQueue\Model\Status::Bad;
169
                }
170
171
                $movie->setStatus(\mQueue\Model\User::getCurrent(), $rating);
172
                $movies[] = $movie;
173
            }
174
175
            $count = count($movies);
176
            if ($count) {
177
                $this->_helper->FlashMessenger(_tr('Movies imported.'));
178
                $this->view->movies = $movies;
179
            } else {
180
                $this->_helper->FlashMessenger(['warning' => _tr('No movies found for import.')]);
181
            }
182
        }
183 1
    }
184
}
185