summaryrefslogtreecommitdiff
path: root/app/Helpers/functions.php
blob: 0914b4040a5b74a12ddf1edbf39a251514c749e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
<?php

/**
 * webtrees: online genealogy
 * Copyright (C) 2019 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

declare(strict_types=1);

use Aura\Router\RouterContainer;
use Fig\Http\Message\StatusCodeInterface;
use Fisharebest\Webtrees\Application;
use Fisharebest\Webtrees\Html;
use Fisharebest\Webtrees\Session as WebtreesSession;
use Fisharebest\Webtrees\View as WebtreesView;
use Fisharebest\Webtrees\Webtrees;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamFactoryInterface;

/**
 * Get the IoC container, or fetch something from it.
 *
 * @param string|null $abstract
 *
 * @return mixed
 */
function app(string $abstract = null)
{
    if ($abstract === null) {
        return Application::getInstance();
    }

    return Application::getInstance()->make($abstract);
}

/**
 * Generate a URL to an asset file in the public folder.
 * Add a version parameter for cache-busting.
 *
 * @param string $path
 *
 * @return string
 */
function asset(string $path): string
{
    if (substr($path, -1) === '/') {
        $version = '';
    } elseif (Webtrees::STABILITY === '') {
        $version = '?v=' . Webtrees::VERSION;
    } else {
        $version = '?v=' . filemtime(Webtrees::ROOT_DIR . 'public/' . $path);
    }

    $base_url = app(ServerRequestInterface::class)->getAttribute('base_url');

    return $base_url . '/public/' . $path . $version;
}

/**
 * Generate a CSRF token form field.
 *
 * @return string
 */
function csrf_field()
{
    return '<input type="hidden" name="_csrf" value="' . e(WebtreesSession::getCsrfToken()) . '">';
}

/**
 * Get the CSRF token value.
 *
 * @return string
 */
function csrf_token()
{
    return WebtreesSession::getCsrfToken();
}

/**
 * @param string $url
 * @param int    $code
 *
 * @return ResponseInterface
 */
function redirect(string $url, $code = StatusCodeInterface::STATUS_FOUND): ResponseInterface
{
    /** @var ResponseFactoryInterface $response_factory */
    $response_factory = app(ResponseFactoryInterface::class);

    return $response_factory
        ->createResponse($code)
        ->withHeader('Location', $url);
}

/**
 * Create a response.
 *
 * @param mixed    $content
 * @param int      $code
 * @param string[] $headers
 *
 * @return ResponseInterface
 */
function response($content = '', $code = StatusCodeInterface::STATUS_OK, $headers = []): ResponseInterface
{
    if ($content === '' && $code === StatusCodeInterface::STATUS_OK) {
        $code = StatusCodeInterface::STATUS_NO_CONTENT;
    }

    if ($headers === []) {
        if (is_string($content)) {
            $headers = [
                'Content-Type'   => 'text/html; charset=utf-8',
                'Content-Length' => (string) strlen($content),
            ];
        } else {
            $content = json_encode($content, JSON_UNESCAPED_UNICODE);
            $headers = [
                'Content-Type'   => 'application/json',
                'Content-Length' => (string) strlen($content),
            ];
        }
    }

    /** @var ResponseFactoryInterface $response_factory */
    $response_factory = app(ResponseFactoryInterface::class);

    /** @var StreamFactoryInterface $stream_factory */
    $stream_factory = app(StreamFactoryInterface::class);

    $stream = $stream_factory->createStream($content);

    $response = $response_factory
        ->createResponse($code)
        ->withBody($stream);

    foreach ($headers as $key => $value) {
        $response = $response->withHeader($key, $value);
    }

    return $response;
}

/**
 * Generate a URL for a named route.
 *
 * @param string  $route_name
 * @param mixed[] $parameters
 *
 * @return string
 */
function route(string $route_name, array $parameters = []): string
{
    $request          = app(ServerRequestInterface::class);
    $base_url         = $request->getAttribute('base_url');
    $router_container = app(RouterContainer::class);
    $route            = $router_container->getMap()->getRoute($route_name);

    // Generate the URL.
    $url = $router_container->getGenerator()->generate($route_name, $parameters);

    // Aura ignores parameters that are not tokens.  We need to add them as query parameters.
    $parameters = array_filter($parameters, static function (string $key) use ($route): bool {
        return !str_contains($route->path, '{' . $key . '}') && !str_contains($route->path, '{/' . $key . '}');
    }, ARRAY_FILTER_USE_KEY);

    if ($request->getAttribute('rewrite_urls') === '1') {
        // Make the pretty URL absolute.
        $base_path = parse_url($base_url, PHP_URL_PATH) ?? '';
        $url = $base_url . substr($url, strlen($base_path));
    } else {
        // Turn the pretty URL into an ugly one.
        $path       = parse_url($url, PHP_URL_PATH);
        $parameters = ['route' => $path] + $parameters;
        $url        = $base_url . '/index.php';
    }

    return Html::url($url, $parameters);
}

/**
 * Cerate and render a view in a single operation.
 *
 * @param string  $name
 * @param mixed[] $data
 *
 * @return string
 */
function view(string $name, array $data = [])
{
    return WebtreesView::make($name, $data);
}