Completed
Push — master ( 834214...ebf38e )
by Ruben
01:35
created

InvokableControllerEndpointType::make()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\LaravelEndpointResources\EndpointTypes;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Spatie\LaravelEndpointResources\EndpointTypes\MultiEndpointType;
7
8
class InvokableControllerEndpointType extends EndpointType implements MultiEndpointType
9
{
10
    /** @var string */
11
    private $controller;
12
13
    /** @var string|null */
14
    private $name;
15
16
    public static function make(string $controller): InvokableControllerEndpointType
17
    {
18
        return new self($controller);
19
    }
20
21
    public function __construct(string $controller)
22
    {
23
        $this->controller = $controller;
24
    }
25
26
    public function name(?string $name): InvokableControllerEndpointType
27
    {
28
        $this->name = $name;
29
30
        return $this;
31
    }
32
33
    public function getEndpoints(Model $model = null): array
34
    {
35
        return $this->resolveEndpointType()->getEndpoints($model);
36
    }
37
38
    public function getCollectionEndpoints(): array
39
    {
40
        return $this->resolveEndpointType()->getEndpoints();
41
    }
42
43
    private function resolveEndpointType(): ActionEndpointType
44
    {
45
        return ActionEndpointType::make([$this->controller])
46
            ->name($this->resolveEndpointName())
47
            ->parameters($this->parameters)
48
            ->prefix($this->prefix);
49
    }
50
51
    private function resolveEndpointName() : string
52
    {
53
        if ($this->name) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->name of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
54
            return $this->name;
55
        }
56
57
        $controller = new $this->controller;
58
59
        if (property_exists($controller, 'endpointName')) {
60
            return $controller->endpointName;
61
        }
62
63
        return 'invoke';
64
    }
65
}
66