Skip to content

Instantly share code, notes, and snippets.

@Neirda24
Last active January 15, 2018 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Neirda24/d662dda169518dc75a5beb924c4182c2 to your computer and use it in GitHub Desktop.
Save Neirda24/d662dda169518dc75a5beb924c4182c2 to your computer and use it in GitHub Desktop.
Sample of how I mocked EightPoints guzzle Clients
[
{
"method": "GET",
"uri": "/api/v1/customers/e9f09b2b-2a71-4f62-9d1d-05d98f933016",
"status": 200,
"data": {
"id": "e9f09b2b-2a71-4f62-9d1d-05d98f933016"
}
}
]
<?php
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Psr7\Response;
use InvalidArgumentException;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
trait GuzzleClientAware
{
/**
* @param string|array $path
*
* @return array
*
* @throws InvalidArgumentException
*/
public function parseJsonFromPath($path): array
{
if (is_array($path)) {
$decodedJsons = array_map([$this, 'parseJsonFromPath'], $path);
$json = call_user_func_array('array_merge', $decodedJsons);
} else {
if (is_dir($path)) {
$finder = new Finder();
$finder
->in($path)
->files()
->name('*.json')
->sortByName()
;
$files = $finder->getIterator();
$decodedJsons = array_map(function (SplFileInfo $file) {
return json_decode($file->getContents(), true);
}, iterator_to_array($files));
$json = call_user_func_array('array_merge', $decodedJsons);
} elseif (is_file($path)) {
$json = json_decode(file_get_contents($path), true);
} else {
throw new InvalidArgumentException("Path `${path}` does not seems to be valid.");
}
}
return $json;
}
/**
* @param array $parsedJson
*
* @return array
*/
public function parseData(array $parsedJson): array
{
$result = [];
foreach ($parsedJson as $row) {
$key = $row['method'] . '_' . $row['uri'];
if (!array_key_exists($key, $result)) {
$result[$key] = [];
}
$result[$key][] = $row;
}
return $result;
}
/**
* @param ContainerInterface $container
* @param string $clientName
* @param array $data
*/
public function updateGuzzleClient(ContainerInterface $container, string $clientName, array $data): void
{
$stackCallback = function (RequestInterface $request, array $options) use ($data) {
$matches = null;
preg_match('#(?:.*\.php)?(?P<relative_path>\/.*)#', $request->getUri()->getPath(), $matches);
$relativePath = $matches['relative_path'];
$key = $request->getMethod() . '_' . $relativePath;
if (!array_key_exists($key, $data)) {
throw new InvalidArgumentException("`$key` not found.");
}
if (1 === count($data[$key])) {
$response = reset($data[$key]);
} else {
$response = array_shift($data[$key]);
}
return new FulfilledPromise(
new Response($response['status'], [], json_encode($response['data']))
);
};
$currentClient = $container->get($clientName);
$currentConfig = $currentClient->getConfig();
/** @var HandlerStack $stack */
$stack = $currentConfig['handler'];
$stack->setHandler($stackCallback);
}
}
<?php
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class MyControllerTest extends WebTestCase
{
use GuzzleClientAware;
/**
* @var Client
*/
private $client;
public function setUp()
{
$this->client = static::createClient();
$this->client->disableReboot();
$this->client->enableProfiler();
$container = $this->client->getContainer();
$this->updateGuzzleClient($container, 'CLIENT_NAME', $this->parseData($this->parseJsonFromPath([
__DIR__ . '/../Resources/data/CLIENT_NAME/file1.json',
__DIR__ . '/../Resources/data/CLIENT_NAME/dir1'
])));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment