File tree Expand file tree Collapse file tree 2 files changed +75
-0
lines changed Expand file tree Collapse file tree 2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace spec \Http \Client \Common \Plugin \Cache \Generator ;
4+
5+ use PhpSpec \ObjectBehavior ;
6+ use Psr \Http \Message \RequestInterface ;
7+ use Psr \Http \Message \StreamInterface ;
8+
9+ class HeaderCacheKeyGeneratorSpec extends ObjectBehavior
10+ {
11+ public function let ()
12+ {
13+ $ this ->beConstructedWith (['Authorization ' , 'Content-Type ' ]);
14+ }
15+
16+ public function it_is_initializable ()
17+ {
18+ $ this ->shouldHaveType ('Http\Client\Common\Plugin\Cache\Generator\HeaderCacheKeyGenerator ' );
19+ }
20+
21+ public function it_is_a_key_generator ()
22+ {
23+ $ this ->shouldImplement ('Http\Client\Common\Plugin\Cache\Generator\CacheKeyGenerator ' );
24+ }
25+
26+ public function it_generates_cache_from_request (RequestInterface $ request , StreamInterface $ body )
27+ {
28+ $ request ->getMethod ()->shouldBeCalled ()->willReturn ('GET ' );
29+ $ request ->getUri ()->shouldBeCalled ()->willReturn ('http://example.com/foo ' );
30+ $ request ->getHeaderLine ('Authorization ' )->shouldBeCalled ()->willReturn ('bar ' );
31+ $ request ->getHeaderLine ('Content-Type ' )->shouldBeCalled ()->willReturn ('application/baz ' );
32+ $ request ->getBody ()->shouldBeCalled ()->willReturn ($ body );
33+ $ body ->__toString ()->shouldBeCalled ()->willReturn ('' );
34+
35+ $ this ->generate ($ request )->shouldReturn ('GET http://example.com/foo Authorization:"bar" Content-Type:"application/baz" ' );
36+ }
37+ }
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace Http \Client \Common \Plugin \Cache \Generator ;
4+
5+ use Psr \Http \Message \RequestInterface ;
6+
7+ /**
8+ * Generate a cache key by using HTTP headers.
9+ *
10+ * @author Tobias Nyholm <tobias.nyholm@gmail.com>
11+ */
12+ class HeaderCacheKeyGenerator implements CacheKeyGenerator
13+ {
14+ /**
15+ * The header names we should take into account when creating the cache key.
16+ *
17+ * @var array
18+ */
19+ private $ headerNames ;
20+
21+ /**
22+ * @param $headerNames
23+ */
24+ public function __construct (array $ headerNames )
25+ {
26+ $ this ->headerNames = $ headerNames ;
27+ }
28+
29+ public function generate (RequestInterface $ request )
30+ {
31+ $ concatenatedHeaders = [];
32+ foreach ($ this ->headerNames as $ headerName ) {
33+ $ concatenatedHeaders [] = sprintf (' %s:"%s" ' , $ headerName , $ request ->getHeaderLine ($ headerName ));
34+ }
35+
36+ return $ request ->getMethod ().' ' .$ request ->getUri ().implode ('' , $ concatenatedHeaders ).' ' .$ request ->getBody ();
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments