Passed
Push — develop ( 04e5ba...4f40fb )
by Greg
20:04 queued 14:02
created

ResponseFactory::response()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 14
nc 8
nop 3
dl 0
loc 24
rs 9.4888
c 1
b 0
f 0
1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2022 webtrees development team
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16
 */
17
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Factories;
21
22
use Fig\Http\Message\StatusCodeInterface;
23
use Fisharebest\Webtrees\Contracts\ResponseFactoryInterface;
24
use Fisharebest\Webtrees\Module\ModuleThemeInterface;
25
use Fisharebest\Webtrees\Registry;
26
use Fisharebest\Webtrees\Webtrees;
27
use Psr\Http\Message\ResponseFactoryInterface as PSR17ResponseFactoryInterface;
28
use Psr\Http\Message\ResponseInterface;
29
use Psr\Http\Message\ServerRequestInterface;
30
use Psr\Http\Message\StreamFactoryInterface;
31
use Psr\Http\Message\UriInterface;
32
33
use function app;
34
use function is_string;
35
use function json_encode;
36
use function view;
37
38
use const JSON_THROW_ON_ERROR;
39
use const JSON_UNESCAPED_UNICODE;
40
41
/**
42
 * Make a PSR-7 response (using a PSR-17 response factory).
43
 */
44
class ResponseFactory implements ResponseFactoryInterface
45
{
46
    private PSR17ResponseFactoryInterface $response_factory;
47
48
    private StreamFactoryInterface $stream_factory;
49
50
    /**
51
     * @param PSR17ResponseFactoryInterface $response_factory
52
     * @param StreamFactoryInterface        $stream_factory
53
     */
54
    public function __construct(PSR17ResponseFactoryInterface $response_factory, StreamFactoryInterface $stream_factory)
55
    {
56
        $this->response_factory = $response_factory;
57
        $this->stream_factory   = $stream_factory;
58
    }
59
60
    /**
61
     * Redirect to a named route.
62
     *
63
     * @param string                                    $route_name
64
     * @param array<bool|int|string|array<string>|null> $parameters
65
     * @param int                                       $status
66
     *
67
     * @return ResponseInterface
68
     *
69
     */
70
    public function redirect(
71
        string $route_name,
72
        array $parameters = [],
73
        int $status = StatusCodeInterface::STATUS_FOUND
74
    ): ResponseInterface {
75
        $url = Registry::routeFactory()->route($route_name, $parameters);
76
77
        return $this->redirectUrl($url, $status);
78
    }
79
80
    /**
81
     * Redirect to a URL.
82
     *
83
     * @param string|UriInterface $url
84
     * @param int                 $code
85
     *
86
     * @return ResponseInterface
87
     */
88
    public function redirectUrl($url, int $code = StatusCodeInterface::STATUS_FOUND): ResponseInterface
89
    {
90
        return $this->response_factory
91
            ->createResponse($code)
92
            ->withHeader('location', (string) $url);
93
    }
94
95
    /**
96
     * @param string|array<mixed>|object $content
97
     * @param int                        $code
98
     * @param array<string,string>       $headers
99
     *
100
     * @return ResponseInterface
101
     */
102
    public function response(string|array|object $content = '', int $code = StatusCodeInterface::STATUS_OK, array $headers = []): ResponseInterface
103
>>>>>>> 90fa61f704... PHP8.0 - Union types
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_SR, expecting '{' or ';' on line 103 at column 0
Loading history...
104
    {
105
        if ($content === '' && $code === StatusCodeInterface::STATUS_OK) {
106
            $code = StatusCodeInterface::STATUS_NO_CONTENT;
107
        }
108
109
        if (is_string($content)) {
110
            $headers['content-type'] ??= 'text/html; charset=UTF-8';
111
        } else {
112
            $content                 = json_encode($content, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
113
            $headers['content-type'] ??= 'application/json';
114
        }
115
116
        $stream = $this->stream_factory->createStream($content);
117
118
        $response = $this->response_factory
119
            ->createResponse($code)
120
            ->withBody($stream);
121
122
        foreach ($headers as $key => $value) {
123
            $response = $response->withHeader($key, $value);
124
        }
125
126
        return $response;
127
    }
128
129
    /**
130
     * Create and render a view, and embed it in an HTML page.
131
     *
132
     * @param string              $view_name
133
     * @param array<string,mixed> $view_data
134
     * @param int                 $status
135
     * @param string              $layout_name
136
     *
137
     * @return ResponseInterface
138
     */
139
    public function view(
140
        string $view_name,
141
        array $view_data,
142
        int $status = StatusCodeInterface::STATUS_OK,
143
        string $layout_name = Webtrees::LAYOUT_DEFAULT
144
    ): ResponseInterface {
145
        // Render the view.
146
        $content = view($view_name, $view_data);
147
148
        // Make the view's data available to the layout.
149
        $layout_data = [
150
            'content' => $content,
151
            'request' => app(ServerRequestInterface::class),
152
            'theme'   => app(ModuleThemeInterface::class),
153
            'title'   => $view_data['title'] ?? Webtrees::NAME,
154
        ];
155
156
        // Embed the content in the layout.
157
        $html = view($layout_name, $layout_data);
158
159
        return $this->response($html, $status);
160
    }
161
}
162