aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/restapi/renderer/DefaultRenderer.php
blob: 836ba36b2cbd9bd897c33e1cb93fde2f8b8248db (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace RESTAPI\Renderer;

/**
 * Default base content renderer class (outputs text/plain).
 *
 * Content renderers are output filters that can reshape data before it
 * is sent to the client.
 * Each content renderer is associated with a certain content type and a
 * certain file extension. This is neccessary for content negotiation.
 *
 * @author     Jan-Hendrik Willms <tleilax+studip@gmail.com>
 * @author     <mlunzena@uos.de>
 * @license    GPL 2 or later
 * @since      Stud.IP 3.0
 * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
 */
class DefaultRenderer
{
    /**
     * Returns an associated content type.
     *
     * @return String Content/mime type for this renderer
     */
    public function contentType()
    {
        return 'text/plain';
    }

    /**
     * Returns an associated extension.
     *
     * @return String Associated extension for this renderer.
     */
    public function extension()
    {
        return '';
    }

    /**
     * Response transformation function.
     *
     * @param \RESTAPI\Response $response  the response to transform
     */
    public function render($response)
    {
        if (!isset($response['Content-Type'])) {
            $response['Content-Type'] = $this->contentType() . ';charset=utf-8';
        }
    }

    /**
     * Detects whether the renderer should respond to either a certain
     * filename (tests by extension) or to a certain media range.
     *
     * @param String $filename    Filename to test against
     * @param mixed  $media_range Media range to test against (optional,
     *                            defaults to request's accept header if set)
     * @return bool Returns whether the renderer should respond
     */
    public function shouldRespondTo($filename, $media_range = null)
    {
        // If no media range is passed, evalute http header "Accept"
        if ($media_range === null && isset($_SERVER['ACCEPT'])) {
            $media_ranges = explode(';', $_SERVER['ACCEPT']);
            $media_range = reset($media_ranges);
        }

        // Test if either the filename has the appropriate extension or
        // if the client accepts the content type
        return ($this->extension() && fnmatch('*' . $this->extension(), $filename))
            || ($media_range && fnmatch($media_range, $this->contentType()));
    }
}