Worker::doJob()   B
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 36
Code Lines 20

Duplication

Lines 12
Ratio 33.33 %

Code Coverage

Tests 12
CRAP Score 4.8

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 12
loc 36
ccs 12
cts 19
cp 0.6316
rs 8.5806
cc 4
eloc 20
nc 8
nop 1
crap 4.8
1
<?php
2
3
namespace Messenger\Sms\Infobip;
4
5
use Cronario\AbstractJob;
6
use Cronario\AbstractWorker;
7
use Messenger\Sms\Job;
8
use Messenger\Sms\ResultException;
9
use Messenger\Sms\Worker as SmsWorker;
10
11
/**
12
 * Class Worker
13
 *
14
 * @package Messenger\Sms\Infobip
15
 */
16
class Worker extends AbstractWorker
17
{
18
19
    protected static $config
20
        = [
21
            AbstractWorker::CONFIG_P_MANAGERS_LIMIT    => 3,
22
            AbstractWorker::CONFIG_P_MANAGER_POOL_SIZE => 5,
23
            SmsWorker::GATEWAY_DISPATCH_CLASS          => '\\Messenger\\Sms\\Worker',
24
            self::CONFIG_P_CLIENT                      => [
25
                'login'    => 'xxx',
26
                'password' => 'xxx',
27
            ],
28
        ];
29
30
    // region CLIENT ********************************************************
31
32
    const CONFIG_P_CLIENT = 'client';
33
34
    /**
35
     * @var \infobip\SmsClient
36
     */
37
    protected $transport;
38
39
    /**
40
     * @return \infobip\SmsClient
41
     */
42 1 View Code Duplication
    protected function getTransport()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
43
    {
44 1
        if (null === $this->transport) {
45 1
            $clientConfig = self::getConfig(self::CONFIG_P_CLIENT);
46 1
            $this->transport = new \infobip\SmsClient($clientConfig['login'], $clientConfig['password']);
47 1
        }
48
49 1
        return $this->transport;
50
    }
51
52
    /**
53
     * @param AbstractJob|Job $job
54
     *
55
     * @return array
56
     */
57 2
    protected function send(AbstractJob $job)
58
    {
59
        $result = [
60 2
            'errors'    => [],
61 2
            'vendor_id' => null,
62 2
        ];
63
64
        try {
65 2
            $transport = $this->getTransport();
66
67 2
            $smsMessage = new \infobip\models\SMSRequest();
68
69 2
            $smsMessage->senderAddress = $job->getSender();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Cronario\AbstractJob as the method getSender() does only exist in the following sub-classes of Cronario\AbstractJob: Messenger\Sms\Job. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
70 2
            $smsMessage->address = $job->getRecipient();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Cronario\AbstractJob as the method getRecipient() does only exist in the following sub-classes of Cronario\AbstractJob: Messenger\Sms\Job. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
71 2
            $smsMessage->message = $job->getText();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Cronario\AbstractJob as the method getText() does only exist in the following sub-classes of Cronario\AbstractJob: Messenger\Sms\Job. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
72
73 2
            $response = $transport->sendSMS($smsMessage);
74
75 1
            $result['vendor_id'] = $response->clientCorrelator;
76
            if ($response->exception != null) {
77
                $result['errors'][] = $response->exception;
78
            }
79
80 2
        } catch (\Exception $ex) {
81 2
            $result['errors'][] = $ex->getMessage();
82
        }
83
84 2
        return $result;
85
    }
86
    // endregion *************************************************************
87
88
    // region VALIDATE ********************************************************
89
90 2 View Code Duplication
    protected function validateJobParams(Job $job)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
91
    {
92 2
        if (empty($job->getSender())) {
93
            throw new ResultException(ResultException::ERROR_PARAM_SENDER);
94
        }
95
96 2
        if (empty($job->getRecipient())) {
97
            throw new ResultException(ResultException::ERROR_PARAM_RECIPIENT);
98
        }
99
100 2
        if (empty($job->getText())) {
101
            throw new ResultException(ResultException::ERROR_PARAM_TEXT);
102
        }
103 2
    }
104
105
    // endregion *************************************************************
106
107
    /**
108
     * @param AbstractJob|Job $job
109
     *
110
     * @throws ResultException
111
     */
112 2
    protected function doJob(AbstractJob $job)
113
    {
114 2
        $this->validateJobParams($job);
0 ignored issues
show
Compatibility introduced by
$job of type object<Cronario\AbstractJob> is not a sub-type of object<Messenger\Sms\Job>. It seems like you assume a child class of the class Cronario\AbstractJob to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
115
116 2
        $resultData = SmsWorker::buildResultDataDefault(__NAMESPACE__);
117
118
        try {
119 2
            $response = $this->send($job);
120
121 2
            $resultData[SmsWorker::P_RESULT_DATA_SUCCESS] = count($response['errors']) == 0;
122 2
            $resultData[SmsWorker::P_RESULT_DATA_VENDOR_ID] = $response['vendor_id'];
123 2
            $resultData[SmsWorker::P_RESULT_DATA_ERRORS] = $response['errors'];
124
125 2
            $job->addDebug(['vendor_response' => $response]);
126
127 2
        } catch (\Exception $ex) {
128
            $job->addDebug(['exception' => $ex->getMessage()]);
129
            throw new ResultException(ResultException::ERROR_TRANSPORT);
130
        }
131
132
133 2 View Code Duplication
        if (false === $resultData[SmsWorker::P_RESULT_DATA_SUCCESS]) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
135 2
            if (!$job->isSync()) {
136
                // redirect result for new root gateway class
137
                $gatewayClass = static::getConfig(SmsWorker::GATEWAY_DISPATCH_CLASS);
138
                $job->addDebug(['set_gateway' => $gatewayClass]);
139
                $job->setWorkerClass($gatewayClass)->save();
140
                throw new ResultException(ResultException::RETRY_GATEWAY_DISPATCH_CLASS);
141
            }
142
143 2
            throw new ResultException(ResultException::R_FAILURE, $resultData);
144
        }
145
146
        throw new ResultException(ResultException::R_SUCCESS, $resultData);
147
    }
148
149
}
150
151
152
153
154
155
156