Passed
Push — master ( 8e0ee7...e38747 )
by Alexpts
01:34
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

3 Methods

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