Completed
Push — master ( 49dc1a...1f58a4 )
by Yaro
06:59
created

InlineHandlerTrait   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 119
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 44%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 8
dl 0
loc 119
ccs 22
cts 50
cp 0.44
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
C handleInline() 0 63 11
B getValidationDataForInlineField() 0 30 6
beforeInit() 0 1 ?
init() 0 1 ?
bound() 0 1 ?
crud() 0 1 ?
can() 0 1 ?
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;
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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
52
                    $request,
53
                    [$keyName => $rules],
54
                    $messages,
55
                    $attributes
56
                );
57
            }
58
        }
59
60 1
        // change app locale, so translatable model's column will be set properly
61
        if ($locale) {
62
            app()->setLocale($locale);
63
        }
64 1
65 1
        $fieldName = $field->name();
66
        $fieldValue = $field->value($request);
67 1
        if ($field->belongsToArray()) {
68
            $fieldName = $field->getAncestorName();
69 1
            $arrayValue = $field->getAttribute($model);
70
            $arrayValue = is_array($arrayValue) ? $arrayValue : [];
71 1
            $fieldValue = $arrayValue + [$field->getDescendantName() => $fieldValue];
72 1
        }
73
74
        $model = $this->crud()->repo()->update($id, [
75
            $fieldName => $fieldValue,
76
        ]);
77
        $field->afterUpdate($model, $request);
78
79
        $this->idEntity = $model->getKey();
0 ignored issues
show
Bug introduced by
The property idEntity does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
80
81
        return response()->json([
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
82
            '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)
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();
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
126
    abstract protected function init();
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
127
    abstract protected function bound();
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
128
    abstract protected function crud(): CRUD;
129
    abstract protected function can($action): bool;
130
}
131