Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Last active February 5, 2018 15:23
Show Gist options
  • Save surferxo3/f3a7ee03de13308d5c1aed250aa70e97 to your computer and use it in GitHub Desktop.
Save surferxo3/f3a7ee03de13308d5c1aed250aa70e97 to your computer and use it in GitHub Desktop.
Silex guzzle provider implementation using handler stack consisting of mapRequest, retry, and log middleware
<?php
/*#############################
* Developer: Mohammad Sharaf Ali
* Designation: Web Developer
* Version: 1.0
*/#############################
$handler = new CurlHandler();
$stack = HandlerStack::create($handler);\
// Sample Guzzle Log Middleware - START
$guzzleLogFormat = 'date_iso_8601::{date_iso_8601}:::date_common_log::{date_common_log}:::uri::{uri}:::host::{host}:::version::{version}:::target::{target}:::hostname::{hostname}:::code::{code}:::phrase::{phrase}:::error::{error}:::req_headers::{req_headers}:::res_headers::{res_headers}:::res_body::{res_body}';
// set logger
$logger = new Logger('api.guzzle.log');
# mongodb handler
try {
/*
* Connection pooling: Remote server has closed the connection
* Try max X no. retries to establish connection to mongodb & atmost one retry is ever needed
*/
$mongoOptions = [
'username' => $app['config.file']['MONGO_USER'],
'password' => $app['config.file']['MONGO_PASSWORD'],
'db' => $app['config.file']['MONGO_DATABASE_NAME'],
'connect' => true,
'w' => 0
];
$mongo = AppHelper::getMongoClient($app['config.file']['MONGO_HOST'], $mongoOptions, $app['config.file']['MONGO_MAX_RETRIES']);
$mongoHandler = new MongoDBHandler($mongo, $app['config.file']['MONGO_DATABASE_NAME'], 'guzzle');
$mongoHandler->setFormatter(new MongoDBFormatter());
$logger->pushHandler($mongoHandler);
} catch (Exception $e) {
// handle when unable to connect to server after retries
# send email
$emailToSend = explode(',', $app['config.file']['TO_EMAIL']);
$app['emailer']('MongoClient Connection Error!', $e->getTraceAsString(), $emailToSend);
# end script execution
AppHelper::toScreen($e->getMessage(), 1);
}
foreach ($logger->getHandlers() as $handler) {
if ($handler instanceof MongoDBHandler) {
$handler->pushProcessor(function(array $record) use ($app) {
//AppHelper::toScreen($record['message'], 1);
$recordArray = explode(':::', $record['message']);
//AppHelper::toScreen($recordArray, 1);
$newRecordArray = [];
array_walk($array, function($val, $key) use (&$newRecordArray) {
$nvp = explode('::', $val);
$newRecordArray[$nvp[0]] = $nvp[1];
});
//AppHelper::toScreen($newRecordArray, 1);
$record['context'] = $newRecordArray;
$record['extra']['key_action'] = $app['request_stack']->getCurrentRequest()->get('_route');
unset($record['message']);
return $record;
});
}
}
$stack->push(Middleware::log($logger, new \GuzzleHttp\MessageFormatter($guzzleLogFormat), \Psr\Log\LogLevel::DEBUG));
// Sample Guzzle Log Middleware - END
/*
* cURL error 6: could not resolve host
* Retry middleware added for max X no. of retries to host
*/
$stack->push(Middleware::retry(AppHelper::retryDecider($app['config.file']['GUZZLE_MAX_RETRIES']), AppHelper::retryDelay()));
$stack->push(Middleware::mapRequest(function(RequestInterface $request) use ($app) {
$queryParams = $request->getUri()->getQuery();
parse_str($queryParams, $queryParams);
if (!empty($queryParams['exclude_url'])) {
unset($queryParams['exclude_url']);
$app['isGuzzleExcludeUrl'] = 1;
} else {
$app['isGuzzleExcludeUrl'] = 0;
}
return new Request(
$request->getMethod(),
$request->getUri(),
$request->getHeaders(),
http_build_query($queryParams, null, '&', PHP_QUERY_RFC3986)
);
}));
$app->register(new GuzzleServiceProvider(), [
'guzzle.request_options' => [
RequestOptions::VERIFY => false,
RequestOptions::ON_STATS => function(TransferStats $stats) use ($app) {
$app['isGuzzle'] = 1;
if (empty($app['isGuzzleExcludeUrl'])) {
$reqeustUri = $stats->getRequest()->getUri();
$queryParams = $reqeustUri->getQuery();
parse_str($queryParams, $queryParams);
// unset secure params
unset($queryParams['username']);
unset($queryParams['loginId']);
unset($queryParams['password']);
// assign app params for global usage
$app['query.params'] = $queryParams;
//$commaSepQueryParams = urldecode(http_build_query($queryParams, '', ', '));
$strQueryParams = http_build_query($queryParams);
$app['summary.log'] = [
'request_uri' => (string) $reqeustUri->withQuery($strQueryParams),
//'request_params' => !empty($commaSepQueryParams) ? $commaSepQueryParams : '-',
'request_params' => !empty($queryParams) ? $queryParams : [],
'response_time' => $stats->getTransferTime()
];
}
},
'curl' => [
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
],
'handler' => $stack
]
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment