Completed
Push — master ( e327bd...2b2b50 )
by Nikolas
03:41
created

DelayedOutputRenderer::render()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 29
rs 8.8571
cc 2
eloc 19
nc 1
nop 1
1
<?php namespace rtens\domin\delivery\web\renderers;
2
3
use rtens\domin\delivery\DelayedOutput;
4
use rtens\domin\delivery\web\Element;
5
use rtens\domin\delivery\web\WebRenderer;
6
7
class DelayedOutputRenderer implements WebRenderer {
8
9
    /**
10
     * @var int If >0, the buffer is filled with null bytes to be forced to flush.
11
     */
12
    public static $bufferSize = 0;
13
14
    /**
15
     * @param mixed $value
16
     * @return bool
17
     */
18
    public function handles($value) {
19
        return $value instanceof DelayedOutput;
20
    }
21
22
    /**
23
     * @param DelayedOutput $value
24
     * @return DelayedOutput
25
     */
26
    public function render($value) {
27
        header('Content-Encoding: none;');
28
        header('X-Accel-Buffering: no');
29
        ob_end_flush();
30
31
        $value->setPrinter(function ($string) {
32
            echo $string;
33
34
            $length = strlen($string);
35
            if (self::$bufferSize > $length) {
36
                echo str_repeat("\x00", self::$bufferSize - $length + 1);
37
            }
38
39
            flush();
40
            ob_flush();
41
        });
42
        $value->setExceptionHandler(function (\Exception $exception) {
43
            echo '</pre>';
44
            echo new Element('div', ['class' => 'alert alert-danger'], [
45
                htmlentities($exception->getMessage())
46
            ]);
47
        });
48
49
        return new DelayedOutput(function () use ($value) {
50
            $value->write('<pre>');
51
            $value->__toString();
52
            $value->write('</pre>');
53
        });
54
    }
55
56
    /**
57
     * @param mixed $value
58
     * @return array|Element[]
59
     */
60
    public function headElements($value) {
61
        return [
62
            new Element('script', [], ['
63
                var scrolled = true;
64
65
                var keepScrolling = setInterval(function () {
66
                    scrolled = true;
67
                    window.scrollTo(0,document.body.scrollHeight);
68
                }, 100);
69
70
                window.addEventListener("scroll", function () {
71
                    if (!scrolled) {
72
                        clearInterval(keepScrolling);
73
                    }
74
                    scrolled = false;
75
                });
76
            '])
77
        ];
78
    }
79
}