ActivityLogger   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 113
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 59
c 2
b 0
f 0
dl 0
loc 113
rs 10
wmc 14

3 Methods

Rating   Name   Duplication   Size   Complexity  
C activity() 0 63 12
A prepareErrorMessage() 0 8 1
A storeActivity() 0 12 1
1
<?php
2
3
namespace jeremykenedy\LaravelLogger\App\Http\Traits;
4
5
use Illuminate\Support\Facades\Auth;
6
use Illuminate\Support\Facades\Log;
7
use Illuminate\Support\Facades\Request;
8
use Illuminate\Support\Facades\Validator;
9
use Jaybizzle\LaravelCrawlerDetect\Facades\LaravelCrawlerDetect as Crawler;
10
use jeremykenedy\LaravelLogger\App\Models\Activity;
11
12
trait ActivityLogger
13
{
14
    /**
15
     * Laravel Logger Log Activity.
16
     *
17
     * @param string $description
18
     *
19
     * @return void
20
     */
21
    public static function activity($description = null)
22
    {
23
        $userType = trans('LaravelLogger::laravel-logger.userTypes.guest');
0 ignored issues
show
Bug introduced by
The function trans was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

23
        $userType = /** @scrutinizer ignore-call */ trans('LaravelLogger::laravel-logger.userTypes.guest');
Loading history...
24
        $userId = null;
25
26
        if (Auth::check()) {
27
            $userType = trans('LaravelLogger::laravel-logger.userTypes.registered');
28
            $userIdField = config('LaravelLogger.defaultUserIDField');
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

28
            $userIdField = /** @scrutinizer ignore-call */ config('LaravelLogger.defaultUserIDField');
Loading history...
29
            $userId = Request::user()->{$userIdField};
30
        }
31
32
        if (Crawler::isCrawler()) {
33
            $userType = trans('LaravelLogger::laravel-logger.userTypes.crawler');
34
            if (is_null($description)) {
35
                $description = $userType.' '.trans('LaravelLogger::laravel-logger.verbTypes.crawled').' '.Request::fullUrl();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 100 characters; contains 125 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
36
            }
37
        }
38
39
        if (!$description) {
40
            switch (strtolower(Request::method())) {
41
                case 'post':
42
                    $verb = trans('LaravelLogger::laravel-logger.verbTypes.created');
43
                    break;
44
45
                case 'patch':
46
                case 'put':
47
                    $verb = trans('LaravelLogger::laravel-logger.verbTypes.edited');
48
                    break;
49
50
                case 'delete':
51
                    $verb = trans('LaravelLogger::laravel-logger.verbTypes.deleted');
52
                    break;
53
54
                case 'get':
55
                default:
56
                    $verb = trans('LaravelLogger::laravel-logger.verbTypes.viewed');
57
                    break;
58
            }
59
60
            $description = $verb.' '.Request::path();
61
        }
62
63
        $data = [
64
            'description'   => $description,
65
            'userType'      => $userType,
66
            'userId'        => $userId,
67
            'route'         => Request::fullUrl(),
68
            'ipAddress'     => Request::ip(),
69
            'userAgent'     => Request::header('user-agent'),
70
            'locale'        => Request::header('accept-language'),
71
            'referer'       => Request::header('referer'),
72
            'methodType'    => Request::method(),
73
        ];
74
75
        // Validation Instance
76
        $validator = Validator::make($data, Activity::rules());
77
        if ($validator->fails()) {
78
            $errors = self::prepareErrorMessage($validator->errors(), $data);
79
            if (config('LaravelLogger.logDBActivityLogFailuresToFile')) {
80
                Log::error('Failed to record activity event. Failed Validation: '.$errors);
81
            }
82
        } else {
83
            self::storeActivity($data);
84
        }
85
    }
86
87
    /**
88
     * Store activity entry to database.
89
     *
90
     * @param array $data
91
     *
92
     * @return void
93
     */
94
    private static function storeActivity($data)
95
    {
96
        Activity::create([
97
            'description'   => $data['description'],
98
            'userType'      => $data['userType'],
99
            'userId'        => $data['userId'],
100
            'route'         => $data['route'],
101
            'ipAddress'     => $data['ipAddress'],
102
            'userAgent'     => $data['userAgent'],
103
            'locale'        => $data['locale'],
104
            'referer'       => $data['referer'],
105
            'methodType'    => $data['methodType'],
106
        ]);
107
    }
108
109
    /**
110
     * Prepare Error Message (add the actual value of the error field).
111
     *
112
     * @param $validator
113
     * @param $data
114
     *
115
     * @return string
116
     */
117
    private static function prepareErrorMessage($validatorErrors, $data)
118
    {
119
        $errors = json_decode(json_encode($validatorErrors, true));
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type integer expected by parameter $options of json_encode(). ( Ignorable by Annotation )

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

119
        $errors = json_decode(json_encode($validatorErrors, /** @scrutinizer ignore-type */ true));
Loading history...
120
        array_walk($errors, function (&$value, $key) use ($data) {
121
            array_push($value, "Value: $data[$key]");
122
        });
123
124
        return json_encode($errors, true);
125
    }
126
}
127