CallbackStream   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 82.61%

Importance

Changes 3
Bugs 0 Features 3
Metric Value
wmc 8
c 3
b 0
f 3
lcom 1
cbo 1
dl 0
loc 54
ccs 19
cts 23
cp 0.8261
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A onFrame() 0 4 1
B wait() 0 16 5
A closeAndRead() 0 5 1
readFrame() 0 1 ?
1
<?php
2
3
namespace Docker\Stream;
4
5
use Psr\Http\Message\StreamInterface;
6
7
abstract class CallbackStream
8
{
9
    protected $stream;
10
11
    private $onNewFrameCallables = [];
12
13 8
    public function __construct(StreamInterface $stream)
14
    {
15 8
        $this->stream = $stream;
16 8
    }
17
18
    /**
19
     * Called when there is a new frame from the stream
20
     *
21
     * @param callable $onNewFrame
22
     */
23 8
    public function onFrame(callable $onNewFrame)
24
    {
25 8
        $this->onNewFrameCallables[] = $onNewFrame;
26 8
    }
27
28
    /**
29
     * Read a frame in the stream
30
     *
31
     * @return mixed
32
     */
33
    abstract protected function readFrame();
34
35
    /**
36
     * Wait for stream to finish and call callables if defined
37
     */
38 8
    public function wait()
39
    {
40 8
        while (!$this->stream->eof()) {
41 8
            $frame = $this->readFrame();
42
43 8
            if ($frame !== null) {
44 8
                if (!is_array($frame)) {
45 8
                    $frame = [$frame];
46 8
                }
47
48 8
                foreach ($this->onNewFrameCallables as $newFrameCallable) {
49 8
                    call_user_func_array($newFrameCallable, $frame);
50 8
                }
51 8
            }
52 8
        }
53 8
    }
54
55
    public function closeAndRead()
56
    {
57
        $this->stream->close();
58
        $this->wait();
59
    }
60
}
61