RestartCommand::getMessageManager()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\NotificationBundle\Command;
15
16
use Sonata\NotificationBundle\Backend\BackendInterface;
17
use Sonata\NotificationBundle\Event\IterateEvent;
18
use Sonata\NotificationBundle\Iterator\ErroneousMessageIterator;
19
use Sonata\NotificationBundle\Model\MessageManagerInterface;
20
use Sonata\NotificationBundle\Selector\ErroneousMessagesSelector;
21
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
22
use Symfony\Component\Console\Input\InputInterface;
23
use Symfony\Component\Console\Input\InputOption;
24
use Symfony\Component\Console\Output\OutputInterface;
25
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
26
27
class RestartCommand extends ContainerAwareCommand
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...d\ContainerAwareCommand has been deprecated with message: since Symfony 4.2, use {@see Command} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
28
{
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function configure(): void
33
    {
34
        $this->setName('sonata:notification:restart');
35
        $this->setDescription('Restart messages with erroneous statuses, only for doctrine backends');
36
        $this->addOption('type', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'List of messages types to restart (separate multiple types with a space)');
37
        $this->addOption('max-attempts', null, InputOption::VALUE_REQUIRED, 'Maximum number of attempts', 6);
38
        $this->addOption('attempt-delay', null, InputOption::VALUE_OPTIONAL, 'Min seconds between two attempts', 10);
39
        $this->addOption('pulling', null, InputOption::VALUE_NONE, 'Run the command as an infinite pulling loop');
40
        $this->addOption('pause', null, InputOption::VALUE_OPTIONAL, 'Seconds between each data pull (used only when pulling option is set)', 500000);
41
        $this->addOption('batch-size', null, InputOption::VALUE_OPTIONAL, 'Number of message to process on each pull (used only when pulling option is set)', 10);
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function execute(InputInterface $input, OutputInterface $output): void
48
    {
49
        $output->writeln('<info>Starting... </info>');
50
51
        if (!is_numeric($input->getOption('max-attempts'))) {
52
            throw new \Exception('Option "max-attempts" is invalid (integer value needed).');
53
        }
54
55
        $pullMode = $input->getOption('pulling');
56
        $manager = $this->getMessageManager();
57
58
        if ($pullMode) {
59
            $messages = new ErroneousMessageIterator(
60
                $manager,
0 ignored issues
show
Bug introduced by
It seems like $manager defined by $this->getMessageManager() on line 56 can be null; however, Sonata\NotificationBundl...Iterator::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
61
                $input->getOption('type'),
0 ignored issues
show
Documentation introduced by
$input->getOption('type') is of type integer|double|string, but the function expects a array.

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...
62
                $input->getOption('pause'),
63
                $input->getOption('batch-size'),
64
                $input->getOption('max-attempts'),
65
                $input->getOption('attempt-delay')
66
            );
67
        } else {
68
            $messages = $this->getErroneousMessageSelector()->getMessages(
69
                $input->getOption('type'),
0 ignored issues
show
Documentation introduced by
$input->getOption('type') is of type integer|double|string, but the function expects a array.

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...
70
                $input->getOption('max-attempts')
71
            );
72
73
            /*
74
             * Check messages count only for not pulling mode
75
             * to avoid PHP warning message
76
             * since ErroneousMessageIterator does not implement Countable.
77
             */
78
            if (0 === \count($messages)) {
79
                $output->writeln('Nothing to restart, bye.');
80
81
                return;
82
            }
83
        }
84
85
        /** @var EventDispatcherInterface $eventDispatcher */
86
        $eventDispatcher = $this->getContainer()->get('event_dispatcher');
87
88
        foreach ($messages as $message) {
89
            $id = $message->getId();
90
91
            $newMessage = $manager->restart($message);
92
93
            $this->getBackend()->publish($newMessage);
94
95
            $output->writeln(sprintf(
96
                'Reset Message %s <info>#%d</info>, new id %d. Attempt #%d',
97
                $newMessage->getType(),
98
                $id,
99
                $newMessage->getId(),
100
                $newMessage->getRestartCount()
101
            ));
102
103
            if ($pullMode) {
104
                $eventDispatcher->dispatch(new IterateEvent($messages, null, $newMessage), IterateEvent::EVENT_NAME);
105
            }
106
        }
107
108
        $output->writeln('<info>Done!</info>');
109
    }
110
111
    /**
112
     * Return the erroneous message selector service.
113
     *
114
     * @return ErroneousMessagesSelector
115
     */
116
    protected function getErroneousMessageSelector()
117
    {
118
        return $this->getContainer()->get('sonata.notification.erroneous_messages_selector');
119
    }
120
121
    /**
122
     * @return MessageManagerInterface
123
     */
124
    protected function getMessageManager()
125
    {
126
        return $this->getContainer()->get('sonata.notification.manager.message');
127
    }
128
129
    /**
130
     * @return BackendInterface
131
     */
132
    protected function getBackend()
133
    {
134
        return $this->getContainer()->get('sonata.notification.backend');
135
    }
136
}
137