Completed
Push — master ( d6e5bd...91fdab )
by Sander
13:05
created

Command/Helper/Analytics/GoalCommandHelper.php (3 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\Helper\Analytics;
3
4
use Kunstmaan\DashboardBundle\Entity\AnalyticsGoal;
5
use Kunstmaan\DashboardBundle\Entity\AnalyticsOverview;
6
7
class GoalCommandHelper extends AbstractAnalyticsCommandHelper
8
{
9
    /**
10
     * @return array
0 ignored issues
show
Should the return type not be array|false? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
11
     */
12
    private function getAllGoals()
13
    {
14
        // Get the goals from the saved profile. These are a maximum of 20 goals.
15
        $goals = $this
16
            ->query
17
            ->getServiceHelper()
18
            ->getService()
19
            ->management_goals
20
            ->listManagementGoals(
21
                $this->configHelper->getAccountId(),
22
                $this->configHelper->getPropertyId(),
23
                $this->configHelper->getProfileId()
24
            )
25
            ->items;
26
27
        if (is_array($goals)) {
28
            return $goals;
29
        }
30
31
        return false;
32
    }
33
34
    /**
35
     * @return array
0 ignored issues
show
Should the return type not be false|string[]?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
36
     */
37
    private function prepareMetrics()
38
    {
39
        $goals = $this->getAllGoals();
40
        if (!$goals) {
41
            return false;
42
        }
43
44
        $metrics = array();
45
        foreach ($goals as $key => $value) {
46
            $metrics[] = 'ga:goal' . ($key + 1) . 'Completions';
47
        }
48
        // Create the metric parameter string, there is a limit of 10 metrics per query, and a max of 20 goals available.
49
        if (count($metrics) <= 10) {
50
            $part1 = implode(',', $metrics);
51
52
            return array($part1);
53
        } else {
54
            $part1 = implode(',', array_slice($metrics, 0, 10));
55
            $part2 = implode(',', array_slice($metrics, 10, 10));
56
57
            return array($part1, $part2);
58
        }
59
    }
60
61
    /**
62
     * @param AnalyticsOverview $overview
63
     * @param                   $metrics
64
     * @param                   $dimensions
65
     *
66
     * @return mixed
67
     */
68 View Code Duplication
    private function requestGoalResults(AnalyticsOverview $overview, $metrics, $dimensions)
69
    {
70
        $timestamps = $this->getTimestamps($overview);
71
72
        // execute query
73
        $results = $this->query->getResultsByDate(
74
            $timestamps['begin'],
75
            $timestamps['end'],
76
            $metrics,
77
            $dimensions
78
        );
79
80
        return $results->getRows();
81
    }
82
83
    /**
84
     * get data and save it for the overview
85
     *
86
     * @param AnalyticsOverview $overview The overview
87
     */
88
    public function getData(&$overview)
89
    {
90
        $this->output->writeln("\t" . 'Fetching goals..');
91
92
        // calculate timespan
93
        $timespan = $overview->getTimespan() - $overview->getStartOffset();
94
        if ($timespan <= 1) {
95
            $extra = array('dimensions' => 'ga:date,ga:hour');
96
            $start = 2;
97
        } else {
98
            if ($timespan <= 7) {
99
                $extra = array('dimensions' => 'ga:date,ga:hour');
100
                $start = 2;
101
            } else {
102
                if ($timespan <= 31) {
103
                    $extra = array('dimensions' => 'ga:week,ga:day,ga:date');
104
                    $start = 3;
105
                } else {
106
                    $extra = array('dimensions' => 'ga:isoYearIsoWeek');
107
                    $start = 1;
108
                }
109
            }
110
        }
111
112
        // add segment
113
        if ($overview->getSegment()) {
114
            $extra['segment'] = $overview->getSegment()->getQuery();
115
        }
116
117
        $goals = $this->getAllGoals();
118
        if (!$goals) {
119
            return;
120
        }
121
        $goaldata = array();
122
123
        // Create an array with for each goal an entry to create the metric parameter.
124
        foreach ($goals as $key => $value) {
125
            $key++;
126
            $goaldata[] = array('position' => $key, 'name' => $value->name);
127
        }
128
129
        $metrics = $this->prepareMetrics();
130
131
        $rows = $this->requestGoalResults($overview, $metrics[0], $extra);
132
        // Execute an extra query if there are more than 10 goals to query
133
        if (count($metrics) > 1) {
134
            $rows2     = $this->requestGoalResults($overview, $metrics[1], $extra);
135
            $rows2size = count($rows2);
136
            for ($i = 0; $i < $rows2size; $i++) {
137
                // Merge the results of the extra query data with the previous query data.
138
                $rows[$i] = array_merge($rows[$i], array_slice($rows2[$i], $start, count($rows2) - $start));
139
            }
140
        }
141
142
        // Create a result array to be parsed and create Goal objects from
143
        $goalCollection = array();
144
        $goaldatasize   = count($goaldata);
145
        for ($i = 0; $i < $goaldatasize; $i++) {
146
            $goalEntry = array();
147
            foreach ($rows as $row) {
148
                // Create a timestamp for each goal visit (this depends on the timespan of the overview: split per hour, day, week, month)
149 View Code Duplication
                if ($timespan <= 1) {
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...
150
                    $timestamp = mktime(
151
                        $row[1],
152
                        0,
153
                        0,
154
                        substr($row[0], 4, 2),
155
                        substr($row[0], 6, 2),
156
                        substr($row[0], 0, 4)
157
                    );
158
                    $timestamp = date('Y-m-d H:00', $timestamp);
159
                } else {
160
                    if ($timespan <= 7) {
161
                        $timestamp = mktime(
162
                            $row[1],
163
                            0,
164
                            0,
165
                            substr($row[0], 4, 2),
166
                            substr($row[0], 6, 2),
167
                            substr($row[0], 0, 4)
168
                        );
169
                        $timestamp = date('Y-m-d H:00', $timestamp);
170
                    } else {
171
                        if ($timespan <= 31) {
172
                            $timestamp = mktime(
173
                                0,
174
                                0,
175
                                0,
176
                                substr($row[2], 4, 2),
177
                                substr($row[2], 6, 2),
178
                                substr($row[2], 0, 4)
179
                            );
180
                            $timestamp = date('Y-m-d H:00', $timestamp);
181
                        } else {
182
                            $timestamp = strtotime(substr($row[0], 0, 4) . 'W' . substr($row[0], 4, 2));
183
                            $timestamp = date('Y-m-d H:00', $timestamp);
184
                        }
185
                    }
186
                }
187
                $goalEntry[$timestamp] = $row[$i + $start];
188
            }
189
            $goalCollection['goal' . $goaldata[$i]['position']]['name']     = $goaldata[$i]['name'];
190
            $goalCollection['goal' . $goaldata[$i]['position']]['position'] = $goaldata[$i]['position'];
191
            $goalCollection['goal' . $goaldata[$i]['position']]['visits']   = $goalEntry;
192
        }
193
194
        // Parse the goals and append them to the overview.
195
        $this->parseGoals($overview, $goalCollection);
196
    }
197
198
199
    /**
200
     * Fetch a specific goals
201
     *
202
     * @param AnalyticsOverview $overview The overview
203
     * @param                   $goalCollection
204
     */
205
    private function parseGoals(&$overview, $goalCollection)
206
    {
207
        $timespan = $overview->getTimespan() - $overview->getStartOffset();
208
        $goals    = $overview->getGoals();
209
        if ($goals) {
210
            // delete existing entries
211
            foreach ($goals as $goal) {
212
                $this->em->remove($goal);
213
            }
214
            $this->em->flush();
215
        }
216
217
        foreach ($goalCollection as $goalEntry) {
218
            // create a new goal
219
            $goal = new AnalyticsGoal();
220
            $goal->setOverview($overview);
221
            $goal->setName($goalEntry['name']);
222
            $goal->setPosition($goalEntry['position']);
223
224
            $chartData   = array();
225
            $totalVisits = 0;
226
            $goalVisits  = 0;
227
            $i           = 0;
228
            // Fill the chartdata array
229
            foreach ($goalEntry['visits'] as $timestamp => $visits) {
230
                $totalVisits += $visits;
231
                if ($timespan <= 7 && $timespan > 1) {
232
                    $goalVisits += $visits;
233
                    if ($i % 5 == 0) {
234
                        $chartData[] = array('timestamp' => $timestamp, 'conversions' => $goalVisits);
235
                        $goalVisits  = 0;
236
                    }
237
                } else {
238
                    $chartData[] = array('timestamp' => $timestamp, 'conversions' => $visits);
239
                }
240
                $i += 1;
241
            }
242
243
            // set the data
244
            $goal->setVisits($totalVisits);
245
            $goal->setChartData(json_encode($chartData));
246
            $this->em->persist($goal);
247
248
            $this->output->writeln(
249
                "\t\t" . 'Fetched goal ' . $goal->getPosition() . ': "' . $goal->getName() . '" @ ' . $totalVisits
250
            );
251
        }
252
    }
253
}
254