Passed
Push — master ( 4e1805...dc06aa )
by Jeremy
45s
created

ActivityLogger::prepareErrorMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace jeremykenedy\LaravelLogger\App\Http\Traits;
4
5
use Crawler;
0 ignored issues
show
Bug introduced by
The type Crawler 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 Illuminate\Support\Facades\Log;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Facades\Log 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...
7
use jeremykenedy\LaravelLogger\App\Models\Activity;
8
use Validator;
0 ignored issues
show
Bug introduced by
The type Validator 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...
9
10
trait ActivityLogger
11
{
12
    /**
13
     * Laravel Logger Log Activity.
14
     *
15
     * @param string $description
16
     *
17
     * @return void
18
     */
19
    public static function activity($description = null)
20
    {
21
        $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

21
        $userType = /** @scrutinizer ignore-call */ trans('LaravelLogger::laravel-logger.userTypes.guest');
Loading history...
22
        $userId = null;
23
24
        if (\Auth::check()) {
0 ignored issues
show
Bug introduced by
The type Auth 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...
25
            $userType = trans('LaravelLogger::laravel-logger.userTypes.registered');
26
            $userId = \Request::user()->id;
0 ignored issues
show
Bug introduced by
The type Request 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...
27
        }
28
29
        if (Crawler::isCrawler()) {
30
            $userType = trans('LaravelLogger::laravel-logger.userTypes.crawler');
31
            $description = $userType.' '.trans('LaravelLogger::laravel-logger.verbTypes.crawled').' '.\Request::fullUrl();
32
        }
33
34
        if (!$description) {
35
            switch (strtolower(\Request::method())) {
36
                case 'post':
37
                    $verb = trans('LaravelLogger::laravel-logger.verbTypes.created');
38
                    break;
39
40
                case 'patch':
41
                case 'put':
42
                    $verb = trans('LaravelLogger::laravel-logger.verbTypes.edited');
43
                    break;
44
45
                case 'delete':
46
                    $verb = trans('LaravelLogger::laravel-logger.verbTypes.deleted');
47
                    break;
48
49
                case 'get':
50
                default:
51
                    $verb = trans('LaravelLogger::laravel-logger.verbTypes.viewed');
52
                    break;
53
            }
54
55
            $description = $verb.' '.\Request::path();
56
        }
57
58
        $data = [
59
            'description'   => $description,
60
            'userType'      => $userType,
61
            'userId'        => $userId,
62
            'route'         => \Request::fullUrl(),
63
            'ipAddress'     => \Request::ip(),
64
            'userAgent'     => \Request::header('user-agent'),
65
            'locale'        => \Request::header('accept-language'),
66
            'referer'       => \Request::header('referer'),
67
            'methodType'    => \Request::method(),
68
        ];
69
70
        // Validation Instance
71
        $validator = Validator::make($data, Activity::Rules([]));
72
        if ($validator->fails()) {
73
            $errors = self::prepareErrorMessage($validator->errors(), $data);
74
            if (config('LaravelLogger.logDBActivityLogFailuresToFile')) {
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

74
            if (/** @scrutinizer ignore-call */ config('LaravelLogger.logDBActivityLogFailuresToFile')) {
Loading history...
75
                Log::error('Failed to record activity event. Failed Validation: '.$errors);
76
            }
77
        } else {
78
            self::storeActivity($data);
79
        }
80
    }
81
82
    /**
83
     * Store activity entry to database.
84
     *
85
     * @param array $data
86
     *
87
     * @return void
88
     */
89
    private static function storeActivity($data)
90
    {
91
        Activity::create([
92
            'description'   => $data['description'],
93
            'userType'      => $data['userType'],
94
            'userId'        => $data['userId'],
95
            'route'         => $data['route'],
96
            'ipAddress'     => $data['ipAddress'],
97
            'userAgent'     => $data['userAgent'],
98
            'locale'        => $data['locale'],
99
            'referer'       => $data['referer'],
100
            'methodType'    => $data['methodType'],
101
        ]);
102
    }
103
    
104
    /**
105
     * Prepare Error Message (add the actual value of the error field)
106
     *
107
     * @param $validator
108
     * @param $data
109
     *
110
     * @return string
111
     */
112
    private static function prepareErrorMessage($validatorErrors, $data)
113
    {
114
        $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

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