StreamRenderer::getView()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 2
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\Resource\RenderInterface;
10
use BEAR\Resource\ResourceObject;
11
12
final class StreamRenderer implements RenderInterface
13
{
14
    /**
15
     * @var RenderInterface
16
     */
17
    private $renderer;
18
19
    /**
20
     * Pushed stream
21
     *
22
     * @var resource[]
23
     */
24
    private $streams = [];
25
26
    /**
27
     * @var StreamerInterface
28
     */
29
    private $streamer;
30
31 4
    public function __construct(RenderInterface $renderer, StreamerInterface $streamer)
32
    {
33 4
        $this->renderer = $renderer;
34 4
        $this->streamer = $streamer;
35 4
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 4
    public function render(ResourceObject $ro)
41
    {
42 4
        $view = $this->getView($ro);
43 4
        $this->streamer->addStreams($this->streams);
44
45 4
        return $view;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 4
    public function getView(ResourceObject $ro)
52
    {
53 4
        if (is_array($ro->body)) {
54 2
            $this->pushArrayBody($ro);
55
56 2
            return $this->renderer->render($ro);
57
        }
58
59 2
        return $this->pushScalarBody($ro);
60
    }
61
62
    /**
63
     * @param resource $item
64
     *
65
     * @return string
66
     */
67 2
    private function pushStream($item) : string
68
    {
69 2
        $id = uniqid(__FUNCTION__ . mt_rand(), true) . '_';
70 2
        $this->streams[$id] = $item; // push
71
72 2
        return $id;
73
    }
74
75 2
    private function pushScalarBody(ResourceObject $ro) : string
76
    {
77 2
        if (is_resource($ro->body) && get_resource_type($ro->body) === 'stream') {
78 1
            return $this->pushStream($ro->body);
79
        }
80
81 1
        return $this->renderer->render($ro);
82
    }
83
84 2
    private function pushArrayBody(ResourceObject $ro)
85
    {
86 2
        foreach ($ro->body as &$item) {
87 2
            if (is_resource($item) && get_resource_type($item) === 'stream') {
88 2
                $item = $this->pushStream($item);
89
            }
90
        }
91 2
    }
92
}
93