1 <?php 2 3 namespace Kevinrob\GuzzleCache\Strategy\Delegate; 4 5 use Kevinrob\GuzzleCache\Strategy\CacheStrategyInterface; 6 use Kevinrob\GuzzleCache\Strategy\NullCacheStrategy; 7 use Psr\Http\Message\RequestInterface; 8 use Psr\Http\Message\ResponseInterface; 9 10 class DelegatingCacheStrategy implements CacheStrategyInterface 11 { 12 /** 13 * @var array 14 */ 15 private $requestMatchers = []; 16 17 /** 18 * @var CacheStrategyInterface 19 */ 20 private $defaultCacheStrategy; 21 22 /** 23 * DelegatingCacheStrategy constructor. 24 */ 25 public function __construct(CacheStrategyInterface $defaultCacheStrategy = null) 26 { 27 $this->defaultCacheStrategy = $defaultCacheStrategy ?: new NullCacheStrategy(); 28 } 29 30 /** 31 * @param CacheStrategyInterface $defaultCacheStrategy 32 */ 33 public function setDefaultCacheStrategy(CacheStrategyInterface $defaultCacheStrategy) 34 { 35 $this->defaultCacheStrategy = $defaultCacheStrategy; 36 } 37 38 /** 39 * @param RequestMatcherInterface $requestMatcher 40 * @param CacheStrategyInterface $cacheStrategy 41 */ 42 final public function registerRequestMatcher(RequestMatcherInterface $requestMatcher, CacheStrategyInterface $cacheStrategy) 43 { 44 $this->requestMatchers[] = [ 45 $requestMatcher, 46 $cacheStrategy, 47 ]; 48 } 49 50 /** 51 * @param RequestInterface $request 52 * @return CacheStrategyInterface 53 */ 54 private function getStrategyFor(RequestInterface $request) 55 { 56 /** 57 * @var RequestMatcherInterface $requestMatcher 58 * @var CacheStrategyInterface $cacheStrategy 59 */ 60 foreach ($this->requestMatchers as $requestMatcher) { 61 list($requestMatcher, $cacheStrategy) = $requestMatcher; 62 if ($requestMatcher->matches($request)) { 63 return $cacheStrategy; 64 } 65 } 66 67 return $this->defaultCacheStrategy; 68 } 69 70 /** 71 * @inheritDoc 72 */ 73 public function fetch(RequestInterface $request) 74 { 75 return $this->getStrategyFor($request)->fetch($request); 76 } 77 78 /** 79 * @inheritDoc 80 */ 81 public function cache(RequestInterface $request, ResponseInterface $response) 82 { 83 return $this->getStrategyFor($request)->cache($request, $response); 84 } 85 86 /** 87 * @inheritDoc 88 */ 89 public function update(RequestInterface $request, ResponseInterface $response) 90 { 91 return $this->getStrategyFor($request)->update($request, $response); 92 } 93 94 /** 95 * {@inheritdoc} 96 */ 97 public function delete(RequestInterface $request) 98 { 99 return $this->getStrategyFor($request)->delete($request); 100 } 101 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body