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

  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 WordpressClient
  10. */
  11. private $wordpressClient;
  12. public function __construct(private readonly Client $redis, private readonly Setting $settings)
  13. {
  14. $this->wordpressClient = new WordpressClient();
  15. }
  16. /**
  17. * @param string $locale
  18. * @param int $limit
  19. */
  20. public function getPosts($locale = 'en', $limit = 4)
  21. {
  22. $excludedCategoriesIds = explode(
  23. ',',
  24. (string) $this->settings->getSetting('features', 'wp_excluded_categories_'.$locale)
  25. );
  26. $posts = $this->wordpressClient->getPosts($locale, $limit, $excludedCategoriesIds) ?: [];
  27. $postsData = [];
  28. foreach ($posts as $post) {
  29. $postData = [];
  30. $postData['id'] = $post->id;
  31. $postData['title'] = $post->title->rendered;
  32. $postData['link'] = $post->link;
  33. if ($postImage = $post->featured_media) {
  34. $media = $this->wordpressClient->getMedia($postImage, $locale);
  35. $postData['image'] = $media->source_url;
  36. }
  37. $postsData[] = $postData;
  38. }
  39. return $postsData;
  40. }
  41. public function setCachedPosts($locale = 'en'): void
  42. {
  43. $posts = $this->getPosts($locale);
  44. if (\count($posts)) {
  45. $this->handleCaching($locale.'_mostWordpressPosts', $posts);
  46. }
  47. }
  48. /**
  49. * @return string
  50. */
  51. public function getCachedPosts($locale = 'en')
  52. {
  53. if ($this->redis->exists($locale.'_mostWordpressPosts')) {
  54. return $this->redis->get($locale.'_mostWordpressPosts');
  55. }
  56. $this->setCachedPosts($locale);
  57. return $this->redis->get($locale.'_mostWordpressPosts');
  58. }
  59. /**
  60. * Serialize and set data in redis.
  61. */
  62. private function handleCaching($key, $result): void
  63. {
  64. $result = json_encode($result);
  65. $this->redis->set($key, $result);
  66. $this->redis->expire($key, 86400);
  67. }
  68. }