src/Aqarmap/Bundle/DiscussionBundle/Service/WordpressManager.php line 78

Open in your IDE?
  1. <?php
  2. namespace Aqarmap\Bundle\DiscussionBundle\Service;
  3. use Aqarmap\Bundle\DiscussionBundle\Client\WordpressClient;
  4. use Aqarmap\Bundle\MainBundle\Service\Setting;
  5. use Predis\Client;
  6. class WordpressManager
  7. {
  8.     /**
  9.      * @var object
  10.      */
  11.     private $redis;
  12.     /**
  13.      * @var object
  14.      */
  15.     private $settings;
  16.     /**
  17.      * @var WordpressClient
  18.      */
  19.     private $wordpressClient;
  20.     public function __construct(Client $redisSetting $settings)
  21.     {
  22.         $this->wordpressClient = new WordpressClient();
  23.         $this->redis $redis;
  24.         $this->settings $settings;
  25.     }
  26.     /**
  27.      * @param string $locale
  28.      * @param int $limit
  29.      */
  30.     public function getPosts($locale 'en'$limit 4)
  31.     {
  32.         $excludedCategoriesIds explode(
  33.             ',',
  34.             (string) $this->settings->getSetting('features''wp_excluded_categories_'.$locale)
  35.         );
  36.         $posts $this->wordpressClient->getPosts($locale$limit$excludedCategoriesIds) ?: [];
  37.         $postsData = [];
  38.         foreach ($posts as $post) {
  39.             $postData = [];
  40.             $postData['id'] = $post->id;
  41.             $postData['title'] = $post->title->rendered;
  42.             $postData['link'] = $post->link;
  43.             if ($postImage $post->featured_media) {
  44.                 $media $this->wordpressClient->getMedia($postImage$locale);
  45.                 $postData['image'] = $media->source_url;
  46.             }
  47.             $postsData[] = $postData;
  48.         }
  49.         return $postsData;
  50.     }
  51.     public function setCachedPosts($locale 'en'): void
  52.     {
  53.         $posts $this->getPosts($locale);
  54.         if (\count($posts)) {
  55.             $this->handleCaching($locale.'_mostWordpressPosts'$posts);
  56.         }
  57.     }
  58.     /**
  59.      * @return string
  60.      */
  61.     public function getCachedPosts($locale 'en')
  62.     {
  63.         if ($this->redis->exists($locale.'_mostWordpressPosts')) {
  64.             return $this->redis->get($locale.'_mostWordpressPosts');
  65.         }
  66.         $this->setCachedPosts($locale);
  67.         return $this->redis->get($locale.'_mostWordpressPosts');
  68.     }
  69.     /**
  70.      * Serialize and set data in redis.
  71.      */
  72.     private function handleCaching($key$result): void
  73.     {
  74.         $result json_encode($result);
  75.         $this->redis->set($key$result);
  76.         $this->redis->expire($key86400);
  77.     }
  78. }