Completed
Push — master ( 0cad9b...2a3bc8 )
by Antonio
06:19
created

BeanstalkdQueueStoreAdapter::enqueue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 1
crap 1
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
    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\...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...
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
    /**
80
     * @return BeanstalkdMailJob|null
81
     */
82 3
    public function dequeue()
83
    {
84 3
        $job = $this->getConnection()->getInstance()->watchOnly($this->queueName)->reserve(0);
85 3
        if ($job instanceof PheanstalkJob) {
86 3
            $data = json_decode($job->getData(), true);
87
88 3
            return new BeanstalkdMailJob(
89
                [
90 3
                    'id' => $data['id'],
91 3
                    'attempt' => $data['attempt'],
92 3
                    'message' => $data['message'],
93 3
                    'pheanstalkJob' => $job,
94
                ]
95 3
            );
96
        }
97
98 2
        return null;
99
    }
100
101
    /**
102
     * @param BeanstalkdMailJob|MailJobInterface $mailJob
103
     */
104 4
    public function ack(MailJobInterface $mailJob)
105
    {
106 4
        if ($mailJob->isNewRecord()) {
107 1
            throw new InvalidCallException('BeanstalkdMailJob cannot be a new object to be acknowledged');
108
        }
109
110 3
        $pheanstalk = $this->getConnection()->getInstance()->useTube($this->queueName);
111 3
        if ($mailJob->isCompleted()) {
112 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...
113 2
        } else {
114 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...
115 1
            $delay = max(0, $timestamp - time());
116
117
            // add back to the queue as it wasn't completed maybe due to some transitory error
118
            // could also be failed.
119 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...
120
        }
121 3
    }
122
123
    /**
124
     *
125
     * @return bool
126
     */
127 2
    public function isEmpty()
128
    {
129 2
        $stats = $this->getConnection()->getInstance()->statsTube($this->queueName);
130
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
     * @param BeanstalkdMailJob|MailJobInterface $mailJob
138
     *
139
     * @return string
140
     */
141 3
    protected function createPayload(MailJobInterface $mailJob)
142
    {
143 3
        return json_encode(
144
            [
145 3
                'id' => $mailJob->isNewRecord() ? sha1(Random::string(32)) : $mailJob->getId(),
146 3
                'attempt' => $mailJob->getAttempt(),
147 3
                'message' => $mailJob->getMessage(),
148
            ]
149 3
        );
150
    }
151
}
152