<?php declare(strict_types=1);
namespace ShopStudio\Blog\Storefront\Page\BlogPost\Comment;
use ShopStudio\Blog\Content\BlogPost\SalesChannel\Comment\AbstractBlogPostCommentRoute;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Shopware\Core\Framework\Routing\Exception\MissingRequestParameterException;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Storefront\Framework\Page\StorefrontSearchResult;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* @since 1.0.0
*/
class BlogPostCommentLoader
{
/**
* @since 1.0.0
*/
private const LIMIT = 10;
/**
* @since 1.0.0
*/
private const DEFAULT_PAGE = 1;
/**
* @since 1.0.0
*/
private const FILTER_LANGUAGE = 'filter-language';
/**
* @since 1.0.0
*/
private EventDispatcherInterface $eventDispatcher;
/**
* @since 1.0.0
*/
private AbstractBlogPostCommentRoute $route;
/**
* @since 1.0.0
*/
public function __construct(
AbstractBlogPostCommentRoute $route,
EventDispatcherInterface $eventDispatcher
) {
$this->eventDispatcher = $eventDispatcher;
$this->route = $route;
}
/**
* @since 1.0.0
*/
public function load(Request $request, SalesChannelContext $context): BlogPostCommentLoaderResult
{
$blogPostId = $request->get('blogPostId');
if (empty($blogPostId)) {
throw new MissingRequestParameterException('blogPostId');
}
$criteria = $this->createCriteria($request, $context);
$comments = $this->route
->load($blogPostId, $request, $context, $criteria)
->getResult()
;
$comments = StorefrontSearchResult::createFrom($comments);
$this->eventDispatcher->dispatch(new BlogPostCommentsLoadedEvent($comments, $context, $request));
$result = BlogPostCommentLoaderResult::createFrom($comments);
$result->setBlogPostId($blogPostId);
$result->setTotalComments($comments->getTotal());
return $result;
}
/**
* @since 1.0.0
*/
private function createCriteria(Request $request, SalesChannelContext $context): Criteria
{
$limit = (int) $request->get('limit', self::LIMIT);
$page = (int) $request->get('p', self::DEFAULT_PAGE);
$offset = $limit * ($page - 1);
$criteria = new Criteria();
$criteria->setLimit($limit);
$criteria->setOffset($offset);
$criteria->addSorting(new FieldSorting('createdAt', FieldSorting::ASCENDING));
if ($request->get('language') === self::FILTER_LANGUAGE) {
$criteria->addPostFilter(
new EqualsFilter('languageId', $context->getContext()->getLanguageId())
);
}
return $criteria;
}
}