Completed
Push — issue/AZ_62_add_command_to_tes... ( be3d81 )
by Dominik
09:46
created

CheckIpAddressIsBlacklistedCommand::execute()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 55
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 55
ccs 0
cts 30
cp 0
rs 7.2446
cc 9
eloc 27
nc 9
nop 2
crap 90

How to fix   Long Method   

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
namespace Azine\MailgunWebhooksBundle\Command;
3
4
use Azine\MailgunWebhooksBundle\Services\AzineMailgunService;
5
use Azine\MailgunWebhooksBundle\Services\HetrixtoolsService\HetrixtoolsServiceResponse;
6
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
7
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
8
use Symfony\Component\Console\Input\InputArgument;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Azine\MailgunWebhooksBundle\Entity\Repositories\MailgunEventRepository;
12
use Azine\MailgunWebhooksBundle\Services\HetrixtoolsService\AzineMailgunHetrixtoolsService;
13
use Azine\MailgunWebhooksBundle\Services\AzineMailgunMailerService;
14
use Symfony\Component\Translation\TranslatorInterface;
15
use Doctrine\Common\Persistence\ManagerRegistry;
16
use Symfony\Component\Process\Process;
17
18
/**
19
 * Checks if the last ip address from MailgunEvent entity is in blacklist
20
 *
21
 */
22
class CheckIpAddressIsBlacklistedCommand extends ContainerAwareCommand
23
{
24
    const NO_RESPONSE_FROM_HETRIX = 'No response from Hetrixtools service, try later.';
25
    const BLACKLIST_REPORT_WAS_SENT = 'Blacklist report was sent.';
26
    const IP_IS_NOT_BLACKLISTED = 'Ip is not blacklisted.';
27
    const STARTING_RETRY = 'Initiating retry of the checking command. Tries left: ';
28
29
    /**
30
     * @var string|null The default command name
31
     */
32
    protected static $defaultName = 'mailgun:check-ip-in-blacklist';
33
34
    /**
35
     * @var ManagerRegistry
36
     */
37
    private $managerRegistry;
38
39
    /**
40
     * @var AzineMailgunHetrixtoolsService
41
     */
42
    private $hetrixtoolsService;
43
44
    /**
45
     * @var AzineMailgunMailerService
46
     */
47
    private $azineMailgunService;
48
49
    /**
50
     * @var string
51
     */
52
    private $kernelRootDir;
53
54
    /**
55
     * @var string
56
     */
57
    private $kernelEnvironment;
58
59
60
    public function __construct(ManagerRegistry $managerRegistry, AzineMailgunHetrixtoolsService $hetrixtoolsService,
61
                                AzineMailgunMailerService $azineMailgunService, $kernelRootDir, $environment)
62
    {
63
        $this->managerRegistry = $managerRegistry;
64
        $this->hetrixtoolsService = $hetrixtoolsService;
65
        $this->azineMailgunService = $azineMailgunService;
66
        $this->kernelRootDir = $kernelRootDir;
67
        $this->kernelEnvironment = $environment;
68
69
        parent::__construct();
70
71
    }
72
73
    protected function configure()
74
    {
75
        $this
76
            ->setName(static::$defaultName)
77
            ->setDescription('Checks if the last sending IP address from MailgunEvent entity is in blacklist')
78
            ->addArgument('numberOfAttempts',
79
                InputArgument::OPTIONAL,
80
                'Number of retry attempts in case if there were no response from hetrixtools or the process of checking blacklist was still in progress')
81
        ;
82
    }
83
84
    protected function execute(InputInterface $input, OutputInterface $output)
85
    {
86
        $manager = $this->managerRegistry->getManager();
87
        /** @var MailgunEventRepository $eventRepository */
88
        $eventRepository = $manager->getRepository('AzineMailgunWebhooksBundle:MailgunEvent');
89
        $ipAddress = $eventRepository->getLastKnownSenderIp();
90
91
        $response = $this->hetrixtoolsService->checkIpAddressInBlacklist($ipAddress);
92
93
        $numberOfAttempts = $input->getArgument("numberOfAttempts");
94
95
        if($numberOfAttempts != null){
96
97
            $this->retry($numberOfAttempts);
98
        }
99
        else{
100
101
            $output->write(self::NO_RESPONSE_FROM_HETRIX);
102
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type of the parent method Symfony\Component\Console\Command\Command::execute of type null|integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
103
        }
104
105
        if($response->status == HetrixtoolsServiceResponse::RESPONSE_STATUS_SUCCESS){
106
107
            if($response->blacklisted_count > 0){
108
109
                try{
110
111
                    $messagesSent = $this->azineMailgunService->sendBlacklistNotification($response, $ipAddress);
112
113
                    if($messagesSent > 0){
114
115
                        $output->write(self::BLACKLIST_REPORT_WAS_SENT." ($ipAddress)");
116
                    }
117
                }
118
                catch (\Exception $e){
119
120
                    $output->write($e->getMessage(), true);
121
                }
122
            }
123
            else{
124
125
                $output->write(self::IP_IS_NOT_BLACKLISTED." ($ipAddress)");
126
            }
127
        }
128
        elseif ($response->status == HetrixtoolsServiceResponse::RESPONSE_STATUS_ERROR){
129
130
            $output->write($response->error_message);
131
132
            if($numberOfAttempts != null && $response->error_message == HetrixtoolsServiceResponse::BLACKLIST_CHECK_IN_PROGRESS){
133
                $output->write(self::STARTING_RETRY . $numberOfAttempts);
134
                $this->retry($numberOfAttempts);
135
            }
136
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type of the parent method Symfony\Component\Console\Command\Command::execute of type null|integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
137
        }
138
    }
139
140
    private function retry($numberOfAttempts)
141
    {
142
        $numberOfAttempts--;
143
144
        $cmd = sprintf(
145
            '%s/console %s %s --env=%s',
146
            static::$defaultName,
147
            $numberOfAttempts,
148
            $this->kernelEnvironment
149
        );
150
151
        $process = new Process( $cmd );
152
        $process->start();
153
    }
154
}