ResourceStoreController::handle()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 3
nc 4
nop 1
1
<?php
2
3
namespace Oscer\Cms\Backend\Http\Controllers;
4
5
use Illuminate\Validation\ValidationException;
6
use Oscer\Cms\Backend\Http\Requests\ResourceRequest;
7
use Oscer\Cms\Backend\Resources\Resource;
8
9
class ResourceStoreController
10
{
11
    public function handle(ResourceRequest $request)
12
    {
13
        $resourceClass = $request->getResource();
14
        $resourceModel = $request->newResourceModel();
15
16
        if ($request->identifier() !== null) {
17
            $resourceModel = $resourceModel->newQuery()->findOrFail($request->identifier());
18
        }
19
20
        /** @var resource $resource */
21
        $resource = new $resourceClass($resourceModel);
22
23
        try {
24
            $savedModel = $resource->save($request);
0 ignored issues
show
Bug introduced by
The method save cannot be called on $resource (of type resource).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
25
        } catch (ValidationException $exception) {
26
            return response()->json(['errors' => $exception->errors()], 422);
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...
27
        }
28
29
        return response()->json(['data' => new $resourceClass($savedModel)]);
30
    }
31
}
32