Test Failed
Push — newinternal ( 8c4587...b2f220 )
by Michael
15:41 queued 06:17
created

PageJobQueue::all()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 65
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 37
c 1
b 0
f 0
dl 0
loc 65
rs 8.7057
cc 6
nc 32
nop 0

How to fix   Long Method   

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
 * Wikipedia Account Creation Assistance tool                                 *
4
 *                                                                            *
5
 * All code in this file is released into the public domain by the ACC        *
6
 * Development Team. Please see team.json for a list of contributors.         *
7
 ******************************************************************************/
8
9
namespace Waca\Pages;
10
11
use Waca\DataObjects\EmailTemplate;
12
use Waca\DataObjects\JobQueue;
13
use Waca\DataObjects\Log;
14
use Waca\DataObjects\Request;
15
use Waca\DataObjects\User;
16
use Waca\Exceptions\ApplicationLogicException;
17
use Waca\Helpers\Logger;
18
use Waca\Helpers\LogHelper;
19
use Waca\Helpers\SearchHelpers\JobQueueSearchHelper;
20
use Waca\Helpers\SearchHelpers\LogSearchHelper;
21
use Waca\Helpers\SearchHelpers\RequestSearchHelper;
22
use Waca\Helpers\SearchHelpers\UserSearchHelper;
23
use Waca\RequestStatus;
24
use Waca\Tasks\PagedInternalPageBase;
25
use Waca\WebRequest;
26
27
class PageJobQueue extends PagedInternalPageBase
28
{
29
    /**
30
     * Main function for this page, when no specific actions are called.
31
     * @return void
32
     */
33
    protected function main()
34
    {
35
        $this->setHtmlTitle('Job Queue Management');
36
37
        $this->prepareMaps();
38
39
        $database = $this->getDatabase();
40
41
        /** @var JobQueue[] $jobList */
42
        $jobList = JobQueueSearchHelper::get($database)
43
            ->statusIn(array('ready', 'waiting', 'running', 'failed'))
44
            ->notAcknowledged()
45
            ->fetch();
46
47
        $userIds = array();
48
        $requestIds = array();
49
50
        foreach ($jobList as $job) {
51
            $userIds[] = $job->getTriggerUserId();
52
            $requestIds[] = $job->getRequest();
53
54
            $job->setDatabase($database);
55
        }
56
57
        $this->assign('canSeeAll', $this->barrierTest('all', User::getCurrent($database)));
58
59
        $this->assign('users', UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username'));
60
        $this->assign('requests', RequestSearchHelper::get($database)->inIds($requestIds)->fetchMap('name'));
61
62
        $this->assign('joblist', $jobList);
63
        $this->setTemplate('jobqueue/main.tpl');
64
    }
65
66
    protected function all()
67
    {
68
        $this->setHtmlTitle('All Jobs');
69
70
        $this->prepareMaps();
71
72
        $database = $this->getDatabase();
73
74
        $searchHelper = JobQueueSearchHelper::get($database);
75
        $this->setSearchHelper($searchHelper);
76
        $this->setupLimits();
77
78
        $filterUser = WebRequest::getString('filterUser');
79
        $filterTask = WebRequest::getString('filterTask');
80
        $filterStatus = WebRequest::getString('filterStatus');
81
        $filterRequest = WebRequest::getString('filterRequest');
82
83
        if ($filterUser !== null) {
84
            $searchHelper->byUser(User::getByUsername($filterUser, $database)->getId());
85
        }
86
87
        if ($filterTask !== null) {
88
            $searchHelper->byTask($filterTask);
89
        }
90
91
        if ($filterStatus !== null) {
92
            $searchHelper->byStatus($filterStatus);
93
        }
94
95
        if ($filterRequest !== null) {
96
            $searchHelper->byRequest($filterRequest);
0 ignored issues
show
Bug introduced by
$filterRequest of type string is incompatible with the type integer expected by parameter $request of Waca\Helpers\SearchHelpe...archHelper::byRequest(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

96
            $searchHelper->byRequest(/** @scrutinizer ignore-type */ $filterRequest);
Loading history...
97
        }
98
99
        /** @var JobQueue[] $jobList */
100
        $jobList = $searchHelper->getRecordCount($count)->fetch();
101
102
        $this->setupPageData($count, array(
103
            'filterUser' => $filterUser,
104
            'filterTask' => $filterTask,
105
            'filterStatus' => $filterStatus,
106
            'filterRequest' => $filterRequest,
107
        ));
108
109
        $userIds = array();
110
        $requestIds = array();
111
112
        foreach ($jobList as $job) {
113
            $userIds[] = $job->getTriggerUserId();
114
            $requestIds[] = $job->getRequest();
115
116
            $job->setDatabase($database);
117
        }
118
119
        $this->getTypeAheadHelper()->defineTypeAheadSource('username-typeahead', function() use ($database) {
120
            return UserSearchHelper::get($database)->fetchColumn('username');
121
        });
122
123
        $this->assign('users', UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username'));
124
        $this->assign('requests', RequestSearchHelper::get($database)->inIds($requestIds)->fetchMap('name'));
125
126
        $this->assign('joblist', $jobList);
127
128
        $this->addJs("/api.php?action=users&all=true&targetVariable=typeaheaddata");
129
130
        $this->setTemplate('jobqueue/all.tpl');
131
    }
132
133
    protected function view()
134
    {
135
        $jobId = WebRequest::getInt('id');
136
        $database = $this->getDatabase();
137
138
        if ($jobId === null) {
139
            throw new ApplicationLogicException('No job specified');
140
        }
141
142
        /** @var JobQueue $job */
143
        $job = JobQueue::getById($jobId, $database);
144
145
        if ($job === false) {
0 ignored issues
show
introduced by
The condition $job === false is always false.
Loading history...
146
            throw new ApplicationLogicException('Could not find requested job');
147
        }
148
149
        $this->prepareMaps();
150
151
        $this->assign('user', User::getById($job->getTriggerUserId(), $database));
152
        $this->assign('request', Request::getById($job->getRequest(), $database));
153
        $this->assign('emailTemplate', EmailTemplate::getById($job->getEmailTemplate(), $database));
154
        $this->assign('parent', JobQueue::getById($job->getParent(), $database));
155
156
        /** @var Log[] $logs */
157
        $logs = LogSearchHelper::get($database)->byObjectType('JobQueue')
158
            ->byObjectId($job->getId())->getRecordCount($logCount)->fetch();
159
        if ($logCount === 0) {
160
            $this->assign('log', array());
161
        }
162
        else {
163
            list($users, $logData) = LogHelper::prepareLogsForTemplate($logs, $database, $this->getSiteConfiguration());
164
165
            $this->assign("log", $logData);
166
            $this->assign("users", $users);
167
        }
168
169
        $this->assignCSRFToken();
170
171
        $this->assign('job', $job);
172
173
        $this->assign('canAcknowledge', $this->barrierTest('acknowledge', User::getCurrent($database)));
174
        $this->assign('canRequeue', $this->barrierTest('requeue', User::getCurrent($database)));
175
176
        $this->setHtmlTitle('Job #{$job->getId()|escape}');
177
        $this->setTemplate('jobqueue/view.tpl');
178
    }
179
180
    protected function acknowledge()
181
    {
182
        if (!WebRequest::wasPosted()) {
183
            throw new ApplicationLogicException('This page does not support GET methods.');
184
        }
185
186
        $this->validateCSRFToken();
187
188
        $jobId = WebRequest::postInt('job');
189
        $database = $this->getDatabase();
190
191
        if ($jobId === null) {
192
            throw new ApplicationLogicException('No job specified');
193
        }
194
195
        /** @var JobQueue $job */
196
        $job = JobQueue::getById($jobId, $database);
197
198
        if ($job === false) {
0 ignored issues
show
introduced by
The condition $job === false is always false.
Loading history...
199
            throw new ApplicationLogicException('Could not find requested job');
200
        }
201
202
        $job->setUpdateVersion(WebRequest::postInt('updateVersion'));
203
        $job->setAcknowledged(true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type integer expected by parameter $acknowledged of Waca\DataObjects\JobQueue::setAcknowledged(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

203
        $job->setAcknowledged(/** @scrutinizer ignore-type */ true);
Loading history...
204
        $job->save();
205
206
        Logger::backgroundJobAcknowledged($database, $job);
207
208
        $this->redirect('jobQueue', 'view', array('id' => $jobId));
209
    }
210
211
    protected function requeue()
212
    {
213
        if (!WebRequest::wasPosted()) {
214
            throw new ApplicationLogicException('This page does not support GET methods.');
215
        }
216
217
        $this->validateCSRFToken();
218
219
        $jobId = WebRequest::postInt('job');
220
        $database = $this->getDatabase();
221
222
        if ($jobId === null) {
223
            throw new ApplicationLogicException('No job specified');
224
        }
225
226
        /** @var JobQueue $job */
227
        $job = JobQueue::getById($jobId, $database);
228
229
        if ($job === false) {
0 ignored issues
show
introduced by
The condition $job === false is always false.
Loading history...
230
            throw new ApplicationLogicException('Could not find requested job');
231
        }
232
233
        $job->setStatus(JobQueue::STATUS_READY);
234
        $job->setUpdateVersion(WebRequest::postInt('updateVersion'));
235
        $job->setAcknowledged(null);
236
        $job->setError(null);
237
        $job->save();
238
239
        /** @var Request $request */
240
        $request = Request::getById($job->getRequest(), $database);
241
        $request->setStatus(RequestStatus::JOBQUEUE);
242
        $request->save();
243
244
        Logger::enqueuedJobQueue($database, $request);
245
        Logger::backgroundJobRequeued($database, $job);
246
247
        $this->redirect('jobQueue', 'view', array('id' => $jobId));
248
    }
249
250
    protected function prepareMaps()
251
    {
252
        $taskNameMap = JobQueue::getTaskDescriptions();
253
254
        $statusDecriptionMap = array(
255
            JobQueue::STATUS_CANCELLED => 'The job was cancelled',
256
            JobQueue::STATUS_COMPLETE  => 'The job completed successfully',
257
            JobQueue::STATUS_FAILED    => 'The job encountered an error',
258
            JobQueue::STATUS_READY     => 'The job is ready to be picked up by the next job runner execution',
259
            JobQueue::STATUS_RUNNING   => 'The job is being run right now by the job runner',
260
            JobQueue::STATUS_WAITING   => 'The job has been picked up by a job runner',
261
            JobQueue::STATUS_HELD      => 'The job has manually held from processing',
262
        );
263
        $this->assign('taskNameMap', $taskNameMap);
264
        $this->assign('statusDescriptionMap', $statusDecriptionMap);
265
    }
266
}
267