Completed
Push — master ( e97c13...1021f1 )
by Timur
02:50
created

ServerResourceCommand::processResponseItem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Laravel\Forge\ServerResources\Commands;
4
5
use Laravel\Forge\Server;
6
use InvalidArgumentException;
7
use Psr\Http\Message\ResponseInterface;
8
use Laravel\Forge\Commands\ServerCommand;
9
10
abstract class ServerResourceCommand extends ServerCommand
11
{
12
    /**
13
     * Item ID.
14
     */
15
    protected $itemId;
16
17
    /**
18
     * Server resource path.
19
     *
20
     * @return string
21
     */
22
    abstract public function resourcePath();
23
24
    /**
25
     * Server resource class name.
26
     *
27
     * @return string
28
     */
29
    abstract public function resourceClass();
30
31
    /**
32
     * Determines if current command is list command.
33
     *
34
     * @return bool
35
     */
36
    protected function isListCommand(): bool
37
    {
38
        return method_exists($this, 'listResponseItemsKey');
39
    }
40
41
    /**
42
     * Command name.
43
     *
44
     * @return string
45
     */
46
    public function command()
47
    {
48
        return $this->resourcePath();
49
    }
50
51
    /**
52
     * HTTP request method.
53
     *
54
     * @return string
55
     */
56
    public function requestMethod()
57
    {
58
        if ($this->isListCommand()) {
59
            return 'GET';
60
        }
61
62
        return is_null($this->itemId) ? 'POST' : 'GET';
63
    }
64
65
    /**
66
     * HTTP request URL.
67
     *
68
     * @param \Laravel\Forge\Server
69
     *
70
     * @return string
71
     */
72
    public function requestUrl(Server $server)
73
    {
74
        $resourcePath = $this->resourcePath();
75
76
        if (!is_null($this->getItemId())) {
77
            $resourcePath .= '/'.$this->getItemId();
78
        }
79
80
        return $server->apiUrl($resourcePath);
81
    }
82
83
    /**
84
     * Set Item ID.
85
     *
86
     * @param int|string $itemId
87
     *
88
     * @return static
89
     */
90
    public function setItemId($itemId)
91
    {
92
        $this->itemId = $itemId;
93
94
        return $this;
95
    }
96
97
    /**
98
     * Get Item ID.
99
     *
100
     * @return int|string|null
101
     */
102
    public function getItemId()
103
    {
104
        return $this->itemId;
105
    }
106
107
    /**
108
     * Processes new response item.
109
     *
110
     * @param mixed $item
111
     *
112
     * @return mixed
113
     */
114
    public function processResponseItem($item)
115
    {
116
        return $item;
117
    }
118
119
    /**
120
     * Handle command response.
121
     *
122
     * @param \Psr\Http\Message\ResponseInterface $response
123
     * @param \Laravel\Forge\Server               $server
124
     *
125
     * @return \Laravel\Forge\ServerResources\ServerResource|array|bool|string
126
     */
127
    public function handleResponse(ResponseInterface $response, Server $server)
128
    {
129
        if ($this->isListCommand()) {
130
            return $this->handleListCommandResponse($response, $server);
131
        }
132
133
        $className = $this->resourceClass();
134
135
        return $this->processResponseItem(
136
            $className::createFromResponse($response, $server)
137
        );
138
    }
139
140
    /**
141
     * List response handler.
142
     *
143
     * @param \Psr\Http\Message\ResponseInterface $response
144
     * @param \Laravel\Forge\Server               $server
145
     *
146
     * @throws \InvalidArgumentException
147
     *
148
     * @return array
149
     */
150
    public function handleListCommandResponse(ResponseInterface $response, Server $server)
151
    {
152
        $itemsKey = $this->listResponseItemsKey();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Laravel\Forge\ServerReso...s\ServerResourceCommand as the method listResponseItemsKey() does only exist in the following sub-classes of Laravel\Forge\ServerReso...s\ServerResourceCommand: Laravel\Forge\Daemons\Commands\ListDaemonsCommand, Laravel\Forge\Firewall\C...istFirewallRulesCommand, Laravel\Forge\Jobs\Commands\ListJobsCommand, Laravel\Forge\Services\M...stMysqlDatabasesCommand, Laravel\Forge\Services\M...s\ListMysqlUsersCommand, Laravel\Forge\Sites\Commands\ListSitesCommand, Laravel\Forge\Sites\Comm...kers\ListWorkersCommand, Laravel\Forge\SshKeys\Commands\ListSshKeysCommand. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
153
154
        $json = json_decode((string) $response->getBody(), true);
155
156
        if (empty($json[$itemsKey])) {
157
            throw new InvalidArgumentException('Given response is not a '.$this->resourcePath().' response.');
158
        }
159
160
        $items = [];
161
        $className = $this->resourceClass();
162
163
        foreach ($json[$itemsKey] as $item) {
164
            $items[] = $this->processResponseItem(new $className($server, $item));
165
        }
166
167
        return $items;
168
    }
169
}
170