File size: 2,232 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php

namespace Mautic\CoreBundle\Service;

use Mautic\CoreBundle\Model\NotificationModel;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Provides translated flash messages.
 */
class FlashBag
{
    public const LEVEL_ERROR     = 'error';

    public const LEVEL_WARNING   = 'warning';

    public const LEVEL_NOTICE    = 'notice';

    public function __construct(
        private Session $session,
        private TranslatorInterface $translator,
        private RequestStack $requestStack,
        private NotificationModel $notificationModel
    ) {
    }

    /**
     * @param string     $message
     * @param array|null $messageVars
     * @param string     $level
     * @param string     $domain
     * @param bool       $addNotification
     */
    public function add($message, $messageVars = [], $level = self::LEVEL_NOTICE, $domain = 'flashes', $addNotification = false): void
    {
        if (false === $domain) {
            // message is already translated
            $translatedMessage = $message;
        } else {
            if (isset($messageVars['pluralCount']) && empty($messageVars['%count%'])) {
                $messageVars['%count%'] = $messageVars['pluralCount'];
            }

            $translatedMessage = $this->translator->trans($message, $messageVars, $domain);
        }

        $this->session->getFlashBag()->add($level, $translatedMessage);

        if (!defined('MAUTIC_INSTALLER') && $addNotification) {
            $iconClass = match ($level) {
                self::LEVEL_WARNING => 'text-warning ri-alert-line',
                self::LEVEL_ERROR   => 'text-danger ri-error-warning-line-circle',
                default             => 'ri-information-2-line',
            };

            // If the user has not interacted with the browser for the last 30 seconds, consider the message unread
            $lastActive = $this->requestStack->getCurrentRequest()->get('mauticUserLastActive', 0);
            $isRead     = $lastActive > 30 ? 0 : 1;

            $this->notificationModel->addNotification($message, $level, $isRead, null, $iconClass);
        }
    }
}