Skip to content

Instantly share code, notes, and snippets.

@jenky
Created December 31, 2021 10:57
Show Gist options
  • Save jenky/61848fb8abce68af791c59858ceb22c3 to your computer and use it in GitHub Desktop.
Save jenky/61848fb8abce68af791c59858ceb22c3 to your computer and use it in GitHub Desktop.
Custom guzzle message formatter to remove binary image from log message
<?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