Completed
Pull Request — master (#30)
by
unknown
05:39
created

CheckIpAddressIsBlacklistedCommand::execute()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 37
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 6.0052

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 37
ccs 18
cts 19
cp 0.9474
rs 8.439
cc 6
eloc 17
nc 7
nop 2
crap 6.0052
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\ORM\EntityManager;
16
17
/**
18
 * Checks if the last ip address from MailgunEvent entity is in blacklist
19
 *
20
 */
21
class CheckIpAddressIsBlacklistedCommand extends ContainerAwareCommand
22
{
23
    const NO_RESPONSE_FROM_HETRIX = 'No response from Hetrixtools service, try later.';
24
    const BLACKLIST_REPORT_WAS_SENT = 'Blacklist report was sent.';
25
    const IP_IS_NOT_BLACKLISTED = 'Ip is not blacklisted.';
26
27
    /**
28
     * @var string|null The default command name
29
     */
30
    protected static $defaultName = 'mailgun:check-ip-in-blacklist';
31
32
    /**
33
     * @var EntityManager
34
     */
35
    private $entityManager;
36
37
    /**
38
     * @var AzineMailgunHetrixtoolsService
39
     */
40
    private $hetrixtoolsService;
41
42
    /**
43
     * @var AzineMailgunMailerService
44
     */
45
    private $azineMailgunService;
46
47
48 2
    public function __construct(EntityManager $entityManager, AzineMailgunHetrixtoolsService $hetrixtoolsService, AzineMailgunMailerService $azineMailgunService)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
49
    {
50 2
        $this->entityManager = $entityManager;
51 2
        $this->hetrixtoolsService = $hetrixtoolsService;
52 2
        $this->azineMailgunService = $azineMailgunService;
53
54 2
        parent::__construct();
55
56 2
    }
57
58 2
    protected function configure()
59
    {
60 2
        $this
61 2
            ->setName(static::$defaultName)
62 2
            ->setDescription('Checks if the last ip address from MailgunEvent entity is in blacklist');
63
        ;
64 2
    }
65
66 2
    protected function execute(InputInterface $input, OutputInterface $output)
67
    {
68 2
        $eventRepository = $this->entityManager->getRepository('AzineMailgunWebhooksBundle:MailgunEvent');
69 2
        $ipAddress = $eventRepository->getLastKnownSenderIp();
70
71 2
        $response = $this->hetrixtoolsService->checkIpAddressInBlacklist($ipAddress);
72
73 2
        if(!$response instanceof HetrixtoolsServiceResponse){
74
75 1
            $output->write(self::NO_RESPONSE_FROM_HETRIX);
76 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...
77
        }
78
79 1
        if($response->status == HetrixtoolsServiceResponse::RESPONSE_STATUS_SUCCESS){
80
81 1
            if($response->blacklisted_count > 0){
82
83
                try{
84
85 1
                    $messagesSent = $this->azineMailgunService->sendBlacklistNotification($response);
86
87 1
                    if($messagesSent > 0){
88
89 1
                        $output->write(self::BLACKLIST_REPORT_WAS_SENT);
90 1
                    }
91
                }
92 1
                catch (\Exception $e){
93
94
                    $output->write($e->getMessage(), true);
95
                }
96 1
            }
97
            else{
98
99 1
                $output->write(self::IP_IS_NOT_BLACKLISTED);
100
            }
101 1
        }
102
    }
103
}