Passed
Push — master ( 160a67...24aef1 )
by Damian
02:17
created

FilesystemQueue::removeFirstLine()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 30
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 6.0029

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 30
ccs 22
cts 23
cp 0.9565
rs 8.9457
c 0
b 0
f 0
cc 6
nc 4
nop 0
crap 6.0029
1
<?php declare(strict_types=1);
2
3
namespace Initx\Driver;
4
5
use Initx\Envelope;
6
use Initx\Exception\IllegalStateException;
7
use Initx\Exception\NoSuchElementException;
8
use Initx\Queue;
9
use JMS\Serializer\SerializerBuilder;
10
use JMS\Serializer\SerializerInterface;
11
use Throwable;
12
13
final class FilesystemQueue implements Queue
14
{
15
    /**
16
     * @var string
17
     */
18
    private $path;
19
20
    /**
21
     * @var SerializerInterface
22
     */
23
    private $serializer;
24
25 7
    public function __construct(string $path, SerializerInterface $serializer = null)
26
    {
27 7
        if (!$serializer) {
28 7
            $separator = DIRECTORY_SEPARATOR;
29 7
            $metaDir = sprintf('%s%s..%s..%sconfig%sjms', __DIR__, $separator, $separator, $separator, $separator);
30 7
            $serializer = SerializerBuilder::create()
31 7
                ->addMetadataDir($metaDir, 'Initx')
32 7
                ->build();
33
        }
34 7
        $this->serializer = $serializer;
35 7
        $this->path = $path;
36 7
    }
37
38
    /**
39
     * Inserts an element if possible, otherwise throwing exception.
40
     *
41
     * @param Envelope $envelope
42
     * @return void
43
     * @throws IllegalStateException
44
     */
45 3
    public function add(Envelope $envelope): void
46
    {
47 3
        if (!$this->write($envelope)) {
48 1
            throw IllegalStateException::create("Could not write to {$this->path}");
49
        }
50 2
    }
51
52
    /**
53
     * Inserts an element if possible.
54
     *
55
     * @param Envelope $envelope
56
     * @return void
57
     */
58 2
    public function offer(Envelope $envelope): void
59
    {
60 2
        $this->write($envelope);
61 2
    }
62
63 5
    private function write(Envelope $envelope): bool
64
    {
65 5
        $content = $this->serializer->serialize($envelope, 'json') . PHP_EOL;
66
        try {
67 5
            $result = (bool)file_put_contents(
68 5
                $this->path,
69 5
                $content,
70 5
                FILE_APPEND
71
            );
72 2
        } catch (Throwable $exception) {
73 2
            $result = false;
74
        }
75
76 5
        return $result;
77
    }
78
79
    /**
80
     * Remove and return head of queue, otherwise throwing exception.
81
     *
82
     * @return Envelope
83
     * @throws NoSuchElementException | IllegalStateException
84
     */
85 3
    public function remove(): Envelope
86
    {
87 3
        if (!$envelope = $this->poll()) {
88 1
            throw new NoSuchElementException('Queue empty');
89
        }
90
91 1
        return $envelope;
92
    }
93
94 3
    private function removeFirstLine(): ?string
95
    {
96 3
        if (!file_exists($this->path)) {
97 1
            throw new IllegalStateException("File $this->path not exists");
98
        }
99 2
        $firstLine = null;
100 2
        if ($handle = fopen($this->path, 'cb+')) {
101 2
            if (!flock($handle, LOCK_EX)) {
102
                fclose($handle);
103
            }
104 2
            $offset = 0;
105 2
            $len = filesize($this->path);
106 2
            while (($line = fgets($handle, 4096)) !== false) {
107 1
                if (!$firstLine) {
108 1
                    $firstLine = $line;
109 1
                    $offset = strlen($firstLine);
110 1
                    continue;
111
                }
112 1
                $pos = ftell($handle);
113 1
                fseek($handle, $pos - strlen($line) - $offset);
114 1
                fwrite($handle, $line);
115 1
                fseek($handle, $pos);
116
            }
117 2
            fflush($handle);
118 2
            ftruncate($handle, $len - $offset);
119 2
            flock($handle, LOCK_UN);
120 2
            fclose($handle);
121
        }
122
123 2
        return $firstLine;
124
    }
125
126
    /**
127
     * Remove and return head of queue, otherwise returning null.
128
     *
129
     * @return Envelope | null
130
     * @throws IllegalStateException
131
     */
132 3
    public function poll(): ?Envelope
133
    {
134 3
        $firstLine = $this->removeFirstLine();
135
136 2
        if (!$firstLine) {
137 1
            return null;
138
        }
139
140 1
        return $this->serializer->deserialize($firstLine, Envelope::class, 'json');
141
    }
142
143
    /**
144
     * Return but do not remove head of queue, otherwise throwing exception.
145
     *
146
     * @return Envelope
147
     * @throws NoSuchElementException
148
     */
149
    public function element(): Envelope
150
    {
151
        // TODO: Implement element() method.
152
    }
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return Initx\Envelope. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
153
154
    /**
155
     * Return but do not remove head of queue, otherwise returning null.
156
     *
157
     * @return Envelope | null
158
     */
159
    public function peek(): ?Envelope
160
    {
161
        // TODO: Implement peek() method.
162
    }
163
}
164