Guest User

Untitled

a guest
Jan 1st, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. <?php
  2. namespace src\Integration;
  3.  
  4. class DataProvider
  5. {
  6. private $host;
  7. private $user;
  8. private $password;
  9.  
  10. /**
  11. * @param $host
  12. * @param $user
  13. * @param $password
  14. */
  15. public function __construct($host, $user, $password)
  16. {
  17. $this->host = $host;
  18. $this->user = $user;
  19. $this->password = $password;
  20. }
  21.  
  22. /**
  23. * @param array $request
  24. *
  25. * @return array
  26. */
  27. public function get(array $request)
  28. {
  29. // returns a response from external service
  30. }
  31. }
  32.  
  33. interface CacheInterface
  34. {
  35. public function get(array $input);
  36.  
  37. public function set(CacheItemInterface $cacheItem, array $value, \DateTime $expireAt = null);
  38. }
  39.  
  40. class Cache implements CacheInterface
  41. {
  42. private $cache;
  43.  
  44. public function __construct(CacheItemPoolInterface $cache)
  45. {
  46. $this->cache = $cache;
  47. }
  48.  
  49. protected function getCacheKey(array $input)
  50. {
  51. return json_encode($input);
  52. }
  53.  
  54. public function get(array $input)
  55. {
  56. $cacheKey = $this->getCacheKey($input);
  57. $cacheItem = $this->cache->getItem($cacheKey);
  58. return $cacheItem;
  59. }
  60.  
  61. public function set(CacheItemInterface $cacheItem, array $value, \DateTime $expireAt = null)
  62. {
  63. $cacheItem->set($value);
  64.  
  65. if (null !== $expiresAt) {
  66. $cacheItem->expiresAt($expiresAt);
  67. }
  68. }
  69. }
  70.  
  71. namespace src\Decorator;
  72.  
  73. use DateTime;
  74. use Exception;
  75. use Psr\Cache\CacheItemPoolInterface;
  76. use Psr\Log\LoggerInterface;
  77. use src\Integration\DataProvider;
  78.  
  79. class DecoratorManager
  80. {
  81. private $cache;
  82. private $logger;
  83. private $provider;
  84.  
  85. */
  86. * @param CacheItemPoolInterface $cache
  87. */
  88. public function __construct(DataProvider $provider, LoggerInterface $logger, CacheInterface $cache)
  89. {
  90. $this->provider = $provider;
  91. $this->logger = $logger;
  92. $this->cache = $cache;
  93. }
  94.  
  95. /**
  96. * {@inheritdoc}
  97. */
  98. public function getResponse(array $input)
  99. {
  100. try {
  101. $cacheItem = $this->cache->get($input);
  102. if ($cacheItem->isHit()) {
  103. return $cacheItem->get();
  104. }
  105.  
  106. $result = $this->provider->get($input);
  107.  
  108. $this->cache
  109. ->set($cacheItem, $result, (new DateTime())->modify('+1 day'));
  110.  
  111. return $result;
  112. } catch (Exception $e) {
  113. $this->logger->critical('Error');
  114. }
  115.  
  116. return [];
  117. }
  118. }
Add Comment
Please, Sign In to add comment