Skip to content

Commit f1fecc8

Browse files
LCH-6356: Adding guzzle 8 compatibility. 2.x. (#166)
* LCH-6356: Adding guzzle 8 compatibility. * LCH-6356: Removing phpstan ignore-error. * LCH-6356: Removing __call method. * LCH-6356: Minimum guzzle version to 6.5. * LCH-6356: Added backward compatibility for guzzle 6 and removed redundant code. * LCH-6356: Created conditional common trait. * LCH-6356: Added todo comment.
1 parent 66b491f commit f1fecc8

File tree

5 files changed

+472
-263
lines changed

5 files changed

+472
-263
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
"ext-json": "*",
1919
"php": ">=7.3",
2020
"psr/log": ">=1.0",
21-
"guzzlehttp/guzzle": ">=6.5 <8.0",
21+
"guzzlehttp/guzzle": ">=6.5",
2222
"symfony/event-dispatcher": ">=4.4",
2323
"symfony/http-foundation": ">=4.4",
2424
"symfony/serializer": ">=4.4"

phpstan.neon

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ parameters:
33
paths:
44
- ./src
55
ignoreErrors:
6-
- '#Class [a-zA-Z0-9\\_:\(\).]* extends [a-zA-Z0-9\\_:@\(\).]*#'
76
- '#Unsafe usage of new static\(\).#'
87
excludePaths:
98
- test/

src/ContentHubClient.php

Lines changed: 7 additions & 261 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,15 @@
33
namespace Acquia\ContentHubClient;
44

55
use Acquia\ContentHubClient\CDF\CDFObject;
6-
use Acquia\ContentHubClient\Guzzle\Middleware\RequestResponseHandler;
76
use Acquia\ContentHubClient\SearchCriteria\SearchCriteria;
87
use Acquia\ContentHubClient\SearchCriteria\SearchCriteriaBuilder;
98
use Acquia\Hmac\Guzzle\HmacAuthMiddleware;
109
use GuzzleHttp\Client;
10+
use GuzzleHttp\ClientInterface;
1111
use GuzzleHttp\Exception\BadResponseException;
1212
use GuzzleHttp\Exception\ClientException;
1313
use GuzzleHttp\Exception\RequestException;
14-
use GuzzleHttp\HandlerStack;
1514
use GuzzleHttp\Psr7\Response;
16-
use Psr\Log\LogLevel;
1715
use Symfony\Component\HttpFoundation\Response as HttpResponse;
1816
use Psr\Http\Message\ResponseInterface;
1917
use Psr\Log\LoggerInterface;
@@ -26,7 +24,9 @@
2624
*
2725
* @package Acquia\ContentHubClient
2826
*/
29-
class ContentHubClient extends Client {
27+
class ContentHubClient implements ClientInterface {
28+
29+
use ContentHubClientTrait;
3030

3131
const LIB_VERSION = '2.x-dev';
3232

@@ -126,30 +126,11 @@ public function __construct(
126126
$config['handler']->push($middleware);
127127
$this->addRequestResponseHandler($config);
128128

129-
parent::__construct($config);
129+
$this->httpClient = ObjectFactory::getGuzzleClient($config);
130+
$this->setConfigs($config);
130131
}
131132
// phpcs:enable
132133

133-
/**
134-
* Pings the service to ensure that it is available.
135-
*
136-
* @return \Psr\Http\Message\ResponseInterface
137-
* Response.
138-
*
139-
* @throws \GuzzleHttp\Exception\RequestException
140-
* @throws \Exception
141-
*
142-
* @since 0.2.0
143-
*/
144-
public function ping(): ResponseInterface {
145-
$makeBaseURL = self::makeBaseURL($this->getConfig()['base_url']);
146-
$client = ObjectFactory::getGuzzleClient([
147-
'base_uri' => $makeBaseURL,
148-
]);
149-
150-
return $client->get('ping');
151-
}
152-
153134
/**
154135
* Discoverability of the API.
155136
*
@@ -406,7 +387,7 @@ public function getEntities(array $uuids) {
406387
* @return \Acquia\ContentHubClient\CDF\CDFObjectInterface
407388
* CDFObject
408389
*/
409-
protected function getCDFObject($data) { // phpcs:ignore
390+
public function getCDFObject($data) { // phpcs:ignore
410391
$event = ObjectFactory::getCDFTypeEvent($data);
411392
$this->dispatcher->dispatch($event, ContentHubLibraryEvents::GET_CDF_CLASS);
412393

@@ -748,18 +729,6 @@ public function getInterestsByWebhook($webhook_uuid) {
748729
return $data['data']['interests'] ?? [];
749730
}
750731

751-
/**
752-
* Get the settings that were used to instantiate this client.
753-
*
754-
* @return \Acquia\ContentHubClient\Settings
755-
* Settings object.
756-
*
757-
* @codeCoverageIgnore
758-
*/
759-
public function getSettings() {
760-
return $this->settings;
761-
}
762-
763732
/**
764733
* Obtains the Settings for the active subscription.
765734
*
@@ -1107,229 +1076,6 @@ public function removeFilterFromWebhook($filter_id, $webhook_id) {
11071076
return self::getResponseJson($response);
11081077
}
11091078

1110-
/**
1111-
* Gets a Json Response from a request.
1112-
*
1113-
* @param \Psr\Http\Message\ResponseInterface $response
1114-
* Response.
1115-
*
1116-
* @return mixed
1117-
* Response array.
1118-
*
1119-
* @throws \Exception
1120-
*/
1121-
public static function getResponseJson(ResponseInterface $response) {
1122-
try {
1123-
$body = (string) $response->getBody();
1124-
}
1125-
catch (\Exception $exception) {
1126-
$message = sprintf("An exception occurred in the JSON response. Message: %s",
1127-
$exception->getMessage());
1128-
throw new \Exception($message);
1129-
}
1130-
1131-
return json_decode($body, TRUE);
1132-
}
1133-
1134-
/**
1135-
* {@inheritdoc}
1136-
*
1137-
* @codeCoverageIgnore
1138-
*/
1139-
public function __call($method, $args) {
1140-
try {
1141-
if (strpos($args[0], '?')) {
1142-
[$uri, $query] = explode('?', $args[0]);
1143-
$parts = explode('/', $uri);
1144-
if ($query) {
1145-
$last = array_pop($parts);
1146-
$last .= "?$query";
1147-
$parts[] = $last;
1148-
}
1149-
}
1150-
else {
1151-
$parts = explode('/', $args[0]);
1152-
}
1153-
$args[0] = self::makePath(...$parts);
1154-
1155-
$args = $this->addSearchCriteriaHeader($args);
1156-
1157-
return parent::__call($method, $args);
1158-
}
1159-
catch (\Exception $e) {
1160-
return $this->getExceptionResponse($method, $args, $e);
1161-
}
1162-
}
1163-
1164-
/**
1165-
* Obtains the appropriate exception Response.
1166-
*
1167-
* Logging error messages according to API call.
1168-
*
1169-
* @param string $method
1170-
* The Request to Plexus, as defined in the content-hub-php library.
1171-
* @param array $args
1172-
* The Request arguments.
1173-
* @param \Exception $exception
1174-
* The Exception object.
1175-
*
1176-
* @return \Psr\Http\Message\ResponseInterface
1177-
* The response after raising an exception.
1178-
*
1179-
* @codeCoverageIgnore
1180-
*/
1181-
protected function getExceptionResponse($method, array $args, \Exception $exception) {
1182-
// If we reach here it is because there was an exception raised in the
1183-
// API call.
1184-
$api_call = $args[0];
1185-
$response = $exception->getResponse();
1186-
if (!$response) {
1187-
$response = $this->getErrorResponse($exception->getCode(), $exception->getMessage());
1188-
}
1189-
$response_body = json_decode($response->getBody(), TRUE);
1190-
$error_code = $response_body['error']['code'] ?? '';
1191-
$error_message = $response_body['error']['message'] ?? '';
1192-
1193-
// Customize Error messages according to API Call.
1194-
switch ($api_call) {
1195-
case'settings/webhooks':
1196-
$log_level = LogLevel::WARNING;
1197-
break;
1198-
1199-
case (preg_match('/filters\?name=*/', $api_call) ? TRUE : FALSE):
1200-
case (preg_match('/settings\/clients\/*/', $api_call) ? TRUE : FALSE):
1201-
case (preg_match('/settings\/webhooks\/.*\/filters/', $api_call) ? TRUE : FALSE):
1202-
$log_level = LogLevel::NOTICE;
1203-
break;
1204-
1205-
default:
1206-
// The default log level is ERROR.
1207-
$log_level = LogLevel::ERROR;
1208-
break;
1209-
}
1210-
1211-
$reason = sprintf("Request ID: %s, Method: %s, Path: \"%s\", Status Code: %s, Reason: %s, Error Code: %s, Error Message: \"%s\". Error data: \"%s\"",
1212-
$response_body['request_id'] ?? '',
1213-
strtoupper($method),
1214-
$api_call,
1215-
$response->getStatusCode(),
1216-
$response->getReasonPhrase(),
1217-
$error_code,
1218-
$error_message,
1219-
print_r($response_body['error']['data'] ?? $response_body['error'] ?? '', TRUE)
1220-
);
1221-
$this->logger->log($log_level, $reason);
1222-
1223-
// Return the response.
1224-
return $response;
1225-
}
1226-
1227-
/**
1228-
* Returns error response.
1229-
*
1230-
* @param int $code
1231-
* Status code.
1232-
* @param string $reason
1233-
* Reason.
1234-
* @param string|null $request_id
1235-
* The request id from the ContentHub service if available.
1236-
*
1237-
* @return \Psr\Http\Message\ResponseInterface
1238-
* Response.
1239-
*/
1240-
protected function getErrorResponse(int $code, string $reason, ?string $request_id = NULL): ResponseInterface {
1241-
if ($code < 100 || $code >= 600) {
1242-
$code = 500;
1243-
}
1244-
$body = [
1245-
'request_id' => $request_id,
1246-
'error' => [
1247-
'code' => $code,
1248-
'message' => $reason,
1249-
],
1250-
];
1251-
return new Response($code, [], json_encode($body), '1.1', $reason);
1252-
}
1253-
1254-
/**
1255-
* Make a base url out of components and add a trailing slash to it.
1256-
*
1257-
* @param string[] $base_url_components
1258-
* Base URL components.
1259-
*
1260-
* @return string
1261-
* Processed string.
1262-
*/
1263-
protected static function makeBaseURL(...$base_url_components): string { // phpcs:ignore
1264-
return self::makePath(...$base_url_components) . '/';
1265-
}
1266-
1267-
/**
1268-
* Make path out of its individual components.
1269-
*
1270-
* @param string[] $path_components
1271-
* Path components.
1272-
*
1273-
* @return string
1274-
* Processed string.
1275-
*/
1276-
protected static function makePath(...$path_components): string { // phpcs:ignore
1277-
return self::gluePartsTogether($path_components, '/');
1278-
}
1279-
1280-
/**
1281-
* Glue all elements of an array together.
1282-
*
1283-
* @param array $parts
1284-
* Parts array.
1285-
* @param string $glue
1286-
* Glue symbol.
1287-
*
1288-
* @return string
1289-
* Processed string.
1290-
*/
1291-
protected static function gluePartsTogether(array $parts, string $glue): string {
1292-
return implode($glue, self::removeAllLeadingAndTrailingSlashes($parts));
1293-
}
1294-
1295-
/**
1296-
* Removes all leading and trailing slashes.
1297-
*
1298-
* Strip all leading and trailing slashes from all components of the given
1299-
* array.
1300-
*
1301-
* @param string[] $components
1302-
* Array of strings.
1303-
*
1304-
* @return string[]
1305-
* Processed array.
1306-
*/
1307-
protected static function removeAllLeadingAndTrailingSlashes(array $components): array {
1308-
return array_map(function ($component) {
1309-
return trim($component, '/');
1310-
}, $components);
1311-
}
1312-
1313-
/**
1314-
* Attaches RequestResponseHandler to handlers stack.
1315-
*
1316-
* @param array $config
1317-
* Client config.
1318-
*
1319-
* @codeCoverageIgnore
1320-
*/
1321-
protected function addRequestResponseHandler(array $config): void {
1322-
if (empty($config['handler']) || empty($this->logger)) {
1323-
return;
1324-
}
1325-
1326-
if (!$config['handler'] instanceof HandlerStack) {
1327-
return;
1328-
}
1329-
1330-
$config['handler']->push(new RequestResponseHandler($this->logger));
1331-
}
1332-
13331079
/**
13341080
* Appends search criteria header.
13351081
*

0 commit comments

Comments
 (0)