Completed
Push — issue/AZ_62_add_command_to_tes... ( be3d81...0cd473 )
by Dominik
02:23
created

CheckIpAddressIsBlacklistedCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 0
crap 1
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 $kernelEnvironment;
53
54
55 3
    public function __construct(ManagerRegistry $managerRegistry, AzineMailgunHetrixtoolsService $hetrixtoolsService,
56
                                AzineMailgunMailerService $azineMailgunService, $environment)
57
    {
58 3
        $this->managerRegistry = $managerRegistry;
59 3
        $this->hetrixtoolsService = $hetrixtoolsService;
60 3
        $this->azineMailgunService = $azineMailgunService;
61 3
        $this->kernelEnvironment = $environment;
62
63 3
        parent::__construct();
64
65 3
    }
66
67 3
    protected function configure()
68
    {
69 3
        $this
70 3
            ->setName(static::$defaultName)
71 3
            ->setDescription('Checks if the last sending IP address from MailgunEvent entity is in blacklist')
72 3
            ->addArgument('numberOfAttempts',
73 3
                InputArgument::OPTIONAL,
74 3
                'Number of retry attempts in case if there were no response from hetrixtools or the process of checking blacklist was still in progress')
75
        ;
76 3
    }
77
78 3
    protected function execute(InputInterface $input, OutputInterface $output)
79
    {
80 3
        $manager = $this->managerRegistry->getManager();
81
        /** @var MailgunEventRepository $eventRepository */
82 3
        $eventRepository = $manager->getRepository('AzineMailgunWebhooksBundle:MailgunEvent');
83 3
        $ipAddress = $eventRepository->getLastKnownSenderIp();
84
85
        try {
86 3
            $response = $this->hetrixtoolsService->checkIpAddressInBlacklist($ipAddress);
87 3
        } catch (\InvalidArgumentException $ex) {
88 1
            $numberOfAttempts = $input->getArgument("numberOfAttempts");
89
90 1
            if ($numberOfAttempts != null) {
91
92
                $this->retry($numberOfAttempts);
93
            } else {
94
95 1
                $output->write(self::NO_RESPONSE_FROM_HETRIX);
96 1
                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...
97
            }
98
        }
99
100 2
        if($response->status == HetrixtoolsServiceResponse::RESPONSE_STATUS_SUCCESS){
101
102 2
            if($response->blacklisted_count > 0){
103
104
                try{
105
106 1
                    $messagesSent = $this->azineMailgunService->sendBlacklistNotification($response, $ipAddress);
107
108 1
                    if($messagesSent > 0){
109
110 1
                        $output->write(self::BLACKLIST_REPORT_WAS_SENT." ($ipAddress)");
111 1
                    }
112
                }
113 1
                catch (\Exception $e){
114
115
                    $output->write($e->getMessage(), true);
116
                }
117 1
            }
118
            else{
119
120 1
                $output->write(self::IP_IS_NOT_BLACKLISTED." ($ipAddress)");
121
            }
122 2
        }
123
        elseif ($response->status == HetrixtoolsServiceResponse::RESPONSE_STATUS_ERROR){
124
125
            $output->write($response->error_message);
126
127
            if($numberOfAttempts != null && $response->error_message == HetrixtoolsServiceResponse::BLACKLIST_CHECK_IN_PROGRESS){
128
                $output->write(self::STARTING_RETRY . $numberOfAttempts);
0 ignored issues
show
Bug introduced by
The variable $numberOfAttempts does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
129
                $this->retry($numberOfAttempts);
130
            }
131
            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...
132
        }
133 2
    }
134
135
    private function retry($numberOfAttempts)
136
    {
137
        $numberOfAttempts--;
138
139
        $cmd = sprintf(
140
            '%s/console %s %s --env=%s',
141
            static::$defaultName,
142
            $numberOfAttempts,
143
            $this->kernelEnvironment
144
        );
145
146
        $process = new Process( $cmd );
147
        $process->start();
148
    }
149
}