Completed
Push — master ( 1de9b7...830752 )
by Kristof
38:46 queued 24:09
created

Controller/GoogleAnalyticsAJAXController.php (10 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\DashboardBundle\Controller;
4
5
use Kunstmaan\AdminBundle\FlashMessages\FlashTypes;
6
use Kunstmaan\DashboardBundle\Command\GoogleAnalyticsDataCollectCommand;
7
use Kunstmaan\DashboardBundle\Entity\AnalyticsGoal;
8
use Kunstmaan\DashboardBundle\Entity\AnalyticsSegment;
9
use Kunstmaan\DashboardBundle\Repository\AnalyticsOverviewRepository;
10
use Symfony\Component\Routing\Annotation\Route;
11
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
12
use Symfony\Component\Console\Input\ArrayInput;
13
use Symfony\Component\Console\Output\NullOutput;
14
use Symfony\Component\HttpFoundation\JsonResponse;
15
use Symfony\Component\HttpFoundation\Request;
16
17
class GoogleAnalyticsAJAXController extends Controller
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...e\Controller\Controller has been deprecated with message: since Symfony 4.2, use {@see AbstractController} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
18
{
19
    /**
20
     * @Route("/updateData", name="KunstmaanDashboardBundle_analytics_update")
21
     */
22
    public function runUpdateAction(Request $request)
23
    {
24
        $configId = $request->query->get('configId');
25
        $segmentId = $request->query->get('segmentId');
26
27
        $command = new GoogleAnalyticsDataCollectCommand();
28
        $command->setContainer($this->container);
29
        $input = new ArrayInput(array('--config' => $configId, '--segment' => $segmentId));
30
        $output = new NullOutput();
31
        $command->run($input, $output);
32
33
        return new JsonResponse(array(), 200, array('Content-Type' => 'application/json'));
34
    }
35
36
    /**
37
     * Return an ajax response with all data for an overview
38
     *
39
     * @Route("/getOverview/{id}", requirements={"id" = "\d+"}, name="KunstmaanDashboardBundle_analytics_overview_ajax")
40
     */
41
    public function getOverviewAction($id)
42
    {
43
        $em = $this->getDoctrine()->getManager();
44
        /** @var AnalyticsOverviewRepository $analyticsOverviewRepository */
45
        $analyticsOverviewRepository = $em->getRepository('KunstmaanDashboardBundle:AnalyticsOverview');
46
        $overview = $analyticsOverviewRepository->find($id);
47
48
        // goals data
49
        $goals = array();
50
        foreach ($overview->getActiveGoals() as $key => $goal) {
51
            /* @var AnalyticsGoal $goal */
52
            $goals[$key]['name'] = $goal->getName();
53
            $goals[$key]['visits'] = $goal->getVisits();
54
            $goals[$key]['id'] = $goal->getId();
55
            $goals[$key]['chartData'] = json_decode($goal->getChartData());
56
        }
57
58
        // overview data
59
        $overviewData = array(
60
            'id' => $overview->getId(),
61
            'chartData' => json_decode($overview->getChartData(), true),
62
            'chartDataMaxValue' => $overview->getChartDataMaxValue(),
63
            'title' => $overview->getTitle(),
64
            'timespan' => $overview->getTimespan(),
65
            'startOffset' => $overview->getStartOffset(),
66
            'sessions' => number_format($overview->getSessions()),
67
            'users' => number_format($overview->getUsers()),
68
            'pagesPerSession' => round($overview->getPagesPerSession(), 2),
69
            'avgSessionDuration' => $overview->getAvgSessionDuration(),
70
            'returningUsers' => number_format($overview->getReturningUsers()),
71
            'newUsers' => round($overview->getNewUsers(), 2),
72
            'pageViews' => number_format($overview->getPageViews()),
73
            'returningUsersPercentage' => $overview->getReturningUsersPercentage(),
74
            'newUsersPercentage' => $overview->getNewUsersPercentage(),
75
        );
76
77
        // put all data in the return array
78
        $return = array(
79
            'responseCode' => 200,
80
            'overview' => $overviewData,
81
            'goals' => $goals,
82
        );
83
84
        // return json response
85
        return new JsonResponse($return, 200, array('Content-Type' => 'application/json'));
86
    }
87
88
    /* =============================== ACCOUNT =============================== */
89
90
    /**
91
     * @Route("/accounts/", name="kunstmaan_dashboard_ajax_accounts")
92
     */
93
    public function getAccountsAction(Request $request)
94
    {
95
        $configHelper = $this->container->get('kunstmaan_dashboard.helper.google.analytics.config');
96
        $configId = $request->query->get('configId');
97
        if ($configId) {
98
            $configHelper->init($configId);
99
        }
100
101
        $accounts = $configHelper->getAccounts();
102
103
        return new JsonResponse($accounts, 200, array('Content-Type' => 'application/json'));
104
    }
105
106
    /**
107
     * @Route("/account/save", name="kunstmaan_dashboard_ajax_account_save")
108
     */
109 View Code Duplication
    public function saveAccountAction(Request $request)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
    {
111
        $accountId = $request->query->get('id');
112
        $configHelper = $this->container->get('kunstmaan_dashboard.helper.google.analytics.config');
113
        $configHelper->saveAccountId($accountId);
114
115
        return new JsonResponse();
116
    }
117
118
    /* =============================== PROPERTY =============================== */
119
120
    /**
121
     * @Route("/properties/", name="kunstmaan_dashboard_ajax_properties")
122
     */
123
    public function getPropertiesAction(Request $request)
124
    {
125
        $accountId = $request->query->get('accountId');
126
        $configHelper = $this->container->get('kunstmaan_dashboard.helper.google.analytics.config');
127
        $configId = $request->query->get('configId');
128
        if ($configId) {
129
            $configHelper->init($configId);
130
        }
131
132
        $properties = $configHelper->getProperties($accountId);
133
134
        return new JsonResponse($properties, 200, array('Content-Type' => 'application/json'));
135
    }
136
137
    /**
138
     * @Route("/property/save", name="kunstmaan_dashboard_ajax_property_save")
139
     */
140 View Code Duplication
    public function savePropertyAction(Request $request)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
141
    {
142
        $propertyId = $request->query->get('id');
143
        $configHelper = $this->container->get('kunstmaan_dashboard.helper.google.analytics.config');
144
        $configHelper->savePropertyId($propertyId);
145
146
        return new JsonResponse();
147
    }
148
149
    /* =============================== PROFILE =============================== */
150
151
    /**
152
     * @Route("/profiles/", name="kunstmaan_dashboard_ajax_profiles")
153
     */
154
    public function getProfilesAction(Request $request)
155
    {
156
        $accountId = $request->query->get('accountId');
157
        $propertyId = $request->query->get('propertyId');
158
        $configHelper = $this->container->get('kunstmaan_dashboard.helper.google.analytics.config');
159
        $configId = $request->query->get('configId');
160
        if ($configId) {
161
            $configHelper->init($configId);
162
        }
163
164
        $profiles = $configHelper->getProfiles($accountId, $propertyId);
165
166
        return new JsonResponse($profiles, 200, array('Content-Type' => 'application/json'));
167
    }
168
169
    /**
170
     * @Route("/profile/save", name="kunstmaan_dashboard_ajax_profile_save")
171
     */
172 View Code Duplication
    public function saveProfileAction(Request $request)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
173
    {
174
        $propertyId = $request->query->get('id');
175
        $configHelper = $this->container->get('kunstmaan_dashboard.helper.google.analytics.config');
176
        $configHelper->saveProfileId($propertyId);
177
178
        return new JsonResponse();
179
    }
180
181
    /* =============================== CONFIG =============================== */
182
183
    /**
184
     * @Route("/config/save", name="kunstmaan_dashboard_ajax_config_save")
185
     */
186
    public function saveConfigAction(Request $request)
187
    {
188
        // get params
189
        $configId = $request->query->get('configId');
190
        $accountId = $request->query->get('accountId');
191
        $propertyId = $request->query->get('propertyId');
192
        $profileId = $request->query->get('profileId');
193
        $disableGoals = $request->query->get('disableGoals');
194
195
        // edit the config
196
        $em = $this->getDoctrine()->getManager();
197
        $config = $em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig')->find($configId);
198
        if ($accountId && $propertyId && $profileId) {
199
            $config->setAccountId($accountId);
200
            $config->setPropertyId($propertyId);
201
            $config->setProfileId($profileId);
202
        }
203
204
        $em->persist($config);
0 ignored issues
show
It seems like $config defined by $em->getRepository('Kuns...nfig')->find($configId) on line 197 can also be of type null; however, Doctrine\Common\Persiste...bjectManager::persist() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
205
        $em->flush();
206
207
        // set the config name
208
        $configHelper = $this->container->get('kunstmaan_dashboard.helper.google.analytics.config');
209
        $configHelper->init($configId);
210
        $profile = $configHelper->getActiveProfile();
211
        $config->setName($profile['profileName']);
212
        $config->setDisableGoals($disableGoals);
213
214
        $em->persist($config);
0 ignored issues
show
It seems like $config defined by $em->getRepository('Kuns...nfig')->find($configId) on line 197 can also be of type null; however, Doctrine\Common\Persiste...bjectManager::persist() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
215
        $em->flush();
216
217
        $this->addFlash(
218
            FlashTypes::SUCCESS,
219
            $this->get('translator')->trans('kuma_admin.ga_ajax_controller.flash.success')
220
        );
221
222
        return new JsonResponse();
223
    }
224
225
    /**
226
     * @Route("/config/remove", name="kunstmaan_dashboard_ajax_config_remove")
227
     */
228
    public function removeConfigAction(Request $request)
229
    {
230
        // get params
231
        $configId = $request->query->get('configId');
232
233
        // edit the config
234
        $em = $this->getDoctrine()->getManager();
235
        $config = $em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig')->find($configId);
236
        $em->remove($config);
0 ignored issues
show
It seems like $config defined by $em->getRepository('Kuns...nfig')->find($configId) on line 235 can also be of type null; however, Doctrine\Common\Persiste...ObjectManager::remove() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
237
        $em->flush();
238
239
        return new JsonResponse();
240
    }
241
242
    /**
243
     * @Route("/config/get", name="kunstmaan_dashboard_ajax_config_get")
244
     */
245
    public function getConfigAction(Request $request)
246
    {
247
        $em = $this->getDoctrine()->getManager();
248
        $config = $em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig')->findFirst();
249
        $accountId = $config->getAccountId();
250
251
        if (!$accountId) {
252
            return new JsonResponse();
253
        }
254
255
        $configHelper = $this->container->get('kunstmaan_dashboard.helper.google.analytics.config');
256
        $configHelper->getAccounts();
257
        $configHelper->getProperties();
258
        $configHelper->getProfiles();
259
    }
260
261
    /* =============================== SEGMENT =============================== */
262
263
    /**
264
     * @Route("/segment/add/", name="kunstmaan_dashboard_ajax_segment_add")
265
     */
266
    public function addSegmentAction(Request $request)
267
    {
268
        $configId = $request->query->get('configId');
269
        $em = $this->getDoctrine()->getManager();
270
271
        // create a new segment
272
        $segment = new AnalyticsSegment();
273
        $query = $request->query->get('query');
274
        $name = $request->query->get('name');
275
        $segment->setQuery($query);
276
        $segment->setName($name);
277
278
        // add the segment to the config
279
        $config = $em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig')->find($configId);
280
        $segment->setConfig($config);
0 ignored issues
show
$config is of type object|null, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
281
        $segments = $config->getSegments();
282
        $segments[] = $segment;
283
        $config->setSegments($segments);
284
285
        $em->persist($config);
0 ignored issues
show
It seems like $config defined by $em->getRepository('Kuns...nfig')->find($configId) on line 279 can also be of type null; however, Doctrine\Common\Persiste...bjectManager::persist() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
286
        $em->flush();
287
288
        return new JsonResponse();
289
    }
290
291
    /**
292
     * @Route("/segment/delete", name="kunstmaan_dashboard_ajax_segment_delete")
293
     */
294
    public function deleteSegmentAction(Request $request)
295
    {
296
        $em = $this->getDoctrine()->getManager();
297
298
        $id = $request->query->get('id');
299
        $em->getRepository('KunstmaanDashboardBundle:AnalyticsSegment')->deleteSegment($id);
300
301
        return new JsonResponse();
302
    }
303
304
    /**
305
     * @Route("/segment/edit", name="kunstmaan_dashboard_ajax_segment_edit")
306
     */
307
    public function editSegmentAction(Request $request)
308
    {
309
        $em = $this->getDoctrine()->getManager();
310
311
        $id = $request->query->get('id');
312
        $query = $request->query->get('query');
313
        $name = $request->query->get('name');
314
        $segment = $em->getRepository('KunstmaanDashboardBundle:AnalyticsSegment')->find($id);
315
        $segment->setName($name);
316
        $segment->setQuery($query);
317
        $em->persist($segment);
0 ignored issues
show
It seems like $segment defined by $em->getRepository('Kuns...icsSegment')->find($id) on line 314 can also be of type null; however, Doctrine\Common\Persiste...bjectManager::persist() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
318
        $em->flush();
319
320
        return new JsonResponse();
321
    }
322
}
323