Issues (3627)

Controller/Api/WidgetApiController.php (4 issues)

1
<?php
2
3
/*
4
 * @copyright   2014 Mautic Contributors. All rights reserved
5
 * @author      Mautic
6
 *
7
 * @link        http://mautic.org
8
 *
9
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
10
 */
11
12
namespace Mautic\DashboardBundle\Controller\Api;
13
14
use Mautic\ApiBundle\Controller\CommonApiController;
15
use Mautic\CoreBundle\Helper\DateTimeHelper;
16
use Mautic\CoreBundle\Helper\InputHelper;
17
use Mautic\DashboardBundle\DashboardEvents;
18
use Mautic\DashboardBundle\Entity\Widget;
19
use Mautic\DashboardBundle\Event\WidgetTypeListEvent;
20
use Symfony\Component\HttpFoundation\Response;
21
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
22
23
/**
24
 * Class WidgetApiController.
25
 */
26
class WidgetApiController extends CommonApiController
27
{
28
    public function initialize(FilterControllerEvent $event)
29
    {
30
        $this->model            = $this->getModel('dashboard');
31
        $this->entityClass      = 'Mautic\DashboardBundle\Entity\Widget';
32
        $this->entityNameOne    = 'widget';
33
        $this->entityNameMulti  = 'widgets';
34
        $this->serializerGroups = [];
35
36
        parent::initialize($event);
37
    }
38
39
    /**
40
     * Obtains a list of available widget types.
41
     *
42
     * @return \Symfony\Component\HttpFoundation\Response
43
     */
44
    public function getTypesAction()
45
    {
46
        $dispatcher = $this->dispatcher;
47
        $event      = new WidgetTypeListEvent();
48
        $event->setTranslator($this->get('translator'));
49
        $dispatcher->dispatch(DashboardEvents::DASHBOARD_ON_MODULE_LIST_GENERATE, $event);
50
        $view = $this->view(['success' => 1, 'types' => $event->getTypes()], Response::HTTP_OK);
51
52
        return $this->handleView($view);
53
    }
54
55
    /**
56
     * Obtains a list of available widget types.
57
     *
58
     * @param string $type of the widget
59
     *
60
     * @return \Symfony\Component\HttpFoundation\Response
61
     */
62
    public function getDataAction($type)
63
    {
64
        $start      = microtime(true);
65
        $timezone   = InputHelper::clean($this->request->get('timezone', null));
66
        $from       = InputHelper::clean($this->request->get('dateFrom', null));
67
        $to         = InputHelper::clean($this->request->get('dateTo', null));
68
        $dataFormat = InputHelper::clean($this->request->get('dataFormat', null));
69
        $unit       = InputHelper::clean($this->request->get('timeUnit', 'Y'));
70
        $dataset    = InputHelper::clean($this->request->get('dataset', []));
71
        $response   = ['success' => 0];
72
73
        try {
74
            DateTimeHelper::validateMysqlDateTimeUnit($unit);
75
        } catch (\InvalidArgumentException $e) {
76
            return $this->returnError($e->getMessage(), Response::HTTP_BAD_REQUEST);
77
        }
78
79
        if ($timezone) {
80
            $fromDate = new \DateTime($from, new \DateTimeZone($timezone));
81
            $toDate   = new \DateTime($to, new \DateTimeZone($timezone));
82
        } else {
83
            $fromDate = new \DateTime($from);
84
            $toDate   = new \DateTime($to);
85
        }
86
87
        $params = [
88
            'timeUnit'   => InputHelper::clean($this->request->get('timeUnit', 'Y')),
89
            'dateFormat' => InputHelper::clean($this->request->get('dateFormat', null)),
90
            'dateFrom'   => $fromDate,
91
            'dateTo'     => $toDate,
92
            'limit'      => (int) $this->request->get('limit', null),
93
            'filter'     => InputHelper::clean($this->request->get('filter', [])),
94
            'dataset'    => $dataset,
95
        ];
96
97
        // Merge filters into the root array as well as that's how widget edit forms send them.
98
        $params = array_merge($params, $params['filter']);
0 ignored issues
show
It seems like $params['filter'] can also be of type string; however, parameter $arrays of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

98
        $params = array_merge($params, /** @scrutinizer ignore-type */ $params['filter']);
Loading history...
99
100
        $cacheTimeout = (int) $this->request->get('cacheTimeout', 0);
101
        $widgetHeight = (int) $this->request->get('height', 300);
102
103
        $widget = new Widget();
104
        $widget->setParams($params);
105
        $widget->setType($type);
106
        $widget->setHeight($widgetHeight);
107
108
        if (null !== $cacheTimeout) {
0 ignored issues
show
The condition null !== $cacheTimeout is always true.
Loading history...
109
            $widget->setCacheTimeout($cacheTimeout);
110
        }
111
112
        $this->model->populateWidgetContent($widget);
0 ignored issues
show
The method populateWidgetContent() does not exist on Mautic\CoreBundle\Model\AbstractCommonModel. It seems like you code against a sub-type of Mautic\CoreBundle\Model\AbstractCommonModel such as Mautic\DashboardBundle\Model\DashboardModel. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

112
        $this->model->/** @scrutinizer ignore-call */ 
113
                      populateWidgetContent($widget);
Loading history...
113
        $data = $widget->getTemplateData();
114
115
        if (!$data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
116
            return $this->notFound();
117
        }
118
119
        if ('raw' == $dataFormat) {
120
            if (isset($data['chartData']['labels']) && isset($data['chartData']['datasets'])) {
121
                $rawData = [];
122
                foreach ($data['chartData']['datasets'] as $dataset) {
123
                    $rawData[$dataset['label']] = [];
124
                    foreach ($dataset['data'] as $key => $value) {
125
                        $rawData[$dataset['label']][$data['chartData']['labels'][$key]] = $value;
126
                    }
127
                }
128
                $data = $rawData;
129
            } elseif (isset($data['raw'])) {
130
                $data = $data['raw'];
131
            }
132
        } else {
133
            if (isset($data['raw'])) {
134
                unset($data['raw']);
135
            }
136
        }
137
138
        $response['cached']         = $widget->isCached();
139
        $response['execution_time'] = microtime(true) - $start;
140
        $response['success']        = 1;
141
        $response['data']           = $data;
142
143
        $view = $this->view($response, Response::HTTP_OK);
144
145
        return $this->handleView($view);
146
    }
147
}
148