aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/StudipResponse.php
blob: a9f1a4c36997643edafe7ba358079fcc4946efb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
class StudipResponse extends Trails\Response
{
    /**
     * Outputs this response to the client using "echo" and "header".
     *
     * This extension allows the body to be a callable and handles generators
     * by outputting the chunks yielded by the generator.
     */
    public function output()
    {
        if (isset($this->status)) {
            $this->send_header(
                "{$_SERVER['SERVER_PROTOCOL']} {$this->status} {$this->reason}",
                true,
                $this->status
            );
        }

        // Send headers
        foreach ($this->headers as $k => $v) {
            $this->send_header("{$k}: {$v}");
        }

        // Determine output
        if (is_callable($this->body)) {
            $output = call_user_func($this->body);
        } else {
            $output = $this->body;
        }

        if ($output instanceof Generator) {
            // Clear output buffer
            while (ob_get_level()) {
                ob_end_clean();
            }

            // Ensure generator will run to the end
            $abort = ignore_user_abort(true);

            // Output chunks yielded by generator
            foreach ($output as $chunk) {
                if (!connection_aborted()) {
                    echo $chunk;
                    flush();
                }
            }

            // Reset user abort to previous state
            ignore_user_abort($abort);
        } else {
            echo $output;
        }
    }
}