Completed
Push — master ( ffecda...e79dfa )
by Benjamin
02:28
created

CronRunCommand::recordJobResult()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 2 Features 0
Metric Value
c 6
b 2
f 0
dl 0
loc 15
rs 9.4285
cc 1
eloc 9
nc 1
nop 4
1
<?php
2
3
namespace Alpixel\Bundle\CronBundle\Command;
4
5
use Alpixel\Bundle\CronBundle\Entity\CronJob;
6
use Alpixel\Bundle\CronBundle\Entity\CronJobResult;
7
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
8
use Symfony\Component\Console\Input\ArgvInput;
9
use Symfony\Component\Console\Input\InputArgument;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Output\OutputInterface;
12
13
class CronRunCommand extends ContainerAwareCommand
14
{
15
    protected function configure()
16
    {
17
        $this->setName('cron:run')
18
             ->setDescription('Runs any currently schedule cron jobs')
19
             ->addArgument('job', InputArgument::OPTIONAL, 'Run only this job (if enabled)');
20
    }
21
22
    protected function execute(InputInterface $input, OutputInterface $output)
23
    {
24
        $start = microtime(true);
25
        $em = $this->getContainer()->get('doctrine.orm.entity_manager');
26
        $jobRepo = $em->getRepository('CronBundle:CronJob');
27
28
        $jobsToRun = [];
29
        if ($jobName = $input->getArgument('job')) {
30
            try {
31
                $jobObj = $jobRepo->findOneByCommand($jobName);
32
                if ($jobObj->getEnabled()) {
33
                    $jobsToRun = [$jobObj];
34
                }
35
            } catch (\Exception $e) {
36
                $output->writeln("Couldn't find a job by the name of $jobName");
37
38
                return CronJobResult::FAILED;
39
            }
40
        } else {
41
            $jobsToRun = $jobRepo->findDueTasks();
42
        }
43
44
        $jobCount = count($jobsToRun);
45
        $output->writeln("Running $jobCount jobs:");
46
47
        foreach ($jobsToRun as $job) {
48
            $this->runJob($job, $output);
49
        }
50
51
        // Flush our results to the DB
52
        $em->flush();
53
54
        $end = microtime(true);
55
        $duration = sprintf('%0.2f', $end - $start);
56
        $output->writeln("Cron run completed in $duration seconds");
57
    }
58
59
    protected function runJob(CronJob $job, OutputInterface $output)
60
    {
61
        $em = $this->getContainer()->get('doctrine.orm.entity_manager');
62
        $output->write('Running '.$job->getCommand().': ');
63
64
        try {
65
            $commandToRun = $this->getApplication()->get($job->getCommand());
66
        } catch (\Symfony\Component\Console\Exception\InvalidArgumentException $ex) {
67
            $output->writeln(' skipped (command no longer exists)');
68
            $this->recordJobResult($em, $job, 0, 'Command no longer exists', CronJobResult::SKIPPED);
0 ignored issues
show
Unused Code introduced by
The call to CronRunCommand::recordJobResult() has too many arguments starting with \Alpixel\Bundle\CronBund...\CronJobResult::SKIPPED.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
69
70
            // No need to reschedule non-existant commands
71
            return;
72
        }
73
74
        $emptyInput = new ArgvInput();
75
        $jobOutput = new MemoryWriter();
76
77
        $jobStart = microtime(true);
78
        try {
79
            $returnCode = $commandToRun->execute($emptyInput, $jobOutput);
80
        } catch (\Exception $ex) {
81
            $returnCode = CronJobResult::FAILED;
82
            $jobOutput->writeln('');
83
            $jobOutput->writeln('Job execution failed with exception '.get_class($ex).':');
84
            $jobOutput->writeln($ex->__toString());
85
        }
86
        $jobEnd = microtime(true);
87
88
        // Clamp the result to accepted values
89
        if ($returnCode < CronJobResult::RESULT_MIN || $returnCode > CronJobResult::RESULT_MAX) {
90
            $returnCode = CronJobResult::FAILED;
91
        }
92
93
        // Output the result
94
        $statusStr = 'unknown';
95
        if ($returnCode == CronJobResult::SKIPPED) {
96
            $statusStr = 'skipped';
97
        } elseif ($returnCode == CronJobResult::SUCCEEDED) {
98
            $statusStr = 'succeeded';
99
        } elseif ($returnCode == CronJobResult::FAILED) {
100
            $statusStr = 'failed';
101
        }
102
103
        $durationStr = sprintf('%0.2f', $jobEnd - $jobStart);
104
        $output->writeln("$statusStr in $durationStr seconds");
105
106
        // Record the result
107
        $this->recordJobResult($job, $jobEnd - $jobStart, $jobOutput->getOutput(), $returnCode);
108
109
        // And update the job with it's next scheduled time
110
        $newTime = new \DateTime();
111
        $newTime = $newTime->add(new \DateInterval($job->getInterval()));
112
        $job->setNextRun($newTime);
0 ignored issues
show
Documentation introduced by
$newTime is of type object<DateTime>, but the function expects a object<Alpixel\Bundle\CronBundle\Entity\datetime>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
113
    }
114
115
    protected function recordJobResult(CronJob $job, $timeTaken, $output, $resultCode)
116
    {
117
        $em = $this->getContainer()->get('doctrine.orm.entity_manager');
118
119
        // Create a new CronJobResult
120
        $result = new CronJobResult();
121
        $result->setJob($job);
122
        $result->setRunTime($timeTaken);
123
        $result->setOutput($output);
124
        $result->setResult($resultCode);
125
126
        // Then update associations and persist it
127
        $job->setMostRecentRun($result);
128
        $em->persist($result);
129
    }
130
}
131