<?php
namespace Aqarmap\Bundle\DiscussionBundle\Service;
use Aqarmap\Bundle\DiscussionBundle\Client\WordpressClient;
use Aqarmap\Bundle\MainBundle\Service\Setting;
use Predis\Client;
class WordpressManager
{
/**
* @var object
*/
private $redis;
/**
* @var object
*/
private $settings;
/**
* @var WordpressClient
*/
private $wordpressClient;
public function __construct(Client $redis, Setting $settings)
{
$this->wordpressClient = new WordpressClient();
$this->redis = $redis;
$this->settings = $settings;
}
/**
* @param string $locale
* @param int $limit
*/
public function getPosts($locale = 'en', $limit = 4)
{
$excludedCategoriesIds = explode(
',',
(string) $this->settings->getSetting('features', 'wp_excluded_categories_'.$locale)
);
$posts = $this->wordpressClient->getPosts($locale, $limit, $excludedCategoriesIds) ?: [];
$postsData = [];
foreach ($posts as $post) {
$postData = [];
$postData['id'] = $post->id;
$postData['title'] = $post->title->rendered;
$postData['link'] = $post->link;
if ($postImage = $post->featured_media) {
$media = $this->wordpressClient->getMedia($postImage, $locale);
$postData['image'] = $media->source_url;
}
$postsData[] = $postData;
}
return $postsData;
}
public function setCachedPosts($locale = 'en'): void
{
$posts = $this->getPosts($locale);
if (\count($posts)) {
$this->handleCaching($locale.'_mostWordpressPosts', $posts);
}
}
/**
* @return string
*/
public function getCachedPosts($locale = 'en')
{
if ($this->redis->exists($locale.'_mostWordpressPosts')) {
return $this->redis->get($locale.'_mostWordpressPosts');
}
$this->setCachedPosts($locale);
return $this->redis->get($locale.'_mostWordpressPosts');
}
/**
* Serialize and set data in redis.
*/
private function handleCaching($key, $result): void
{
$result = json_encode($result);
$this->redis->set($key, $result);
$this->redis->expire($key, 86400);
}
}