Completed
Pull Request — master (#40)
by Matthew
17:20
created

QueueController::jobsAllAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 12
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 12
loc 12
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Dtc\QueueBundle\Controller;
4
5
use Dtc\QueueBundle\Doctrine\DoctrineJobManager;
6
use Dtc\QueueBundle\Exception\UnsupportedException;
7
use Dtc\QueueBundle\Model\BaseJob;
8
use Dtc\QueueBundle\Model\Worker;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
12
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\StreamedResponse;
15
16
class QueueController extends Controller
17
{
18
    use ControllerTrait;
19
20
    /**
21
     * Summary stats.
22
     *
23
     * @Route("/")
24 1
     * @Route("/status/")
25
     * @Template("@DtcQueue/Queue/status.html.twig")
26 1
     */
27 1
    public function statusAction()
28
    {
29 1
        $params = array();
30 1
        $jobManager = $this->get('dtc_queue.manager.job');
31
32 1
        $params['status'] = $jobManager->getStatus();
33
        $this->addCssJs($params);
34
35
        return $params;
36
    }
37
38
    /**
39
     * List jobs in system by default.
40 1
     *
41
     * @Route("/jobs_all", name="dtc_queue_jobs_all")
42 1
     *
43 1
     * @throws UnsupportedException
44 1
     */
45 1 View Code Duplication
    public function jobsAllAction()
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...
46 1
    {
47
        $this->validateManagerType('dtc_queue.manager.job');
48 1
        $class1 = $this->container->getParameter('dtc_queue.class.job');
49
        $class2 = $this->container->getParameter('dtc_queue.class.job_archive');
50 1
        $label1 = 'Non-Archived Jobs';
51
        $label2 = 'Archived Jobs';
52
53
        $params = $this->getDualGridParams($class1, $class2, $label1, $label2);
54
55
        return $this->render('@DtcQueue/Queue/grid.html.twig', $params);
56
    }
57 1
58
    /**
59 1
     * @Route("/archive", name="dtc_queue_archive")
60 1
     * @Method({"POST"})
61
     *
62 1
     * @throws UnsupportedException
63
     */
64
    public function archiveAction(Request $request)
65
    {
66
        return $this->streamResults($request, 'archiveAllJobs');
67 1
    }
68
69 1
    /**
70
     * @Route("/reset-stalled", name="dtc_queue_reset_stalled")
71
     *
72
     * @param Request $request
73
     *
74
     * @return StreamedResponse
75
     *
76
     * @throws UnsupportedException
77 1
     */
78 1
    public function resetStalledAction(Request $request)
79
    {
80 1
        return $this->streamResults($request, 'resetStalledJobs');
81
    }
82
83
    /**
84
     * @Route("/prune-stalled", name="dtc_queue_prune_stalled")
85
     *
86
     * @param Request $request
87
     *
88
     * @return StreamedResponse
89 1
     *
90
     * @throws UnsupportedException
91 1
     */
92 1
    public function pruneStalledAction(Request $request)
93 1
    {
94 1
        return $this->streamResults($request, 'pruneStalledJobs');
95 1
    }
96 1
97 1
    /**
98 1
     * @param Request $request
99
     * @param $functionName
100 1
     *
101
     * @return StreamedResponse
102 1
     *
103
     * @throws UnsupportedException
104
     */
105
    public function streamResults(Request $request, $functionName)
106
    {
107
        $jobManager = $this->get('dtc_queue.manager.job');
108
        if (!$jobManager instanceof DoctrineJobManager) {
109
            throw new UnsupportedException('$jobManager must be instance of '.DoctrineJobManager::class);
110
        }
111 1
112
        $streamingResponse = new StreamedResponse($this->getStreamFunction($request, $functionName));
113 1
        $streamingResponse->headers->set('Content-Type', 'application/x-ndjson');
114 1
        $streamingResponse->headers->set('X-Accel-Buffering', 'no');
115 1
116 1
        return $streamingResponse;
117 1
    }
118 1
119 1
    /**
120 1
     * @param Request $request
121
     * @param string  $functionName
122 1
     *
123
     * @return \Closure
124
     */
125
    protected function getStreamFunction(Request $request, $functionName)
126
    {
127
        $jobManager = $this->get('dtc_queue.manager.job');
128
        $workerName = $request->get('workerName');
129
        $methodName = $request->get('method');
130
        $total = null;
131
        $callback = function ($count, $totalCount) use (&$total) {
132
            if (null !== $totalCount && null === $total) {
133
                $total = $totalCount;
134
                echo json_encode(['total' => $total]);
135 2
                echo "\n";
136
                flush();
137 2
138 2
                return;
139 2
            }
140 2
            echo json_encode(['count' => $count]);
141 2
            echo "\n";
142
            flush();
143 2
        };
144 2
145 2
        return function () use ($jobManager, $callback, $workerName, $methodName, $functionName, &$total) {
146 2
            switch ($functionName) {
147
                case 'archiveAllJobs':
148 2
                    $total = $jobManager->countLiveJobs($workerName, $methodName);
149
                    echo json_encode(['total' => $total]);
150 2
                    echo "\n";
151 2
                    flush();
152 2
                    if ($total > 0) {
153
                        $jobManager->archiveAllJobs($workerName, $methodName, $callback);
154 2
                    }
155
                    break;
156
                default:
157
                    $jobManager->$functionName($workerName, $methodName, $callback);
158
                    break;
159
            }
160
        };
161
    }
162 1
163
    /**
164 1
     * List jobs in system by default.
165 1
     *
166 1
     * @Template("@DtcQueue/Queue/jobs.html.twig")
167 1
     * @Route("/jobs", name="dtc_queue_jobs")
168 1
     *
169
     * @throws UnsupportedException
170 1
     */
171 View Code Duplication
    public function jobsAction()
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...
172 1
    {
173
        $this->validateManagerType('dtc_queue.manager.job');
174
        $managerType = $this->container->getParameter('dtc_queue.manager.job');
175
        $rendererFactory = $this->get('dtc_grid.renderer.factory');
176
        $renderer = $rendererFactory->create('datatables');
177
        $gridSource = $this->get('dtc_queue.grid_source.jobs_waiting.'.('mongodb' === $managerType ? 'odm' : $managerType));
178
        $renderer->bind($gridSource);
179
        $params = $renderer->getParams();
180
        $this->addCssJs($params);
181 1
182
        $params['worker_methods'] = $this->get('dtc_queue.manager.job')->getWorkersAndMethods();
183 1
        $params['prompt_message'] = 'This will archive all non-running jobs';
184 1
185
        return $params;
186 1
    }
187 1
188
    /**
189
     * List jobs in system by default.
190 1
     *
191 1
     * @Template("@DtcQueue/Queue/jobs_running.html.twig")
192 1
     * @Route("/jobs_running", name="dtc_queue_jobs_running")
193
     */
194 1 View Code Duplication
    public function runningJobsAction()
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...
195
    {
196
        $this->validateManagerType('dtc_queue.manager.job');
197
        $managerType = $this->container->getParameter('dtc_queue.manager.job');
198
        $rendererFactory = $this->get('dtc_grid.renderer.factory');
199
        $renderer = $rendererFactory->create('datatables');
200
        $gridSource = $this->get('dtc_queue.grid_source.jobs_running.'.('mongodb' === $managerType ? 'odm' : $managerType));
201
        $renderer->bind($gridSource);
202
        $params = $renderer->getParams();
203
        $this->addCssJs($params);
204
205
        $params['worker_methods'] = $this->get('dtc_queue.manager.job')->getWorkersAndMethods(BaseJob::STATUS_RUNNING);
206
        $params['prompt_message'] = 'This will prune all stalled jobs';
207
208
        return $params;
209
    }
210
211
    /**
212
     * @param string $class1
213
     * @param string $class2
214
     * @param string $label1
215
     * @param string $label2
216
     *
217
     * @return \Symfony\Component\HttpFoundation\Response
218
     *
219
     * @throws \Exception
220
     */
221
    protected function getDualGridParams($class1, $class2, $label1, $label2)
222
    {
223
        $rendererFactory = $this->get('dtc_grid.renderer.factory');
224
        $renderer = $rendererFactory->create('datatables');
225
        $gridSource = $this->get('dtc_grid.manager.source')->get($class1);
226
        $renderer->bind($gridSource);
227
        $params = $renderer->getParams();
228
229
        $renderer2 = $rendererFactory->create('datatables');
230
        $gridSource = $this->get('dtc_grid.manager.source')->get($class2);
231
        $renderer2->bind($gridSource);
232
        $params2 = $renderer2->getParams();
233
234
        $params['archive_grid'] = $params2['dtc_grid'];
235
236
        $params['dtc_queue_grid_label1'] = $label1;
237
        $params['dtc_queue_grid_label2'] = $label2;
238
        $this->addCssJs($params);
239
240
        return $params;
241
    }
242
243
    /**
244
     * List jobs in system by default.
245
     *
246
     * @Route("/runs", name="dtc_queue_runs")
247
     */
248 View Code Duplication
    public function runsAction()
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...
249
    {
250
        $this->validateRunManager();
251
        $class1 = $this->container->getParameter('dtc_queue.class.run');
252
        $class2 = $this->container->getParameter('dtc_queue.class.run_archive');
253
        $label1 = 'Live Runs';
254
        $label2 = 'Archived Runs';
255
256
        $params = $this->getDualGridParams($class1, $class2, $label1, $label2);
257
258
        return $this->render('@DtcQueue/Queue/grid.html.twig', $params);
259
    }
260
261
    /**
262
     * List registered workers in the system.
263
     *
264
     * @Route("/workers", name="dtc_queue_workers")
265
     * @Template("@DtcQueue/Queue/workers.html.twig")
266
     */
267
    public function workersAction()
268
    {
269
        $workerManager = $this->get('dtc_queue.manager.worker');
270
        $workers = $workerManager->getWorkers();
271
272
        $workerList = [];
273
        foreach ($workers as $workerName => $worker) {
274
            /* @var Worker $worker */
275
            $workerList[$workerName] = get_class($worker);
276
        }
277
        $params = ['workers' => $workerList];
278
        $this->addCssJs($params);
279
280
        return $params;
281
    }
282
}
283