Completed
Push — master ( 446c01...fcb59d )
by Ruud
113:27 queued 101:23
created

GoalCommandHelper::requestGoalResults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14

Duplication

Lines 14
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 14
loc 14
ccs 0
cts 11
cp 0
rs 9.7998
c 0
b 0
f 0
cc 1
nc 1
nop 3
crap 2
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
0 ignored issues
show
Documentation introduced by
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...
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
0 ignored issues
show
Documentation introduced by
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...
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
        }
55
56
        $part1 = implode(',', \array_slice($metrics, 0, 10));
57
        $part2 = implode(',', \array_slice($metrics, 10, 10));
58
59
        return array($part1, $part2);
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)
0 ignored issues
show
Duplication introduced by
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...
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
        } elseif ($timespan <= 7) {
99
            $extra = array('dimensions' => 'ga:date,ga:hour');
100
            $start = 2;
101
        } elseif ($timespan <= 31) {
102
            $extra = array('dimensions' => 'ga:week,ga:day,ga:date');
103
            $start = 3;
104
        } else {
105
            $extra = array('dimensions' => 'ga:isoYearIsoWeek');
106
            $start = 1;
107
        }
108
109
        // add segment
110
        if ($overview->getSegment()) {
111
            $extra['segment'] = $overview->getSegment()->getQuery();
0 ignored issues
show
Bug introduced by
The method getQuery cannot be called on $overview->getSegment() (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...
112
        }
113
114
        $goals = $this->getAllGoals();
115
        if (!$goals) {
116
            return;
117
        }
118
        $goaldata = array();
119
120
        // Create an array with for each goal an entry to create the metric parameter.
121
        foreach ($goals as $key => $value) {
122
            ++$key;
123
            $goaldata[] = array('position' => $key, 'name' => $value->name);
124
        }
125
126
        $metrics = $this->prepareMetrics();
127
128
        $rows = $this->requestGoalResults($overview, $metrics[0], $extra);
129
        // Execute an extra query if there are more than 10 goals to query
130
        if (\count($metrics) > 1) {
131
            $rows2 = $this->requestGoalResults($overview, $metrics[1], $extra);
132
            $rows2size = \count($rows2);
133
            for ($i = 0; $i < $rows2size; ++$i) {
134
                // Merge the results of the extra query data with the previous query data.
135
                $rows[$i] = array_merge($rows[$i], \array_slice($rows2[$i], $start, \count($rows2) - $start));
136
            }
137
        }
138
139
        // Create a result array to be parsed and create Goal objects from
140
        $goalCollection = array();
141
        $goaldatasize = \count($goaldata);
142
        for ($i = 0; $i < $goaldatasize; ++$i) {
143
            $goalEntry = array();
144
            foreach ($rows as $row) {
145
                // Create a timestamp for each goal visit (this depends on the timespan of the overview: split per hour, day, week, month)
146 View Code Duplication
                if ($timespan <= 1) {
0 ignored issues
show
Duplication introduced by
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...
147
                    $timestamp = mktime(
148
                        $row[1],
149
                        0,
150
                        0,
151
                        substr($row[0], 4, 2),
152
                        substr($row[0], 6, 2),
153
                        substr($row[0], 0, 4)
154
                    );
155
                    $timestamp = date('Y-m-d H:00', $timestamp);
156
                } elseif ($timespan <= 7) {
157
                    $timestamp = mktime(
158
                        $row[1],
159
                        0,
160
                        0,
161
                        substr($row[0], 4, 2),
162
                        substr($row[0], 6, 2),
163
                        substr($row[0], 0, 4)
164
                    );
165
                    $timestamp = date('Y-m-d H:00', $timestamp);
166
                } elseif ($timespan <= 31) {
167
                    $timestamp = mktime(
168
                        0,
169
                        0,
170
                        0,
171
                        substr($row[2], 4, 2),
172
                        substr($row[2], 6, 2),
173
                        substr($row[2], 0, 4)
174
                    );
175
                    $timestamp = date('Y-m-d H:00', $timestamp);
176
                } else {
177
                    $timestamp = strtotime(substr($row[0], 0, 4) . 'W' . substr($row[0], 4, 2));
178
                    $timestamp = date('Y-m-d H:00', $timestamp);
179
                }
180
                $goalEntry[$timestamp] = $row[$i + $start];
181
            }
182
            $goalCollection['goal' . $goaldata[$i]['position']]['name'] = $goaldata[$i]['name'];
183
            $goalCollection['goal' . $goaldata[$i]['position']]['position'] = $goaldata[$i]['position'];
184
            $goalCollection['goal' . $goaldata[$i]['position']]['visits'] = $goalEntry;
185
        }
186
187
        // Parse the goals and append them to the overview.
188
        $this->parseGoals($overview, $goalCollection);
189
    }
190
191
    /**
192
     * Fetch a specific goals
193
     *
194
     * @param AnalyticsOverview $overview       The overview
195
     * @param                   $goalCollection
196
     */
197
    private function parseGoals(&$overview, $goalCollection)
198
    {
199
        $timespan = $overview->getTimespan() - $overview->getStartOffset();
200
        $goals = $overview->getGoals();
201
        if ($goals) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $goals of type Kunstmaan\DashboardBundle\Entity\AnalyticsGoal[] 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...
202
            // delete existing entries
203
            foreach ($goals as $goal) {
204
                $this->em->remove($goal);
205
            }
206
            $this->em->flush();
207
        }
208
209
        foreach ($goalCollection as $goalEntry) {
210
            // create a new goal
211
            $goal = new AnalyticsGoal();
212
            $goal->setOverview($overview);
0 ignored issues
show
Documentation introduced by
$overview is of type object<Kunstmaan\Dashboa...tity\AnalyticsOverview>, 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...
213
            $goal->setName($goalEntry['name']);
214
            $goal->setPosition($goalEntry['position']);
215
216
            $chartData = array();
217
            $totalVisits = 0;
218
            $goalVisits = 0;
219
            $i = 0;
220
            // Fill the chartdata array
221
            foreach ($goalEntry['visits'] as $timestamp => $visits) {
222
                $totalVisits += $visits;
223
                if ($timespan <= 7 && $timespan > 1) {
224
                    $goalVisits += $visits;
225
                    if ($i % 5 == 0) {
226
                        $chartData[] = array('timestamp' => $timestamp, 'conversions' => $goalVisits);
227
                        $goalVisits = 0;
228
                    }
229
                } else {
230
                    $chartData[] = array('timestamp' => $timestamp, 'conversions' => $visits);
231
                }
232
                ++$i;
233
            }
234
235
            // set the data
236
            $goal->setVisits($totalVisits);
237
            $goal->setChartData(json_encode($chartData));
238
            $this->em->persist($goal);
239
240
            $this->output->writeln(
241
                "\t\t" . 'Fetched goal ' . $goal->getPosition() . ': "' . $goal->getName() . '" @ ' . $totalVisits
242
            );
243
        }
244
    }
245
}
246