GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( b53e25...97d577 )
by Ash
02:58
created

APAnalytics::update()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace AshPowell\APAnalytics;
4
5
use App\User;
0 ignored issues
show
Bug introduced by
The type App\User was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use AshPowell\APAnalytics\Jobs\Track;
7
use Illuminate\Database\Eloquent\Model;
8
use InvalidArgumentException;
9
use MongoDB\Driver\Cursor;
10
use MongoDB\Model\BSONDocument;
11
12
class APAnalytics
13
{
14
    protected $connection;
15
    protected $namespace;
16
17
    /**
18
     * Instantiate a new instance.
19
     *
20
     * @return void
21
     */
22
    public function __construct()
23
    {
24
        $this->connection = config('apanalytic.db_connection', 'mongodb');
25
        $this->namespace  = config('apanalytic.namespace', '\App\\');
26
    }
27
28
    /**
29
     * Track the Analytic.
30
     *
31
     * @return void
32
     * @param  mixed      $collection
33
     * @param  mixed      $items
34
     * @param  null|mixed $userId
35
     * @param  mixed      $params
36
     */
37
    public function track($collection, $items, $userId = null, $params = [])
38
    {
39
        Track::dispatch($collection, $items, $userId, $params);
40
41
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The expression return true returns the type true which is incompatible with the documented return type void.
Loading history...
42
    }
43
44
    public function update($collection, $item, $params)
45
    {
46
        Track::dispatch($collection, $item, null, $params, 'update');
47
48
        return true;
49
    }
50
51
    /**
52
     * Get the Analytics.
53
     *
54
     * @return void
55
     * @param  mixed      $collection
56
     * @param  null|mixed $timeframe
57
     * @param  null|mixed $filters
58
     * @param  mixed      $interval
59
     */
60
    public function show($collection, $interval = 'count', $timeframe = null, $filters = null)
61
    {
62
        $start          = $timeframe ? array_get($timeframe, 'start') : null;
63
        $end            = $timeframe ? array_get($timeframe, 'end') : null;
64
        $matchArray     = [];
65
        $filters        = json_decode($filters);
66
        $intervalFormat = '%Y-%m-%dT%H';
67
        $aggregate      = [];
68
69
        $model = $this->namespace.studly_case(str_singular($collection)).'Analytic';
70
71
        if (! class_exists($model)) {
72
            throw new InvalidArgumentException("Model {$model} does not exist.");
73
        }
74
75
        if ($filters) {
76
            foreach ($filters as $filter) {
77
                $propertyValue = $filter->property_value;
78
79
                if (is_numeric($propertyValue)) {
80
                    $propertyValue = (int) $propertyValue;
81
                }
82
83
                $matchArray = array_merge($matchArray, [$filter->property_name => $propertyValue]);
84
            }
85
        }
86
87
        abort_unless($this->canViewAnalytic($matchArray, auth()->user()), 403, 'You dont have permission to view these analytics');
88
89
        if ($start) {
90
            $matchArray['created_at']['$gte'] = mongoTime($start);
91
        }
92
93
        if ($end) {
94
            $matchArray['created_at']['$lt'] = mongoTime($end);
95
        }
96
97
        if ($matchArray) {
98
            $aggregate[] = ['$match' => $matchArray];
99
        }
100
101
        if ($interval != 'count') {
102
            if ($interval == 'daily') {
103
                $intervalFormat = '%Y-%m-%d';
104
            }
105
106
            if ($interval == 'weekly') {
107
                $intervalFormat = '%Y-%U';
108
            }
109
110
            if ($interval == 'monthly') {
111
                $intervalFormat = '%Y-%m';
112
            }
113
114
            $aggregate[] =  [
115
                '$group' => [
116
                    '_id' => [
117
                        '$dateToString' => ['date' => '$created_at', 'format' => $intervalFormat],
118
                    ],
119
                    'count' => [
120
                        '$sum' => 1,
121
                    ],
122
                    'created_at' => [
123
                        '$first' => '$created_at',
124
                    ],
125
                ],
126
            ];
127
128
            $aggregate[] = ['$sort' => ['created_at' => 1]];
129
130
            $aggregate[] = [
131
                '$project' => [
132
                    '_id'        => 0,
133
                    'created_at' => 1,
134
                    'count'      => 1,
135
                ],
136
            ];
137
        }
138
139
        $data = $model::raw(function ($collection) use ($matchArray, $interval, $aggregate) {
140
            if ($interval == 'count') {
141
                return $collection->count($matchArray);
142
            }
143
144
            if ($aggregate) {
145
                return $collection->aggregate($aggregate, ['allowDiskUse' => true]);
146
            }
147
        });
148
149
        return $data;
150
    }
151
152
    /**
153
     * Convert the Cursor to Laravel Models.
154
     *
155
     * @return void
156
     * @param  mixed      $data
157
     * @param  null|mixed $model
158
     */
159
    private function toModels($data, $model = null)
0 ignored issues
show
Unused Code introduced by
The method toModels() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
160
    {
161
        if (! $model) {
162
            $model = '\Jenssegers\Mongodb\Eloquent\Model';
163
        }
164
165
        if (! class_exists($model)) {
166
            throw new InvalidArgumentException("Model {$model} does not exist.");
167
        }
168
169
        if ($data instanceof Cursor) {
170
            // Convert MongoCursor results to a collection of models.
171
            $data = iterator_to_array($data, false);
172
173
            return $model::hydrate($data);
174
        } elseif ($data instanceof BSONDocument) {
175
            // Convert Mongo BSONDocument to a single object.
176
            $data = $data::getArrayCopy();
0 ignored issues
show
Bug Best Practice introduced by
The method ArrayObject::getArrayCopy() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

176
            /** @scrutinizer ignore-call */ 
177
            $data = $data::getArrayCopy();
Loading history...
177
178
            return $model::newFromBuilder((array) $data);
179
        } elseif (is_array($data) && array_key_exists('_id', $data)) {
180
            // The result is a single object.
181
            return $model::newFromBuilder((array) $data);
182
        }
183
184
        return $data;
185
    }
186
187
    /**
188
     * Check specified user has permission to see these analytics.
189
     *
190
     * @param array $filterArray
191
     * @param User  $user
192
     *
193
     * @return bool
194
     */
195
    private function canViewAnalytic($filterArray, User $user)
196
    {
197
        $modelsToCheck = config('apanalytics.models_require_ownership');
198
199
        if (count($modelsToCheck)) {
200
            foreach ($modelsToCheck as $model) {
201
                $modelName = studly_case(str_singular($model));
202
                $modelId   = array_get($filterArray, strtolower($modelName).'.id');
203
204
                if ($modelId) {
205
                    $modelClass = $this->namespace.$modelName;
206
                    $model      = $modelClass::find($modelId);
207
208
                    if ($model && $user->isOwner($model)) {
209
                        return true;
210
                    }
211
212
                    return false;
213
                }
214
            }
215
        }
216
217
        return true;
218
    }
219
}
220