File size: 2,220 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
67
68
69
70
71
72
73
74
75
76
77
<?php

namespace Mautic\DashboardBundle\Dashboard;

use Mautic\CoreBundle\Helper\UserHelper;
use Mautic\DashboardBundle\Model\DashboardModel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class Widget
{
    public const FORMAT_HUMAN = 'M j, Y';

    public const FORMAT_MYSQL = 'Y-m-d';

    public function __construct(
        private DashboardModel $dashboardModel,
        private UserHelper $userHelper,
        private Session $session
    ) {
    }

    /**
     * Get ready widget to populate in template.
     *
     * @return bool|\Mautic\DashboardBundle\Entity\Widget
     */
    public function get(int $widgetId)
    {
        /** @var \Mautic\DashboardBundle\Entity\Widget $widget */
        $widget = $this->dashboardModel->getEntity($widgetId);

        if (null === $widget || !$widget->getId()) {
            throw new NotFoundHttpException('Not found.');
        }

        if ($widget->getCreatedBy() !== $this->userHelper->getUser()->getId()) {
            // Unauthorized access
            throw new AccessDeniedException();
        }

        $filter = $this->dashboardModel->getDefaultFilter();

        $this->dashboardModel->populateWidgetContent($widget, $filter);

        return $widget;
    }

    /**
     * Set filter from POST to session.
     *
     * @throws \Exception
     */
    public function setFilter(Request $request): void
    {
        if (!$request->isMethod(Request::METHOD_POST)) {
            return;
        }

        $dateRangeFilter = $request->get('daterange', []);

        if (!empty($dateRangeFilter['date_from'])) {
            $from = new \DateTime($dateRangeFilter['date_from']);
            $this->session->set('mautic.daterange.form.from', $from->format(self::FORMAT_MYSQL));
        }

        if (!empty($dateRangeFilter['date_to'])) {
            $to = new \DateTime($dateRangeFilter['date_to']);
            $this->session->set('mautic.daterange.form.to', $to->format(self::FORMAT_MYSQL));
        }

        $this->dashboardModel->clearDashboardCache();
    }
}