GuzzleAdapter::post()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 12

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
dl 16
loc 16
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 12
nc 4
nop 2
1
<?php
2
3
/*
4
 * This file is part of Laravel SMSFactor.
5
 *
6
 * (c) Filippo Galante <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace IlGala\SMSFactor\Adapters;
13
14
use Guzzle\Http\Client;
15
use Guzzle\Http\ClientInterface;
16
use Guzzle\Http\Exception\RequestException;
17
use Guzzle\Http\Message\Response;
18
use IlGala\SMSFactor\Exceptions\HttpException;
19
20
/**
21
 * @author Filippo Galante <[email protected]>
22
 */
23
class GuzzleAdapter implements AdapterInterface
24
{
25
26
    /**
27
     * @var ClientInterface
28
     */
29
    protected $client;
30
31
    /**
32
     * @var Response
33
     */
34
    protected $response;
35
36
    /**
37
     * @param string               $username
38
     * @param string               $password
39
     * @param string               $accept
40
     * @param ClientInterface|null $client
41
     */
42
    public function __construct($username, $password, $accept, ClientInterface $client = null)
43
    {
44
        $this->client = $client ?: new Client();
45
        $this->client->setDefaultOption('headers/sfusername', $username);
46
        $this->client->setDefaultOption('headers/sfpassword', $password);
47
        $this->client->setDefaultOption('headers/Accept', $accept);
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53 View Code Duplication
    public function get($url)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
54
    {
55
        try {
56
            $this->response = $this->client->get($url)->send();
57
        } catch (RequestException $e) {
58
            $this->response = $e->getResponse();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Guzzle\Http\Exception\RequestException as the method getResponse() does only exist in the following sub-classes of Guzzle\Http\Exception\RequestException: Guzzle\Http\Exception\BadResponseException, Guzzle\Http\Exception\ClientErrorResponseException, Guzzle\Http\Exception\ServerErrorResponseException, Guzzle\Http\Exception\TooManyRedirectsException. 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...
59
            $this->handleError();
60
        }
61
        return $this->response->getBody(true);
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 View Code Duplication
    public function delete($url)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
68
    {
69
        try {
70
            $this->response = $this->client->delete($url)->send();
71
        } catch (RequestException $e) {
72
            $this->response = $e->getResponse();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Guzzle\Http\Exception\RequestException as the method getResponse() does only exist in the following sub-classes of Guzzle\Http\Exception\RequestException: Guzzle\Http\Exception\BadResponseException, Guzzle\Http\Exception\ClientErrorResponseException, Guzzle\Http\Exception\ServerErrorResponseException, Guzzle\Http\Exception\TooManyRedirectsException. 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...
73
            $this->handleError();
74
        }
75
        return $this->response->getBody(true);
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81 View Code Duplication
    public function put($url, $content = '')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
82
    {
83
        $request = $this->client->put($url);
84
        if (is_array($content)) {
85
            $request->setBody(json_encode($content), 'application/json');
86
        } else {
87
            $request->setBody($content);
88
        }
89
        try {
90
            $this->response = $request->send();
91
        } catch (RequestException $e) {
92
            $this->response = $e->getResponse();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Guzzle\Http\Exception\RequestException as the method getResponse() does only exist in the following sub-classes of Guzzle\Http\Exception\RequestException: Guzzle\Http\Exception\BadResponseException, Guzzle\Http\Exception\ClientErrorResponseException, Guzzle\Http\Exception\ServerErrorResponseException, Guzzle\Http\Exception\TooManyRedirectsException. 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...
93
            $this->handleError();
94
        }
95
        return $this->response->getBody(true);
96
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101 View Code Duplication
    public function post($url, $content = '')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
    {
103
        $request = $this->client->post($url);
104
        if (is_array($content)) {
105
            $request->setBody(json_encode($content), 'application/json');
106
        } else {
107
            $request->setBody($content);
108
        }
109
        try {
110
            $this->response = $request->send();
111
        } catch (RequestException $e) {
112
            $this->response = $e->getResponse();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Guzzle\Http\Exception\RequestException as the method getResponse() does only exist in the following sub-classes of Guzzle\Http\Exception\RequestException: Guzzle\Http\Exception\BadResponseException, Guzzle\Http\Exception\ClientErrorResponseException, Guzzle\Http\Exception\ServerErrorResponseException, Guzzle\Http\Exception\TooManyRedirectsException. 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...
113
            $this->handleError();
114
        }
115
        return $this->response->getBody(true);
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121 View Code Duplication
    public function getLatestResponseHeaders()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
122
    {
123
        if (null === $this->response) {
124
            return;
125
        }
126
        return [
127
            'reset' => (int) (string) $this->response->getHeader('RateLimit-Reset'),
128
            'remaining' => (int) (string) $this->response->getHeader('RateLimit-Remaining'),
129
            'limit' => (int) (string) $this->response->getHeader('RateLimit-Limit'),
130
        ];
131
    }
132
133
    /**
134
     * @throws HttpException
135
     */
136 View Code Duplication
    protected function handleError()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
137
    {
138
        $body = (string) $this->response->getBody(true);
139
        $code = (int) $this->response->getStatusCode();
140
        $content = json_decode($body);
141
        throw new HttpException(isset($content->message) ? $content->message : 'Request not processed.', $code);
142
    }
143
}
144