Completed
Push — master ( 9a7beb...fe7356 )
by Jeroen
13:51
created

Command/Helper/Analytics/GoalCommandHelper.php (1 issue)

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\Command\Helper\Analytics;
4
5
use Kunstmaan\DashboardBundle\Entity\AnalyticsGoal;
6
use Kunstmaan\DashboardBundle\Entity\AnalyticsOverview;
7
8
class GoalCommandHelper extends AbstractAnalyticsCommandHelper
9
{
10
    /**
11
     * @return array
12
     */
13
    private function getAllGoals()
14
    {
15
        // Get the goals from the saved profile. These are a maximum of 20 goals.
16
        $goals = $this
17
            ->query
18
            ->getServiceHelper()
19
            ->getService()
20
            ->management_goals
21
            ->listManagementGoals(
22
                $this->configHelper->getAccountId(),
23
                $this->configHelper->getPropertyId(),
24
                $this->configHelper->getProfileId()
25
            )
26
            ->items;
27
28
        if (is_array($goals)) {
29
            return $goals;
30
        }
31
32
        return false;
33
    }
34
35
    /**
36
     * @return array
37
     */
38
    private function prepareMetrics()
39
    {
40
        $goals = $this->getAllGoals();
41
        if (!$goals) {
42
            return false;
43
        }
44
45
        $metrics = array();
46
        foreach ($goals as $key => $value) {
47
            $metrics[] = 'ga:goal' . ($key + 1) . 'Completions';
48
        }
49
        // Create the metric parameter string, there is a limit of 10 metrics per query, and a max of 20 goals available.
50
        if (count($metrics) <= 10) {
51
            $part1 = implode(',', $metrics);
52
53
            return array($part1);
54
        } else {
55
            $part1 = implode(',', array_slice($metrics, 0, 10));
56
            $part2 = implode(',', array_slice($metrics, 10, 10));
57
58
            return array($part1, $part2);
59
        }
60
    }
61
62
    /**
63
     * @param AnalyticsOverview $overview
64
     * @param                   $metrics
65
     * @param                   $dimensions
66
     *
67
     * @return mixed
68
     */
69 View Code Duplication
    private function requestGoalResults(AnalyticsOverview $overview, $metrics, $dimensions)
70
    {
71
        $timestamps = $this->getTimestamps($overview);
72
73
        // execute query
74
        $results = $this->query->getResultsByDate(
75
            $timestamps['begin'],
76
            $timestamps['end'],
77
            $metrics,
78
            $dimensions
79
        );
80
81
        return $results->getRows();
82
    }
83
84
    /**
85
     * get data and save it for the overview
86
     *
87
     * @param AnalyticsOverview $overview The overview
88
     */
89
    public function getData(&$overview)
90
    {
91
        $this->output->writeln("\t" . 'Fetching goals..');
92
93
        // calculate timespan
94
        $timespan = $overview->getTimespan() - $overview->getStartOffset();
95
        if ($timespan <= 1) {
96
            $extra = array('dimensions' => 'ga:date,ga:hour');
97
            $start = 2;
98
        } else {
99
            if ($timespan <= 7) {
100
                $extra = array('dimensions' => 'ga:date,ga:hour');
101
                $start = 2;
102
            } else {
103
                if ($timespan <= 31) {
104
                    $extra = array('dimensions' => 'ga:week,ga:day,ga:date');
105
                    $start = 3;
106
                } else {
107
                    $extra = array('dimensions' => 'ga:isoYearIsoWeek');
108
                    $start = 1;
109
                }
110
            }
111
        }
112
113
        // add segment
114
        if ($overview->getSegment()) {
115
            $extra['segment'] = $overview->getSegment()->getQuery();
116
        }
117
118
        $goals = $this->getAllGoals();
119
        if (!$goals) {
120
            return;
121
        }
122
        $goaldata = array();
123
124
        // Create an array with for each goal an entry to create the metric parameter.
125
        foreach ($goals as $key => $value) {
126
            ++$key;
127
            $goaldata[] = array('position' => $key, 'name' => $value->name);
128
        }
129
130
        $metrics = $this->prepareMetrics();
131
132
        $rows = $this->requestGoalResults($overview, $metrics[0], $extra);
133
        // Execute an extra query if there are more than 10 goals to query
134
        if (count($metrics) > 1) {
135
            $rows2 = $this->requestGoalResults($overview, $metrics[1], $extra);
136
            $rows2size = count($rows2);
137
            for ($i = 0; $i < $rows2size; ++$i) {
138
                // Merge the results of the extra query data with the previous query data.
139
                $rows[$i] = array_merge($rows[$i], array_slice($rows2[$i], $start, count($rows2) - $start));
140
            }
141
        }
142
143
        // Create a result array to be parsed and create Goal objects from
144
        $goalCollection = array();
145
        $goaldatasize = count($goaldata);
146
        for ($i = 0; $i < $goaldatasize; ++$i) {
147
            $goalEntry = array();
148
            foreach ($rows as $row) {
149
                // Create a timestamp for each goal visit (this depends on the timespan of the overview: split per hour, day, week, month)
150
                if ($timespan <= 1) {
151
                    $timestamp = mktime(
152
                        $row[1],
153
                        0,
154
                        0,
155
                        substr($row[0], 4, 2),
156
                        substr($row[0], 6, 2),
157
                        substr($row[0], 0, 4)
158
                    );
159
                    $timestamp = date('Y-m-d H:00', $timestamp);
160
                } else {
161
                    if ($timespan <= 7) {
162
                        $timestamp = mktime(
163
                            $row[1],
164
                            0,
165
                            0,
166
                            substr($row[0], 4, 2),
167
                            substr($row[0], 6, 2),
168
                            substr($row[0], 0, 4)
169
                        );
170
                        $timestamp = date('Y-m-d H:00', $timestamp);
171
                    } else {
172
                        if ($timespan <= 31) {
173
                            $timestamp = mktime(
174
                                0,
175
                                0,
176
                                0,
177
                                substr($row[2], 4, 2),
178
                                substr($row[2], 6, 2),
179
                                substr($row[2], 0, 4)
180
                            );
181
                            $timestamp = date('Y-m-d H:00', $timestamp);
182 View Code Duplication
                        } else {
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...
183
                            $timestamp = strtotime(substr($row[0], 0, 4) . 'W' . substr($row[0], 4, 2));
184
                            $timestamp = date('Y-m-d H:00', $timestamp);
185
                        }
186
                    }
187
                }
188
                $goalEntry[$timestamp] = $row[$i + $start];
189
            }
190
            $goalCollection['goal' . $goaldata[$i]['position']]['name'] = $goaldata[$i]['name'];
191
            $goalCollection['goal' . $goaldata[$i]['position']]['position'] = $goaldata[$i]['position'];
192
            $goalCollection['goal' . $goaldata[$i]['position']]['visits'] = $goalEntry;
193
        }
194
195
        // Parse the goals and append them to the overview.
196
        $this->parseGoals($overview, $goalCollection);
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