Streamer::getStream()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 21
c 0
b 0
f 0
ccs 16
cts 16
cp 1
rs 9.3142
cc 3
eloc 16
nc 3
nop 1
crap 3
1
<?php
2
/**
3
 * This file is part of the BEAR.Streamer package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace BEAR\Streamer;
8
9
use BEAR\Streamer\Annotation\Stream;
10
11
final class Streamer implements StreamerInterface
12
{
13
    private $stream;
14
15
    /**
16
     * @var array
17
     */
18
    private $streams = [];
19
20
    /**
21
     * @Stream
22
     *
23
     * @param resource $stream
24
     */
25 4
    public function __construct($stream)
26
    {
27 4
        $this->stream = $stream;
28 4
    }
29
30
    /**
31
     * @param resource[] $streams
32
     */
33 4
    public function addStreams(array $streams)
34
    {
35 4
        $this->streams += $streams;
36 4
    }
37
38
    /**
39
     * Return single root stream
40
     *
41
     * @return resource
42
     */
43 4
    public function getStream(string $string)
44
    {
45 4
        $stream = $this->stream;
46 4
        rewind($stream);
47 4
        $hash = array_keys($this->streams);
48 4
        $regex = sprintf('/(%s)/', implode('|', $hash));
49 4
        preg_match_all($regex, $string, $match, PREG_SET_ORDER);
50 4
        $list = $this->collect($match);
0 ignored issues
show
Bug introduced by
It seems like $match can also be of type null; however, BEAR\Streamer\Streamer::collect() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
51 4
        $bodies = preg_split($regex, $string);
52 4
        foreach ($bodies as $body) {
53 4
            fwrite($stream, $body);
54 4
            $index = array_shift($list);
55 4
            if (isset($this->streams[$index])) {
56 2
                $popStream = $this->streams[$index];
57 2
                rewind($popStream);
58 4
                stream_copy_to_stream($popStream, $stream);
59
            }
60
        }
61
62 4
        return $stream;
63
    }
64
65 4
    private function collect(array $match) : array
66
    {
67 4
        $list = [];
68 4
        foreach ($match as $item) {
69 4
            $list[] = $item[0];
70
        }
71
72 4
        return $list;
73
    }
74
}
75