Test Setup Failed
Push — master ( 016bc5...505cdc )
by Alec
02:25
created

StdErrOutputAdapter::write()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 7
rs 10
cc 3
nc 4
nop 3
1
<?php declare(strict_types=1);
2
3
namespace AlecRabbit\Spinner\Core\Adapters;
4
5
use AlecRabbit\Spinner\Core\Contracts\OutputInterface;
6
use function AlecRabbit\typeOf;
7
8
/**
9
 * Class StdErrOutputAdapter
10
 *
11
 * @codeCoverageIgnore
12
 */
13
class StdErrOutputAdapter implements OutputInterface
14
{
15
    /** @var resource */
16
    protected $stream;
17
18
    /**
19
     * StdErrOutputAdapter constructor.
20
     * @param mixed $stream
21
     */
22
    public function __construct($stream = STDERR)
23
    {
24
        if (!\is_resource($stream)) {
25
            throw new \InvalidArgumentException(
26
                '$stream is not a resource [' . typeOf($stream) . ']. It should never happen.'
27
            );
28
        }
29
        $this->stream = $stream;
30
    }
31
32
33
    /** {@inheritDoc} */
34
    public function write($messages, $newline = false, $options = 0): void
35
    {
36
        if (!is_iterable($messages)) {
37
            $messages = [$messages];
38
        }
39
        foreach ($messages as $message) {
40
            $this->doWrite($message, $newline);
41
        }
42
    }
43
44
    /**
45
     * Writes a message to STDERR.
46
     *
47
     * @param string $message A message to write to STDERR
48
     * @param bool $newline Whether to add a newline or not
49
     */
50
    protected function doWrite(string $message, bool $newline): void
51
    {
52
        if ($newline) {
53
            $message .= PHP_EOL;
54
        }
55
56
        if (false === @fwrite($this->stream, $message)) {
57
            // should never happen
58
            throw new \RuntimeException('Unable to write output.');
59
        }
60
61
        fflush($this->stream);
62
    }
63
64
    /**
65
     * @return resource
66
     */
67
    public function getStream()
68
    {
69
        return $this->stream;
70
    }
71
}
72