Output::output()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 13
rs 10
cc 2
nc 2
nop 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Jasny\Controller\Traits;
5
6
use Psr\Http\Message\ResponseInterface;
7
use Mimey\MimeTypes;
8
9
/**
10
 * Methods for a controller to send a response
11
 */
12
trait Output
13
{
14
    /**
15
     * Get response, set for controller
16
     */
17
    abstract protected function getResponse(): ResponseInterface;
18
19
    /**
20
     * Set response.
21
     */
22
    abstract protected function setResponse(ResponseInterface $response): void;
23
24
    /**
25
     * Get MIME type for extension
26
     */
27
    protected function getMime(string $format): string
28
    {
29
        // Check if it's already MIME
30
        if (str_contains($format, '/')) {
31
            return $format;
32
        }
33
        
34
        $mime = (new MimeTypes())->getMimeType($format);
35
36
        if (!isset($mime)) {
37
            throw new \UnexpectedValueException("Format '$format' doesn't correspond with a MIME type");
38
        }
39
        
40
        return $mime;
41
    }
42
43
    /**
44
     * Output data as json.
45
     *
46
     * @param mixed $data
47
     * @param int   $flags   Flags for json_encode
48
     * @return $this
49
     */
50
    protected function json(mixed $data, int $flags = 0): static
51
    {
52
        return $this->output(json_encode($data, $flags), 'application/json');
53
    }
54
55
    /**
56
     * Output result
57
     *
58
     * @param string      $content
59
     * @param string|null $format  Output format as MIME or extension
60
     * @return $this
61
     */
62
    protected function output(string $content, ?string $format = null): static
63
    {
64
        $response = $this->getResponse();
65
66
        if ($format !== null) {
67
            $contentType = $this->getMime($format);
68
            $response = $response->withHeader('Content-Type', $contentType);
69
        }
70
71
        $response->getBody()->write($content);
72
        $this->setResponse($response);
73
74
        return $this;
75
    }
76
}
77