Completed
Push — master ( ef610a...dc0762 )
by Gabor
24:45
created

FinalMiddleware::filterHeaderName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
/**
3
 * WebHemi.
4
 *
5
 * PHP version 5.6
6
 *
7
 * @copyright 2012 - 2016 Gixx-web (http://www.gixx-web.com)
8
 * @license   https://opensource.org/licenses/MIT The MIT License (MIT)
9
 *
10
 * @link      http://www.gixx-web.com
11
 */
12
namespace WebHemi\Middleware;
13
14
use Psr\Http\Message\ResponseInterface;
15
use Psr\Http\Message\ServerRequestInterface;
16
use RuntimeException;
17
use WebHemi\Config\ConfigInterface;
18
use WebHemi\Adapter\Renderer\RendererAdapterInterface;
19
20
/**
21
 * Class FinalMiddleware.
22
 */
23
class FinalMiddleware implements MiddlewareInterface
24
{
25
    /** @var RendererAdapterInterface */
26
    private $templateRenderer;
27
    /** @var ConfigInterface */
28
    private $templateConfig;
29
30
    /**
31
     * FinalMiddleware constructor.
32
     *
33
     * @param RendererAdapterInterface $templateRenderer
34
     * @param ConfigInterface          $templateConfig
35
     */
36
    public function __construct(RendererAdapterInterface $templateRenderer, ConfigInterface $templateConfig)
37
    {
38
        $this->templateRenderer = $templateRenderer;
39
        $this->templateConfig = $templateConfig;
40
    }
41
42
    /**
43
     * Sends out the headers and prints the response body to the output.
44
     *
45
     * @param ServerRequestInterface $request
46
     * @param ResponseInterface      $response
47
     *
48
     * @return ResponseInterface
49
     */
50
    public function __invoke(ServerRequestInterface &$request, ResponseInterface $response)
51
    {
52
        if (headers_sent()) {
53
            throw new RuntimeException('Unable to emit response; headers already sent');
54
        }
55
56
        $content = $response->getBody();
57
58
        // Handle errors here.
59
        if ($response->getStatusCode() !== 200) {
60
            $errorTemplate = $this->templateConfig->get('template_map/error' . $response->getStatusCode());
61
            $error = $request->getAttribute('exception');
62
            $content = $this->templateRenderer->render($errorTemplate, ['exception' => $error]);
0 ignored issues
show
Documentation introduced by
$errorTemplate is of type array|object<WebHemi\Config\Config>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
63
        }
64
65
        $response = $this->injectContentLength($response);
66
67
        $reasonPhrase = $response->getReasonPhrase();
68
        header(sprintf(
69
            'HTTP/%s %d%s',
70
            $response->getProtocolVersion(),
71
            $response->getStatusCode(),
72
            ($reasonPhrase ? ' ' . $reasonPhrase : '')
73
        ));
74
75
        foreach ($response->getHeaders() as $headerName => $values) {
76
            $name  = $this->filterHeaderName($headerName);
77
            $first = true;
78
            foreach ($values as $value) {
79
                header(sprintf(
80
                    '%s: %s',
81
                    $name,
82
                    $value
83
                ), $first);
84
                $first = false;
85
            }
86
        }
87
88
        echo $content;
89
        return $response;
90
    }
91
92
    /**
93
     * Inject the Content-Length header if is not already present.
94
     *
95
     * @param ResponseInterface $response
96
     *
97
     * @return ResponseInterface
98
     */
99
    private function injectContentLength(ResponseInterface $response)
100
    {
101
        if (!$response->hasHeader('Content-Length')&& !is_null($response->getBody()->getSize())) {
102
            $response = $response->withHeader('Content-Length', (string) $response->getBody()->getSize());
103
        }
104
105
        return $response;
106
    }
107
108
    /**
109
     * Filter a header name to word case.
110
     *
111
     * @param string $headerName
112
     *
113
     * @return string
114
     */
115
    private function filterHeaderName($headerName)
116
    {
117
        $filtered = str_replace('-', ' ', $headerName);
118
        $filtered = ucwords($filtered);
119
        return str_replace(' ', '-', $filtered);
120
    }
121
}
122