Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
UnauthorizedResponse
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
4
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        $signature = Request::getActual()->getServer('SERVER_SIGNATURE');
19
20        // When JSON is requested, return JSON error
21        if ($request->getServer('HTTP_ACCEPT') == 'application/json') {
22            $data = [
23                'code' => 401,
24                'error' => 'Unauthorized',
25                'message' => $realm,
26            ];
27            if (is_string($signature)) {
28                $data['signature'] = $signature;
29            }
30            $html = json_encode($data, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
31            $this->addHeader('Content-type: application/json');
32        } else {
33            $html = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">' . PHP_EOL
34                . '<html><head>' . PHP_EOL
35                . '<title>401 Unauthorized</title>' . PHP_EOL
36                . '</head><body>' . PHP_EOL
37                . '<h1>Unauthorized</h1>' . PHP_EOL
38                . '<p>This server could not verify that you' . PHP_EOL
39                . 'are authorized to access the document' . PHP_EOL
40                . 'requested.  Either you supplied the wrong' . PHP_EOL
41                . 'credentials (e.g., bad password), or your' . PHP_EOL
42                . 'browser doesn\'t understand how to supply' . PHP_EOL
43                . 'the credentials required.</p>' . PHP_EOL
44                . '<hr>' . (is_string($signature) ? $signature : '') . PHP_EOL
45                . '</body></html>';
46        }
47        parent::__construct($html, 1);
48
49        $this->setResponseCode(401);
50        $this->addHeader('WWW-Authenticate: Basic realm="' . str_replace('"', '\\"', $realm) . '"');
51    }
52}