Advertisement
Guest User

To review code

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