Test Setup Failed
Push — master ( 246aa3...2d0e6f )
by Alexpts
01:50
created

Writer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 95%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 50
ccs 19
cts 20
cp 0.95
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PTS\Transport;
4
5
class Writer implements WriterInterface
6
{
7
8
    protected int $maxChunkSize = 0;
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...
9
10
    public function setMaxChunkSize(int $size = 8192): void
11 4
    {
12
        $this->maxChunkSize = $size;
13 4
    }
14 4
15
    /**
16
     * @param resource $target
17
     * @param string $buffer
18
     * @param int|null $length - записать число байт в сокет
19
     *
20
     * @return int число записанных байт
21
     */
22
    public function write($target, string $buffer, int $length = null): int
23 16
    {
24
        $length = $length ?? mb_strlen($buffer, '8bit');
25 16
26
        $written = 0;
27 16
        while ($written < $length) {
28 16
            $size = $this->getWriteSize($length, $written);
29 12
            $chunk = mb_strcut($buffer, $written, $size, '8bit');
30 12
            $byteCount = @fwrite($target, $chunk, $size);
31 12
32
            if (!$byteCount) {
33 12
                break;
34
            }
35
36
            $written += $byteCount;
37 12
        }
38
39
        return $written;
40 16
    }
41
42
    protected function getWriteSize(int $allSize, int $written): int
43 12
    {
44
        $maxSize = $this->maxChunkSize;
45 12
        if ($maxSize === 0) {
46 12
            return $allSize;
47 12
        }
48
49
        $needWrite = $allSize - $written;
50 3
51
        return $needWrite > $maxSize ? $maxSize : $needWrite;
52 3
    }
53
}
54