Created
December 31, 2021 10:57
-
-
Save jenky/61848fb8abce68af791c59858ceb22c3 to your computer and use it in GitHub Desktop.
Custom guzzle message formatter to remove binary image from log message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Helpers; | |
use GuzzleHttp\MessageFormatter as Formatter; | |
use GuzzleHttp\Psr7\MultipartStream; | |
use Illuminate\Support\Str; | |
use Psr\Http\Message\RequestInterface; | |
use Psr\Http\Message\ResponseInterface; | |
class MessageFormatter extends Formatter | |
{ | |
/** | |
* {@inheritDoc} | |
*/ | |
public function format( | |
RequestInterface $request, | |
ResponseInterface $response = null, | |
\Exception $error = null | |
) { | |
$result = parent::format($request, $response, $error); | |
$body = $request->getBody(); | |
if ($body instanceof MultipartStream) { | |
return $this->removeRawBinary($body->getBoundary(), $result); | |
} | |
return $result; | |
} | |
/** | |
* Remove the binary data from the log. | |
* | |
* @param string $boundary | |
* @param string $log | |
* @return string | |
*/ | |
protected function removeRawBinary(string $boundary, string $log) | |
{ | |
$parts = preg_split("/-+$boundary/", $log); | |
$output = []; | |
foreach ($parts as $part) { | |
if (Str::contains($part, 'image/')) { | |
preg_match('/.*?\/(jpg|jpeg|png|gif)/is', $part, $matches); | |
if (isset($matches[0])) { | |
$output[] = $matches[0]."\r\n"; | |
} | |
continue; | |
} | |
$output[] = $part; | |
} | |
return implode("\r\n".'--'.$boundary, $output); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment