Completed
Push — master ( 9eae13...e56856 )
by Antonio
04:26
created

BeanstalkdQueueStoreAdapter   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 142
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 94.64%

Importance

Changes 2
Bugs 0 Features 2
Metric Value
wmc 15
c 2
b 0
f 2
lcom 1
cbo 6
dl 0
loc 142
ccs 53
cts 56
cp 0.9464
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A init() 0 6 1
A getConnection() 0 4 1
A enqueue() 0 15 2
A dequeue() 0 18 2
A ack() 0 18 3
A isEmpty() 0 8 3
A createPayload() 0 10 2
1
<?php
2
namespace Da\Mailer\Queue\Backend\Beanstalk;
3
4
use Da\Mailer\Exception\InvalidCallException;
5
use Da\Mailer\Queue\Backend\MailJobInterface;
6
use Da\Mailer\Queue\Backend\QueueStoreAdapterInterface;
7
use Pheanstalk\Job as PheanstalkJob;
8
use Pheanstalk\Pheanstalk;
9
use phpseclib\Crypt\Random;
10
11
class BeanstalkdQueueStoreAdapter implements QueueStoreAdapterInterface
12
{
13
    /**
14
     * @var string the queue name
15
     */
16
    private $queueName;
17
    /**
18
     * @var int the time to run. Defaults to Pheanstalkd::DEFAULT_TTR.
19
     */
20
    private $timeToRun;
21
    /**
22
     * @var BeanstalkdQueueStoreConnection
23
     */
24
    protected $connection;
25
26
    /**
27
     * BeanstalkdQueueStoreAdapter constructor.
28
     *
29
     * @param BeanstalkdQueueStoreConnection $connection
30
     * @param string $queueName
31
     * @param int $timeToRun
32
     */
33 4
    public function __construct(
34
        BeanstalkdQueueStoreConnection $connection,
35
        $queueName = 'mail_queue',
36
        $timeToRun = Pheanstalk::DEFAULT_TTR
37
    ) {
38 4
        $this->connection = $connection;
39 4
        $this->queueName = $queueName;
40 4
        $this->timeToRun = $timeToRun;
41 4
        $this->init();
42 4
    }
43
44
    /**
45
     * @return BeanstalkdQueueStoreAdapter
46
     */
47 4
    public function init()
48
    {
49 4
        $this->getConnection()->connect();
50
51 4
        return $this;
52
    }
53
54
    /**
55
     * @return BeanstalkdQueueStoreConnection
56
     */
57 4
    public function getConnection()
58
    {
59 4
        return $this->connection;
60
    }
61
62
    /**
63
     * @param BeanstalkdMailJob|MailJobInterface $mailJob
64
     *
65
     * @return int
66
     */
67 3
    public function enqueue(MailJobInterface $mailJob)
68
    {
69 3
        $timestamp = $mailJob->getTimeToSend();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Da\Mailer\Queue\Backend\MailJobInterface as the method getTimeToSend() does only exist in the following implementations of said interface: Da\Mailer\Queue\Backend\...stalk\BeanstalkdMailJob, Da\Mailer\Queue\Backend\Pdo\PdoMailJob, Da\Mailer\Queue\Backend\Redis\RedisMailJob.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
70 3
        $payload = $this->createPayload($mailJob);
71 3
        if ($payload === false) {
72
            var_dump(json_last_error_msg());
0 ignored issues
show
Security Debugging Code introduced by
var_dump(json_last_error_msg()); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
73
            ob_flush();
74
        }
75 3
        $delay = (int)max(Pheanstalk::DEFAULT_DELAY, $timestamp - time());
76
77 3
        return $this->getConnection()
78 3
            ->getInstance()
79 3
            ->useTube($this->queueName)
80 3
            ->put($payload, Pheanstalk::DEFAULT_PRIORITY, $delay, $this->timeToRun);
81
    }
82
83 3
    public function dequeue()
84
    {
85 3
        $job = $this->getConnection()->getInstance()->watchOnly($this->queueName)->reserve(0);
86 3
        if ($job instanceof PheanstalkJob) {
87 3
            $data = json_decode($job->getData(), true);
88
89 3
            return new BeanstalkdMailJob(
90
                [
91 3
                    'id' => $data['id'],
92 3
                    'attempt' => $data['attempt'],
93 3
                    'message' => $data['message'],
94
                    'pheanstalkJob' => $job
95 3
                ]
96 3
            );
97
        }
98
99 2
        return null;
100
    }
101
102
    /**
103
     * @param BeanstalkdMailJob|MailJobInterface $mailJob
104
     */
105 4
    public function ack(MailJobInterface $mailJob)
106
    {
107 4
        if ($mailJob->isNewRecord()) {
108 1
            throw new InvalidCallException('BeanstalkdMailJob cannot be a new object to be acknowledged');
109
        }
110
111 3
        $pheanstalk = $this->getConnection()->getInstance()->useTube($this->queueName);
112 3
        if ($mailJob->isCompleted()) {
113 2
            $pheanstalk->delete($mailJob->getPheanstalkJob());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Da\Mailer\Queue\Backend\MailJobInterface as the method getPheanstalkJob() does only exist in the following implementations of said interface: Da\Mailer\Queue\Backend\...stalk\BeanstalkdMailJob.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
114 2
        } else {
115 1
            $timestamp = $mailJob->getTimeToSend();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Da\Mailer\Queue\Backend\MailJobInterface as the method getTimeToSend() does only exist in the following implementations of said interface: Da\Mailer\Queue\Backend\...stalk\BeanstalkdMailJob, Da\Mailer\Queue\Backend\Pdo\PdoMailJob, Da\Mailer\Queue\Backend\Redis\RedisMailJob.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
116 1
            $delay = max(0, $timestamp - time());
117
118
            // add back to the queue as it wasn't completed maybe due to some transitory error
119
            // could also be failed.
120 1
            $pheanstalk->release($mailJob->getPheanstalkJob(), Pheanstalk::DEFAULT_PRIORITY, $delay);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Da\Mailer\Queue\Backend\MailJobInterface as the method getPheanstalkJob() does only exist in the following implementations of said interface: Da\Mailer\Queue\Backend\...stalk\BeanstalkdMailJob.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
121
        }
122 3
    }
123
124
    /**
125
     *
126
     * @return bool
127
     */
128 2
    public function isEmpty()
129
    {
130 2
        $stats = $this->getConnection()->getInstance()->statsTube($this->queueName);
131 2
        return (int)$stats->current_jobs_delayed === 0
132 2
        && (int)$stats->current_jobs_urgent === 0
133 2
        && (int)$stats->current_jobs_ready === 0;
134
135
    }
136
137
    /**
138
     * @param BeanstalkdMailJob|MailJobInterface $mailJob
139
     *
140
     * @return string
141
     */
142 3
    protected function createPayload(MailJobInterface $mailJob)
143
    {
144 3
        return json_encode(
145
            [
146 3
                'id' => $mailJob->isNewRecord() ? sha1(Random::string(32)) : $mailJob->getId(),
147 3
                'attempt' => $mailJob->getAttempt(),
148 3
                'message' => $mailJob->getMessage(),
149
            ]
150 3
        );
151
    }
152
}
153