Completed
Push — master ( 91fdab...75a7b9 )
by
unknown
13:37
created

Command/GoogleAnalyticsDataCollectCommand.php (6 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
namespace Kunstmaan\DashboardBundle\Command;
3
4
use Doctrine\ORM\EntityManager;
5
use Kunstmaan\DashboardBundle\Command\Helper\Analytics\ChartDataCommandHelper;
6
use Kunstmaan\DashboardBundle\Command\Helper\Analytics\GoalCommandHelper;
7
use Kunstmaan\DashboardBundle\Command\Helper\Analytics\MetricsCommandHelper;
8
use Kunstmaan\DashboardBundle\Command\Helper\Analytics\UsersCommandHelper;
9
use Kunstmaan\DashboardBundle\Entity\AnalyticsOverview;
10
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Input\InputOption;
13
use Symfony\Component\Console\Output\OutputInterface;
14
use Doctrine\ORM\EntityManagerInterface;
15
use Kunstmaan\DashboardBundle\Helper\Google\Analytics\ServiceHelper;
16
17
/**
18
 * @final since 5.1
19
 * NEXT_MAJOR extend from `Command` and remove `$this->getContainer` usages
20
 */
21
class GoogleAnalyticsDataCollectCommand extends ContainerAwareCommand
22
{
23
    /** @var EntityManagerInterface $em */
24
    private $em;
25
26
    /** @var OutputInterface $output */
27
    private $output;
28
29
    /** @var int $errors */
30
    private $errors = 0;
31
32
    /** @var ServiceHelper */
33
    private $serviceHelper;
34
35
    /**
36
     * @param EntityManagerInterface|null   $em
37
     * @param ServiceHelper                 $serviceHelper
38
     */
39
    public function __construct(/* EntityManagerInterface */ $em = null, ServiceHelper $serviceHelper = null)
40
    {
41
        parent::__construct();
42
43
        if (!$em instanceof EntityManagerInterface) {
44
            @trigger_error(sprintf('Passing a command name as the first argument of "%s" is deprecated since version symfony 3.4 and will be removed in symfony 4.0. If the command was registered by convention, make it a service instead. ', __METHOD__), E_USER_DEPRECATED);
45
46
            $this->setName(null === $em ? 'kuma:dashboard:widget:googleanalytics:data:collect' : $em);
47
48
            return;
49
        }
50
51
        $this->em = $em;
52
        $this->serviceHelper = $serviceHelper;
53
    }
54
55
    /**
56
     * Configures the current command.
57
     */
58
    protected function configure()
59
    {
60
        $this
61
            ->setName('kuma:dashboard:widget:googleanalytics:data:collect')
62
            ->setDescription('Collect the Google Analytics dashboard widget data')
63
            ->addOption(
64
                'config',
65
                null,
66
                InputOption::VALUE_OPTIONAL,
67
                'Specify to only update one config',
68
                false
69
            )
70
            ->addOption(
71
                'segment',
72
                null,
73
                InputOption::VALUE_OPTIONAL,
74
                'Specify to only update one segment',
75
                false
76
            )
77
            ->addOption(
78
                'overview',
79
                null,
80
                InputOption::VALUE_OPTIONAL,
81
                'Specify to only update one overview',
82
                false
83
            );
84
    }
85
86
    /**
87
     * @param InputInterface  $input
88
     * @param OutputInterface $output
89
     * @return int|null|void
90
     */
91
    protected function execute(InputInterface $input, OutputInterface $output)
92
    {
93
        if (null === $this->em) {
94
            $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
95
        }
96
97
        if (null === $this->serviceHelper) {
98
            $this->serviceHelper = $this->getContainer()->get('kunstmaan_dashboard.helper.google.analytics.service');
99
        }
100
101
        $this->output = $output;
102
103
        // check if token is set
104
        $configHelper = $this->getContainer()->get('kunstmaan_dashboard.helper.google.analytics.config');
105
        if (!$configHelper->tokenIsSet()) {
106
            $this->output->writeln('You haven\'t configured a Google account yet');
107
            return;
108
        }
109
110
        // get params
111
        $configId = false;
112
        $segmentId = false;
113
        $overviewId = false;
114
        try {
115
            $configId  = $input->getOption('config');
116
            $segmentId = $input->getOption('segment');
117
            $overviewId = $input->getOption('overview');
118
        } catch (\Exception $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
119
120
        // get the overviews
121
        try {
122
            $overviews = [];
123
124
            if ($overviewId) {
125
                $overviews[] = $this->getSingleOverview($overviewId);
126 View Code Duplication
            } else if ($segmentId) {
0 ignored issues
show
This code seems to be duplicated across 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...
127
                $overviews = $this->getOverviewsOfSegment($segmentId);
128
            } else if ($configId) {
129
                $overviews = $this->getOverviewsOfConfig($configId);
130
            } else {
131
                $overviews = $this->getAllOverviews();
132
            }
133
134
            // update the overviews
135
            $this->updateData($overviews);
136
            $result = '<fg=green>Google Analytics data updated with <fg=red>'.$this->errors.'</fg=red> error';
137
            $result .= $this->errors != 1 ? 's</fg=green>' : '</fg=green>';
138
            $this->output->writeln($result); // done
139
        } catch (\Exception $e) {
140
            $this->output->writeln($e->getMessage());
141
        }
142
143
    }
144
145
    /**
146
     * get a single overview
147
     * @param int $overviewId
148
     * @return AnalyticsOverview
149
     */
150
    private function getSingleOverview($overviewId)
151
    {
152
        // get specified overview
153
        $overviewRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsOverview');
154
        $overview = $overviewRepository->find($overviewId);
155
156
        if (!$overview) {
157
            throw new \Exception('Unkown overview ID');
158
        }
159
160
        return $overview;
161
    }
162
163
    /**
164
     * get all overviews of a segment
165
     * @param int $segmentId
166
     * @return array
167
     */
168 View Code Duplication
    private function getOverviewsOfSegment($segmentId)
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...
169
    {
170
        // get specified segment
171
        $segmentRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsSegment');
172
        $segment = $segmentRepository->find($segmentId);
173
174
        if (!$segment) {
175
            throw new \Exception('Unkown segment ID');
176
        }
177
178
        // init the segment
179
        $segmentRepository->initSegment($segment);
180
181
        // get the overviews
182
        return $segment->getOverviews();
183
    }
184
185
    /**
186
     * get all overviews of a config
187
     * @param int $configId
188
     * @return array
189
     */
190
    private function getOverviewsOfConfig($configId)
191
    {
192
        $configRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig');
193
        $segmentRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsSegment');
194
        $overviewRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsOverview');
195
        // get specified config
196
        $config = $configRepository->find($configId);
197
198
        if (!$config) {
199
            throw new \Exception('Unkown config ID');
200
        }
201
202
        // create default overviews for this config if none exist yet
203
        if (!count($config->getOverviews())) {
204
            $overviewRepository->addOverviews($config);
205
        }
206
207
        // init all the segments for this config
208
        $segments = $config->getSegments();
209
        foreach ($segments as $segment) {
210
            $segmentRepository->initSegment($segment);
211
        }
212
213
        // get the overviews
214
        return $config->getOverviews();
215
    }
216
217
    /**
218
     * get all overviews
219
     *
220
     * @return array
0 ignored issues
show
Consider making the return type a bit more specific; maybe use object[].

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
221
     */
222 View Code Duplication
    private function getAllOverviews()
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...
223
    {
224
        $configRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig');
225
        $overviewRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsOverview');
226
        $segmentRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsSegment');
227
        $configs = $configRepository->findAll();
228
229
        foreach ($configs as $config) {
230
            // add overviews if none exist yet
231
            if (count($config->getOverviews()) == 0) {
232
                $overviewRepository->addOverviews($config);
233
            }
234
235
            // init all the segments for this config
236
            $segments = $config->getSegments();
237
            foreach ($segments as $segment) {
238
                $segmentRepository->initSegment($segment);
239
            }
240
        }
241
242
        // get all overviews
243
        return $overviewRepository->findAll();
244
    }
245
246
    /**
247
     * update the overviews
248
     *
249
     * @param array $overviews collection of all overviews which need to be updated
250
     */
251
    public function updateData($overviews)
252
    {
253
        // helpers
254
        $queryHelper = $this->getContainer()->get('kunstmaan_dashboard.helper.google.analytics.query');
255
        $configHelper = $this->getContainer()->get('kunstmaan_dashboard.helper.google.analytics.config');
256
        $metrics = new MetricsCommandHelper($configHelper, $queryHelper, $this->output, $this->em);
257
        $chartData = new ChartDataCommandHelper($configHelper, $queryHelper, $this->output, $this->em);
258
        $goals = new GoalCommandHelper($configHelper, $queryHelper, $this->output, $this->em);
259
        $visitors = new UsersCommandHelper($configHelper, $queryHelper, $this->output, $this->em);
260
261
        // get data per overview
262
        foreach ($overviews as $overview) {
263
            $configHelper->init($overview->getConfig()->getId());
264
            /** @var AnalyticsOverview $overview */
265
            $this->output->writeln('Fetching data for overview "<fg=green>' . $overview->getTitle() . '</fg=green>"');
266
267
            try {
268
                // metric data
269
                $metrics->getData($overview);
270
                if ($overview->getSessions()) { // if there are any visits
271
                    // day-specific data
272
                    $chartData->getData($overview);
273
274
                    // get goals
275
                    $goals->getData($overview);
276
277
                    // visitor types
278
                    $visitors->getData($overview);
279
                } else {
280
                    // reset overview
281
                    $this->reset($overview);
282
                    $this->output->writeln("\t" . 'No visitors');
283
                }
284
            // persist entity back to DB
285
                $this->output->writeln("\t" . 'Persisting..');
286
                $this->em->persist($overview);
287
                $this->em->flush($overview);
288
289
                $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig')->setUpdated($overview->getConfig()->getId());
0 ignored issues
show
The method getId cannot be called on $overview->getConfig() (of type integer).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
290
            } catch (\Google_ServiceException $e) {
291
                $error = explode(')', $e->getMessage());
292
                $error = $error[1];
293
                $this->output->writeln("\t" . '<fg=red>Invalid segment: </fg=red>' .$error);
294
                $this->errors += 1;
295
            }
296
        }
297
    }
298
299
300
    /**
301
     * Reset the data for the overview
302
     *
303
     * @param AnalyticsOverview $overview The overview
304
     */
305
    private function reset(AnalyticsOverview $overview)
306
    {
307
        // reset overview
308
        $overview->setNewUsers(0);
309
        $overview->setReturningUsers(0);
310
    }
311
}
312