xref: /webtrees/app/FlashMessages.php (revision 8b67c11a1199191915b4af08a3841e7ce9d528b6)
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 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees;
19
20use stdClass;
21
22/**
23 * Generate messages in one request and display them in the next.
24 */
25class FlashMessages
26{
27    // Session storage key
28    private const FLASH_KEY = 'flash_messages';
29
30    /**
31     * Add a message to the session storage.
32     *
33     * @param string $text
34     * @param string $status "success", "info", "warning" or "danger"
35     *
36     * @return void
37     */
38    public static function addMessage($text, $status = 'info')
39    {
40        $message         = new stdClass();
41        $message->text   = $text;
42        $message->status = $status;
43
44        $messages   = Session::get(self::FLASH_KEY, []);
45        $messages[] = $message;
46        Session::put(self::FLASH_KEY, $messages);
47    }
48
49    /**
50     * Get the current messages, and remove them from session storage.
51     *
52     * @return stdClass[]
53     */
54    public static function getMessages(): array
55    {
56        $messages = Session::get(self::FLASH_KEY, []);
57        Session::forget(self::FLASH_KEY);
58
59        return $messages;
60    }
61}
62