Completed
Pull Request — master (#7)
by Klaus
02:27
created

QueueService::perform()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Linio\Component\Queue;
6
7
use Exception;
8
use Linio\Component\Queue\Adapter\NullAdapter;
9
use Linio\Component\Util\Json;
10
use Psr\Log\LoggerInterface;
11
use Psr\Log\NullLogger;
12
13
class QueueService
14
{
15
    protected AdapterInterface $adapter;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
16
    protected LoggerInterface $logger;
17
18
    public function __construct()
19
    {
20
        $this->adapter = new NullAdapter();
21
        $this->logger = new NullLogger();
22
    }
23
24
    public function add(Job $job): bool
25
    {
26
        try {
27
            $this->prepare($job);
28
            $this->adapter->add($job);
29
        } catch (Exception $e) {
30
            $this->logger->error('[Queue] An error has occurred when adding job: ' . $e->getMessage(), (array) $e);
31
32
            return false;
33
        }
34
35
        return true;
36
    }
37
38
    public function perform(Job $job): bool
39
    {
40
        try {
41
            $this->adapter->perform($job);
42
        } catch (Exception $e) {
43
            $message = sprintf('[Queue] An error has occurred while performing "%s": %s', get_class($job), $e->getMessage());
44
            $this->logger->error($message, (array) $e);
45
46
            return false;
47
        }
48
49
        return true;
50
    }
51
52
    protected function prepare(Job $job): void
53
    {
54
        $payload = $job->getPayload();
55
56
        if ($payload && !is_scalar($payload)) {
57
            $job->setPayload(Json::encode($payload));
58
        }
59
    }
60
61
    public function setAdapter(AdapterInterface $adapter): void
62
    {
63
        $this->adapter = $adapter;
64
    }
65
66
    public function setLogger(LoggerInterface $logger): void
67
    {
68
        $this->logger = $logger;
69
    }
70
}
71