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 ( ef5122...a9751c )
by Ash
02:48
created

APAnalytics::show()   C

Complexity

Conditions 13
Paths 132

Size

Total Lines 74
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 35
nc 132
nop 4
dl 0
loc 74
rs 6.35
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 Illuminate\Support\Facades\DB;
9
use InvalidArgumentException;
10
use MongoDB\Driver\Cursor;
11
use MongoDB\Model\BSONDocument;
12
13
class APAnalytics
14
{
15
    protected $connection;
16
    protected $namespace;
17
18
    /**
19
     * Instantiate a new instance.
20
     *
21
     * @return void
22
     */
23
    public function __construct()
24
    {
25
        $this->connection = config('apanalytic.db_connection', 'mongodb');
26
        $this->namespace  = config('apanalytic.namespace', '\App\\');
27
    }
28
29
    /**
30
     * Track the Analytic.
31
     *
32
     * @return void
33
     * @param  mixed      $collection
34
     * @param  mixed      $items
35
     * @param  null|mixed $userId
36
     * @param  mixed      $params
37
     */
38
    public function track($collection, $items, $userId = null, $params = [])
39
    {
40
        Track::dispatch($collection, $items, $userId, $params);
41
42
        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...
43
    }
44
45
    /**
46
     * Get the Analytics.
47
     *
48
     * @return void
49
     * @param  mixed      $collection
50
     * @param  null|mixed $timeframe
51
     * @param  null|mixed $filters
52
     * @param  mixed      $interval
53
     */
54
    public function show($collection, $interval = 'count', $timeframe = null, $filters = null)
55
    {
56
        $start        = $timeframe ? array_get($timeframe, 'start') : null;
57
        $end          = $timeframe ? array_get($timeframe, 'end') : null;
58
        $matchArray   = [];
59
        $filters      = json_decode($filters);
60
61
        $model = $this->namespace.studly_case(str_singular($collection)).'Analytic';
62
63
        if (! class_exists($model)) {
64
            throw new InvalidArgumentException("Model {$model} does not exist.");
65
        }
66
67
        if ($filters) {
68
            foreach ($filters as $filter) {
69
                $propertyValue = $filter->property_value;
70
71
                if (is_numeric($propertyValue)) {
72
                    $propertyValue = (int) $propertyValue;
73
                }
74
75
                $matchArray = array_merge($matchArray, [$filter->property_name => $propertyValue]);
76
            }
77
        }
78
79
        abort_unless($this->canViewAnalytic($matchArray, auth()->user()), 403, 'You dont have permission to view these analytics');
80
81
        if ($start) {
82
            $matchArray['created_at']['$gte'] = mongoTime($start);
83
        }
84
85
        if ($end) {
86
            $matchArray['created_at']['$lt'] = mongoTime($end);
87
        }
88
89
        $aggregate = [];
90
91
        if ($matchArray) {
92
            $aggregate[] = ['$match' => $matchArray];
93
        }
94
95
        $aggregate[] = ['$sort' => ['created_at' => 1]];
96
97
        $aggregate[] = [
98
            '$project' => [
99
                'created_at' => 1
100
            ],
101
        ];
102
103
        //$aggregate[] = ['$batchSize' => 1000];
104
105
        // $data = DB::connection($this->connection)
106
        //     ->collection($collection)
107
        //     ->raw(function ($query) use ($aggregate) {
108
        //         return $query->aggregate($aggregate);
109
        //     });
110
111
        $data = DB::connection($this->connection)
112
                ->collection($collection)
0 ignored issues
show
Bug introduced by
The method collection() does not exist on Illuminate\Database\ConnectionInterface. It seems like you code against a sub-type of Illuminate\Database\ConnectionInterface such as Jenssegers\Mongodb\Connection. ( Ignorable by Annotation )

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

112
                ->/** @scrutinizer ignore-call */ collection($collection)
Loading history...
113
                ->raw(function ($collection) use ($matchArray, $interval, $aggregate) {
114
                    if ($interval == 'count') {
115
                        return $collection->count($matchArray);
116
                    }
117
118
                    if ($aggregate) {
119
                        return $collection->aggregate($aggregate, ['allowDiskUse' => true]);
120
                    }
121
                });
122
123
        if ($interval != 'count') {
124
            $data = $this->toModels($data, $model);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $data is correct as $this->toModels($data, $model) targeting AshPowell\APAnalytics\APAnalytics::toModels() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
125
        }
126
127
        return $data;
128
    }
129
130
    /**
131
     * Convert the Cursor to Laravel Models.
132
     *
133
     * @param [type] $model
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
134
     * @param [type] $data
135
     *
136
     * @return void
137
     */
138
    private function toModels($data, $model = null)
139
    {
140
        if (! $model) {
141
            $model = '\Jenssegers\Mongodb\Eloquent\Model';
142
        }
143
144
        if (! class_exists($model)) {
145
            throw new InvalidArgumentException("Model {$model} does not exist.");
146
        }
147
148
        if ($data instanceof Cursor) {
149
            // Convert MongoCursor results to a collection of models.
150
            $data = iterator_to_array($data, false);
151
152
            return $model::hydrate($data);
153
        } elseif ($data instanceof BSONDocument) {
154
            // Convert Mongo BSONDocument to a single object.
155
            $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

155
            /** @scrutinizer ignore-call */ 
156
            $data = $data::getArrayCopy();
Loading history...
156
157
            return $model::newFromBuilder((array) $data);
158
        } elseif (is_array($data) && array_key_exists('_id', $data)) {
159
            // The result is a single object.
160
            return $model::newFromBuilder((array) $data);
161
        }
162
163
        return $data;
164
    }
165
166
    /**
167
     * Check specified user has permission to see these analytics.
168
     *
169
     * @param array $filterArray
170
     * @param User  $user
171
     *
172
     * @return bool
173
     */
174
    private function canViewAnalytic($filterArray, User $user)
175
    {
176
        $modelsToCheck = config('apanalytics.models_require_ownership');
177
178
        if (count($modelsToCheck)) {
179
            foreach ($modelsToCheck as $model) {
180
                $modelName = studly_case(str_singular($model));
181
                $modelId   = array_get($filterArray, strtolower($modelName).'.id');
182
183
                if ($modelId) {
184
                    $modelClass = $this->namespace.$modelName;
185
                    $model      = $modelClass::find($modelId);
186
187
                    if ($model && $user->isOwner($model)) {
188
                        return true;
189
                    }
190
191
                    return false;
192
                }
193
            }
194
        }
195
196
        return true;
197
    }
198
}
199