89 lines
3.1 KiB
PHP
89 lines
3.1 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\Review\Plugin;
|
|
|
|
use Closure;
|
|
use Magento\Catalog\Block\Product\ReviewRendererInterface;
|
|
use Magento\Catalog\Model\Product;
|
|
use Magento\Framework\App\ResourceConnection;
|
|
use Magento\Review\Block\Product\ReviewRenderer;
|
|
use Magento\Review\Model\Review;
|
|
use Magento\Store\Model\StoreManagerInterface;
|
|
|
|
class ReviewRendererPlugin
|
|
{
|
|
public function __construct(
|
|
private readonly ResourceConnection $resourceConnection,
|
|
private readonly StoreManagerInterface $storeManager
|
|
) {
|
|
}
|
|
|
|
public function aroundGetReviewsSummaryHtml(
|
|
ReviewRenderer $subject,
|
|
Closure $proceed,
|
|
Product $product,
|
|
$templateType = ReviewRendererInterface::DEFAULT_VIEW,
|
|
$displayIfNoReviews = false
|
|
): string {
|
|
$result = $proceed($product, $templateType, $displayIfNoReviews);
|
|
|
|
if ($templateType === ReviewRendererInterface::SHORT_VIEW) {
|
|
$subject->setTemplate('Esun_Review::helper/summary_short.phtml');
|
|
$subject->setProduct($product);
|
|
$subject->setDisplayIfEmpty($displayIfNoReviews);
|
|
|
|
return $subject->toHtml();
|
|
}
|
|
|
|
if (!$displayIfNoReviews) {
|
|
return $result;
|
|
}
|
|
|
|
$summary = $this->getApprovedReviewSummary((int)$product->getId());
|
|
$reviewsCount = $summary['reviews_count'] ?: (int)$subject->getReviewsCount();
|
|
$ratingSummary = $summary['rating_summary'] ?: (int)$subject->getRatingSummary();
|
|
|
|
$subject->setTemplate('Esun_Review::review/summary-empty-rating.phtml');
|
|
$subject->setProduct($product);
|
|
$subject->setDisplayIfEmpty($displayIfNoReviews);
|
|
$subject->setData('esun_reviews_count', $reviewsCount);
|
|
$subject->setData('esun_rating_summary', $ratingSummary);
|
|
|
|
return $subject->toHtml();
|
|
}
|
|
|
|
private function getApprovedReviewSummary(int $productId): array
|
|
{
|
|
$connection = $this->resourceConnection->getConnection();
|
|
$storeId = (int)$this->storeManager->getStore()->getId();
|
|
|
|
$select = $connection->select()
|
|
->from(['r' => $this->resourceConnection->getTableName('review')], [])
|
|
->join(
|
|
['rs' => $this->resourceConnection->getTableName('review_store')],
|
|
'rs.review_id = r.review_id',
|
|
[]
|
|
)
|
|
->joinLeft(
|
|
['v' => $this->resourceConnection->getTableName('rating_option_vote')],
|
|
'v.review_id = r.review_id',
|
|
[]
|
|
)
|
|
->where('r.entity_pk_value = ?', $productId)
|
|
->where('r.status_id = ?', Review::STATUS_APPROVED)
|
|
->where('rs.store_id IN (?)', [0, $storeId])
|
|
->columns([
|
|
'reviews_count' => new \Zend_Db_Expr('COUNT(DISTINCT r.review_id)'),
|
|
'rating_summary' => new \Zend_Db_Expr('ROUND(AVG(v.percent))'),
|
|
]);
|
|
|
|
$summary = $connection->fetchRow($select) ?: [];
|
|
|
|
return [
|
|
'reviews_count' => (int)($summary['reviews_count'] ?? 0),
|
|
'rating_summary' => (int)($summary['rating_summary'] ?? 0),
|
|
];
|
|
}
|
|
}
|