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.
Test Setup Failed
Push — master ( 9eef94...445856 )
by Ash
02:42
created

APAnalytics   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 136
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 24
eloc 57
dl 0
loc 136
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A track() 0 3 1
B show() 0 47 9
A canViewAnalytic() 0 23 6
B toModels() 0 25 7
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
    public function track($collection, $items, $userId = null, $params = [])
30
    {
31
        Track::dispatch($collection, $items, $userId, $params);
32
    }
33
34
    public function show($collection, $timeframe = null, $filters = null)
35
    {
36
        $start        = $timeframe ? array_get($timeframe, 'start') : null;
37
        $end          = $timeframe ? array_get($timeframe, 'end') : null;
38
        $matchArray   = [];
39
        $filters      = json_decode($filters);
40
41
        $model = $this->namespace.studly_case(str_singular($collection)) . 'Analytic';
42
43
        if (!class_exists($model)) {
44
            throw new InvalidArgumentException("Model {$model} does not exist.");
45
        }
46
47
        if ($filters) {
48
            foreach ($filters as $filter) {
49
                $propertyValue = $filter->property_value;
50
51
                if (is_numeric($propertyValue)) {
52
                    $propertyValue = (int) $propertyValue;
53
                }
54
55
                $matchArray = array_merge($matchArray, [$filter->property_name => $propertyValue]);
56
            }
57
        }
58
59
        abort_unless($this->canViewAnalytic($matchArray, auth()->user()), 403, 'You dont have permission to view these analytics');
60
61
        if ($start) {
62
            $matchArray['created_at']['$gte'] = mongoTime($start);
63
        }
64
65
        if ($end) {
66
            $matchArray['created_at']['$lt'] = mongoTime($end);
67
        }
68
69
        $data = DB::connection($this->connection)
70
            ->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

70
            ->/** @scrutinizer ignore-call */ collection($collection)
Loading history...
71
            ->raw(function ($query) use ($matchArray) {
72
                return $query->aggregate([
73
                    [ '$match' => $matchArray ],
74
                    [ '$sort' => ['created_at' => 1] ]
75
                ]);
76
            });
77
78
        $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...
79
80
        return $data;
81
    }
82
83
    /**
84
     * Convert the Cursor to Laravel Models
85
     *
86
     * @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...
87
     * @param [type] $data
88
     *
89
     * @return void
90
     */
91
    private function toModels($data, $model = null)
92
    {
93
        if (!$model) {
94
            $model = '\Jenssegers\Mongodb\Eloquent\Model';
95
        }
96
        if (!class_exists($model)) {
97
            throw new InvalidArgumentException("Model {$model} does not exist.");
98
        }
99
100
        if ($data instanceof Cursor) {
101
            // Convert MongoCursor results to a collection of models.
102
            $data = iterator_to_array($data, false);
103
104
            return $model::hydrate($data);
105
        } elseif ($data instanceof BSONDocument) {
106
            // Convert Mongo BSONDocument to a single object.
107
            $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

107
            /** @scrutinizer ignore-call */ 
108
            $data = $data::getArrayCopy();
Loading history...
108
109
            return $model::newFromBuilder((array) $data);
110
        } elseif (is_array($data) && array_key_exists('_id', $data)) {
111
            // The result is a single object.
112
            return $model::newFromBuilder((array) $data);
113
        }
114
115
        return $data;
116
    }
117
118
    /**
119
     * Check specified user has permission to see these analytics
120
     *
121
     * @param Array $filterArray
122
     * @param User  $user
123
     *
124
     * @return boolean
125
     */
126
    private function canViewAnalytic($filterArray, User $user)
127
    {
128
        $modelsToCheck = config('apanalytics.models_require_ownership');
129
130
        if (count($modelsToCheck)) {
131
            foreach ($modelsToCheck as $model) {
132
                $modelName = studly_case(str_singular($model));
133
                $modelId   = array_get($filterArray, strtolower($modelName).'.id');
134
135
                if ($modelId) {
136
                    $modelClass = $this->namespace.$modelName;
137
                    $model      = $modelClass::find($modelId);
138
139
                    if ($model && $user->isOwner($model)) {
140
                        return true;
141
                    }
142
143
                    return false;
144
                }
145
            }
146
        }
147
148
        return true;
149
    }
150
}
151