Passed
Pull Request — master (#141)
by Matthew
19:49
created

TrendsController::getDatabasePlatform()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Dtc\QueueBundle\Controller;
4
5
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Platforms\MariaDb1027Platform was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Doctrine\DBAL\Platforms\MySqlPlatform;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Platforms\MySqlPlatform was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Doctrine\DBAL\Platforms\OraclePlatform;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Platforms\OraclePlatform was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Platforms\PostgreSqlPlatform was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use Doctrine\DBAL\Platforms\SqlitePlatform;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Platforms\SqlitePlatform was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Doctrine\ODM\MongoDB\DocumentManager;
0 ignored issues
show
Bug introduced by
The type Doctrine\ODM\MongoDB\DocumentManager was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Doctrine\ORM\EntityManager;
0 ignored issues
show
Bug introduced by
The type Doctrine\ORM\EntityManager was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Dtc\QueueBundle\Doctrine\DoctrineJobTimingManager;
13
use Dtc\QueueBundle\Model\JobTiming;
14
use Dtc\QueueBundle\ODM\JobManager;
15
use Dtc\QueueBundle\ODM\JobTimingManager;
16
use Symfony\Component\DependencyInjection\ContainerInterface;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Depend...tion\ContainerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
use Symfony\Component\HttpFoundation\JsonResponse;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpFoundation\JsonResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use Symfony\Component\HttpFoundation\Request;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpFoundation\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
20
class TrendsController
21 2
{
22
    use ControllerTrait;
23 2
24 2
    private $container;
25
26
    public function __construct(ContainerInterface $container)
27
    {
28
        $this->container = $container;
29 1
    }
30
31 1
    public function getDatabasePlatform(\Dtc\QueueBundle\ORM\JobTimingManager $jobTimingManager)
32 1
    {
33 1
        $connection = $jobTimingManager->getObjectManager()->getConnection();
34 1
        if (method_exists($connection, 'getDatabasePlatform')) {
35
            return $connection->getDatabasePlatform();
36 1
        }
37
38
        return null;
39 1
    }
40
41 1
    private function testForYearFunction(\Dtc\QueueBundle\ORM\JobTimingManager $jobTimingManager)
42 1
    {
43 1
        $foundYearFunction = false;
44 1
        $platform = $this->getDatabasePlatform($jobTimingManager);
45 1
        $reason = 'Platform: '.get_class($platform).' not supported';
46
        if ($platform instanceof MySqlPlatform || $platform instanceof MariaDb1027Platform) {
47
            $foundYearFunction = class_exists('Oro\ORM\Query\AST\Platform\Functions\Mysql\Year') || class_exists('DoctrineExtensions\Query\Mysql\Year');
48 1
            $reason = "<h2>Please install (composer require) one of the following:</h2>\n<pre>\noro/doctrine-extensions\nbeberlei/DoctrineExtensions</pre>";
49 1
        } elseif ($platform instanceof PostgreSqlPlatform) {
50 1
            $foundYearFunction = class_exists('Oro\ORM\Query\AST\Platform\Functions\Postgresql\Year') || class_exists('DoctrineExtensions\Query\Postgresql\Year');
51
            $reason = "<h2>Please install (composer require) one of the following:</h2>\n<pre>\noro/doctrine-extensions\nbeberlei/DoctrineExtensions</pre>";
52
        } elseif ($platform instanceof OraclePlatform) {
53 1
            $foundYearFunction = class_exists('DoctrineExtensions\Query\Oracle\Year');
54 1
            $reason = "<h2>Please install (composer require) the following:</h2><pre>\nbeberlei/DoctrineExtensions</pre>";
55 1
        } elseif ($platform instanceof SqlitePlatform) {
56 1
            $foundYearFunction = class_exists('DoctrineExtensions\Query\Sqlite\Year');
57
            $reason = "<h2>Please install (composer require) the following:</h2><pre>\nbeberlei/DoctrineExtensions</pre>";
58
        }
59 1
60
        return [$foundYearFunction, $reason];
61
    }
62
63
    /**
64
     * Show a graph of job trends.
65
     */
66 1
    public function trends()
67
    {
68 1
        $recordTimings = $this->container->getParameter('dtc_queue.timings.record');
69 1
        $jobTimingManager = $this->container->get('dtc_queue.manager.job_timing');
70
        $foundYearFunction = true;
71
        $reason = null;
72 1
        if ($jobTimingManager instanceof \Dtc\QueueBundle\ORM\JobTimingManager) {
73 1
            list($foundYearFunction, $reason) = $this->testForYearFunction($jobTimingManager);
74 1
        }
75
        $params = ['record_timings' => $recordTimings, 'states' => JobTiming::getStates(), 'found_year_function' => $foundYearFunction, 'found_year_reason' => $reason];
76 1
        $this->addCssJs($params);
77
78
        return $this->render('@DtcQueue/Queue/trends.html.twig', $params);
79 1
    }
80 1
81 1
    public function timings(Request $request)
82 1
    {
83 1
        $begin = $request->query->get('begin');
84
        $end = $request->query->get('end');
85 1
        $type = $request->query->get('type', 'HOUR');
86 1
        $beginDate = \DateTime::createFromFormat('Y-m-d\TH:i:s.uO', $begin) ?: null;
87
        if ($beginDate instanceof \DateTime) {
88
            $beginDate->setTimezone(new \DateTimeZone(date_default_timezone_get()));
89 1
        }
90 1
        $endDate = \DateTime::createFromFormat('Y-m-d\TH:i:s.uO', $end) ?: \Dtc\QueueBundle\Util\Util::getMicrotimeDateTime();
91
        if ($endDate instanceof \DateTime) {
0 ignored issues
show
introduced by
$endDate is always a sub-type of DateTime.
Loading history...
92
            $endDate->setTimezone(new \DateTimeZone(date_default_timezone_get()));
93
        }
94
95
        $recordTimings = $this->container->getParameter('dtc_queue.timings.record');
96
        $params = [];
97
        if ($recordTimings) {
98
            $params = $this->calculateTimings($type, $beginDate, $endDate);
99
        }
100
101
        return new JsonResponse($params);
102
    }
103 1
104
    /**
105 1
     * @param \DateTime|null $beginDate
106 1
     * @param \DateTime      $endDate
107 1
     */
108 1
    protected function calculateTimings($type, $beginDate, $endDate)
109
    {
110 1
        $params = [];
111
        $this->validateJobTimingManager();
112
113
        /** @var DoctrineJobTimingManager $jobTimingManager */
114
        $jobTimingManager = $this->container->get('dtc_queue.manager.job_timing');
115
        if ($jobTimingManager instanceof JobTimingManager) {
116
            $timings = $this->getJobTimingsOdm($type, $endDate, $beginDate);
117
        } else {
118
            $timings = $this->getJobTimingsOrm($type, $endDate, $beginDate);
119
        }
120 1
121
        $timingStates = JobTiming::getStates();
122 1
        $timingsDates = [];
123 1
        foreach (array_keys($timingStates) as $state) {
124 1
            if (!isset($timings[$state])) {
125 1
                continue;
126 1
            }
127
            $timingsData = $timings[$state];
128
            $timingsDates = array_unique(array_merge(array_keys($timingsData), $timingsDates));
129 1
        }
130 1
131
        $format = $this->getDateFormat($type);
132
        usort($timingsDates, function ($date1str, $date2str) use ($format) {
133
            $date1 = \DateTime::createFromFormat($format, $date1str);
134 1
            $date2 = \DateTime::createFromFormat($format, $date2str);
135
            if (!$date2) {
136
                return false;
137 1
            }
138
            if (!$date1) {
139
                return false;
140 1
            }
141
            $date1->setTimezone(new \DateTimeZone(date_default_timezone_get()));
142 1
            $date2->setTimezone(new \DateTimeZone(date_default_timezone_get()));
143 1
144 1
            return $date1 > $date2;
145
        });
146
147 1
        $timingsDatesAdjusted = $this->getTimingsDatesAdjusted($timingsDates, $format);
148 1
        $this->setTimingsData($timingStates, $timings, $timingsDates, $params);
149 1
        $params['timings_dates'] = $timingsDates;
150
        $params['timings_dates_rfc3339'] = $timingsDatesAdjusted;
151
152 1
        return $params;
153
    }
154
155
    /**
156
     * Timings offset by timezone if necessary.
157
     *
158
     * @param string $format
159
     *
160 1
     * @return array
161
     */
162 1
    protected function getTimingsDatesAdjusted(array $timingsDates, $format)
163 1
    {
164 1
        $timezoneOffset = $this->container->getParameter('dtc_queue.timings.timezone_offset');
165 1
        $timingsDatesAdjusted = [];
166 1
        foreach ($timingsDates as $dateStr) {
167 1
            $date = \DateTime::createFromFormat($format, $dateStr);
168 1
            if (false === $date) {
169 1
                throw new \InvalidArgumentException("'$dateStr' is not in the right format: ".DATE_RFC3339);
170 1
            }
171 1
            $date->setTimezone(new \DateTimeZone(date_default_timezone_get()));
172 1
            if (0 !== $timezoneOffset) {
173 1
                // This may too simplistic in areas that observe DST - does the database or PHP code observe DST?
174 1
                $date->setTimestamp($date->getTimestamp() + ($timezoneOffset * 3600));
175 1
            }
176 1
            $timingsDatesAdjusted[] = $date->format(DATE_RFC3339);
177 1
        }
178 1
179 1
        return $timingsDatesAdjusted;
180 1
    }
181 1
182 1
    protected function setTimingsData(array $timingStates, array $timings, array $timingsDates, array &$params)
183 1
    {
184 1
        foreach (array_keys($timingStates) as $state) {
185 1
            if (!isset($timings[$state])) {
186 1
                continue;
187 1
            }
188 1
189 1
            $timingsData = $timings[$state];
190 1
            foreach ($timingsDates as $date) {
191 1
                $params['timings_data_'.$state][] = isset($timingsData[$date]) ? $timingsData[$date] : 0;
192 1
            }
193 1
        }
194 1
    }
195 1
196 1
    /**
197 1
     * @param string                                 $type
198
     * @param \Doctrine\ODM\MongoDB\Aggregation\Expr $expr
0 ignored issues
show
Bug introduced by
The type Doctrine\ODM\MongoDB\Aggregation\Expr was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
199
     *
200
     * @return mixed
201
     */
202
    protected function addJobTimingsDateInfo($type, $expr)
203
    {
204
        switch ($type) {
205
            case 'YEAR':
206
                return $expr->field('year')
207
                    ->year('$finishedAt');
208
            case 'MONTH':
209
                return $expr->field('year')
210
                    ->year('$finishedAt')
211
                    ->field('month')
212
                    ->month('$finishedAt');
213
            case 'DAY':
214
                return $expr->field('year')
215
                    ->year('$finishedAt')
216
                    ->field('month')
217
                    ->month('$finishedAt')
218
                    ->field('day')
219
                    ->dayOfMonth('$finishedAt');
220
            case 'HOUR':
221
                return $expr->field('year')
222
                    ->year('$finishedAt')
223
                    ->field('month')
224
                    ->month('$finishedAt')
225
                    ->field('day')
226
                    ->dayOfMonth('$finishedAt')
227
                    ->field('hour')
228
                    ->hour('$finishedAt');
229
            case 'MINUTE':
230
                return $expr->field('year')
231
                    ->year('$finishedAt')
232
                    ->field('month')
233
                    ->month('$finishedAt')
234
                    ->field('day')
235
                    ->dayOfMonth('$finishedAt')
236
                    ->field('hour')
237 1
                    ->hour('$finishedAt')
238
                    ->field('minute')
239
                    ->minute('$finishedAt');
240 1
            default:
241 1
                throw new \InvalidArgumentException("Unknown type $type");
242
        }
243
    }
244 1
245
    protected function getJobTImingsOdmMapReduce($builder, $type, \DateTime $end, \DateTime $begin = null)
246 1
    {
247 1
        $regexInfo = $this->getRegexDate($type);
248
        if (!$begin) {
249
            $begin = clone $end;
250
            $begin->sub($regexInfo['interval']);
251 1
        }
252 1
253 1
        $mapFunc = 'function() {
254 1
            var dateStr = this.finishedAt.toISOString();
255
            dateStr = dateStr.replace(/'.$regexInfo['replace']['regex']."/,'".$regexInfo['replace']['replacement']."');
256
            var dateBegin = new Date('".$begin->format('c')."');
257 1
            var dateEnd = new Date('".$end->format('c')."');
258 1
            if (this.finishedAt >= dateBegin && this.finishedAt <= dateEnd) {
259 1
                var result = {};
260 1
                result[dateStr] = 1;
261
                emit(this.status, result);
262
            }
263 1
        }";
264 1
265 1
        // Run a map reduce function get worker and status break down
266 1
        $reduceFunc = JobManager::REDUCE_FUNCTION;
267 1
        $builder->map($mapFunc)
268 1
            ->reduce($reduceFunc);
269 1
        $query = $builder->getQuery();
270 1
        $results = $query->execute();
271 1
        $resultHash = [];
272
        foreach ($results as $info) {
273 1
            $resultHash[$info['_id']] = $info['value'];
274 1
        }
275 1
276 1
        return $resultHash;
277 1
    }
278 1
279
    protected function getJobTimingsOdm($type, \DateTime $end, \DateTime $begin = null)
280
    {
281 1
        /** @var JobTimingManager $runManager */
282
        $jobTimingManager = $this->container->get('dtc_queue.manager.job_timing');
283
        $jobTimingClass = $jobTimingManager->getJobTimingClass();
284
285
        /** @var DocumentManager $documentManager */
286
        $documentManager = $jobTimingManager->getObjectManager();
287
288
        $builder = $documentManager->createQueryBuilder($jobTimingClass);
289
        if (method_exists($builder, 'map')) {
290
            return $this->getJobTimingsOdmMapReduce($builder, $type, $end, $begin);
291 1
        }
292
293 1
        $regexInfo = $this->getRegexDate($type);
294 1
        if (!$begin) {
295 1
            $begin = clone $end;
296 1
            $begin->sub($regexInfo['interval']);
297 1
        }
298 1
299 1
        $aggregationBuilder = $documentManager->createAggregationBuilder($jobTimingClass);
300 1
        $expr = $this->addJobTimingsDateInfo($type, $aggregationBuilder->expr());
301
        $expr = $expr->field('status')
302 1
                ->expression('$status');
303 1
304 1
        $aggregationBuilder
305 1
            ->match()
306 1
                ->field('finishedAt')
307
                ->gte($begin)
308 1
                ->lte($end)
309 1
            ->group()
310 1
                    ->field('id')
311 1
                    ->expression($expr)
312 1
                    ->field('value')
313 1
                    ->sum(1);
314
315 1
        $results = $aggregationBuilder->execute();
316
        $resultHash = [];
317
        foreach ($results as $result) {
318
            $key = $result['_id']['status'];
319
            $dateStr = $this->getAggregationResultDateStr($type, $result['_id']);
320
            $resultHash[$key][$dateStr] = $result['value'];
321 1
        }
322
323 1
        return $resultHash;
324 1
    }
325 1
326 1
    /**
327 1
     * Formats the aggregation result into the desired date string format.
328 1
     *
329 1
     * @param string $type
330 1
     *
331 1
     * @return string
332 1
     */
333 1
    protected function getAggregationResultDateStr($type, array $result)
334
    {
335
        switch ($type) {
336
            case 'YEAR':
337
                return $result['year'];
338
            case 'MONTH':
339 1
                return "{$result['year']}-".str_pad($result['month'], 2, '0', STR_PAD_LEFT);
340
            case 'DAY':
341 1
                $str = "{$result['year']}-".str_pad($result['month'], 2, '0', STR_PAD_LEFT);
342 1
                $str .= '-'.str_pad($result['day'], 2, '0', STR_PAD_LEFT);
343 1
344 1
                return $str;
345 1
            case 'HOUR':
346 1
                $str = "{$result['year']}-".str_pad($result['month'], 2, '0', STR_PAD_LEFT);
347 1
                $str .= '-'.str_pad($result['day'], 2, '0', STR_PAD_LEFT);
348 1
                $str .= ' '.str_pad($result['hour'], 2, '0', STR_PAD_LEFT);
349 1
350 1
                return $str;
351 1
            case 'MINUTE':
352 1
                $str = "{$result['year']}-".str_pad($result['month'], 2, '0', STR_PAD_LEFT);
353 1
                $str .= '-'.str_pad($result['day'], 2, '0', STR_PAD_LEFT);
354 1
                $str .= ' '.str_pad($result['hour'], 2, '0', STR_PAD_LEFT);
355 1
                $str .= ':'.str_pad($result['minute'], 2, '0', STR_PAD_LEFT);
356 1
357
                return $str;
358
            default:
359
                throw new \InvalidArgumentException("Invalid date format type '$type''");
360
        }
361 1
    }
362
363 1
    protected function getDateFormat($type)
364 1
    {
365 1
        switch ($type) {
366 1
            case 'YEAR':
367 1
                return 'Y';
368 1
            case 'MONTH':
369 1
                return 'Y-m';
370 1
            case 'DAY':
371 1
                return 'Y-m-d';
372 1
            case 'HOUR':
373 1
                return 'Y-m-d H';
374 1
            case 'MINUTE':
375 1
                return 'Y-m-d H:i';
376 1
            default:
377 1
                throw new \InvalidArgumentException("Invalid date format type '$type''");
378 1
        }
379
    }
380
381
    protected function getRegexDate($type)
382
    {
383 1
        switch ($type) {
384
            case 'YEAR':
385
                return ['replace' => ['regex' => '(\d+)\-(\d+)\-(\d+)T(\d+):(\d+):(\d+).+$', 'replacement' => '$1'],
386 1
                    'interval' => new \DateInterval('P10Y'), ];
387 1
            case 'MONTH':
388
                return ['replace' => ['regex' => '(\d+)\-(\d+)\-(\d+)T(\d+):(\d+):(\d+).+$', 'replacement' => '$1-$2'],
389 1
                    'interval' => new \DateInterval('P12M'), ];
390
            case 'DAY':
391 1
                return ['replace' => ['regex' => '(\d+)\-(\d+)\-(\d+)T(\d+):(\d+):(\d+).+$', 'replacement' => '$1-$2-$3'],
392
                    'interval' => new \DateInterval('P31D'), ];
393 1
            case 'HOUR':
394 1
                return ['replace' => ['regex' => '(\d+)\-(\d+)\-(\d+)T(\d+):(\d+):(\d+).+$', 'replacement' => '$1-$2-$3 $4'],
395 1
                    'interval' => new \DateInterval('PT24H'), ];
396
            case 'MINUTE':
397
                return ['replace' => ['regex' => '(\d+)\-(\d+)\-(\d+)T(\d+):(\d+):(\d+).+$', 'replacement' => '$1-$2-$3 $4:$5'],
398 1
                    'interval' => new \DateInterval('PT3600S'), ];
399 1
        }
400 1
        throw new \InvalidArgumentException("Invalid type $type");
401 1
    }
402 1
403 1
    protected function getOrmGroupBy($type)
404 1
    {
405 1
        switch ($type) {
406
            case 'YEAR':
407
                return ['groupby' => 'YEAR(j.finishedAt)',
408 1
                    'interval' => new \DateInterval('P10Y'), ];
409
            case 'MONTH':
410 1
                return ['groupby' => 'CONCAT(YEAR(j.finishedAt),\'-\',MONTH(j.finishedAt))',
411 1
                    'interval' => new \DateInterval('P12M'), ];
412 1
            case 'DAY':
413 1
                return ['groupby' => 'CONCAT(YEAR(j.finishedAt),\'-\',MONTH(j.finishedAt),\'-\',DAY(j.finishedAt))',
414
                    'interval' => new \DateInterval('P31D'), ];
415
            case 'HOUR':
416 1
                return ['groupby' => 'CONCAT(YEAR(j.finishedAt),\'-\',MONTH(j.finishedAt),\'-\',DAY(j.finishedAt),\' \',HOUR(j.finishedAt))',
417
                    'interval' => new \DateInterval('PT24H'), ];
418
            case 'MINUTE':
419 1
                return ['groupby' => 'CONCAT(YEAR(j.finishedAt),\'-\',MONTH(j.finishedAt),\'-\',DAY(j.finishedAt),\' \',HOUR(j.finishedAt),\':\',MINUTE(j.finishedAt))',
420
                    'interval' => new \DateInterval('PT3600S'), ];
421 1
        }
422
        throw new \InvalidArgumentException("Invalid type $type");
423
    }
424 1
425
    protected function getJobTimingsOrm($type, \DateTime $end, \DateTime $begin = null)
426 1
    {
427 1
        /** @var JobTimingManager $jobTimingManager */
428 1
        $jobTimingManager = $this->container->get('dtc_queue.manager.job_timing');
429
        $jobTimingClass = $jobTimingManager->getJobTimingClass();
430 1
        /** @var EntityManager $entityManager */
431 1
        $entityManager = $jobTimingManager->getObjectManager();
432 1
433
        $groupByInfo = $this->getOrmGroupBy($type);
434 1
435 1
        if (!$begin) {
436 1
            $begin = clone $end;
437 1
            $begin->sub($groupByInfo['interval']);
438
        }
439 1
440 1
        $queryBuilder = $entityManager->createQueryBuilder()->select("j.status as status, count(j.finishedAt) as thecount, {$groupByInfo['groupby']} as thedate")
441 1
            ->from($jobTimingClass, 'j')
442 1
            ->where('j.finishedAt <= :end')
443 1
            ->andWhere('j.finishedAt >= :begin')
444
            ->setParameter(':end', $end)
445 1
            ->setParameter(':begin', $begin)
446
            ->groupBy('status')
447
            ->addGroupBy('thedate');
448 1
449
        $result = $queryBuilder
450
            ->getQuery()->getArrayResult();
451
452
        $resultHash = [];
453
        foreach ($result as $row) {
454
            $date = $this->formatOrmDateTime($type, $row['thedate']);
455
            $resultHash[$row['status']][$date] = intval($row['thecount']);
456
        }
457
458
        return $resultHash;
459
    }
460
461
    protected function strPadLeft($str)
462
    {
463
        return str_pad($str, 2, '0', STR_PAD_LEFT);
464
    }
465
466
    protected function formatOrmDateTime($type, $str)
467
    {
468
        switch ($type) {
469
            case 'MONTH':
470
                $parts = explode('-', $str);
471
472
                return $parts[0].'-'.$this->strPadLeft($parts[1]);
473
            case 'DAY':
474
                $parts = explode('-', $str);
475
476
                return $parts[0].'-'.$this->strPadLeft($parts[1]).'-'.$this->strPadLeft($parts[2]);
477
            case 'HOUR':
478
                $parts = explode(' ', $str);
479
                $dateParts = explode('-', $parts[0]);
480
481
                return $dateParts[0].'-'.$this->strPadLeft($dateParts[1]).'-'.$this->strPadLeft($dateParts[2]).' '.$this->strPadLeft($parts[1]);
482
            case 'MINUTE':
483
                $parts = explode(' ', $str);
484
                $dateParts = explode('-', $parts[0]);
485
                $timeParts = explode(':', $parts[1]);
486
487
                return $dateParts[0].'-'.$this->strPadLeft($dateParts[1]).'-'.$this->strPadLeft($dateParts[2]).' '.$this->strPadLeft($timeParts[0]).':'.$this->strPadLeft($timeParts[1]);
488
        }
489
490
        return $str;
491
    }
492
}
493