<?php
declare(strict_types=1);
namespace App\Module\Cms\Provider;
use App\Module\Catalog\Provider\CategoryTreeProvider;
use App\Module\Cms\Repository\StoryRepository;
use App\Module\StoryblokService\Business\StoryblokClient;
use App\Store\StoreContext;
use Denios\Data\Cms\Story;
use RuntimeException;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\Cache\CacheInterface;
/**
* Class CmsUnpublishedContentProvider
*
* @package App\Module\Cms\Provider
*/
class CmsUnpublishedContentProvider extends CmsContentProvider
{
private RequestStack $requestStack;
private bool $showPreview = false;
private StoryblokClient $storyblokClient;
/**
* CmsUnpublishedContentProvider constructor.
*
* @param StoreContext $storeContext
* @param CategoryTreeProvider $categoryTreeProvider
* @param RequestStack $requestStack
* @param StoryblokClient $storyblokClient
* @param StoryRepository $storyRepository
* @param CacheInterface $cache
*/
public function __construct(
StoreContext $storeContext,
CategoryTreeProvider $categoryTreeProvider,
RequestStack $requestStack,
StoryblokClient $storyblokClient,
StoryRepository $storyRepository,
CacheInterface $cache
) {
parent::__construct($storeContext, $categoryTreeProvider, $storyRepository, $cache);
$this->requestStack = $requestStack;
$this->storyblokClient = $storyblokClient;
}
/**
* @param string $fullSlug
* @param string|null $prefix
* @return Story|null
*/
private function getContentByFullSlug(string $fullSlug, string $prefix = null): ?Story
{
if (!$this->showPreview) {
throw new RuntimeException(sprintf('Unexpected call of %s while showPreview is false.', __METHOD__));
}
return $this->storyblokClient->getPreviewByFullSlug($fullSlug, '');
}
/**
* @param string $contentId
* @return Story|null
*/
public function getContentById(string $contentId): ?Story
{
if (!$this->showPreview) {
return parent::getContentById($contentId);
}
return $this->storyblokClient->getPreviewByUuid($contentId);
}
/**
* Because the $slug is not the storyblok slug, we can not use it to load preview data.
*
* @param string $store
* @param string $locale
* @param string $slug
* @param string|null $prefix
* @return Story|null
*/
public function getContentBySlug(string $store, string $locale, string $slug, string $prefix = null): ?Story
{
return parent::getContentBySlug($store, $locale, $slug, $prefix);
}
/**
* @param string|null $prefix
* @return Story|null
*/
public function getContentBySlugForCurrentPage(string $prefix = null): ?Story
{
if (!$this->showPreview) {
return parent::getContentBySlugForCurrentPage($prefix);
}
if ($this->currentStory !== null) {
return $this->currentStory;
}
$request = $this->requestStack->getMainRequest();
$fullSlug = $request->get('fullSlug');
return $this->currentStory = $this->getContentByFullSlug($fullSlug, $prefix);
}
/**
* @param bool $showPreview
* @return void
*/
public function setShowPreview(bool $showPreview): void
{
$this->showPreview = $showPreview;
}
}