Passed
Pull Request — master (#190)
by Dmitriy
02:42
created

SendAgainMiddleware::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.1481

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 3
dl 0
loc 7
ccs 2
cts 3
cp 0.6667
crap 2.1481
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Queue\Middleware;
6
7
use InvalidArgumentException;
8
use Yiisoft\Queue\Message\MessageInterface;
9
use Yiisoft\Queue\Message\FailureEnvelope;
10
use Yiisoft\Queue\QueueInterface;
11
12
/**
13
 * Failure strategy which resends the given message to a queue.
14
 */
15
final class SendAgainMiddleware implements MiddlewareInterface
16
{
17
    public const META_KEY_RESEND = 'failure-strategy-resend-attempts';
18
19
    /**
20
     * @param string $id A unique id to differentiate two and more objects of this class
21
     * @param int $maxAttempts Maximum attempts count for this strategy with the given $id before it will give up
22
     */
23 5
    public function __construct(
24
        private string $id,
25
        private int $maxAttempts,
26
        private QueueInterface $queue
27
    ) {
28 5
        if ($maxAttempts < 1) {
29
            throw new InvalidArgumentException("maxAttempts parameter must be a positive integer, $this->maxAttempts given.");
30
        }
31
    }
32
33 5
    public function process(Request $request, MessageHandlerInterface $handler): Request {
34 5
        $message = $request->getMessage();
35 5
        if ($this->suites($message)) {
36 3
            $envelope = new FailureEnvelope($message, $this->createMeta($message));
37 3
            $envelope = $this->queue->push($envelope);
38
39 3
            $request = $request->withMessage($envelope);
40 3
            return $request->withQueue($this->queue);
41
        }
42
43 3
        return $handler->handle($request);
44
    }
45
46 5
    private function suites(MessageInterface $message): bool
47
    {
48 5
        return $this->getAttempts($message) < $this->maxAttempts;
49
    }
50
51 3
    private function createMeta(MessageInterface $message): array
52
    {
53 3
        $metadata = $message->getMetadata();
54 3
        $metadata[$this->getMetaKey()] = $this->getAttempts($message) + 1;
55
56 3
        return $metadata;
57
    }
58
59 5
    private function getAttempts(MessageInterface $message): int
60
    {
61 5
        $result = $message->getMetadata()[$this->getMetaKey()] ?? 0;
62 5
        if ($result < 0) {
63 2
            $result = 0;
64
        }
65
66 5
        return (int) $result;
67
    }
68
69 5
    private function getMetaKey(): string
70
    {
71 5
        return self::META_KEY_RESEND . "-$this->id";
72
    }
73
}
74