Completed
Push — master ( 3fbfb5...43cfb4 )
by Kirill
116:33 queued 110:37
created

AbstractResource::fetch()   B

Complexity

Conditions 3
Paths 1

Size

Total Lines 36
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 20
nc 1
nop 1
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of GitterApi package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
namespace Gitter\Resources;
9
10
use Gitter\Adapters\AdapterInterface;
11
use Gitter\Adapters\HttpAdapter;
12
use Gitter\Adapters\StreamAdapter;
13
use Gitter\Route;
14
use Gitter\Client;
15
use Gitter\Support\Observer;
16
use GuzzleHttp\Exception\ClientException;
17
use Serafim\Evacuator\Evacuator;
18
use GuzzleHttp\Exception\RequestException;
19
20
/**
21
 * Class AbstractResource
22
 * @package Gitter\Resources
23
 */
24
abstract class AbstractResource implements ResourceInterface
25
{
26
    /**
27
     * @var null
28
     */
29
    private $client;
30
31
    /**
32
     * AbstractResource constructor.
33
     * @param Client $client
34
     */
35
    public function __construct(Client $client)
36
    {
37
        $this->client = $client;
0 ignored issues
show
Documentation Bug introduced by
It seems like $client of type object<Gitter\Client> is incompatible with the declared type null of property $client.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
38
    }
39
40
    /**
41
     * @return Client
42
     */
43
    protected function client(): Client
44
    {
45
        return $this->client;
46
    }
47
48
    /**
49
     * @param Route $route
50
     * @return array|mixed
51
     * @throws \GuzzleHttp\Exception\ClientException
52
     * @throws \GuzzleHttp\Exception\RequestException
53
     * @throws \Throwable
54
     * @throws \Exception
55
     * @throws \RuntimeException
56
     * @throws \InvalidArgumentException
57
     */
58
    protected function fetch(Route $route): array
59
    {
60
        $rescue = (new Evacuator(function () use ($route) {
61
            return (array)$this->viaHttp()->request($route);
62
        }))
63
            // If response has status code 4xx
64
            ->onError(function (ClientException $e) {
65
                $this->client->logger->error(get_class($e) . '  ' . $e->getMessage());
66
67
                switch ($e->getResponse()->getStatusCode()) {
68
                    case 429: // 429 Too Many Requests
69
                        sleep(2);
70
                        return null;
71
                }
72
73
                throw $e;
74
            })
75
            // On internal errors
76
            ->onError(function (RequestException $e) {
77
                $this->client->logger->error($e->getMessage());
78
79
                // Throws request exception if SSL error
80
                if (false !== strpos($e->getMessage(), 'SSL certificate problem')) {
81
                    throw $e;
82
                }
83
            })
84
            // Other
85
            ->onError(function (\Exception $e) {
86
                $this->client->logger->error($e->getMessage());
87
                throw $e;
88
            })
89
            ->retries($this->client->getRetriesCount())
0 ignored issues
show
Bug introduced by
The method getRetriesCount cannot be called on $this->client (of type null).

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...
90
            ->invoke();
91
92
        return $rescue;
93
    }
94
95
    /**
96
     * @param Route $route
97
     * @return Observer
98
     * @throws \Throwable
99
     * @throws \InvalidArgumentException
100
     */
101
    protected function stream(Route $route): Observer
102
    {
103
        return (new Evacuator(function() use ($route) {
104
            return $this->viaStream()->request($route);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Gitter\Adapters\AdapterInterface as the method request() does only exist in the following implementations of said interface: Gitter\Adapters\HttpAdapter, Gitter\Adapters\StreamAdapter.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
105
        }))
106
            ->onError(function (\Exception $e) {
107
                $this->client->logger->error($e->getMessage());
108
            })
109
            ->retries($this->client->getRetriesCount())
0 ignored issues
show
Bug introduced by
The method getRetriesCount cannot be called on $this->client (of type null).

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...
110
            ->invoke();
111
    }
112
113
    /**
114
     * @return AdapterInterface|HttpAdapter
115
     */
116
    protected function viaHttp(): HttpAdapter
117
    {
118
        return $this->client->viaHttp();
0 ignored issues
show
Bug introduced by
The method viaHttp cannot be called on $this->client (of type null).

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...
119
    }
120
121
    /**
122
     * @return AdapterInterface|StreamAdapter
123
     */
124
    protected function viaStream(): StreamAdapter
125
    {
126
        return $this->client->viaStream();
0 ignored issues
show
Bug introduced by
The method viaStream cannot be called on $this->client (of type null).

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...
127
    }
128
}
129