Skip to content
This repository has been archived by the owner on Aug 10, 2022. It is now read-only.

Commit

Permalink
Merge pull request #7 from assertis/3.x.x
Browse files Browse the repository at this point in the history
compatible with guzzle 6.x
  • Loading branch information
orzeuek authored Jun 1, 2017
2 parents 8b8780a + 6e87efe commit 41caabf
Show file tree
Hide file tree
Showing 9 changed files with 247 additions and 118 deletions.
8 changes: 4 additions & 4 deletions src/Client/BatchRequestFailureException.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
namespace Assertis\Http\Client;

use Assertis\Http\Request\BatchRequest;
use Assertis\Http\Response\BatchResults;
use Exception;
use GuzzleHttp\BatchResults;

/**
* @author Michał Tatarynowicz <[email protected]>
Expand All @@ -16,7 +16,7 @@ class BatchRequestFailureException extends Exception
*/
private $batchRequest;
/**
* @var BatchResults
* @var array
*/
private $batchResults;

Expand Down Expand Up @@ -46,9 +46,9 @@ public function getBatchRequest(): BatchRequest
}

/**
* @return BatchResults
* @return array
*/
public function getBatchResults(): BatchResults
public function getBatchResults(): array
{
return $this->batchResults;
}
Expand Down
42 changes: 22 additions & 20 deletions src/Client/Client.php
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
<?php declare(strict_types = 1);
<?php declare(strict_types=1);

namespace Assertis\Http\Client;

use Assertis\Http\Request\BatchRequest;
use Assertis\Http\Request\Request;
use Assertis\Http\Response\BatchResults;
use Exception;
use GuzzleHttp\ClientInterface as GuzzleClientInterface;
use GuzzleHttp\Event\SubscriberInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Message\ResponseInterface;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request as GuzzleRequest;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;

/**
* A simplified HTTP client.
Expand Down Expand Up @@ -39,13 +42,19 @@ public function __construct(GuzzleClientInterface $http)
*/
public function createRequest(Request $request): RequestInterface
{
$settings = [
'body' => $request->getBody(),
'query' => $request->getQuery(),
'headers' => $request->getHeaders(),
];
$body = $request->getBody();
$headers = $request->getHeaders();
$query = empty($request->getQuery()) ? "" : "?".http_build_query($request->getQuery());
$rawBaseUrl = $this->guzzleClient->getConfig("base_url");
if(empty($rawBaseUrl)){
throw new RuntimeException("Base url is not provided!");
}
// trimming is here to avoid issues with "/" - too much slashes or missing slashes.
$baseUrl = rtrim($rawBaseUrl, "/");
$url = "/".ltrim($request->getUrl(),'/');
$uri = new Uri($baseUrl . $url . $query);

return $this->guzzleClient->createRequest($request->getType(), $request->getUrl(), $settings);
return new GuzzleRequest($request->getType(), $uri, $headers, $body);
}

/**
Expand Down Expand Up @@ -74,16 +83,16 @@ public function send(Request $request): ResponseInterface
/**
* @inheritdoc
*/
public function sendBatch(BatchRequest $batchRequest): array
public function sendBatch(BatchRequest $batchRequest): BatchResults
{
$requests = array_map([$this, 'createRequest'], $batchRequest->getRequests());
$batchResults = Pool::batch($this->guzzleClient, $requests);
$batchResults = new BatchResults(Pool::batch($this->guzzleClient, $requests));

if ($batchResults->getFailures()) {
throw new BatchRequestFailureException($batchRequest, $batchResults);
}

return $batchResults->getSuccessful();
return $batchResults;
}

/**
Expand All @@ -94,11 +103,4 @@ public function getGuzzleClient()
return $this->guzzleClient;
}

/**
* @inheritdoc
*/
public function attachSubscriber(SubscriberInterface $subscriber)
{
$this->guzzleClient->getEmitter()->attach($subscriber);
}
}
22 changes: 13 additions & 9 deletions src/Client/ClientCached.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
use Assertis\Http\Request\CachedBatchRequest;
use Assertis\Http\Request\CachedRequest;
use GuzzleHttp\Client as GuzzleClient;
use Memcache;
use Memcached;
use Psr\Http\Message\ResponseInterface;

/**
* Caching implementation for http client for nrs service.
Expand All @@ -15,15 +16,15 @@
class ClientCached extends Client
{
/**
* @var Memcache
* @var Memcached
*/
private $memcache;

/**
* @param GuzzleClient $http
* @param Memcache $memcache
* @param Memcached $memcache
*/
public function __construct(GuzzleClient $http, Memcache $memcache)
public function __construct(GuzzleClient $http, Memcached $memcache)
{
parent::__construct($http);
$this->memcache = $memcache;
Expand All @@ -37,15 +38,17 @@ public function __construct(GuzzleClient $http, Memcache $memcache)
*/
public function sendCached(CachedRequest $request)
{
$cached = $this->memcache->get($request->getCacheKey());
$k = $request->getCacheKey();
$cached = $this->memcache->get($k);
if (false !== $cached) {
return $cached;
}

$response = $this->send($request);
$this->memcache->set($request->getCacheKey(), (string)$response->getBody(), 0, $request->getCacheFor());
$body = $response->getBody()->getContents();
$this->memcache->set($request->getCacheKey(), $body, 0);

return $response->getBody();
return $body;
}

/**
Expand All @@ -64,11 +67,12 @@ public function sendCachedBatch(CachedBatchRequest $batchRequest)
$responses = $this->sendBatch($batchRequest);
$out = [];

/* @var ResponseInterface $response */
foreach ($responses as $response) {
$out[] = is_object($response) ? (string)$response->getBody() : null;
$out[] = is_object($response) ? (string)$response->getBody()->getContents() : null;
}

$this->memcache->set($batchRequest->getCacheKey(), serialize($out), 0, $batchRequest->getCacheFor());
$this->memcache->set($batchRequest->getCacheKey(), serialize($out));

return $out;
}
Expand Down
16 changes: 5 additions & 11 deletions src/Client/ClientInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

use Assertis\Http\Request\BatchRequest;
use Assertis\Http\Request\Request;
use GuzzleHttp\Event\SubscriberInterface;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Message\ResponseInterface;
use Assertis\Http\Response\BatchResults;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
* Http client interface
Expand All @@ -33,14 +33,8 @@ public function send(Request $request): ResponseInterface;
* Send multiple requests in parallel.
*
* @param BatchRequest $requests
* @return ResponseInterface[]
* @return BatchResults
*/
public function sendBatch(BatchRequest $requests): array;
public function sendBatch(BatchRequest $requests): BatchResults;

/**
* Attach a subscriber that gets notified of requests.
*
* @param SubscriberInterface $subscriber
*/
public function attachSubscriber(SubscriberInterface $subscriber);
}
7 changes: 3 additions & 4 deletions src/Request/CachedRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,11 @@ class CachedRequest extends Request
private $cacheKey;

/**
* Create request to send by http
*
* CachedRequest constructor.
* @param string $url
* @param string $body
* @param string $cacheKey
* @param int $cacheFor
* @param array $cacheKey
* @param string $cacheFor
* @param string $type
*/
public function __construct($url, $body, $cacheKey, $cacheFor, $type = self::DEFAULT_TYPE)
Expand Down
1 change: 1 addition & 0 deletions src/Request/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class Request
const POST = 'POST';
const GET = 'GET';
const PUT = 'PUT';
const DELETE = 'DELETE';

const DEFAULT_TYPE = self::POST;

Expand Down
162 changes: 162 additions & 0 deletions src/Response/BatchResult.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
<?php
declare(strict_types=1);

namespace Assertis\Http\Response;

use ArrayAccess;
use ArrayIterator;
use Countable;
use IteratorAggregate;
use RuntimeException;
use SplObjectStorage;

/**
* Represents the result of a batch operation. This result container is
* iterable, countable, and you can can get a result by value using the
* getResult function.
*
* Successful results are anything other than exceptions. Failure results are
* exceptions.
*
* Class stolen from GuzzleHttp v5.2 (it's no more in 6+)
*/
class BatchResults implements Countable, IteratorAggregate, ArrayAccess
{
private $hash;

/**
* BatchResults constructor.
* @param array $objects
*/
public function __construct(array $objects)
{
$hash = new SplObjectStorage();
foreach ($objects as $obj){
$hash->attach($obj);
}
$this->hash = $hash;
}

/**
* Get the keys that are available on the batch result.
*
* @return array
*/
public function getKeys()
{
return iterator_to_array($this->hash);
}

/**
* Gets a result from the container for the given object. When getting
* results for a batch of requests, provide the request object.
*
* @param object $forObject Object to retrieve the result for.
*
* @return mixed|null
*/
public function getResult($forObject)
{
return isset($this->hash[$forObject]) ? $this->hash[$forObject] : null;
}

/**
* Get an array of successful results.
*
* @return array
*/
public function getSuccessful()
{
$results = [];
foreach ($this->hash as $key) {
if (!($this->hash[$key] instanceof \Exception)) {
$results[] = $this->hash[$key];
}
}

return $results;
}

/**
* Get an array of failed results.
*
* @return array
*/
public function getFailures()
{
$results = [];
foreach ($this->hash as $key) {
if ($this->hash[$key] instanceof \Exception) {
$results[] = $this->hash[$key];
}
}

return $results;
}

/**
* Allows iteration over all batch result values.
*
* @return ArrayIterator
*/
public function getIterator()
{
$results = [];
foreach ($this->hash as $key) {
$results[] = $this->hash[$key];
}

return new ArrayIterator($results);
}

/**
* Counts the number of elements in the batch result.
*
* @return int
*/
public function count()
{
return count($this->hash);
}

/**
* Checks if the batch contains a specific numerical array index.
*
* @param int $key Index to access
*
* @return bool
*/
public function offsetExists($key)
{
return $key < count($this->hash);
}

/**
* Allows access of the batch using a numerical array index.
*
* @param int $key Index to access.
*
* @return mixed|null
*/
public function offsetGet($key)
{
$i = -1;
foreach ($this->hash as $obj) {
if ($key === ++$i) {
return $this->hash[$obj];
}
}

return null;
}

public function offsetUnset($key)
{
throw new RuntimeException('Not implemented');
}

public function offsetSet($key, $value)
{
throw new RuntimeException('Not implemented');
}
}
Loading

0 comments on commit 41caabf

Please sign in to comment.