ResponseFactory::fromErrors()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 9.424
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Nestecha\LaravelJsonApiValidation;
4
5
use Illuminate\Http\JsonResponse;
6
use Neomerx\JsonApi\Document\Error;
7
8
class ResponseFactory
9
{
10
11
    /**
12
     * @param  Error[]  $errors
13
     * @return JsonResponse
14
     */
15
    public function fromErrors(array $errors)
16
    {
17
        $result = [];
18
19
        foreach ($errors as $error) {
20
            $result[] = collect(
21
                [
22
                    'idx' => $error->getId(),
23
                    'links' => $error->getLinks(),
24
                    'status' => $error->getStatus(),
25
                    'code' => $error->getCode(),
26
                    'title' => $error->getTitle(),
27
                    'detail' => $error->getDetail(),
28
                    'source' => $error->getSource(),
29
                    'meta' => $error->getMeta()
30
                ]
31
            )->reject(
32
                function ($item)
33
                {
34
                    return is_null($item);
35
                }
36
            )->toArray();
37
        }
38
39
        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...
40
            [
41
                'errors' => $result
42
            ],
43
            422
44
        );
45
    }
46
}