TranscodingHandler::read()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 34
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 17
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 34
ccs 18
cts 18
cp 1
crap 5
rs 9.3888
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Uxmp\Core\Component\Io\Transcoder;
6
7
use Psr\Log\LoggerInterface;
8
9
final class TranscodingHandler
10
{
11
    private string $buffer = '';
12
13
    /** @var null|resource */
14
    private $handle;
15
16 4
    public function __construct(
17
        private readonly ?LoggerInterface $logger,
18
        private readonly TranscoderInterface $transcoder,
19
    ) {
20 4
    }
21
22
    /**
23
     * @param int<0, max> $length
24
     */
25 3
    public function __invoke(int $length): string
26
    {
27 3
        $this->logger?->debug(sprintf('request: %d bytes', $length));
28
29 3
        $chunk = $this->read($length);
30
31 3
        $this->logger?->debug(sprintf('got %d bytes', strlen($chunk)));
32
33 3
        if ($chunk !== '') {
34 2
            if (strlen($chunk) < $length) {
35 1
                $chunk .= str_repeat("\0", $length - strlen($chunk));
36
37 1
                $this->logger?->debug('add null values');
38
            }
39
40 2
            return $chunk;
41
        }
42
43
        // return only null (if the content length is greater than the actual size)
44 1
        return str_repeat("\0", $length);
45
    }
46
47 3
    private function read(int $length): string
48
    {
49 3
        $result = '';
50
51 3
        if ($this->handle === null) {
52 3
            $this->handle = $this->transcoder->getHandle();
53
        }
54
55 3
        while (strlen($this->buffer) < $length) {
56 3
            $chunk = (string) fread($this->handle, $length);
57
58 3
            $this->logger?->debug(sprintf('read %d bytes - got %d', $length, strlen($chunk)));
59
60 3
            if ($chunk === '') {
61 2
                $result = $this->buffer;
62
63 2
                $this->buffer = '';
64 2
                break;
65
            }
66
67 2
            $this->logger?->debug(sprintf('buffer %d bytes (+%d)', strlen($this->buffer) + strlen($chunk), strlen($chunk)));
68
69 2
            $this->buffer .= $chunk;
70
71 2
            if (strlen($this->buffer) >= $length) {
72 1
                $result = substr($this->buffer, 0, $length);
73
74 1
                $this->buffer = substr($this->buffer, $length);
75
76 1
                break;
77
            }
78
        }
79
80 3
        return $result;
81
    }
82
}
83