StfalconMailerCommand::execute()   D
last analyzed

Complexity

Conditions 18
Paths 20

Size

Total Lines 90
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 61
dl 0
loc 90
rs 4.8666
c 0
b 0
f 0
cc 18
nc 20
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Stfalcon\Bundle\EventBundle\Command;
4
5
use Application\Bundle\DefaultBundle\Service\MyMailer;
6
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Input\InputOption;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Stfalcon\Bundle\EventBundle\Entity\Mail;
11
12
/**
13
 * Class StfalconMailerCommand.
14
 */
15
class StfalconMailerCommand extends ContainerAwareCommand
16
{
17
    /**
18
     * Set options.
19
     */
20
    protected function configure()
21
    {
22
        $this
23
            ->setName('stfalcon:mailer')
24
            ->setDescription('Send message from queue')
25
            ->addOption('amount', null, InputOption::VALUE_OPTIONAL, 'Amount of mails which will send per operation. Default 10.')
26
            ->addOption('host', null, InputOption::VALUE_OPTIONAL, 'Site host. Default fwdays.com.');
27
    }
28
29
    /**
30
     * @param InputInterface  $input
31
     * @param OutputInterface $output
32
     *
33
     * @return int|null|void
34
     *
35
     * @throws \Doctrine\ORM\OptimisticLockException
36
     */
37
    protected function execute(InputInterface $input, OutputInterface $output)
38
    {
39
        /** @var \Symfony\Component\Routing\RequestContext $context */
40
        $context = $this->getContainer()->get('router')->getContext();
41
        $context->setHost('fwdays.com');
42
        $context->setScheme('http');
43
44
        $limit = 10;
45
46
        if ($input->getOption('amount')) {
47
            $limit = (int) $input->getOption('amount');
48
        }
49
50
        if ($input->getOption('host')) {
51
            $context->setHost($input->getOption('host'));
0 ignored issues
show
Bug introduced by
It seems like $input->getOption('host') can also be of type string[]; however, parameter $host of Symfony\Component\Routin...questContext::setHost() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

51
            $context->setHost(/** @scrutinizer ignore-type */ $input->getOption('host'));
Loading history...
52
        }
53
54
        /** @var $em \Doctrine\ORM\EntityManager */
55
        $em = $this->getContainer()->get('doctrine.orm.entity_manager');
56
        /** @var $mailer MyMailer */
57
        $mailer = $this->getContainer()->get('app.my_mailer.service');
58
        /** @var $mailerHelper \Stfalcon\Bundle\EventBundle\Helper\StfalconMailerHelper */
59
        $mailerHelper = $this->getContainer()->get('stfalcon_event.mailer_helper');
60
        /** @var $queueRepository \Stfalcon\Bundle\EventBundle\Repository\MailQueueRepository */
61
        $queueRepository = $em->getRepository('StfalconEventBundle:MailQueue');
62
63
        $mailsQueue = $queueRepository->getMessages($limit);
64
        $logger = $this->getContainer()->get('logger');
65
        /* @var $mail Mail */
66
        foreach ($mailsQueue as $item) {
67
            $user = $item->getUser();
68
            $mail = $item->getMail();
69
70
            if (!(
71
                $user &&
72
                $mail &&
73
                $user->isEnabled() &&
74
                $user->isSubscribe() &&
75
                $user->isEmailExists() &&
76
                filter_var($user->getEmail(), FILTER_VALIDATE_EMAIL)
77
            )) {
78
                $mail->decTotalMessages();
79
                $em->remove($item);
80
                $em->flush();
81
                continue;
82
            }
83
84
            try {
85
                $message = $mailerHelper->formatMessage($user, $mail);
86
            } catch (\Exception $e) {
87
                $logger->addError('Mailer:'.$e->getMessage(), ['email' => $user->getEmail()]);
88
89
                $mail->decTotalMessages();
90
                $em->remove($item);
91
                $em->flush();
92
                continue;
93
            }
94
95
            $headers = $message->getHeaders();
96
            $http = $this->getContainer()->get('router')->generate(
97
                'unsubscribe',
98
                [
99
                    'hash' => $user->getSalt(),
100
                    'userId' => $user->getId(),
101
                    'mailId' => $mail->getId(),
102
                ],
103
                true
104
            );
105
106
            $headers->removeAll('List-Unsubscribe');
107
            $headers->addTextHeader('List-Unsubscribe', '<'.$http.'>');
108
            $failed = [];
109
            if ($mailer->send($message, $failed)) {
110
                $mail->incSentMessage();
111
                $item->setIsSent(true);
112
                $em->flush();
113
            } else {
114
                $logger->addError('Mailer send exception', [
115
                    'mail_id' => $mail->getId(),
116
                    'user_id' => $user->getId(),
117
                    'error_swift_message' => isset($failed['error_swift_message']) ? $failed['error_swift_message'] : '',
118
                    'error_swift_code' => isset($failed['error_swift_code']) ? $failed['error_swift_code'] : '',
119
                    'error_swift_trace' => isset($failed['error_swift_trace']) ? $failed['error_swift_trace'] : '',
120
                    'error_exception_message' => isset($failed['error_exception_message']) ? $failed['error_exception_message'] : '',
121
                    'error_exception_code' => isset($failed['error_exception_code']) ? $failed['error_exception_code'] : '',
122
                    'error_exception_trace' => isset($failed['error_exception_trace']) ? $failed['error_exception_trace'] : '',
123
                ]);
124
            }
125
        }
126
        $em->flush();
127
    }
128
}
129