Completed
Push — master ( 44b229...b8c9f6 )
by Stéphane
01:02
created

SendGrid::requestRaw()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
namespace StephaneCoinon\SendGridActivity;
4
5
use Http\Client\Common\Plugin\BaseUriPlugin;
6
use Http\Client\HttpClient;
7
use Http\Discovery\MessageFactoryDiscovery;
8
use Http\Discovery\UriFactoryDiscovery;
9
use StephaneCoinon\SendGridActivity\HttpClientFactory;
10
use StephaneCoinon\SendGridActivity\Requests\Request;
11
use StephaneCoinon\SendGridActivity\Support\Collection;
12
13
/**
14
 * SendGrid API client.
15
 */
16
class SendGrid
17
{
18
    /**
19
     * API base URL.
20
     *
21
     * @var string
22
     */
23
    protected $apiUrl = 'https://api.sendgrid.com';
24
25
    /**
26
     * API version.
27
     *
28
     * @var string
29
     */
30
    protected $apiVersion = 'v3';
31
32
    /**
33
     * Underlying HTTP client.
34
     *
35
     * @var \Http\Client\HttpClient
36
     */
37
    protected $client;
38
39
    /**
40
     * Message factory.
41
     *
42
     * @var \Http\Message\MessageFactory
43
     */
44
    protected $messageFactory;
45
46
    /**
47
     * Make a new ApiClient instance.
48
     *
49
     * If $client is null, a new HttpClient using $apiKey is instantiated.
50
     * If $apiKey is null, SENDGRID_API_KEY environment variable is used.
51
     * $apiKey is not used when $client is specified.
52
     *
53
     * @param null|string $apiKey
54
     * @param null|\Http\Client\HttpClient $client
55
     */
56
    public function __construct($apiKey = null, HttpClient $client = null)
57
    {
58
        $this->messageFactory = MessageFactoryDiscovery::find();
59
        $this->client = $client ?? HttpClientFactory::create(
60
            $apiKey ?? getenv('SENDGRID_API_KEY'),
61
            [
0 ignored issues
show
Documentation introduced by
array(new \Http\Client\C...ateUri($this->apiUrl))) is of type array<integer,object<Htt...ugin\\BaseUriPlugin>"}>, but the function expects a array<integer,object<Ste...ndGridActivity\Plugin>>.

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...
62
                new BaseUriPlugin(
63
                    UriFactoryDiscovery::find()->createUri($this->apiUrl)
64
                )
65
            ]
66
        );
67
    }
68
69
    /**
70
     * Static constructor to get a ApiClient instance with a given HTTP client.
71
     *
72
     * @param  \Http\Client\HttpClient $client
73
     * @return self
74
     */
75
    public static function newWithClient(HttpClient $client)
76
    {
77
        return new static(null, $client);
78
    }
79
80
    /**
81
     * Set the underlying HTTP client.
82
     *
83
     * @param  \Http\Client\HttpClient $client
84
     * @return self
85
     */
86
    public function withClient(HttpClient $client): self
87
    {
88
        $this->client = $client;
89
90
        return $this;
91
    }
92
93
    /**
94
     * Get underlying HTTP client.
95
     *
96
     * @return \Http\Client\HttpClient
97
     */
98
    public function getClient(): HttpClient
99
    {
100
        return $this->client;
101
    }
102
103
    /**
104
     * Make a "raw" HTTP request.
105
     *
106
     * JSON responses are automatically decoded to an array.
107
     *
108
     * @param  string $method HTTP method
109
     * @param  string $url
110
     * @return string|array|\Illuminate\Support\Collection
111
     */
112
    public function requestRaw(string $method, string $url = '')
113
    {
114
        $response = $this->client->sendRequest(
115
            $this->messageFactory->createRequest(
116
                $method, "{$this->apiVersion}/{$url}"
117
            )
118
        );
119
120
        if ($response->getStatusCode() != 200) {
121
            var_dump(['request failed' => $response->getBody()->getContents()]); die();
0 ignored issues
show
Security Debugging Code introduced by
var_dump(array('request ...ody()->getContents())); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
122
            // throw new \Exception('Request failed');
123
        }
124
125
        $content = $response->getBody()->getContents();
126
        $contentType = $response->getHeader('Content-Type');
127
        $isJson = in_array('application/json', $contentType);
128
129
        return $isJson ? Collection::collect(json_decode($content, true)) : $content;
130
    }
131
132
    /**
133
     * Make a request using a Request instance.
134
     *
135
     * @param  Request $request
136
     * @return Response|Response[]
137
     */
138
    public function request(Request $request)
139
    {
140
        $responseModel = $request->getResponseModel();
141
        $response = $this->requestRaw(
142
            $request->getMethod(), $request->buildUrl()
143
        );
144
145
        return $responseModel::createFromApiResponse($response);
146
    }
147
}
148