-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuzzle.php
More file actions
58 lines (48 loc) · 1.57 KB
/
Copy pathGuzzle.php
File metadata and controls
58 lines (48 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
namespace ADT\Utils;
use Exception;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Message;
use Throwable;
class Guzzle
{
private const MAX_BODY_LENGTH = 10000;
/**
* @throws Throwable
*/
public static function handleException(Throwable $e): ?Exception
{
if ($e instanceof GuzzleException) {
$message = '';
if ($e instanceof ConnectException || $e instanceof RequestException) {
$message = "--- REQUEST ---\n" . self::sanitizeMessage(Message::toString($e->getRequest())) . "\n --- RESPONSE ---\n";
}
$message .= ($e instanceof RequestException && $e->getResponse() ? self::sanitizeMessage(Message::toString($e->getResponse())) : $e->getMessage());
throw new Exception($message);
}
throw $e;
}
private static function sanitizeMessage(string $message): string
{
// Odstraneni binarnich dat (null byty apod.)
if (preg_match('/[^\x20-\x7E\x0A\x0D\t]/u', $message)) {
// Najdeme konec hlavicek (prazdny radek)
$headerEnd = strpos($message, "\r\n\r\n");
if ($headerEnd === false) {
$headerEnd = strpos($message, "\n\n");
}
if ($headerEnd !== false) {
$headers = substr($message, 0, $headerEnd);
return $headers . "\n\n[binary data removed]";
}
return '[binary data removed]';
}
// Oriznuti prilis dlouhych textovych odpovedi
if (strlen($message) > self::MAX_BODY_LENGTH) {
return substr($message, 0, self::MAX_BODY_LENGTH) . "\n\n... [truncated, total " . strlen($message) . " bytes]";
}
return $message;
}
}