• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

RonasIT / laravel-helpers / 14260163152

04 Apr 2025 07:20AM UTC coverage: 77.591% (-1.5%) from 79.092%
14260163152

Pull #111

github

web-flow
Merge 630f28118 into 38fbefe16
Pull Request #111: #98 assertEqualsFixture add reference to assertable fixture to error message

7 of 7 new or added lines in 1 file covered. (100.0%)

34 existing lines in 2 files now uncovered.

1108 of 1428 relevant lines covered (77.59%)

12.45 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.62
/src/Services/HttpRequestService.php
1
<?php
2

3
namespace RonasIT\Support\Services;
4

5
use GuzzleHttp\Client;
6
use Illuminate\Support\Arr;
7
use GuzzleHttp\Cookie\CookieJar;
8
use Psr\Http\Message\ResponseInterface;
9
use GuzzleHttp\Exception\RequestException;
10
use Riverline\MultiPartParser\StreamedPart;
11
use RonasIT\Support\Exceptions\InvalidJSONFormatException;
12
use RonasIT\Support\Exceptions\UnknownRequestMethodException;
13

14
class HttpRequestService
15
{
16
    protected $debug;
17

18
    protected $connectTimeout = 0;
19
    protected $allowRedirects = true;
20

21
    protected $options = [];
22
    protected $cookies = null;
23

24
    protected $response;
25

26
    public function __construct()
27
    {
28
        $this->debug = config('defaults.http_service_debug', false);
19✔
29
    }
30

31
    public function set(string $key, $value): self
32
    {
33
        $this->options[$key] = $value;
1✔
34

35
        return $this;
1✔
36
    }
37

38
    public function json(): array
39
    {
40
        $stringResponse = (string) $this->response->getBody();
2✔
41

42
        $result = json_decode($stringResponse, true);
2✔
43

44
        if (json_last_error() !== JSON_ERROR_NONE) {
2✔
45
            throw new InvalidJSONFormatException($stringResponse);
1✔
46
        }
47

48
        return $result;
1✔
49
    }
50

51
    public function getResponse(): ResponseInterface
52
    {
53
        return $this->response;
1✔
54
    }
55

56
    public function saveCookieSession(): self
57
    {
UNCOV
58
        $this->cookies = app(CookieJar::class);
×
59

UNCOV
60
        return $this;
×
61
    }
62

63
    public function getCookie(): array
64
    {
65
        if (empty($this->cookies)) {
×
UNCOV
66
            return [];
×
67
        }
68

UNCOV
69
        return $this->cookies->toArray();
×
70
    }
71

72
    public function allowRedirects(bool $value = true): self
73
    {
74
        $this->allowRedirects = $value;
1✔
75

76
        return $this;
1✔
77
    }
78

79
    public function setConnectTimeout(int $seconds = 0): self
80
    {
81
        $this->connectTimeout = $seconds;
1✔
82

83
        return $this;
1✔
84
    }
85

86
    public function get(string $url, array $data = [], array $headers = []): self
87
    {
88
        return $this->send('get', $url, $data, $headers);
5✔
89
    }
90

91
    public function post(string $url, array $data, array $headers = []): self
92
    {
93
        return $this->send('post', $url, $data, $headers);
2✔
94
    }
95

96
    public function delete(string $url, array $headers = []): self
97
    {
98
        return $this->send('delete', $url, [], $headers);
1✔
99
    }
100

101
    public function put(string $url, array $data, array $headers = []): self
102
    {
103
        return $this->send('put', $url, $data, $headers);
8✔
104
    }
105

106
    public function patch(string $url, array $data, array $headers = []): self
107
    {
108
        return $this->send('patch', $url, $data, $headers);
1✔
109
    }
110

111
    public function send(string $method, string $url, array $data = [], array $headers = []): self
112
    {
113
        $startTime = microtime(true);
18✔
114

115
        $this->logRequest($method, $url, $data, $headers);
18✔
116

117
        try {
118
            $this->response = $this->sendRequest($method, $url, $data, $headers);
18✔
119

120
            return $this;
16✔
121
        } catch (RequestException $exception) {
2✔
122
            $this->response = $exception->getResponse();
1✔
123

124
            throw $exception;
1✔
125
        } finally {
126
            $this->logResponse($startTime);
18✔
127
            $this->options = [];
18✔
128
        }
129
    }
130

131
    public function multipart(): array
132
    {
133
        $content = $this->response
1✔
134
            ->getBody()
1✔
135
            ->getContents();
1✔
136

137
        $stream = fopen('php://temp', 'rw');
1✔
138
        fwrite($stream, $content);
1✔
139
        rewind($stream);
1✔
140

141
        return app()
1✔
142
            ->makeWith(StreamedPart::class, ['stream' => $stream])
1✔
143
            ->getParts();
1✔
144
    }
145

146
    protected function sendRequest($method, $url, array $data = [], array $headers = []): ResponseInterface
147
    {
148
        $headers = array_change_key_case($headers);
16✔
149

150
        $this->setOptions($headers);
16✔
151
        $this->setData($method, $headers, $data);
16✔
152

153
        $client = app(Client::class);
16✔
154

155
        switch ($method) {
156
            case 'get':
16✔
157
                $response = $client->get($url, $this->options);
3✔
158
                break;
3✔
159
            case 'post':
13✔
160
                $response = $client->post($url, $this->options);
2✔
161
                break;
2✔
162
            case 'put':
11✔
163
                $response = $client->put($url, $this->options);
8✔
164
                break;
8✔
165
            case 'patch':
3✔
166
                $response = $client->patch($url, $this->options);
1✔
167
                break;
1✔
168
            case 'delete':
2✔
169
                $response = $client->delete($url, $this->options);
1✔
170
                break;
1✔
171
            default:
172
                throw new UnknownRequestMethodException($method);
1✔
173
        }
174

175
        return $response;
15✔
176
    }
177

178
    /**
179
     * @codeCoverageIgnore
180
     * @deprecated please use
181
     * https://laravel.com/docs/10.x/telescope and
182
     * https://packagist.org/packages/muhammadhuzaifa/telescope-guzzle-watcher instead
183
     */
184
    protected function logRequest(string $typeOfRequest, string $url, array $data, array $headers): void
185
    {
186
        if ($this->debug) {
187
            logger('');
188
            logger('-------------------------------------');
189
            logger('');
190
            logger("sending {$typeOfRequest} request:", [
191
                'url' => $url,
192
                'data' => $data,
193
                'headers' => $headers,
194
            ]);
195
            logger('');
196
        }
197
    }
198

199
    /**
200
     * @codeCoverageIgnore
201
     * @deprecated please use
202
     * https://laravel.com/docs/10.x/telescope and
203
     * https://packagist.org/packages/muhammadhuzaifa/telescope-guzzle-watcher instead
204
     */
205
    protected function logResponse(?float $time = null): void
206
    {
207
        $endTime = (empty($time)) ? null : microtime(true) - $time;
208

209
        if ($this->debug) {
210
            logger('');
211
            logger('-------------------------------------');
212
            logger('');
213
            logger('getting response: ');
214
            logger('code', ["<{$this->response->getStatusCode()}>"]);
215
            logger('body', ["<{$this->response->getBody()}>"]);
216
            logger('time', [$endTime]);
217
            logger('');
218
        }
219
    }
220

221
    protected function setOptions(array $headers): self
222
    {
223
        $this->options['headers'] = $headers;
16✔
224
        $this->options['cookies'] = $this->cookies;
16✔
225
        $this->options['allow_redirects'] = $this->allowRedirects;
16✔
226
        $this->options['connect_timeout'] = $this->connectTimeout;
16✔
227

228
        return $this;
16✔
229
    }
230

231
    protected function setData(string $method, array $headers, array $data = []): void
232
    {
233
        if (empty($data)) {
16✔
234
            return;
4✔
235
        }
236

237
        if ($method == 'get') {
12✔
238
            $this->options['query'] = $data;
1✔
239

240
            return;
1✔
241
        }
242

243
        $contentType = Arr::get($headers, 'content-type');
11✔
244

245
        if (preg_match('/application\/json/', $contentType)) {
11✔
246
            $this->options['json'] = $data;
5✔
247
        } elseif (preg_match('/application\/x-www-form-urlencoded/', $contentType)) {
6✔
248
            $this->options['form_params'] = $data;
1✔
249
        } elseif (preg_match('/multipart\/form-data/', $contentType)) {
5✔
250
            Arr::forget($this->options, 'headers.content-type');
1✔
251
            $this->options['multipart'] = $this->convertToMultipart($data);
1✔
252
        } else {
253
            $this->options['body'] = json_encode($data);
4✔
254
        }
255
    }
256

257
    protected function convertToMultipart(array $data, ?string $parentKey = null): array
258
    {
259
        $result = [];
1✔
260

261
        foreach ($data as $key => $value) {
1✔
262
            $preparedKey = is_int($key) || is_null($parentKey)
1✔
263
                ? $key
1✔
264
                : "{$parentKey}[{$key}]";
1✔
265

266
            if (is_array($value)) {
1✔
267
                $result = array_merge($result, $this->convertToMultipart($value, $preparedKey));
1✔
268
            } else {
269
                $result[] = [
1✔
270
                    'name' => $preparedKey,
1✔
271
                    'contents' => $value,
1✔
272
                ];
1✔
273
            }
274
        }
275

276
        return $result;
1✔
277
    }
278
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc