<?php declare(strict_types=1);
namespace Samson\Subscriber;
/***
*
* This file is part of the "SAMSON Shop" project.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* (c) 2022
*
***/
use Samson\CustomFieldSet\Constants\ProductCustomFieldConstants;
use Shopware\Core\Content\Product\Aggregate\ProductReview\ProductReviewEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductPageSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $mediaRepository;
public function __construct(EntityRepositoryInterface $mediaRepository)
{
$this->mediaRepository = $mediaRepository;
}
/** {@inheritDoc} */
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductPageLoaded'
];
}
public function onProductPageLoaded(ProductPageLoadedEvent $event)
{
$this->setReviewPointsAndCount($event);
$this->setProductBackgroundImage($event);
}
private function setReviewPointsAndCount(ProductPageLoadedEvent $event): void
{
if (!is_null($event->getPage()->getProduct()->getCmsPage())) {
return;
}
$reviews = $event->getPage()->getReviews();
$points = 0;
if ($reviews->count() > 0) {
/** @var ProductReviewEntity $review */
foreach ($reviews as $review) {
$points += $review->getPoints();
}
$points = round($points / $reviews->count() * 2) / 2;
}
$event->getPage()->getProduct()->assign(['reviewPoints' => $points]);
$event->getPage()->getProduct()->assign(['reviewCount' => $reviews->count()]);
}
private function setProductBackgroundImage(ProductPageLoadedEvent $event): void
{
$product = $event->getPage()->getProduct();
if (!isset($product->getCustomFields()[ProductCustomFieldConstants::CUSTOM_FIELD_PRODUCT_IMAGE_SHOW_BACKGROUND_IMAGE])) {
return;
}
$showBackgroundImage = $product->getCustomFields()[ProductCustomFieldConstants::CUSTOM_FIELD_PRODUCT_IMAGE_SHOW_BACKGROUND_IMAGE];
if ($showBackgroundImage) {
if (!isset($product->getCustomFields()[ProductCustomFieldConstants::CUSTOM_FIELD_PRODUCT_IMAGE_BACKGROUND_IMAGE])) {
return;
}
$mediaId = $product->getCustomFields()[ProductCustomFieldConstants::CUSTOM_FIELD_PRODUCT_IMAGE_BACKGROUND_IMAGE];
$media = $this->mediaRepository->search(new Criteria([$mediaId]), $event->getContext())->first();
if (!is_null($media)) {
$customFields = $product->getCustomFields();
$customFields[ProductCustomFieldConstants::CUSTOM_FIELD_PRODUCT_IMAGE_BACKGROUND_IMAGE] = $media;
$product->setCustomFields($customFields);
}
}
}
}