Completed
Push — master ( 63e497...b4518a )
by Brent
68:55 queued 63:23
created

ViewModel::createVariableFromMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Spatie\ViewModels;
4
5
use Closure;
6
use ReflectionClass;
7
use ReflectionMethod;
8
use Illuminate\Support\Str;
9
use Illuminate\Http\JsonResponse;
10
use Illuminate\Support\Collection;
11
use Illuminate\Contracts\Support\Arrayable;
12
use Illuminate\Contracts\Support\Responsable;
13
use ReflectionProperty;
14
use Symfony\Component\HttpFoundation\Response;
15
16
class ViewModel implements Arrayable, Responsable
17
{
18
    protected $ignore = [];
19
20
    protected $view = '';
21
22
    public function toArray(): array
23
    {
24
        return $this
25
            ->items()
26
            ->all();
27
    }
28
29
    public function toResponse($request): Response
30
    {
31
        if ($request->wantsJson()) {
32
            return new JsonResponse($this->items()->toJson());
33
        }
34
35
        if ($this->view) {
36
            return response()->view($this->view, $this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Spatie\ViewModels\ViewModel>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Bug introduced by
The method view 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...
37
        }
38
39
        return new JsonResponse($this->items()->toJson());
40
    }
41
42
    public function view(string $view): ViewModel
43
    {
44
        $this->view = $view;
45
46
        return $this;
47
    }
48
49
    protected function items(): Collection
50
    {
51
        $class = new ReflectionClass($this);
52
53
        $publicProperties = collect($class->getProperties(ReflectionProperty::IS_PUBLIC))
54
            ->reject(function (ReflectionProperty $property) {
55
                return $this->shouldIgnore($property->getName());
56
            })
57
            ->mapWithKeys(function (ReflectionProperty $property) {
58
                return [$property->getName() => $this->{$property->getName()}];
59
            });
60
61
        $publicMethods = collect($class->getMethods(ReflectionMethod::IS_PUBLIC))
62
            ->reject(function (ReflectionMethod $method) {
63
                return $this->shouldIgnore($method->getName());
64
            })
65
            ->mapWithKeys(function (ReflectionMethod $method) {
66
                return [$method->getName() => $this->createVariableFromMethod($method)];
67
            });
68
69
        return $publicProperties->merge($publicMethods);
70
    }
71
72
    protected function shouldIgnore(string $methodName): bool
73
    {
74
        if (Str::startsWith($methodName, '__')) {
75
            return false;
76
        }
77
78
        return in_array($methodName, $this->ignoredMethods());
79
    }
80
81
    protected function ignoredMethods(): array
82
    {
83
        return array_merge([
84
            'toArray',
85
            'toResponse',
86
            'view',
87
        ], $this->ignore);
88
    }
89
90
    protected function createVariableFromMethod(ReflectionMethod $method)
91
    {
92
        if ($method->getNumberOfParameters() === 0) {
93
            return $this->{$method->getName()}();
94
        }
95
96
        return Closure::fromCallable([$this, $method->getName()]);
97
    }
98
}
99