WritableStream   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 35
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A write() 0 6 3
A __construct() 0 12 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Core\Output;
6
7
use AlecRabbit\Spinner\Contract\Output\IWritableStream;
8
use AlecRabbit\Spinner\Exception\InvalidArgument;
9
use AlecRabbit\Spinner\Exception\RuntimeException;
10
use Traversable;
11
12
final class WritableStream implements IWritableStream
13
{
14
    /**
15
     * @var resource
16
     */
17
    private $stream;
18
19
    /**
20
     * @throws InvalidArgument
21
     */
22
    public function __construct(mixed $stream)
23
    {
24
        if (!is_resource($stream) || get_resource_type($stream) !== 'stream') {
25
            throw new InvalidArgument(
26
                sprintf(
27
                    'Argument is expected to be a stream(resource), "%s" given.',
28
                    get_debug_type($stream)
29
                )
30
            );
31
        }
32
33
        $this->stream = $stream;
34
    }
35
36
    /**
37
     * @codeCoverageIgnore
38
     *
39
     * @inheritDoc
40
     */
41
    public function write(Traversable $data): void
42
    {
43
        /** @var string $item */
44
        foreach ($data as $item) {
45
            if (fwrite($this->stream, $item) === false) {
46
                throw new RuntimeException('Was unable to write to a stream.');
47
            }
48
        }
49
        // fflush($this->stream);
50
    }
51
}
52