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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
<?php
namespace Gedcomx\Extensions\FamilySearch\Rs\Client\Util;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\MessageInterface;
class LoggerMiddleware
{
public static function middleware($logger)
{
return function(callable $handler) use ($logger) {
return function(RequestInterface $request, array $options) use ($handler, $logger) {
$logger->info($request->getMethod() . ' ' . $request->getUri());
$logger->debug(self::printHeaders($request));
$logger->debug($request->getBody());
$promise = $handler($request, $options);
return $promise->then(function(ResponseInterface $response) use ($logger) {
$statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase();
if($statusCode >= 400 && $statusCode < 500){
$logger->error($statusCode . ' ' . $reason);
}
else if($statusCode == 503){
$logger->alert($statusCode . ' ' . $reason);
}
else if($statusCode >= 500){
$logger->critical($statusCode . ' ' . $reason);
}
else {
$logger->info($statusCode . ' ' . $reason);
}
$logger->debug(self::printHeaders($response));
$logger->debug($response->getBody());
if($response->getHeader('warning')){
$logger->warning($response->getHeaderLine('warning'));
}
return $response;
});
};
};
}
private static function printHeaders(MessageInterface $message)
{
$headers = [];
foreach($message->getHeaders() as $name => $values){
$headers[] = $name . ': ' . implode(', ', $values);
}
return implode("\n", $headers);
}
}