Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
25 / 25
UnauthorizedResponse
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
25 / 25
 __construct
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
25 / 25
1<?php
2
3namespace Miniframe\Response;
4
5use Miniframe\Core\Request;
6use Miniframe\Core\Response;
7
8class UnauthorizedResponse extends Response
9{
10    /**
11     * Construct the response
12     *
13     * @param string $realm Realm we need to identify to.
14     */
15    public function __construct(string $realm)
16    {
17        $request = Request::getActual();
18
19        // When JSON is requested, return JSON error
20        if ($request->getServer('HTTP_ACCEPT') == 'application/json') {
21            $html = json_encode([
22                'code' => 401,
23                'error' => 'Unauthorized',
24                'message' => $realm,
25            ], JSON_PRETTY_PRINT);
26            $this->addHeader('Content-type: application/json');
27        } else {
28            $html = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">' . PHP_EOL
29                . '<html><head>' . PHP_EOL
30                . '<title>401 Unauthorized</title>' . PHP_EOL
31                . '</head><body>' . PHP_EOL
32                . '<h1>Unauthorized</h1>' . PHP_EOL
33                . '<p>This server could not verify that you' . PHP_EOL
34                . 'are authorized to access the document' . PHP_EOL
35                . 'requested.  Either you supplied the wrong' . PHP_EOL
36                . 'credentials (e.g., bad password), or your' . PHP_EOL
37                . 'browser doesn\'t understand how to supply' . PHP_EOL
38                . 'the credentials required.</p>' . PHP_EOL
39                . '<hr>' . (Request::getActual()->getServer('SERVER_SIGNATURE') ?? '') . PHP_EOL
40                . '</body></html>';
41        }
42        parent::__construct($html, 1);
43
44        $this->setResponseCode(401);
45        $this->addHeader('WWW-Authenticate: Basic realm="' . str_replace('"', '\\"', $realm) . '"');
46    }
47}