Skip to content
37 changes: 37 additions & 0 deletions spec/Cache/Generator/HeaderCacheKeyGeneratorSpec.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace spec\Http\Client\Common\Plugin\Cache\Generator;

use PhpSpec\ObjectBehavior;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamInterface;

class HeaderCacheKeyGeneratorSpec extends ObjectBehavior
{
public function let()
{
$this->beConstructedWith(['Authorization', 'Content-Type']);
}

public function it_is_initializable()
{
$this->shouldHaveType('Http\Client\Common\Plugin\Cache\Generator\HeaderCacheKeyGenerator');
}

public function it_is_a_key_generator()
{
$this->shouldImplement('Http\Client\Common\Plugin\Cache\Generator\CacheKeyGenerator');
}

public function it_generates_cache_from_request(RequestInterface $request, StreamInterface $body)
{
$request->getMethod()->shouldBeCalled()->willReturn('GET');
$request->getUri()->shouldBeCalled()->willReturn('http://example.com/foo');
$request->getHeaderLine('Authorization')->shouldBeCalled()->willReturn('bar');
$request->getHeaderLine('Content-Type')->shouldBeCalled()->willReturn('application/baz');
$request->getBody()->shouldBeCalled()->willReturn($body);
$body->__toString()->shouldBeCalled()->willReturn('');

$this->generate($request)->shouldReturn('GET http://example.com/foo Authorization:"bar" Content-Type:"application/baz" ');
}
}
38 changes: 38 additions & 0 deletions src/Cache/Generator/HeaderCacheKeyGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Http\Client\Common\Plugin\Cache\Generator;

use Psr\Http\Message\RequestInterface;

/**
* Generate a cache key by using HTTP headers.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class HeaderCacheKeyGenerator implements CacheKeyGenerator
{
/**
* The header names we should take into account when creating the cache key.
*
* @var array
*/
private $headerNames;

/**
* @param $headerNames
*/
public function __construct(array $headerNames)
{
$this->headerNames = $headerNames;
}

public function generate(RequestInterface $request)
{
$concatenatedHeaders = [];
foreach ($this->headerNames as $headerName) {
$concatenatedHeaders[] = sprintf(' %s:"%s"', $headerName, $request->getHeaderLine($headerName));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

calling getHeaderLine for a header that is not defined simply returns an empty string. just double-checked in the psr-7 spec. so this is fine

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

}

return $request->getMethod().' '.$request->getUri().implode('', $concatenatedHeaders).' '.$request->getBody();
}
}