Completed
Push — master ( 8f1815...8f409a )
by Antonio
02:27
created

BeanstalkdQueueStoreAdapter::ack()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 11
cts 11
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 1
crap 3
1
<?php
2
namespace Da\Mailer\Queue\Backend\Beanstalkd;
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
    protected $queueName;
17
    /**
18
     * @var int the time to run. Defaults to Pheanstalkd::DEFAULT_TTR.
19
     */
20
    protected $timeToRun;
21
    /**
22
     * @var BeanstalkdQueueStoreConnection
23
     */
24
    protected $connection;
25
    /**
26
     * @var int Reserves/locks a ready job in a watched tube. A timeout value of 0 will cause the server to immediately
27
     * return either a response or TIMED_OUT.  A positive value of timeout will limit the amount of time the client will
28
     * block on the reserve request until a job becomes available.
29
     *
30
     * We highly recommend a non-zero value. Defaults to 5.
31
     */
32
    protected $reserveTimeout;
33
34
    /**
35
     * BeanstalkdQueueStoreAdapter constructor.
36
     *
37
     * @param BeanstalkdQueueStoreConnection $connection
38
     * @param string $queueName
39
     * @param int $timeToRun
40
     * @param int $reserveTimeOut
41
     */
42 4
    public function __construct(
43
        BeanstalkdQueueStoreConnection $connection,
44
        $queueName = 'mail_queue',
45
        $timeToRun = Pheanstalk::DEFAULT_TTR,
46
        $reserveTimeOut = 5
47
    ) {
48 4
        $this->connection = $connection;
49 4
        $this->queueName = $queueName;
50 4
        $this->timeToRun = $timeToRun;
51 4
        $this->reserveTimeout = $reserveTimeOut;
52 4
        $this->init();
53 4
    }
54
55
    /**
56
     * @return BeanstalkdQueueStoreAdapter
57
     */
58 4
    public function init()
59
    {
60 4
        $this->getConnection()->connect();
61
62 4
        return $this;
63
    }
64
65
    /**
66
     * @return BeanstalkdQueueStoreConnection
67
     */
68 4
    public function getConnection()
69
    {
70 4
        return $this->connection;
71
    }
72
73
    /**
74
     * @param BeanstalkdMailJob|MailJobInterface $mailJob
75
     *
76
     * @return int
77
     */
78 3
    public function enqueue(MailJobInterface $mailJob)
79
    {
80 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\...talkd\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...
81 3
        $payload = $this->createPayload($mailJob);
82 3
        $delay = (int) max(Pheanstalk::DEFAULT_DELAY, $timestamp - time());
83
84 3
        return $this->getConnection()
85 3
            ->getInstance()
86 3
            ->useTube($this->queueName)
87 3
            ->put($payload, Pheanstalk::DEFAULT_PRIORITY, $delay, $this->timeToRun);
88
    }
89
90
    /**
91
     * @return BeanstalkdMailJob|null
92
     */
93 3
    public function dequeue()
94
    {
95 3
        $job = $this->getConnection()->getInstance()->watch($this->queueName)->reserve($this->reserveTimeout);
96 3
        if ($job instanceof PheanstalkJob) {
97 3
            $data = json_decode($job->getData(), true);
98
99 3
            return new BeanstalkdMailJob(
100
                [
101 3
                    'id' => $data['id'],
102 3
                    'attempt' => $data['attempt'],
103 3
                    'message' => $data['message'],
104 3
                    'pheanstalkJob' => $job,
105
                ]
106 3
            );
107
        }
108
109 2
        return null;
110
    }
111
112
    /**
113
     * @param BeanstalkdMailJob|MailJobInterface $mailJob
114
     */
115 4
    public function ack(MailJobInterface $mailJob)
116
    {
117 4
        if ($mailJob->isNewRecord()) {
118 1
            throw new InvalidCallException('BeanstalkdMailJob cannot be a new object to be acknowledged');
119
        }
120
121 3
        $pheanstalk = $this->getConnection()->getInstance()->useTube($this->queueName);
122 3
        if ($mailJob->isCompleted()) {
123 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\...talkd\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...
124 2
        } else {
125 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\...talkd\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...
126 1
            $delay = max(0, $timestamp - time());
127
128
            // add back to the queue as it wasn't completed maybe due to some transitory error
129
            // could also be failed.
130 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\...talkd\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...
131
        }
132 3
    }
133
134
    /**
135
     *
136
     * @return bool
137
     */
138 2
    public function isEmpty()
139
    {
140 2
        $stats = $this->getConnection()->getInstance()->statsTube($this->queueName);
141
142 2
        return (int) $stats->current_jobs_delayed === 0
143 2
        && (int) $stats->current_jobs_urgent === 0
144 2
        && (int) $stats->current_jobs_ready === 0;
145
    }
146
147
    /**
148
     * @param BeanstalkdMailJob|MailJobInterface $mailJob
149
     *
150
     * @return string
151
     */
152 3
    protected function createPayload(MailJobInterface $mailJob)
153
    {
154 3
        return json_encode(
155
            [
156 3
                'id' => $mailJob->isNewRecord() ? sha1(Random::string(32)) : $mailJob->getId(),
157 3
                'attempt' => $mailJob->getAttempt(),
158 3
                'message' => $mailJob->getMessage(),
159
            ]
160 3
        );
161
    }
162
}
163