Skip to content

Commit

Permalink
Merge pull request #117 from mageplaza/2.4-develop
Browse files Browse the repository at this point in the history
2.4-develop
  • Loading branch information
Shinichi69 authored Dec 28, 2021
2 parents f193c10 + c58c1d5 commit df78f80
Show file tree
Hide file tree
Showing 3 changed files with 153 additions and 42 deletions.
75 changes: 71 additions & 4 deletions Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@
namespace Mageplaza\Seo\Helper;

use Exception;
use Magento\Catalog\Model\Product;
use Magento\CatalogInventory\Model\Stock\StockItemRepository;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Theme\Block\Html\Header\Logo;
use Mageplaza\Core\Helper\AbstractData as CoreHelper;

Expand All @@ -33,6 +39,30 @@ class Data extends CoreHelper
{
const CONFIG_MODULE_PATH = 'seo';

/**
* @var StockItemRepository
*/
protected $stockItemRepository;

/**
* Data constructor.
*
* @param Context $context
* @param ObjectManagerInterface $objectManager
* @param StoreManagerInterface $storeManager
* @param StockItemRepository $stockItemRepository
*/
public function __construct(
Context $context,
ObjectManagerInterface $objectManager,
StoreManagerInterface $storeManager,
StockItemRepository $stockItemRepository
) {
$this->stockItemRepository = $stockItemRepository;

parent::__construct($context, $objectManager, $storeManager);
}

/**
* @param string $code
* @param null $storeId
Expand Down Expand Up @@ -123,10 +153,11 @@ public function getDuplicateConfig($code = null, $storeId = null)
public function createStructuredData($data, $prefixComment = '', $subfixComment = '')
{
$applicationLdJson = $prefixComment;
$applicationLdJson .= '<script type="application/ld+json">' . json_encode(
$data,
JSON_PRETTY_PRINT
) . '</script>';
$applicationLdJson .= '<script type="application/ld+json">'
. json_encode(
$data,
JSON_PRETTY_PRINT
) . '</script>';
$applicationLdJson .= $subfixComment;

return $applicationLdJson;
Expand Down Expand Up @@ -159,4 +190,40 @@ public function getStoreId()

return $storeId;
}

/**
* @param Product $product
*
* @return float|int
*/
public function getQtySale($product)
{
try {
$stock = $this->stockItemRepository->get($product->getId());

if ($this->versionCompare('2.3.0')) {
$totalQty = 0;
$getSalableQuantityDataBySku = $this->createObject(
\Magento\InventorySalesAdminUi\Model\GetSalableQuantityDataBySku::class
);
if ($product->getTypeId() === Configurable::TYPE_CODE) {
$typeInstance = $product->getTypeInstance();
$childProductCollection = $typeInstance->getUsedProducts($product);
foreach ($childProductCollection as $childProduct) {
$qty = $getSalableQuantityDataBySku->execute($childProduct->getSku());
$totalQty += isset($qty[0]['qty']) ? $qty[0]['qty'] : 0;
}
} else {
$qty = $getSalableQuantityDataBySku->execute($product->getSku());
$totalQty += isset($qty[0]['qty']) ? $qty[0]['qty'] : 0;
}

return $totalQty;
}

return $stock->getIsInStock() ? $stock->getQty() : 0;
} catch (Exception $e) {
return 0;
}
}
}
118 changes: 81 additions & 37 deletions Plugin/SeoRender.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Exception;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductFactory;
use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory;
use Magento\CatalogInventory\Api\Data\StockItemInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\CatalogInventory\Model\Stock\StockItemRepository;
Expand Down Expand Up @@ -162,6 +163,11 @@ class SeoRender
*/
protected $reviewResourceModel;

/**
* @var CollectionFactory
*/
protected $collectionFactory;

/**
* SeoRender constructor.
*
Expand All @@ -185,6 +191,7 @@ class SeoRender
* @param ModuleManager $moduleManager
* @param RatingFactory $ratingFactory
* @param ReviewResourceModel $reviewResourceModel
* @param CollectionFactory $collectionFactory
*/
public function __construct(
PageConfig $pageConfig,
Expand All @@ -206,7 +213,8 @@ public function __construct(
ReviewCollection $reviewCollection,
ModuleManager $moduleManager,
RatingFactory $ratingFactory,
ReviewResourceModel $reviewResourceModel
ReviewResourceModel $reviewResourceModel,
CollectionFactory $collectionFactory
) {
$this->pageConfig = $pageConfig;
$this->request = $request;
Expand All @@ -228,6 +236,7 @@ public function __construct(
$this->_moduleManager = $moduleManager;
$this->ratingFactory = $ratingFactory;
$this->reviewResourceModel = $reviewResourceModel;
$this->collectionFactory = $collectionFactory;
}

/**
Expand Down Expand Up @@ -404,6 +413,7 @@ public function getEntitySummary($product)

/**
* Show product structured data
*
* @return string
*
* Learn more: https://developers.google.com/structured-data/rich-snippets/products#single_product_page
Expand All @@ -412,7 +422,10 @@ public function showProductStructuredData()
{
if ($currentProduct = $this->getProduct()) {
try {
$productId = $currentProduct->getId() ?: $this->request->getParam('id');
$priceAttributes = $this->collectionFactory->create()
->addVisibleFilter()->addFieldToFilter('attribute_code', ['like' => "%price%"])
->getColumnValues('attribute_code');
$productId = $currentProduct->getId() ?: $this->request->getParam('id');

$product = $this->productFactory->create()->load($productId);
$availability = $product->isAvailable() ? 'InStock' : 'OutOfStock';
Expand All @@ -421,10 +434,21 @@ public function showProductStructuredData()
$product->getStore()->getWebsiteId()
);
$priceValidUntil = $currentProduct->getSpecialToDate();
$modelAttribute = $this->helperData->getRichsnippetsConfig('model_value');
$modelValue = $product->getResource()
->getAttribute($this->helperData->getRichsnippetsConfig('model_value'))
->getAttribute($modelAttribute)
->getFrontend()->getValue($product);
$modelName = $this->helperData->getRichsnippetsConfig('model_name');
if ($modelAttribute === 'quantity_and_stock_status') {
$modelValue = $this->helperData->getQtySale($product);
}
if ($modelValue && in_array($modelAttribute, $priceAttributes, true)) {
$modelValue = number_format($this->_priceHelper->currency($modelValue, false), 2);

if ($modelAttribute === 'price') {
$modelValue = $currentProduct->getPriceInfo()->getPrice('final_price')->getValue();
}
}
$modelName = $this->helperData->getRichsnippetsConfig('model_name');

$productStructuredData = [
'@context' => 'http://schema.org/',
Expand All @@ -442,7 +466,8 @@ public function showProductStructuredData()
'availability' => 'http://schema.org/' . $availability,
'url' => $currentProduct->getProductUrl()
],
$modelName => $modelValue ?: $modelName
$modelName => (($modelAttribute === 'quantity_and_stock_status' && $modelValue >=0)
|| $modelValue) ? $modelValue : $modelName
];
$productStructuredData = $this->addProductStructuredDataByType(
$currentProduct->getTypeId(),
Expand Down Expand Up @@ -479,13 +504,27 @@ public function showProductStructuredData()
: date('Y-m-d', $time);
}

if (!$this->_moduleManager->isEnabled('Mageplaza_Shopbybrand')) {
$brandValue = $product->getResource()
->getAttribute($this->helperData->getRichsnippetsConfig('brand'))
if (!$this->_moduleManager->isEnabled('Mageplaza_Shopbybrand')
|| !isset($productStructuredData['brand'])) {
$brandAttribute = $this->helperData->getRichsnippetsConfig('brand');
$brandValue = $product->getResource()
->getAttribute($brandAttribute)
->getFrontend()->getValue($product);

$productStructuredData['brand']['@type'] = 'Thing';
$productStructuredData['brand']['name'] = $brandValue ?: 'Brand';
if ($brandAttribute === 'quantity_and_stock_status') {
$brandValue = $this->helperData->getQtySale($product);
}

if ($brandValue && in_array($brandAttribute, $priceAttributes, true)) {
$brandValue = number_format($this->_priceHelper->currency($brandValue, false), 2);
if ($brandAttribute === 'price') {
$brandValue = $currentProduct->getPriceInfo()->getPrice('final_price')->getValue();
}
}

$productStructuredData['brand']['@type'] = 'Brand';
$productStructuredData['brand']['name'] = (($brandAttribute === 'quantity_and_stock_status'
&& $brandValue >=0) || $brandValue) ? $brandValue : 'Brand';
}

$collection = $this->_reviewCollection->create()
Expand All @@ -494,13 +533,26 @@ public function showProductStructuredData()
)->addEntityFilter(
'product',
$product->getId()
)->setDateOrder();
if ($collection->getData()) {
foreach ($collection->getData() as $review) {
$productStructuredData['review'][] = [
)->addRateVotes()->setDateOrder();
if ($collection->getSize()) {
foreach ($collection as $review) {
$reviewData = [
'@type' => 'Review',
'author' => $review['nickname']
'author' => [
'@type' => 'Person',
'name' => $review->getNickname()
]
];
if ($review->getRatingVotes()->getData()) {
$ratingVotes = $review->getRatingVotes()->getData();
$vote = array_first($ratingVotes);
$reviewData['reviewRating'] = [
'@type' => 'Rating',
'ratingValue' => $vote['percent'],
'bestRating' => '100'
];
}
$productStructuredData['review'][] = $reviewData;
}
}

Expand All @@ -519,16 +571,6 @@ public function showProductStructuredData()
);
$productStructuredData = $objectStructuredData->getMpdata();

// Compatible with Mageplaza Shop By Brand
if (!isset($productStructuredData['brand'])) {
$brandValue = $product->getResource()
->getAttribute($this->helperData->getRichsnippetsConfig('brand'))
->getFrontend()->getValue($product);

$productStructuredData['brand']['@type'] = 'Thing';
$productStructuredData['brand']['name'] = $brandValue ?: 'Brand';
}

return $this->helperData->createStructuredData(
$productStructuredData,
'<!-- Product Structured Data by Mageplaza SEO-->'
Expand All @@ -537,6 +579,8 @@ public function showProductStructuredData()
$this->messageManager->addError(__('Can not add structured data'));
}
}

return '';
}

/**
Expand Down Expand Up @@ -622,7 +666,7 @@ public function getSocialProfiles()
'linkedin',
'myspace',
'pinterest',
'soundclound',
'soundcloud',
'tumblr'
];
foreach ($socialNetwork as $value) {
Expand Down Expand Up @@ -745,20 +789,20 @@ public function getDownloadableProductStructuredData($currentProduct, $productSt
*/
public function getConfigurableProductStructuredData($currentProduct, $productStructuredData)
{
$productStructuredData['offers']['@type'] = 'AggregateOffer';
$productStructuredData['offers']['@type'] = 'AggregateOffer';
try {
$productStructuredData['offers']['highPrice'] = $currentProduct->getPriceInfo()->getPrice('regular_price')
->getMaxRegularAmount()->getValue();
->getMaxRegularAmount()->getValue();
$productStructuredData['offers']['lowPrice'] = $currentProduct->getPriceInfo()->getPrice('regular_price')
->getMinRegularAmount()->getValue();
->getMinRegularAmount()->getValue();
} catch (Exception $exception) {
$productStructuredData['offers']['highPrice'] = 0;
$productStructuredData['offers']['lowPrice'] = 0;
}
$offerData = [];
$typeInstance = $currentProduct->getTypeInstance();
$childProductCollection = $typeInstance->getUsedProductCollection($currentProduct)
->addAttributeToSelect('*');
$offerData = [];
$typeInstance = $currentProduct->getTypeInstance();
$childProductCollection = $typeInstance->getUsedProductCollection($currentProduct)
->addAttributeToSelect('*');
foreach ($childProductCollection as $child) {
$imageUrl = $this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA)
. 'catalog/product' . $child->getImage();
Expand Down Expand Up @@ -790,12 +834,12 @@ public function getConfigurableProductStructuredData($currentProduct, $productSt
*/
public function getBundleProductStructuredData($currentProduct, $productStructuredData)
{
$productStructuredData['offers']['@type'] = 'AggregateOffer';
$productStructuredData['offers']['@type'] = 'AggregateOffer';
try {
$productStructuredData['offers']['highPrice'] = $currentProduct->getPriceInfo()->getPrice('regular_price')
->getMaximalPrice()->getValue();
->getMaximalPrice()->getValue();
$productStructuredData['offers']['lowPrice'] = $currentProduct->getPriceInfo()->getPrice('regular_price')
->getMinimalPrice()->getValue();
->getMinimalPrice()->getValue();
} catch (Exception $exception) {
$productStructuredData['offers']['highPrice'] = 0;
$productStructuredData['offers']['lowPrice'] = 0;
Expand All @@ -808,7 +852,7 @@ public function getBundleProductStructuredData($currentProduct, $productStructur
$currentProduct
);
foreach ($childProductCollection as $child) {
$imageUrl = $this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA)
$imageUrl = $this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA)
. 'catalog/product' . $child->getImage();

$offerData[] = [
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"mageplaza/module-core": "^1.4.5"
},
"type": "magento2-module",
"version": "4.1.3",
"version": "4.1.4",
"license": "proprietary",
"keywords": [
"magento 2",
Expand Down

0 comments on commit df78f80

Please sign in to comment.