Completed
Push — master ( 851558...1b6b48 )
by Oscar
09:15
created

WhoopsHandlerContainer::unknown()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace Middlewares;
5
6
use Psr\Container\ContainerInterface;
7
use Whoops\Handler\HandlerInterface;
8
use Whoops\Handler\JsonResponseHandler;
9
use Whoops\Handler\PlainTextHandler;
10
use Whoops\Handler\PrettyPageHandler;
11
use Whoops\Handler\XmlResponseHandler;
12
13
/**
14
 * Resolve a callable using a container.
15
 */
16
class WhoopsHandlerContainer implements ContainerInterface
17
{
18
    /**
19
     * {@inheritdoc}
20
     */
21
    public function has($id)
22
    {
23
        return true;
24
    }
25
26
    /**
27
     * {@inheritdoc}
28
     *
29
     * @return HandlerInterface
30
     */
31
    public function get($id)
32
    {
33
        $format = self::getPreferredFormat($id);
34
35
        return $this->$format();
36
    }
37
38
    protected function json(): HandlerInterface
39
    {
40
        $handler = new JsonResponseHandler();
41
        $handler->addTraceToOutput(true);
42
43
        return $handler;
44
    }
45
46
    protected function xml(): HandlerInterface
47
    {
48
        $handler = new XmlResponseHandler();
49
        $handler->addTraceToOutput(true);
50
51
        return $handler;
52
    }
53
54
    protected function html(): HandlerInterface
55
    {
56
        return new PrettyPageHandler();
57
    }
58
59
    protected function plain(): HandlerInterface
60
    {
61
        $handler = new PlainTextHandler();
62
        $handler->addTraceToOutput(true);
63
64
        return $handler;
65
    }
66
67
    protected function unknown(): HandlerInterface
68
    {
69
        return $this->html();
70
    }
71
72
    /**
73
     * Returns the preferred format used by whoops.
74
     */
75
    protected static function getPreferredFormat(string $accept): string
76
    {
77
        if (static::isCli()) {
78
            return 'plain';
79
        }
80
81
        $formats = [
82
            'json' => ['application/json'],
83
            'html' => ['text/html'],
84
            'xml' => ['text/xml'],
85
            'plain' => ['text/plain', 'text/css', 'text/javascript'],
86
        ];
87
88
        foreach ($formats as $format => $mimes) {
89
            foreach ($mimes as $mime) {
90
                if (stripos($accept, $mime) !== false) {
91
                    return $format;
92
                }
93
            }
94
        }
95
96
        return 'unknown';
97
    }
98
99
    protected static function isCli(): bool
100
    {
101
        return php_sapi_name() === 'cli';
102
    }
103
}
104