Guest User

Untitled

a guest
Jun 17th, 2020
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.66 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Example;
  4.  
  5. use Doctrine\Common\Cache\Cache;
  6. use GuzzleHttp\Client;
  7. use Symfony\Component\Filesystem\Filesystem;
  8.  
  9. interface Fetcher
  10. {
  11.     public function fetch(string $url): string;
  12. }
  13.  
  14. class HttpFetcher implements Fetcher
  15. {
  16.     /**
  17.      * @var Client
  18.      */
  19.     private $httpClient;
  20.  
  21.  
  22.     public function fetch(string $url): string
  23.     {
  24.         return $this->httpClient->get($url);
  25.     }
  26. }
  27.  
  28. abstract class DecoratorFetcher implements Fetcher
  29. {
  30.     /**
  31.      * @var Fetcher
  32.      */
  33.     protected $next;
  34.  
  35.     public function __construct(Fetcher $next)
  36.     {
  37.         $this->next = $next;
  38.     }
  39. }
  40.  
  41. class CachingFetcher extends DecoratorFetcher
  42. {
  43.     private const CACHE_ID = 'cycki';
  44.  
  45.     /**
  46.      * @var Cache
  47.      */
  48.     private $cache;
  49.  
  50.     public function __construct(Fetcher $next, Cache $cache)
  51.     {
  52.         parent::__construct($next);
  53.  
  54.         $this->cache = $cache;
  55.     }
  56.  
  57.     public function fetch(string $url): string
  58.     {
  59.         if ($this->cache->contains(self::CACHE_ID)) {
  60.             return $this->cache->fetch(self::CACHE_ID);
  61.         }
  62.  
  63.         $content = $this->fetch($url);
  64.  
  65.         $this->cache->save(self::CACHE_ID, $content);
  66.  
  67.         return $content;
  68.     }
  69. }
  70.  
  71. class CreatingBackupFetcher extends DecoratorFetcher
  72. {
  73.     private const FILE = 'some/path.txt';
  74.  
  75.     /**
  76.      * @var Filesystem
  77.      */
  78.     private $filesystem;
  79.  
  80.     public function __construct(Fetcher $next, Filesystem $filesystem)
  81.     {
  82.         parent::__construct($next);
  83.  
  84.         $this->filesystem = $filesystem;
  85.     }
  86.  
  87.     public function fetch(string $url): string
  88.     {
  89.         $content = $this->next->fetch($url);
  90.  
  91.         $this->filesystem->remove(self::FILE);
  92.  
  93.         $this->filesystem->touch(self::FILE);
  94.  
  95.         $this->filesystem->appendToFile(self::FILE, $content);
  96.  
  97.         return $content;
  98.     }
  99. }
Add Comment
Please, Sign In to add comment