Completed
Push — master ( 9c742a...1858b1 )
by Fèvre
14s
created

AdminController::_buildStats()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
dl 16
loc 16
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 1
1
<?php
2
namespace App\Controller\Admin;
3
4
use App\Controller\AppController;
5
use Cake\Cache\Cache;
6
use Cake\Core\Configure;
7
use Cake\I18n\Number;
8
use Mexitek\PHPColors\Color;
9
use Widop\GoogleAnalytics\Client;
10
use Widop\GoogleAnalytics\Query;
11
use Widop\GoogleAnalytics\Service;
12
use Widop\HttpAdapter\CurlHttpAdapter;
13
14
class AdminController extends AppController
15
{
16
17
    /**
18
     * Index page.
19
     *
20
     * @return void
21
     */
22
    public function home()
23
    {
24
        if (Configure::read('Analytics.enabled') === true) {
25
            $httpAdapter = new CurlHttpAdapter();
26
            $client = new Client(Configure::read('Analytics.client_id'), Configure::read('Analytics.private_key'), $httpAdapter);
27
            $service = new Service($client);
28
29
            $statistics = Cache::remember('statistics', function () use ($service) {
30
                $statistics = new Query(Configure::read('Analytics.profile_id'));
31
                $statistics
32
                    ->setStartDate(new \DateTime(Configure::read('Analytics.start_date')))
33
                    ->setEndDate(new \DateTime())
34
                    ->setMetrics([
35
                        'ga:visits', 'ga:visitors', 'ga:pageviews', 'ga:pageviewsPerVisit',
36
                        'ga:avgtimeOnSite', 'ga:visitBounceRate', 'ga:percentNewVisits'
37
                    ]);
38
39
                return $service->query($statistics);
40
            }, 'analytics');
41
42 View Code Duplication
            $browsers = Cache::remember('browsers', function () use ($service) {
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...
43
                $browsers = new Query(Configure::read('Analytics.profile_id'));
44
                $browsers
45
                    ->setStartDate(new \DateTime(Configure::read('Analytics.start_date')))
46
                    ->setEndDate(new \DateTime())
47
                    ->setDimensions(['ga:browser'])
48
                    ->setMetrics(['ga:pageviews'])
49
                    ->setSorts(['ga:pageviews'])
50
                    ->setFilters(['ga:browser==Chrome,ga:browser==Firefox,ga:browser==Internet Explorer,ga:browser==Safari,ga:browser==Opera']);
51
52
                return $service->query($browsers);
53
            }, 'analytics');
54
55
            $continents = Cache::remember('continents', function () use ($service) {
56
                $continentsRows = new Query(Configure::read('Analytics.profile_id'));
57
                $continentsRows
58
                    ->setStartDate(new \DateTime(Configure::read('Analytics.start_date')))
59
                    ->setEndDate(new \DateTime())
60
                    ->setDimensions(['ga:continent'])
61
                    ->setMetrics(['ga:visitors'])
62
                    ->setSorts(['ga:visitors'])
63
                    ->setFilters(['ga:continent==Africa,ga:continent==Americas,ga:continent==Asia,ga:continent==Europe,ga:continent==Oceania']);
64
65
                $continentsRows = $service->query($continentsRows);
66
67
                $color = new Color("1abc9c");
68
                $light = 1;
69
70
                $continents = [];
71
72
                foreach (array_reverse($continentsRows->getRows()) as $continentRow) {
73
                    $continent = [];
74
                    $continent['label'] = $continentRow[0];
75
                    $continent['data'] = $continentRow[1];
76
                    $continent['color'] = '#' . $color->lighten($light);
77
78
                    array_push($continents, $continent);
79
                    $light += 10;
80
                }
81
82
                return $continents;
83
            }, 'analytics');
84
85 View Code Duplication
            $graphVisitors = Cache::remember('graphVisitors', function () use ($service) {
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...
86
                $graphVisitors = new Query(Configure::read('Analytics.profile_id'));
87
                $graphVisitors
88
                    ->setStartDate(new \DateTime('-7 days'))
89
                    ->setEndDate(new \DateTime())
90
                    ->setDimensions(['ga:date'])
91
                    ->setMetrics(['ga:visits', 'ga:pageviews'])
92
                    ->setSorts(['ga:date']);
93
94
                return $service->query($graphVisitors);
95
            }, 'analytics');
96
97
            $this->set(compact('statistics', 'browsers', 'continents', 'graphVisitors'));
98
        }
99
100
        $this->loadModel('Users');
101
        //UsersGraph
102
        $usersGraphCount = $this->Users
0 ignored issues
show
Documentation introduced by
The property Users does not exist on object<App\Controller\Admin\AdminController>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
103
            ->find('all')
104
            ->select([
105
                'date' => 'DATE_FORMAT(created,\'%d-%m-%Y\')',
106
                'count' => 'COUNT(id)'
107
            ])
108
            ->group('DATE(created)')
109
            ->order([
110
                'date' => 'desc'
111
            ])
112
            ->where([
113
                'UNIX_TIMESTAMP(DATE(created)) >' => (new \DateTime('-8 days'))->getTimestamp()
114
            ])
115
            ->toArray();
116
117
        $usersGraph = [];
118
119
        //Fill the new array with the date of the 8 past days and give them the value 0.
120
        for ($i = 0; $i < 8; $i++) {
121
            $date = new \DateTime("$i days ago");
122
123
            $usersGraph[$date->format('d-m-Y')] = 0;
124
        }
125
126
        //Foreach value that we got in the database, parse the array by the key date,
127
        //and if the key exist, attribute the new value.
128
        foreach ($usersGraphCount as $user) {
129
            $usersGraph[$user->date] = intval($user->count);
130
        }
131
        $usersGraph = array_reverse($usersGraph);
132
133
        $stats = $this->_buildStats([
134
            'Users' => 'Model.Users.register',
135
            'Articles' => 'Model.BlogArticles.new',
136
            'ArticlesLikes' => 'Model.BlogArticlesLikes.new',
137
            'ArticlesComments' => 'Model.BlogArticlesComments.new'
138
        ]);
139
140
        $this->set(compact('stats', 'usersGraph'));
141
    }
142
143
    /**
144
     * Build the statistics for the home page.
145
     *
146
     * @param array $array The array of statistics to build.
147
     *
148
     * @return array
149
     */
150 View Code Duplication
    protected function _buildStats(array $array)
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...
151
    {
152
        $statistics = [];
153
154
        foreach ($array as $type => $event) {
155
            $statistics[$type] = Cache::remember($type, function () {
156
                $this->eventManager()->attach(new Statistics());
0 ignored issues
show
Deprecated Code introduced by
The method Cake\Event\EventManager::attach() has been deprecated with message: 3.0.0 Use on() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

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

Loading history...
157
                $event = new Event($event);
0 ignored issues
show
Bug introduced by
The variable $event seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
158
                $this->eventManager()->dispatch($event);
159
160
                return $event->result;
161
            }, 'statistics');
162
        }
163
164
        return $statistics;
165
    }
166
}
167