InlineHandlerTrait::handleInline()   B
last analyzed

Complexity

Conditions 11
Paths 32

Size

Total Lines 61
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 15.1269

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 38
c 1
b 0
f 0
nc 32
nop 1
dl 0
loc 61
ccs 25
cts 37
cp 0.6757
crap 15.1269
rs 7.3166

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 Yaro\Jarboe\Http\Controllers\Traits\Handlers;
4
5
use Illuminate\Foundation\Http\FormRequest;
6
use Illuminate\Http\Request;
7
use Spatie\Permission\Exceptions\UnauthorizedException;
8
use Yaro\Jarboe\Exceptions\PermissionDenied;
9
use Yaro\Jarboe\Table\CRUD;
10
use Yaro\Jarboe\Table\Fields\AbstractField;
0 ignored issues
show
Bug introduced by
The type Yaro\Jarboe\Table\Fields\AbstractField 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...
11
12
trait InlineHandlerTrait
13
{
14
    /**
15
     * Handle inline update action.
16
     *
17
     * @param Request $request
18
     * @return \Illuminate\Http\JsonResponse
19
     * @throws PermissionDenied
20
     * @throws \ReflectionException
21
     */
22 3
    public function handleInline(Request $request)
23
    {
24 3
        $this->beforeInit();
25 3
        $this->init();
26 3
        $this->bound();
27
28 3
        if (!$this->can('inline')) {
29 2
            throw UnauthorizedException::forPermissions(['inline']);
30
        }
31
32 1
        $id = $request->get('_pk');
33 1
        $value = $request->get('_value');
34 1
        $locale = $request->get('_locale');
35
        /** @var AbstractField $field */
36 1
        $field = $this->crud()->getFieldByName($request->get('_name'));
37
38 1
        $request->replace(
39 1
            $request->all() + [$field->name() => $value]
40
        );
41
42 1
        $model = $this->crud()->repo()->find($id);
43 1
        if (!$field->isInline() || !$this->crud()->actions()->isAllowed('edit', $model) || $field->isReadonly()) {
44
            throw new PermissionDenied();
45
        }
46
47 1
        if (method_exists($this, 'update')) {
48
            $keyName = $field->belongsToArray() ? $field->getDotPatternName() : $field->name();
49
            list($rules, $messages, $attributes) = $this->getValidationDataForInlineField($request, $keyName);
50
            if ($rules) {
51
                $this->validate(
0 ignored issues
show
Bug introduced by
It seems like validate() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

51
                $this->/** @scrutinizer ignore-call */ 
52
                       validate(
Loading history...
52
                    $request,
53
                    [$keyName => $rules],
54
                    $messages,
55
                    $attributes
56
                );
57
            }
58
        }
59
60
        // change app locale, so translatable model's column will be set properly
61 1
        if ($locale) {
62
            app()->setLocale($locale);
0 ignored issues
show
introduced by
The method setLocale() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

62
            app()->/** @scrutinizer ignore-call */ setLocale($locale);
Loading history...
63
        }
64
65 1
        $fieldName = $field->name();
66 1
        $fieldValue = $field->value($request);
67 1
        if ($field->belongsToArray()) {
68
            $fieldName = $field->getAncestorName();
69
            $arrayValue = $field->getAttribute($model);
70
            $arrayValue = is_array($arrayValue) ? $arrayValue : [];
71
            $fieldValue = $arrayValue + [$field->getDescendantName() => $fieldValue];
72
        }
73
74 1
        $model = $this->crud()->repo()->update($id, [
75 1
            $fieldName => $fieldValue,
76
        ]);
77 1
        $field->afterUpdate($model, $request);
78
79 1
        $this->idEntity = $model->getKey();
0 ignored issues
show
Bug Best Practice introduced by
The property idEntity does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
80
81 1
        return response()->json([
82 1
            'value' => $field->getAttribute($model, $locale),
83
        ]);
84
    }
85
86
    /**
87
     * Get validation data for inline field.
88
     *
89
     * @param Request $request
90
     * @param $name
91
     * @return array
92
     * @throws \ReflectionException
93
     */
94
    protected function getValidationDataForInlineField(Request $request, $name)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

94
    protected function getValidationDataForInlineField(/** @scrutinizer ignore-unused */ Request $request, $name)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
95
    {
96
        $rules = [];
97
        $messages = [];
98
        $attributes = [];
99
100
        $reflection = new \ReflectionClass(get_class($this));
101
        $method = $reflection->getMethod('update');
102
        $parameters = $method->getParameters();
103
        $firstParam = $parameters[0] ?? null;
104
        $isRequestAsFirstParameter = $firstParam && $firstParam->getClass();
105
        if ($isRequestAsFirstParameter) {
106
            $formRequestClass = $firstParam->getClass()->getName();
107
            /** @var FormRequest $formRequest */
108
            $formRequest = new $formRequestClass();
109
            if (method_exists($formRequest, 'rules')) {
110
                foreach ($formRequest->rules() as $param => $paramRules) {
111
                    if (preg_match('~^'. preg_quote($name) .'(\.\*)?$~', $param)) {
112
                        return [
113
                            $paramRules,
114
                            $formRequest->messages(),
115
                            $formRequest->attributes(),
116
                        ];
117
                    }
118
                }
119
            }
120
        }
121
122
        return [$rules, $messages, $attributes];
123
    }
124
125
    abstract protected function beforeInit();
126
    abstract protected function init();
127
    abstract protected function bound();
128
    abstract protected function crud(): CRUD;
129
    abstract protected function can($action): bool;
130
}
131