xref: /webtrees/app/Helpers/functions.php (revision ad7270802ba57a28d195fc58fcc55f26458a779a)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17declare(strict_types=1);
18
19use Fisharebest\Webtrees\Application;
20use Fisharebest\Webtrees\Webtrees;
21use Illuminate\Cache\Repository;
22
23/**
24 * Get the IoC container, or fetch something from it.
25 *
26 * @param string|null $abstract
27 *
28 * @return Application|Repository|mixed
29 */
30function app(string $abstract = null)
31{
32    if ($abstract === null) {
33        return Application::getInstance();
34    } else {
35        return Application::getInstance()->make($abstract);
36    }
37}
38
39/**
40 * Generate a URL to an asset file in the public folder.
41 * Add a version parameter for cache-busting.
42 *
43 * @param string $path
44 *
45 * @return string
46 */
47function asset(string $path): string
48{
49    if (Webtrees::STABILITY === '') {
50        $version = Webtrees::VERSION;
51    } else {
52        $version = filemtime(WT_ROOT . 'public/' . $path);
53    }
54
55    return 'public/' . $path . '?v=' . $version;
56}
57
58/**
59 * Generate a CSRF token form field.
60 *
61 * @return string
62 */
63function csrf_field()
64{
65    return '<input type="hidden" name="csrf" value="' . e(\Fisharebest\Webtrees\Session::getCsrfToken()) . '">';
66}
67
68/**
69 * Get the CSRF token value.
70 *
71 * @return string
72 */
73function csrf_token()
74{
75    return \Fisharebest\Webtrees\Session::getCsrfToken();
76}
77
78/**
79 * Generate a URL for a named route.
80 *
81 * @param string $route
82 * @param array  $parameters
83 * @param bool   $absolute
84 *
85 * @return string
86 */
87function route(string $route, array $parameters = [], bool $absolute = true): string
88{
89    $parameters = ['route' => $route] + $parameters;
90
91    if ($absolute) {
92        return \Fisharebest\Webtrees\Html::url(WT_BASE_URL . 'index.php', $parameters);
93    }
94
95    return \Fisharebest\Webtrees\Html::url('index.php', $parameters);
96}
97
98/**
99 * Cerate and render a view in a single operation.
100 *
101 * @param string  $name
102 * @param mixed[] $data
103 *
104 * @return string
105 */
106function view(string $name, array $data = [])
107{
108    return \Fisharebest\Webtrees\View::make($name, $data);
109}
110