Completed
Pull Request — master (#39)
by Pascal
09:52
created

ProcessEventCommand::isLimitReached()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 3
nc 5
nop 4
crap 20
1
<?php
2
3
namespace Itkg\DelayEventBundle\Command;
4
5
use Itkg\DelayEventBundle\Handler\LockHandlerInterface;
6
use Itkg\DelayEventBundle\Model\Event;
7
use Itkg\DelayEventBundle\Processor\EventProcessor;
8
use Itkg\DelayEventBundle\Repository\EventRepository;
9
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Input\InputOption;
12
use Symfony\Component\Console\Output\OutputInterface;
13
14
/**
15
 * Class ProcessEventCommand
16
 */
17
class ProcessEventCommand extends ContainerAwareCommand
18
{
19
    /**
20
     * @var EventRepository
21
     */
22
    private $eventRepository;
23
24
    /**
25
     * @var EventProcessor
26
     */
27
    private $eventProcessor;
28
29
    /**
30
     * @var LockHandlerInterface
31
     */
32
    private $lockHandler;
33
34
    /**
35
     * @var array
36
     */
37
    private $channels;
38
39
    /**
40
     * ProcessEventCommand constructor.
41
     *
42
     * @param EventRepository      $eventRepository
43
     * @param EventProcessor       $eventProcessor
44
     * @param LockHandlerInterface $lockHandler
45
     * @param array                $channels
46
     * @param null|string          $name
47
     */
48
    public function __construct(
49
        EventRepository $eventRepository,
50
        EventProcessor $eventProcessor,
51
        LockHandlerInterface $lockHandler,
52
        array $channels = [],
53
        $name = null
54
    ) {
55
        $this->eventRepository = $eventRepository;
56
        $this->eventProcessor = $eventProcessor;
57
        $this->lockHandler = $lockHandler;
58
        $this->channels = $channels;
59
60
        parent::__construct($name);
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 View Code Duplication
    protected function configure()
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...
67
    {
68
        $this
69
            ->setName('itkg_delay_event:process')
70
            ->setDescription('Process async events')
71
            ->addOption(
72
                'channel',
73
                'c',
74
                InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED,
75
                'Specify the channels to process (default: [\'default\'])',
76
                ['default']
77
            );
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    protected function execute(InputInterface $input, OutputInterface $output)
84
    {
85
        $channels = $input->getOption('channel');
86
87
        foreach ($channels as $channel) {
88
            if (!isset($this->channels[$channel])) {
89
                $output->writeln(
90
                    sprintf(
91
                        '<error>Channel <info>%s</info> is not configured.</error>',
92
                        $channel
93
                    )
94
                );
95
96
                continue;
97
            }
98
99
            if ($this->lockHandler->isLocked($channel)) {
100
                $output->writeln(
101
                    sprintf(
102
                        'Command is locked by another process for channel <info>%s</info>.',
103
                        $channel
104
                    )
105
                );
106
107
                continue;
108
            }
109
110
            $output->writeln(
111
                sprintf(
112
                    'Process events for channel <info>%s</info>',
113
                    $channel
114
                )
115
            );
116
117
            $this->lockHandler->lock($channel);
118
119
            $processedEventsCount = 0;
120
            $commandStartTime = time();
121
            $maxProcessedQueueSize = $this->channels[$channel]['events_limit_per_run'];
0 ignored issues
show
Unused Code introduced by
$maxProcessedQueueSize is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
122
            $event = null;
123
124
            try {
125
                while (!$this->isLimitReached(
126
                    $commandStartTime,
127
                    $processedEventsCount,
128
                    $this->channels[$channel]['duration_limit_per_run'],
129
                    $this->channels[$channel]['events_limit_per_run'])
130
                ) {
131
                    if (!$this->lockHandler->isLocked($channel)) {
132
                        $output->writeln(
133
                            sprintf(
134
                                '<error>Lock for channel <info>%s</info> has been released outside of the process.</error>',
135
                                $channel
136
                            )
137
                        );
138
139
                        break;
140
                    }
141
142
                    $event = $this->eventRepository->findFirstTodoEvent(
143
                        false,
144
                        $this->channels[$channel]['include'],
145
                        $this->channels[$channel]['exclude']
146
                    );
147
148
                    if (!$event instanceof Event) {
149
                        break;
150
                    }
151
152
                    $event->setDelayed(false);
153
                    $this->eventProcessor->process($event);
154
                    $processedEventsCount++;
155
                }
156
            } catch (\Exception $e) {
157
                if ($event instanceof Event) {
158
                    $output->writeln(
159
                        sprintf(
160
                            '<info>[%s]</info> <error> An error occurred while processing event "%s".</error>',
161
                            $channel,
162
                            $event->getOriginalName()
163
                        )
164
                    );
165
                }
166
167
                $output->writeln(sprintf('<info>[%s]</info> <error>%s</error>', $channel, $e->getMessage()));
168
                $output->writeln($e->getTraceAsString());
169
            }
170
171
            $this->lockHandler->release($channel);
172
        }
173
    }
174
175
    /**
176
     * @param int $commandStartTime
177
     * @param int $processedEventsCount
178
     * @param int $maxDurationPerRun
179
     * @param int $maxProcessedEventPerRun
180
     */
181
    private function isLimitReached($commandStartTime, $processedEventsCount, $maxDurationPerRun, $maxProcessedEventPerRun)
182
    {
183
        return (($maxProcessedEventPerRun !== null && $processedEventsCount >= $maxProcessedEventPerRun)
184
            || ($maxDurationPerRun !== null && (time() - $commandStartTime) >= $maxDurationPerRun));
185
    }
186
}
187