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.
Completed
Push — master ( 6aec2c...7e27f4 )
by Ash
02:49
created

Track::handle()   C

Complexity

Conditions 12
Paths 156

Size

Total Lines 77
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 2 Features 1
Metric Value
cc 12
eloc 48
c 6
b 2
f 1
nc 156
nop 0
dl 0
loc 77
rs 6.4999

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\Jobs;
4
5
use AshPowell\APAnalytics\Events\AnalyticTracked;
6
use Illuminate\Bus\Queueable;
7
use Illuminate\Contracts\Queue\ShouldQueue;
8
use Illuminate\Database\Eloquent\Collection;
9
use Illuminate\Database\Eloquent\Model;
10
use Illuminate\Foundation\Bus\Dispatchable;
11
use Illuminate\Pagination\LengthAwarePaginator;
12
use Illuminate\Pagination\Paginator;
13
use Illuminate\Queue\InteractsWithQueue;
14
use Illuminate\Queue\SerializesModels;
15
use Illuminate\Support\Arr;
16
use Illuminate\Support\Facades\DB;
17
use Illuminate\Support\Str;
18
use Log;
19
20
class Track implements ShouldQueue
21
{
22
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
0 ignored issues
show
introduced by
The trait Illuminate\Queue\SerializesModels requires some properties which are not provided by AshPowell\APAnalytics\Jobs\Track: $id, $class, $relations
Loading history...
23
24
    public $mongodb_connection;
25
    public $collection;
26
    public $items;
27
    public $userId;
28
    public $params;
29
    public $type;
30
31
    /**
32
     * Create a new event instance.
33
     *
34
     * @return void
35
     * @param  mixed $collection
36
     * @param  mixed $items
37
     * @param  mixed $userId
38
     * @param  mixed $params
39
     * @param  mixed $type
40
     */
41
    public function __construct($collection, $items, $userId, $params, $type = 'insert')
42
    {
43
        $this->queue = 'analytics';
44
45
        $this->mongodb_connection = config('apanalytics.db_connection', 'mongodb');
46
        $this->collection         = $collection;
47
        $this->items              = $items;
48
        $this->userId             = $userId;
49
        $this->params             = $params;
50
        $this->type               = $type;
51
    }
52
53
    public function handle()
54
    {
55
        $connection = $this->mongodb_connection;
56
        $collection = $this->collection;
57
        $items      = $this->items;
58
        $userId     = $this->userId;
59
        $params     = $this->params;
60
        $type       = $this->type;
61
        $valid      = true;
62
63
        if ($type != 'update') {
64
            if ($items != null) {
65
                $valid = ($items instanceof Collection) ? $items->count() : ($items instanceof Model) ? 1 : count($items);
66
            } else {
67
                $valid = false;
68
            }
69
        }
70
71
        if ($valid) {
72
            $collection = Str::plural($collection);
73
            $items      = $this->formatItems($items);
74
            $postEvent  = in_array($collection, config('apanalytics.format_collections'));
75
            $event      = $this->prepEventData($postEvent, $items, $userId, $params, $collection);
76
77
            try {
78
                if ($type == 'insert') {
79
                    if ($postEvent) {
80
                        foreach ($items as $item) {
81
                            $basename = strtolower(class_basename($item));
82
83
                            $data = [
84
                                $basename => [
85
                                    'id'   => $item->id ?? null,
86
                                    'type' => $item->type ?? null,
87
                                ],
88
                                'business' => [
89
                                    'id' => $item->business->id ?? null,
90
                                ],
91
                            ];
92
93
                            // Add Extra Stuff
94
                            $data = $this->addExtraEventData($data, $userId, $params);
95
96
                            event(new AnalyticTracked($collection, $basename, $data));
97
98
                            $event[] = $data;
99
                        }
100
                    }
101
102
                    // Basic created ie user
103
                    if (! $postEvent) {
104
                        foreach ($items as $item) {
105
                            $basename = strtolower(class_basename($item));
106
                            $data     = [
107
                                $basename => [
108
                                    'id'   => $item->id ?? null,
109
                                ],
110
                            ];
111
                        }
112
113
                        event(new AnalyticTracked($collection, $basename, $data));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $data does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $basename does not seem to be defined for all execution paths leading up to this point.
Loading history...
114
                    }
115
116
                    return DB::connection($connection)
117
                        ->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

117
                        ->/** @scrutinizer ignore-call */ collection($collection)
Loading history...
118
                        ->insert($event);
119
                }
120
121
                // Type is update
122
                $basename = strtolower(Str::singular($collection));
123
124
                return DB::connection($connection)
125
                        ->collection($collection)
126
                        ->where("{$basename}_id", $items)
127
                        ->update($params);
128
            } catch (\Exception $e) {
129
                Log::error('Error Logging Event', ['error' => $e->getMessage()]);
130
            }
131
        }
132
    }
133
134
    private function prepEventData($postEvent, $items, $userId, $params, $collection)
135
    {
136
        if ($postEvent) {
137
            return [];
138
        }
139
140
        if (is_array($items) && $collection != 'visits') {
141
            return $items;
142
        }
143
144
        return $this->addExtraEventData($items, $userId, $params);
145
    }
146
147
    private function formatItems($items)
148
    {
149
        $formattedItems = $items;
150
151
        if (is_array($formattedItems)) {
152
            return $formattedItems;
153
        }
154
155
        if ($items instanceof Paginator || $items instanceof LengthAwarePaginator) {
156
            $formattedItems = $items->items();
157
        }
158
159
        return Arr::wrap($formattedItems);
160
    }
161
162
    private function addExtraEventData($data, $userId, $params)
163
    {
164
        // Merge our extra parameters
165
        if (is_array($params) && count($params)) {
166
            $data = array_merge($data, $params);
167
        }
168
169
        // Standard stuff
170
        $data = array_merge($data, [
171
            'user_id'    => $userId ?? auth()->id() ?? null,
172
            'created_at' => mongoTime(),
173
        ]);
174
175
        return $data;
176
    }
177
}
178