Completed
Push — 1.x ( d4bf15...1f27e1 )
by Joel
02:59
created

DockerRawStream::readFrame()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 23
rs 8.5907
cc 5
eloc 13
nc 16
nop 0
1
<?php
2
3
namespace Docker\Stream;
4
5
use Psr\Http\Message\StreamInterface;
6
7
class DockerRawStream
8
{
9
    const HEADER = 'application/vnd.docker.raw-stream';
10
11
    /** @var StreamInterface Stream for the response */
12
    protected $stream;
13
14
    /** @var callable[] A list of callable to call when there is a stdin output */
15
    protected $onStdinCallables = [];
16
17
    /** @var callable[] A list of callable to call when there is a stdout output */
18
    protected $onStdoutCallables = [];
19
20
    /** @var callable[] A list of callable to call when there is a stderr output */
21
    protected $onStderrCallables = [];
22
23
    public function __construct(StreamInterface $stream)
24
    {
25
        $this->stream = $stream;
26
    }
27
28
    /**
29
     * Add a callable to read stdin
30
     *
31
     * @param callable $callback
32
     */
33
    public function onStdin(callable $callback)
34
    {
35
        $this->onStdinCallables[] = $callback;
36
    }
37
38
    /**
39
     * Add a callable to read stdout
40
     *
41
     * @param callable $callback
42
     */
43
    public function onStdout(callable $callback)
44
    {
45
        $this->onStdoutCallables[] = $callback;
46
    }
47
48
    /**
49
     * Add a callable to read stderr
50
     *
51
     * @param callable $callback
52
     */
53
    public function onStderr(callable $callback)
54
    {
55
        $this->onStderrCallables[] = $callback;
56
    }
57
58
    /**
59
     * Read a frame in the stream
60
     */
61
    protected function readFrame()
62
    {
63
        $header  = $this->stream->read(8);
64
        $decoded = unpack('C1type/C3/N1size', $header);
65
        $output  = $this->stream->read($decoded['size']);
66
        $callbackList = [];
67
68
        if ($decoded['type'] == 0) {
69
            $callbackList = $this->onStdinCallables;
70
        }
71
72
        if ($decoded['type'] == 1) {
73
            $callbackList = $this->onStdoutCallables;
74
        }
75
76
        if ($decoded['type'] == 2) {
77
            $callbackList = $this->onStderrCallables;
78
        }
79
80
        foreach ($callbackList as $callback) {
81
            $callback($output);
82
        }
83
    }
84
85
    /**
86
     * Wait for stream to finish and call callables if defined
87
     */
88
    public function wait()
89
    {
90
        while (!$this->stream->eof()) {
91
            $this->readFrame();
92
        }
93
    }
94
}
95