Completed
Push — master ( 67d12b...6cac8e )
by Antonio
04:02
created

BeanstalkdQueueStoreAdapter   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 138
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 1 Features 2
Metric Value
wmc 14
c 3
b 1
f 2
lcom 1
cbo 6
dl 0
loc 138
ccs 52
cts 52
cp 1
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 11 1
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
        $delay = (int) max(Pheanstalk::DEFAULT_DELAY, $timestamp - time());
72
73 3
        return $this->getConnection()
74 3
            ->getInstance()
75 3
            ->useTube($this->queueName)
76 3
            ->put($payload, Pheanstalk::DEFAULT_PRIORITY, $delay, $this->timeToRun);
77
    }
78
79 3
    public function dequeue()
80
    {
81 3
        $job = $this->getConnection()->getInstance()->watchOnly($this->queueName)->reserve(0);
82 3
        if ($job instanceof PheanstalkJob) {
83 3
            $data = json_decode($job->getData(), true);
84
85 3
            return new BeanstalkdMailJob(
86
                [
87 3
                    'id' => $data['id'],
88 3
                    'attempt' => $data['attempt'],
89 3
                    'message' => $data['message'],
90 3
                    'pheanstalkJob' => $job,
91
                ]
92 3
            );
93
        }
94
95 2
        return null;
96
    }
97
98
    /**
99
     * @param BeanstalkdMailJob|MailJobInterface $mailJob
100
     */
101 4
    public function ack(MailJobInterface $mailJob)
102
    {
103 4
        if ($mailJob->isNewRecord()) {
104 1
            throw new InvalidCallException('BeanstalkdMailJob cannot be a new object to be acknowledged');
105
        }
106
107 3
        $pheanstalk = $this->getConnection()->getInstance()->useTube($this->queueName);
108 3
        if ($mailJob->isCompleted()) {
109 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...
110 2
        } else {
111 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...
112 1
            $delay = max(0, $timestamp - time());
113
114
            // add back to the queue as it wasn't completed maybe due to some transitory error
115
            // could also be failed.
116 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...
117
        }
118 3
    }
119
120
    /**
121
     *
122
     * @return bool
123
     */
124 2
    public function isEmpty()
125
    {
126 2
        $stats = $this->getConnection()->getInstance()->statsTube($this->queueName);
127
128 2
        return (int) $stats->current_jobs_delayed === 0
129 2
        && (int) $stats->current_jobs_urgent === 0
130 2
        && (int) $stats->current_jobs_ready === 0;
131
    }
132
133
    /**
134
     * @param BeanstalkdMailJob|MailJobInterface $mailJob
135
     *
136
     * @return string
137
     */
138 3
    protected function createPayload(MailJobInterface $mailJob)
139
    {
140 3
        return json_encode(
141
            [
142 3
                'id' => $mailJob->isNewRecord() ? sha1(Random::string(32)) : $mailJob->getId(),
143 3
                'attempt' => $mailJob->getAttempt(),
144 3
                'message' => $mailJob->getMessage(),
145
            ]
146 3
        );
147
    }
148
}
149