ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,25 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Api;
/**
* Interface IndexMethodWrapper
* @api
*/
interface IndexMethodWrapperInterface
{
/**
* @return \Amasty\Sorting\Api\IndexedMethodInterface
*/
public function getSource();
/**
* @return \Magento\Framework\Indexer\ActionInterface
*/
public function getIndexer();
}
+44
View File
@@ -0,0 +1,44 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Api;
/**
* Interface IndexedMethodInterface
* @api
*/
interface IndexedMethodInterface extends MethodInterface
{
/**
* @return string
*/
public function getIndexTableName();
/**
* Full reindex.
* Truncate index table, commit insert, revert on error
*
* @return void
* @throws \Exception
*/
public function reindex();
/**
* insert to index table
*
* @return $this
*/
public function doReindex();
/**
* Returns Sorting method Table Column name
* which is using for order collection
*
* @return string
*/
public function getSortingColumnName();
}
+51
View File
@@ -0,0 +1,51 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Api;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
/**
* Interface IndexedMethodInterface
* @api
*/
interface MethodInterface
{
/**
* Apply sorting method to collection
*
* @param Collection $collection
* @param string $direction
*
* @return $this
*/
public function apply($collection, $direction);
public function applyCustomAttribute(Collection $collection, string $direction): void;
/**
* Returns Sorting method Code for using in code
*
* @return string
*/
public function getMethodCode();
/**
* Returns Sorting method Name for using like Method label
*
* @return string
*/
public function getMethodName();
/**
* Get method label for store
*
* @param null|int|\Magento\Store\Model\Store $store
*
* @return string
*/
public function getMethodLabel($store = null);
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Api;
/**
* @api
*/
interface ProductReviewLinkProcessorInterface
{
/**
* @param int $productId
* @param int $reviewId
*/
public function create(int $productId, int $reviewId): void;
/**
* @param int $productId
* @param int $reviewId
*/
public function remove(int $productId, int $reviewId): void;
}
+96
View File
@@ -0,0 +1,96 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Block\Adminhtml;
use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Amasty\Sorting\Helper\Data as SortingHelper;
use Magento\Catalog\Model\Config;
class Position extends Field
{
/**
* @var SortingHelper
*/
private $helper;
/**
* @var Config
*/
private $config;
public function __construct(
SortingHelper $helper,
Config $config,
Context $context
) {
parent::__construct($context);
$this->helper = $helper;
$this->config = $config;
}
protected function _construct()
{
$this->setTemplate('Amasty_Sorting::/position.phtml');
}
/**
* @param AbstractElement $element
* @return string
*/
public function render(AbstractElement $element)
{
$this->setElement($element);
return $this->_toHtml();
}
/**
* @return array
*/
public function getPositions()
{
$positions = (array) $this->helper->getSortOrder();
if ($positions === []) {
$positions = $this->getOptionalArray();
} else {
$availableOptions = $this->getOptionalArray();
// delete disabled options
$positions = array_intersect($availableOptions, $positions);
$newOptions = array_diff($availableOptions, $positions);
$positions = array_merge($positions, $newOptions);
}
return $positions;
}
/**
* @param $index
* @return string
*/
public function getNamePrefix($index)
{
return $this->getElement()->getName() . '[' . $index . ']';
}
private function getOptionalArray()
{
$positions = [];
$methods = $this->config->getAttributeUsedForSortByArray();
foreach ($methods as $key => $methodObject) {
if (is_object($methodObject)) {
$positions[$key] = $methodObject->getText();
} else {
$positions[$key] = $methodObject;
}
}
return $positions;
}
}
@@ -0,0 +1,26 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Block\Adminhtml\System\Config;
class DisableSorting extends \Magento\Config\Block\System\Config\Form\Field
{
public const REPLACE_TARGET = 'category_edit_url';
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
*
* @return mixed|string
*/
protected function _renderValue(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$value = parent::_renderValue($element);
$value = str_replace(self::REPLACE_TARGET, $this->getUrl('catalog/category/index'), $value);
return $value;
}
}
@@ -0,0 +1,154 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Block\Adminhtml\System\Config;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Information extends \Magento\Config\Block\System\Config\Form\Fieldset
{
/**
* @var string
*/
private $userGuide = 'https://amasty.com/docs/doku.php?id=magento_2:improved-sorting';
/**
* @var array
*/
private $enemyExtensions = [];
/**
* @var string
*/
private $content;
/**
* @var \Magento\Framework\Module\Manager
*/
private $moduleManager;
public function __construct(
\Magento\Backend\Block\Context $context,
\Magento\Backend\Model\Auth\Session $authSession,
\Magento\Framework\View\Helper\Js $jsHelper,
\Magento\Framework\Module\Manager $moduleManager,
array $data = []
) {
parent::__construct($context, $authSession, $jsHelper, $data);
$this->moduleManager = $moduleManager;
}
/**
* Render fieldset html
*
* @param AbstractElement $element
* @return string
*/
public function render(AbstractElement $element)
{
$html = $this->_getHeaderHtml($element);
$this->setContent(__('Please update Amasty Base module. Re-upload it and replace all the files.'));
$this->_eventManager->dispatch(
'amasty_base_add_information_content',
['block' => $this]
);
$html .= $this->getContent();
$html .= $this->_getFooterHtml($element);
$html = str_replace(
'amasty_information]" type="hidden" value="0"',
'amasty_information]" type="hidden" value="1"',
$html
);
$html = preg_replace('(onclick=\"Fieldset.toggleCollapse.*?\")', '', $html);
return $html;
}
/**
* @return array|string
*/
public function getAdditionalModuleContent()
{
if ($this->moduleManager->isEnabled('Magento_GraphQl')
&& !$this->moduleManager->isEnabled('Amasty_SortingGraphQl')
) {
$result[] = [
'type' => 'message-notice',
'text' => __('Enable improved-sorting-graphql module to '
. 'activate GraphQl and Sorting. '
. 'Please, run the following command in the SSH: '
. 'composer require amasty/improved-sorting-graphql')
];
}
if ($this->moduleManager->isEnabled('Yotpo_Yotpo')
&& !$this->moduleManager->isEnabled('Amasty_Yotpo')
) {
$result[] = [
'type' => 'message-notice',
'text' => __('Enable amasty/yotpo module to '
. 'activate Yotpo and Sorting. '
. 'Please, run the following command in the SSH: '
. 'composer require amasty/yotpo')
];
}
return $result ?? '';
}
/**
* @return string
*/
public function getUserGuide()
{
return $this->userGuide;
}
/**
* @param string $userGuide
*/
public function setUserGuide($userGuide)
{
$this->userGuide = $userGuide;
}
/**
* @return array
*/
public function getEnemyExtensions()
{
return $this->enemyExtensions;
}
/**
* @param array $enemyExtensions
*/
public function setEnemyExtensions($enemyExtensions)
{
$this->enemyExtensions = $enemyExtensions;
}
/**
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* @param string $content
*/
public function setContent($content)
{
$this->content = $content;
}
}
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Block\Adminhtml\System\Config;
use Magento\Framework\Data\Form\Element\AbstractElement;
class SortingNotice extends \Magento\Config\Block\System\Config\Form\Fieldset
{
/**
* @var \Amasty\Sorting\Model\Di\Wrapper
*/
private $ruleCollection;
public function __construct(
\Magento\Backend\Block\Context $context,
\Magento\Backend\Model\Auth\Session $authSession,
\Magento\Framework\View\Helper\Js $jsHelper,
\Amasty\Sorting\Model\Di\Wrapper $ruleCollection,
array $data = []
) {
parent::__construct($context, $authSession, $jsHelper, $data);
$this->ruleCollection = $ruleCollection;
}
public function render(AbstractElement $element)
{
$this->setElement($element);
$header = $this->_getHeaderHtml($element);
$elements = $this->_getChildrenElementsHtml($element);
$footer = $this->_getFooterHtml($element);
$notice = $this->generateNoticeMessageHtml();
return $header . $notice . $elements . $footer;
}
/**
* @return string
*/
private function generateNoticeMessageHtml(): string
{
$content = '';
if ($this->ruleCollection->getSize()) {
$content = '<div class="amasty-info-block">'
. '<div class="amasty-additional-content"><span class="message message-notice">'
. __(
'Please kindly note: if products on a search results page match the conditions of Amasty Elastic '
. 'Search Relevance Rules, the settings listed below will be ignored and products '
. 'will get sorted by relevance'
)
. '</div></div></div>';
}
return $content;
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Block;
use Amasty\Sorting\Helper\Data;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Amasty\Base\Model\Serializer as JsonSerializer;
class Direction extends Template
{
public const PERMANENT_DIRECTION_ATTRIBUTES = [
'price_asc',
'price_desc'
];
/**
* @var string
*/
protected $_template = 'Amasty_Sorting::direction.phtml';
/**
* @var Data
*/
private $helper;
/**
* @var JsonSerializer
*/
private $jsonSerializer;
public function __construct(
Data $helper,
JsonSerializer $jsonSerializer,
Context $context,
array $data = []
) {
parent::__construct($context, $data);
$this->helper = $helper;
$this->jsonSerializer = $jsonSerializer;
}
/**
* @return string
*/
protected function _toHtml()
{
$result = '';
if ($this->isDirectionCanBeHide()) {
$result = parent::_toHtml();
}
return $result;
}
/**
* @return bool
*/
private function isDirectionCanBeHide(): bool
{
$result = false;
foreach ($this->getPermanentDirectionAttributes() as $attribute) {
if ($result = !$this->helper->isMethodDisabled($attribute)) {
break;
}
}
return $result;
}
/**
* @return array
*/
public function getPermanentDirectionAttributes(): array
{
return static::PERMANENT_DIRECTION_ATTRIBUTES;
}
/**
* @return string
*/
public function getPermanentDirectionAttributesJson(): string
{
return $this->jsonSerializer->serialize($this->getPermanentDirectionAttributes());
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Block\Widget;
use Amasty\Sorting\Model\Source\SortOrder;
use Amasty\Sorting\ViewModel\Helpers;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Helper\Image;
use Magento\Catalog\Helper\Product\Compare;
use Magento\CatalogWidget\Block\Product\ProductsList;
use Magento\Framework\DB\Select;
class Featured extends ProductsList
{
public const DEFAULT_COLLECTION_SORT_BY = 'name';
public const DEFAULT_COLLECTION_ORDER = SortOrder::SORT_ASC;
public const IMAGE_TYPE = 'featured_products_sidebar';
/**
* @return \Magento\Catalog\Model\ResourceModel\Product\Collection
*/
public function createCollection()
{
$collection = parent::createCollection();
$collection->getSelect()->reset(Select::ORDER);
$collection->setOrder($this->getSortBy(), $this->getSortOrder());
$this->_eventManager->dispatch(
'catalog_block_product_list_collection',
['collection' => $collection]
);
return $collection;
}
/**
* @return string
*/
public function getSortBy()
{
if (!$this->hasData('sort_by')) {
$this->setData('sort_by', self::DEFAULT_COLLECTION_SORT_BY);
}
return $this->getData('sort_by');
}
/**
* @return string
*/
public function getSortOrder()
{
if (!$this->hasData('amsorting_sort_order')) {
$this->setData('amsorting_sort_order', self::DEFAULT_COLLECTION_ORDER);
}
return $this->getData('amsorting_sort_order');
}
/**
* @param ProductInterface $product
* @return Image
*/
public function getImageModel(ProductInterface $product): Image
{
return $this->_imageHelper->init($product, self::IMAGE_TYPE);
}
/**
* @param ProductInterface $product
* @return string
*/
public function getProductName(ProductInterface $product): string
{
/** @var Helpers|null $helper */
$helper = $this->getHelpers();
return $helper
? $helper->getProductAttribute($product, $product->getName(), ProductInterface::NAME)
: '';
}
/**
* @param ProductInterface $product
* @return string
*/
public function getPostData(ProductInterface $product): string
{
/** @var Helpers|null $helper */
$helper = $this->getHelpers();
return $helper
? $helper->getPostData($this->getAddToCartUrl($product), (int) $product->getEntityId())
: '';
}
public function isWishListAllow(): bool
{
/** @var Helpers|null $helper */
$helper = $this->getHelpers();
return $helper ? $helper->getWishlistHelper()->isAllow() : false;
}
private function getHelpers(): ?Helpers
{
return $this->getData('helpers');
}
public function getCompareHelper(): ?Compare
{
/** @var Helpers|null $helper */
$helper = $this->getHelpers();
return $helper ? $helper->getCompareHelper() : null;
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Cron;
use Amasty\Sorting\Model\Elasticsearch\IsElasticSort;
use Amasty\Sorting\Model\Indexer\Summary;
use Magento\CatalogSearch\Model\Indexer\Fulltext\Processor as FulltextProcessor;
class Reindex
{
/**
* @var Summary
*/
private $summary;
/**
* @var IsElasticSort
*/
private $isElasticSort;
/**
* @var FulltextProcessor
*/
private $fulltextProcessor;
public function __construct(Summary $summary, IsElasticSort $isElasticSort, FulltextProcessor $fulltextProcessor)
{
$this->summary = $summary;
$this->isElasticSort = $isElasticSort;
$this->fulltextProcessor = $fulltextProcessor;
}
/**
* Reindex all sorting indexable methods;
* trigger elasticsearch reindex if needed.
*
* @return void
*/
public function execute(): void
{
$this->summary->reindexAll();
if ($this->isElasticSort->execute(true)) {
$this->fulltextProcessor->reindexAll();
}
}
}
+218
View File
@@ -0,0 +1,218 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Helper;
use Amasty\Base\Model\Serializer;
use Amasty\Sorting\Model\Elasticsearch\IsElasticSort;
use Magento\CatalogInventory\Model\Configuration;
use Magento\Store\Model\ScopeInterface;
/**
* @deprecated Use config provider.
* @see \Amasty\Sorting\Model\ConfigProvider
* @see \Amasty\Sorting\Model\Method\IsMethodDisabledByConfig
*/
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public const CONFIG_SORT_ORDER = 'general/sort_order';
public const SEARCH_SORTING = 'amsorting_search';
/**
* @var Serializer
*/
private $serializer;
/**
* @var IsElasticSort
*/
private $isElasticSort;
public function __construct(
\Amasty\Base\Model\Serializer $serializer,
\Magento\Framework\App\Helper\Context $context,
IsElasticSort $isElasticSort
) {
parent::__construct($context);
$this->serializer = $serializer;
$this->isElasticSort = $isElasticSort;
}
/**
* Get config value for Store
*
* @param string $path
* @param null|string|bool|int|\Magento\Store\Model\Store $store
*
* @return mixed
*/
public function getScopeValue($path, $store = null)
{
return $this->scopeConfig->getValue(
'amsorting/' . $path,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$store
);
}
/**
* @deprecated
*
* Is Sorting Method Disabled
*
* @param string $methodCode
* @param int|null $storeId
* @return bool
*/
public function isMethodDisabled($methodCode, $storeId = null)
{
$result = false;
$disabledMethods = $this->getScopeValue('general/disable_methods', $storeId);
if ($disabledMethods && !empty($disabledMethods)) {
$disabledMethods = explode(',', $disabledMethods);
foreach ($disabledMethods as $disabledCode) {
if (trim($disabledCode) == $methodCode) {
$result = true;
break;
}
}
}
return $result;
}
/**
* Getting default sorting on search pages
*
* @return array
*/
public function getSearchSorting()
{
$defaultSorting = [];
foreach (['search_1', 'search_2', 'search_3'] as $path) {
if ($sort = $this->getScopeValue('default_sorting/' . $path)) {
$defaultSorting[] = $sort;
}
}
return $defaultSorting;
}
/**
* @return bool
*/
public function isYotpoEnabled()
{
return $this->getScopeValue('rating_summary/yotpo')
&& $this->_moduleManager->isEnabled('Amasty_Yotpo')
&& $this->_moduleManager->isEnabled('Yotpo_Yotpo');
}
/**
* @param null|int $storeId
* @return int
*/
public function getQtyOutStock($storeId = null)
{
return (int)$this->scopeConfig->getValue(
Configuration::XML_PATH_MIN_QTY,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
/**
* @return array
* @deprecated
* @see \Amasty\Sorting\Model\ConfigProvider::getSortOrder
*/
public function getSortOrder(): array
{
$value = $this->getScopeValue(self::CONFIG_SORT_ORDER);
if ($value) {
$value = $this->serializer->unserialize($value);
}
if (!$value) {
$value = [];
}
return $value;
}
/**
* @param null|int $store
*
* @return array
*/
public function getCategorySorting($store = null)
{
$defaultSorting = [];
foreach (['category_1', 'category_2', 'category_3'] as $path) {
if ($sort = $this->getScopeValue('default_sorting/' . $path, $store)) {
$defaultSorting[] = $sort;
}
}
return $defaultSorting;
}
/**
* @deprecated
*
* @param bool $skipStoreCheck
* @return bool
*/
public function isElasticSort(bool $skipStoreCheck = false)
{
return $this->isElasticSort->execute($skipStoreCheck);
}
/**
* @deprecated
* @see GetAttributeCodesForSorting
* @return array
*/
public function getAmastyAttributesCodes()
{
$result = [
'created_at',
$this->getScopeValue('bestsellers/best_attr'),
$this->getScopeValue('most_viewed/viewed_attr'),
$this->getScopeValue('new/new_attr')
];
return array_filter($result);
}
/**
* @param null|int $storeId
* @return int
*/
public function getNonImageLast($storeId = null)
{
return (int) $this->getScopeValue('general/no_image_last', $storeId);
}
/**
* @param null|int $storeId
* @return int
*/
public function getOutOfStockLast($storeId = null)
{
return (int) $this->getScopeValue('general/out_of_stock_last', $storeId);
}
/**
* @param null|int $storeId
* @return bool
*/
public function isOutOfStockByQty($storeId = null)
{
return (bool) $this->getScopeValue('general/out_of_stock_qty', $storeId);
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Catalog\Toolbar;
use Amasty\Sorting\Helper\Data;
class GetDefaultDirection
{
public const ALWAYS_DESC = [
'price_desc'
];
public const ALWAYS_ASC = [
'price_asc'
];
public const RELEVANCE_ORDER = 'relevance';
/**
* @var Data
*/
private $helper;
public function __construct(Data $helper)
{
$this->helper = $helper;
}
/**
* @param string $order
* @return string
*/
public function execute(string $order): string
{
return $this->isDescDirection($order) ? 'desc' : 'asc';
}
private function isDescDirection(string $order): bool
{
$attributeCodes = $this->helper->getScopeValue('general/desc_attributes');
$shouldBeDesc = array_merge(self::ALWAYS_DESC, [self::RELEVANCE_ORDER]);
if ($attributeCodes) {
$shouldBeDesc = array_merge($shouldBeDesc, explode(',', $attributeCodes));
}
return in_array($order, $shouldBeDesc);
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Config\Backend;
use Magento\Cron\Model\Config\Source\Frequency;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Value;
use Magento\Framework\App\Config\ValueFactory;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Psr\Log\LoggerInterface;
class CronExpr extends Value
{
public const CRON_STRING_PATH = 'crontab/index/jobs/amsorting/schedule/cron_expr';
public const CRON_MODEL_PATH = 'crontab/index/jobs/amsorting/run/model';
/**
* @var ValueFactory
*/
private $configValueFactory;
/**
* @var string
*/
private $runModelPath = '';
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(
Context $context,
Registry $registry,
ScopeConfigInterface $config,
TypeListInterface $cacheTypeList,
ValueFactory $configValueFactory,
LoggerInterface $logger,
AbstractResource $resource = null,
AbstractDb $resourceCollection = null,
$runModelPath = '',
array $data = []
) {
$this->runModelPath = $runModelPath;
$this->configValueFactory = $configValueFactory;
$this->logger = $logger;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
/**
* @return CronExpr
*/
public function afterSave()
{
try {
$this->configValueFactory->create()->load(
self::CRON_STRING_PATH,
'path'
)->setValue(
$this->getCronExprString()
)->setPath(
self::CRON_STRING_PATH
)->save();
$this->configValueFactory->create()->load(
self::CRON_MODEL_PATH,
'path'
)->setValue(
$this->runModelPath
)->setPath(
self::CRON_MODEL_PATH
)->save();
} catch (\Exception $e) {
$this->logger->error(__('We can\'t save the cron expression.'));
$this->logger->error($e->getMessage());
}
return parent::afterSave();
}
private function getCronExprString(): string
{
$time = $this->getData('groups/cron/fields/time/value');
$frequency = $this->getData('groups/cron/fields/frequency/value');
$cronExprArray = [
(int) $time[1],
(int) $time[0],
$frequency == Frequency::CRON_MONTHLY ? '1' : '*',
'*',
$frequency == Frequency::CRON_WEEKLY ? '1' : '*',
];
return join(' ', $cronExprArray);
}
}
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Config\Backend;
use Amasty\Sorting\Model\MethodProvider;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Framework\App\Config\Value;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
class GlobalSorting extends Value
{
/**
* @return GlobalSorting
* @throws LocalizedException
*/
public function afterSave(): GlobalSorting
{
if ($this->isValueChanged()
&& $this->getValue()
&& $this->getMethodProvider()->getMethodByCode($this->getValue()) === null
&& !$this->isAttributeExists($this->getValue())
) {
throw new LocalizedException(
__('Please input valid attribute name or Amasty sorting method for global sorting.')
);
}
return parent::afterSave();
}
/**
* If attribute code is numeric return false, because attribute_code not support numeric values.
*
* @param string $attributeCode
* @return bool
*/
private function isAttributeExists(string $attributeCode): bool
{
if (is_numeric($attributeCode)) {
return false;
}
try {
$this->getAttributeRepository()->get($attributeCode);
$result = true;
} catch (NoSuchEntityException $e) {
$result = false;
}
return $result;
}
/**
* @return MethodProvider
*/
private function getMethodProvider(): MethodProvider
{
return $this->getData('method_provider');
}
/**
* @return ProductAttributeRepositoryInterface
*/
private function getAttributeRepository(): ProductAttributeRepositoryInterface
{
return $this->getData('attribute_repository');
}
}
@@ -0,0 +1,24 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Config\Backend;
class SimpleText extends \Magento\Framework\App\Config\Value
{
public function beforeSave()
{
if ($this->isValueChanged() && isset($this->_data['escaper'])) {
/** @var \Magento\Framework\Escaper $escaper */
$escaper = $this->_data['escaper'];
$this->setValue(
$escaper->escapeHtml($this->getValue())
);
}
return parent::beforeSave();
}
}
+254
View File
@@ -0,0 +1,254 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model;
use Amasty\Base\Model\Serializer;
use Amasty\Base\Model\ConfigProviderAbstract;
use Magento\CatalogInventory\Model\Configuration;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class ConfigProvider extends ConfigProviderAbstract
{
public const DEFAULT_SORTING_SECTION = 'default_sorting';
public const DEFAULT_SORTING_SEARCH_PAGES_1 = 'search_1';
public const DEFAULT_SORTING_SEARCH_PAGES_2 = 'search_2';
public const DEFAULT_SORTING_SEARCH_PAGES_3 = 'search_3';
public const DEFAULT_SORTING_CATEGORY_PAGES_1 = 'category_1';
public const DEFAULT_SORTING_CATEGORY_PAGES_2 = 'category_2';
public const DEFAULT_SORTING_CATEGORY_PAGES_3 = 'category_3';
public const DISABLED_METHODS_PATH = 'general/disable_methods';
public const CONFIG_SORT_ORDER = 'general/sort_order';
public const NON_IMAGES_LAST_ENABLED_PATH = 'general/no_image_last';
public const OUT_OF_STOCK_LAST_ENABLED_PATH = 'general/out_of_stock_last';
public const OUT_OF_STOCK_BY_QTY_PATH = 'general/out_of_stock_qty';
public const GLOBAL_SORTING_PATH = 'advanced/global';
public const GLOBAL_SORTING_DIRECTION_PATH = 'advanced/global_direction';
public const BESTSELLER_ATTRIBUTE_CODE_PATH = 'bestsellers/best_attr';
private const BESTSELLER_EXCLUDE_PATH = 'bestsellers/exclude';
private const BESTSELLER_PERIOD_PATH = 'bestsellers/best_period';
public const MOSTVIEWED_ATTRIBUTE_CODE_PATH = 'most_viewed/viewed_attr';
public const NEW_ATTRIBUTE_CODE_PATH = 'new/new_attr';
private const REVENUE_LABEL_PATH = 'revenue/label';
private const REVENUE_ATTRIBUTE_CODE_PATH = 'revenue/attr';
private const REVENUE_PERIOD_PATH = 'revenue/period';
private const REVENUE_EXCLUDE_PATH = 'revenue/exclude';
/**
* @var string
*/
protected $pathPrefix = 'amsorting/';
/**
* @var Serializer
*/
private $serializer;
public function __construct(
ScopeConfigInterface $scopeConfig,
Serializer $serializer
) {
parent::__construct($scopeConfig);
$this->serializer = $serializer;
}
/**
* @param int|null $storeId
* @return array
*/
public function getDefaultSortingSearchPages(?int $storeId = null): array
{
$paths = [
self::DEFAULT_SORTING_SEARCH_PAGES_1,
self::DEFAULT_SORTING_SEARCH_PAGES_2,
self::DEFAULT_SORTING_SEARCH_PAGES_3
];
return $this->getDefaultOrders($paths, $storeId);
}
/**
* @param int|null $storeId
* @return array
*/
public function getDefaultSortingCategoryPages(?int $storeId = null): array
{
$paths = [
self::DEFAULT_SORTING_CATEGORY_PAGES_1,
self::DEFAULT_SORTING_CATEGORY_PAGES_2,
self::DEFAULT_SORTING_CATEGORY_PAGES_3
];
return $this->getDefaultOrders($paths, $storeId);
}
/**
* @return array
*/
public function getSortOrder(): array
{
$value = $this->getValue(self::CONFIG_SORT_ORDER);
if ($value) {
$value = $this->serializer->unserialize($value);
}
if (!$value) {
$value = [];
}
return $value;
}
private function getDefaultOrders(array $paths, ?int $storeId = null): array
{
$defaultOrders = [];
foreach ($paths as $path) {
$orderCode = $this->getValue(
sprintf('%s/%s', self::DEFAULT_SORTING_SECTION, $path),
$storeId
);
if ($orderCode) {
$defaultOrders[] = $orderCode;
}
}
return $defaultOrders;
}
/**
* @param null|int $storeId
* @return string[]
*/
public function getDisabledMethods(?int $storeId = null): array
{
$disabledMethods = $this->getValue(self::DISABLED_METHODS_PATH, $storeId);
if (empty($disabledMethods)) {
$disabledMethods = [];
} else {
$disabledMethods = explode(',', $disabledMethods);
}
return $disabledMethods;
}
/**
* @return string|null
*/
public function getGlobalSorting(): ?string
{
return $this->getValue(self::GLOBAL_SORTING_PATH);
}
/**
* @return string
*/
public function getGlobalSortingDirection(): string
{
return (string) $this->getValue(self::GLOBAL_SORTING_DIRECTION_PATH);
}
public function getBestsellerAttributeCode(): string
{
return (string) $this->getValue(self::BESTSELLER_ATTRIBUTE_CODE_PATH);
}
public function getMostviewedAttributeCode(): ?string
{
return $this->getValue(self::MOSTVIEWED_ATTRIBUTE_CODE_PATH);
}
public function getNewAttributeCode(): ?string
{
return $this->getValue(self::NEW_ATTRIBUTE_CODE_PATH);
}
/**
* @return string
*/
public function getRevenueAttributeCode(): string
{
return (string)$this->getValue(self::REVENUE_ATTRIBUTE_CODE_PATH);
}
/**
* @return string
*/
public function getRevenueLabel(): string
{
return (string)$this->getValue(self::REVENUE_LABEL_PATH);
}
/**
* @return int
*/
public function getRevenuePeriod(): int
{
return (int)$this->getValue(self::REVENUE_PERIOD_PATH);
}
/**
* @return string
*/
public function getExcludedOrderStatusesForRevenue(): array
{
$excludedStatuses = (string)$this->getValue(self::REVENUE_EXCLUDE_PATH);
return explode(',', $excludedStatuses);
}
/**
* @return array
*/
public function getExcludedOrderStatusesForBestsellers(): array
{
$excludedStatuses = (string)$this->getValue(self::BESTSELLER_EXCLUDE_PATH);
return explode(',', $excludedStatuses);
}
/**
* @return int
*/
public function getBestsellersPeriod(): int
{
return (int)$this->getValue(self::BESTSELLER_PERIOD_PATH);
}
public function isNonImagesLastEnabled(?int $storeId): bool
{
return $this->isSetFlag(self::NON_IMAGES_LAST_ENABLED_PATH, $storeId);
}
public function isOutOfStockLastEnabled(?int $storeId): bool
{
return $this->isSetFlag(self::OUT_OF_STOCK_LAST_ENABLED_PATH, $storeId);
}
public function isOutOfStockByQty(?int $storeId): bool
{
return $this->isSetFlag(self::OUT_OF_STOCK_BY_QTY_PATH, $storeId);
}
public function getQtyOutStock(?int $storeId = null): int
{
return (int) $this->scopeConfig->getValue(
Configuration::XML_PATH_MIN_QTY,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Di;
class Wrapper
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManagerInterface;
/**
* @var string
*/
private $name;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManagerInterface,
$name = ''
) {
$this->objectManagerInterface = $objectManagerInterface;
$this->name = $name;
}
// @codingStandardsIgnoreStart
/**
* @param $name
* @param $arguments
* @return bool|mixed
*/
public function __call($name, $arguments)
{
$result = false;
if ($this->name && (class_exists($this->name) || interface_exists($this->name))) {
$object = $this->objectManagerInterface->get($this->name);
$result = call_user_func_array([$object, $name], $arguments);
}
return $result;
}
// @codingStandardsIgnoreEnd
}
@@ -0,0 +1,144 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter;
class AdditionalFieldMapper
{
public const ES_DATA_TYPE_STRING = 'string';
public const ES_DATA_TYPE_TEXT = 'text';
public const ES_DATA_TYPE_FLOAT = 'float';
public const ES_DATA_TYPE_INT = 'integer';
public const ES_DATA_TYPE_DATE = 'date';
/** @deprecated */
public const ES_DATA_TYPE_ARRAY = 'array';
/**
* @var array
*/
private $fields = [];
/**
* @var \Magento\Customer\Model\Session
*/
private $customerSession;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
private $storeManager;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
\Magento\Store\Model\StoreManagerInterface $storeManager,
array $fields = []
) {
$this->customerSession = $customerSession;
$this->storeManager = $storeManager;
$this->fields = $fields;
}
/**
* @param mixed $subject
* @param array $result
* @return array
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetAllAttributesTypes($subject, array $result)
{
foreach ($this->fields as $fieldName => $fieldType) {
if (is_object($fieldType) && ($fieldType instanceof AdditionalFieldMapperInterface)) {
$attributeTypes = $fieldType->getAdditionalAttributeTypes();
// @codingStandardsIgnoreLine
$result = array_merge($result, $attributeTypes);
continue;
}
if (empty($fieldName)) {
continue;
}
if ($this->isValidFieldType($fieldType)) {
$result[$fieldName] = ['type' => $fieldType];
}
}
return $result;
}
/**
* Amasty Elastic entity builder plugin
*
* @param mixed $subject
* @param array $result
* @return array
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterBuildEntityFields($subject, array $result)
{
return $this->afterGetAllAttributesTypes($subject, $result);
}
/**
* @param mixed $subject
* @param callable $proceed
* @param string $attributeCode
* @param array $context
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @return string
*/
public function aroundGetFieldName($subject, callable $proceed, $attributeCode, $context = [])
{
if (isset($this->fields[$attributeCode]) && is_object($this->fields[$attributeCode])) {
$filedMapper = $this->fields[$attributeCode];
if ($filedMapper instanceof AdditionalFieldMapperInterface) {
return $filedMapper->getFiledName($context);
}
}
return $proceed($attributeCode, $context);
}
/**
* @param mixed $subject
* @param callable $proceed
* @param BucketInterface $bucket
* @return string
*/
public function aroundMapFieldName($subject, callable $proceed, $fieldName)
{
if (isset($this->fields[$fieldName]) && is_object($this->fields[$fieldName])) {
$filedMapper = $this->fields[$fieldName];
if ($filedMapper instanceof AdditionalFieldMapperInterface) {
$context = [
'customerGroupId' => $this->customerSession->getCustomerGroupId(),
'websiteId' => $this->storeManager->getWebsite()->getId()
];
return $filedMapper->getFiledName($context);
}
}
return $proceed($fieldName);
}
/**
* @param $fieldType
* @return bool
*/
private function isValidFieldType($fieldType)
{
switch ($fieldType) {
case self::ES_DATA_TYPE_STRING:
case self::ES_DATA_TYPE_DATE:
case self::ES_DATA_TYPE_INT:
case self::ES_DATA_TYPE_FLOAT:
break;
default:
$fieldType = false;
break;
}
return $fieldType;
}
}
@@ -0,0 +1,23 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapper;
use Amasty\Sorting\Model\Elasticsearch\Adapter\IndexedDataMapper;
class Bestseller extends IndexedDataMapper
{
public const FIELD_NAME = 'bestsellers';
/**
* @inheritdoc
*/
public function getIndexerCode()
{
return 'amasty_sorting_bestseller';
}
}
@@ -0,0 +1,23 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapper;
use Amasty\Sorting\Model\Elasticsearch\Adapter\IndexedDataMapper;
class Commented extends IndexedDataMapper
{
public const FIELD_NAME = 'reviews_count';
/**
* @inheritdoc
*/
public function getIndexerCode()
{
return 'amasty_yotpo_review';
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapper;
use Amasty\Sorting\Helper\Data;
use Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapperInterface;
class Image implements DataMapperInterface
{
/**
* @var Data
*/
private $data;
public function __construct(Data $data)
{
$this->data = $data;
}
public function map(int $entityId, array $entityIndexData, int $storeId, ?array $context = []): array
{
$value = isset($context['document']['small_image'])
? (int) ($context['document']['small_image'] !== 'no_selection')
: 0;
return ['non_images_last' => $value];
}
public function isAllowed(int $storeId): bool
{
return (bool) $this->data->getNonImageLast($storeId);
}
}
@@ -0,0 +1,23 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapper;
use Amasty\Sorting\Model\Elasticsearch\Adapter\IndexedDataMapper;
class MostViewed extends IndexedDataMapper
{
public const FIELD_NAME = 'most_viewed';
/**
* @inheritdoc
*/
public function getIndexerCode()
{
return 'amasty_sorting_most_viewed';
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapper;
use Amasty\Sorting\Model\Elasticsearch\Adapter\IndexedDataMapper;
class Revenue extends IndexedDataMapper
{
public const FIELD_NAME = 'revenue';
public function getIndexerCode(): string
{
return 'amasty_sorting_revenue';
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapper;
use Amasty\Sorting\Model\Elasticsearch\Adapter\IndexedDataMapper;
use Amasty\Sorting\Model\Method\IsMethodEnabled;
use Amasty\Sorting\Model\ResourceModel\Method\Saving as SavingResource;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
class Saving extends IndexedDataMapper
{
public const FIELD_NAME = 'saving';
/**
* @var CollectionFactory
*/
private $collectionFactory;
public function __construct(
CollectionFactory $collectionFactory,
SavingResource $resourceMethod,
IsMethodEnabled $isMethodEnabled
) {
parent::__construct($resourceMethod, $isMethodEnabled);
$this->collectionFactory = $collectionFactory;
}
/**
* Saving is not indexed method.
* @return bool
*/
public function getIndexerCode()
{
return false;
}
protected function forceLoad(int $storeId, ?array $entityIds = []): array
{
/** @var Collection $collection */
$collection = $this->collectionFactory->create();
$collection->setStoreId($storeId);
$collection->addPriceData();
if (!empty($entityIds)) {
$collection->addIdFilter($entityIds);
}
$this->resourceMethod->setLimitColumns(true);
$this->resourceMethod->apply($collection, '');
$this->resourceMethod->setLimitColumns(false);
return $this->resourceMethod->getConnection()->fetchPairs($collection->getSelect());
}
}
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapper;
use Amasty\Sorting\Helper\Data;
use Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapperInterface;
use Amasty\Sorting\Model\Elasticsearch\SkuRegistry;
use Amasty\Sorting\Model\Inventory\GetQtyInterface;
use Amasty\Sorting\Model\ResourceModel\Inventory;
use Magento\Store\Model\StoreManagerInterface;
class Stock implements DataMapperInterface
{
/**
* @var Data
*/
private $data;
/**
* @var Inventory
*/
private $inventory;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var SkuRegistry
*/
private $skuRegistry;
/**
* @var GetQtyInterface
*/
private $getQty;
public function __construct(
Data $data,
Inventory $inventory,
StoreManagerInterface $storeManager,
SkuRegistry $skuRegistry,
GetQtyInterface $getQty
) {
$this->data = $data;
$this->inventory = $inventory;
$this->storeManager = $storeManager;
$this->skuRegistry = $skuRegistry;
$this->getQty = $getQty;
}
public function map(int $entityId, array $entityIndexData, int $storeId, ?array $context = []): array
{
$sku = $this->skuRegistry->getSku((int) $entityId);
if (!$sku) {
return ['out_of_stock_last' => 1];
}
if ($this->data->isOutOfStockByQty($storeId)) {
$currentQty = $this->getQty->execute(
$sku,
$this->storeManager->getStore($storeId)->getWebsite()->getCode()
);
$value = $currentQty !== null && $currentQty > $this->data->getQtyOutStock($storeId);
} else {
$value = $this->inventory->getStockStatus(
$sku,
$this->storeManager->getStore($storeId)->getWebsite()->getCode()
);
}
return ['out_of_stock_last' => (int) $value];
}
public function isAllowed(int $storeId): bool
{
return (bool) $this->data->getOutOfStockLast($storeId);
}
}
@@ -0,0 +1,23 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapper;
use Amasty\Sorting\Model\Elasticsearch\Adapter\IndexedDataMapper;
class Toprated extends IndexedDataMapper
{
public const FIELD_NAME = 'rating_summary_field';
/**
* @inheritdoc
*/
public function getIndexerCode()
{
return 'amasty_yotpo_review';
}
}
@@ -0,0 +1,23 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapper;
use Amasty\Sorting\Model\Elasticsearch\Adapter\IndexedDataMapper;
class Wished extends IndexedDataMapper
{
public const FIELD_NAME = 'wished';
/**
* @inheritdoc
*/
public function getIndexerCode()
{
return 'amasty_sorting_wished';
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter;
interface DataMapperInterface
{
/**
* Prepare index data for using in search engine metadata
*
* @param int $entityId
* @param array $entityIndexData
* @param int $storeId
* @param array $context
* @return array
*/
public function map(int $entityId, array $entityIndexData, int $storeId, ?array $context = []): array;
public function isAllowed(int $storeId): bool;
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch\Adapter;
use Amasty\Sorting\Model\Method\IsMethodEnabled;
use Amasty\Sorting\Model\ResourceModel\Method\AbstractMethod;
abstract class IndexedDataMapper implements DataMapperInterface
{
public const DEFAULT_VALUE = 0;
/**
* @var AbstractMethod
*/
protected $resourceMethod;
/**
* @var array|null
*/
protected $values = null;
/**
* @var IsMethodEnabled
*/
private $isMethodEnabled;
public function __construct(
AbstractMethod $resourceMethod,
IsMethodEnabled $isMethodEnabled
) {
$this->resourceMethod = $resourceMethod;
$this->isMethodEnabled = $isMethodEnabled;
}
/**
* @return string
*/
abstract public function getIndexerCode();
/**
* @param int $storeId
* @param array|null $entityIds
* @return array
*/
protected function forceLoad(int $storeId, ?array $entityIds = []): array
{
return $this->resourceMethod->getIndexedValues($storeId, $entityIds);
}
public function isAllowed(int $storeId): bool
{
return $this->isMethodEnabled->execute($this->resourceMethod->getMethodCode(), $storeId);
}
public function map(int $entityId, array $entityIndexData, int $storeId, ?array $context = []): array
{
$value = $this->values[$entityId] ?? self::DEFAULT_VALUE;
return [static::FIELD_NAME => $value];
}
public function loadEntities(int $storeId, array $entityIds): void
{
if ($this->values === null) {
$this->values = $this->forceLoad($storeId, $entityIds);
}
}
public function clearValues(): void
{
$this->values = null;
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch;
class ApplierFlag
{
/**
* @var bool
*/
private $flag = false;
public function enable(): void
{
$this->flag = true;
}
public function disable(): void
{
$this->flag = false;
}
public function get(): bool
{
return $this->flag;
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch;
use Magento\CatalogSearch\Model\ResourceModel\EngineInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\StoreManager;
class IsElasticSort
{
/**
* @var ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var StoreManager
*/
private $storeManager;
public function __construct(
ScopeConfigInterface $scopeConfig,
StoreManager $storeManager
) {
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
}
public function execute(bool $skipStoreCheck = false): bool
{
return $this->checkSearchEngine($this->scopeConfig->getValue(EngineInterface::CONFIG_ENGINE_PATH))
&& ($skipStoreCheck || $this->storeManager->getStore()->getId());
}
private function checkSearchEngine(?string $engineName): bool
{
return strpos($engineName, 'elast') !== false || $engineName === 'opensearch';
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Elasticsearch;
use Amasty\Sorting\Model\ResourceModel\Product\LoadSkuMap;
use Amasty\Sorting\Model\ResourceModel\Product\LoadTypeMap;
class SkuRegistry
{
/**
* Where key is entityId; value is sku.
* @var array|null
*/
private $skuRelations;
/**
* Where key is sku; value is typeId.
* @var array|null
*/
private $typeRelations;
/**
* @var LoadSkuMap
*/
private $loadSkuMap;
/**
* @var LoadTypeMap
*/
private $loadTypeMap;
public function __construct(LoadSkuMap $loadSkuMap, LoadTypeMap $loadTypeMap)
{
$this->loadSkuMap = $loadSkuMap;
$this->loadTypeMap = $loadTypeMap;
}
/**
* @param array $entityIds
* @return void
*/
public function save(array $entityIds): void
{
$this->skuRelations = $this->loadSkuMap->execute($entityIds);
$this->typeRelations = $this->loadTypeMap->execute(array_values($this->skuRelations));
}
/**
* @return void
*/
public function clear(): void
{
$this->skuRelations = null;
}
/**
* @param int $entityId
* @return string
*/
public function getSku(int $entityId): string
{
return $this->skuRelations[$entityId] ?? '';
}
/**
* @param string $sku
* @return string
*/
public function getType(string $sku): string
{
return $this->typeRelations[$sku] ?? '';
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model;
use Amasty\Sorting\Api\IndexMethodWrapperInterface;
use Amasty\Sorting\Api\IndexedMethodInterface;
use Amasty\Sorting\Model\Indexer\AbstractIndexer;
/**
* This Class used for DI VirtualType
*/
class IndexMethodWrapper implements IndexMethodWrapperInterface
{
/**
* @var IndexedMethodInterface
*/
private $source;
/**
* @var AbstractIndexer
*/
private $indexer;
/**
* IndexMethodWrapper constructor.
*
* @param IndexedMethodInterface $source
* @param AbstractIndexer $indexer
*/
public function __construct(
IndexedMethodInterface $source,
AbstractIndexer $indexer
) {
$this->source = $source;
$this->indexer = $indexer;
}
/**
* @return IndexedMethodInterface
*/
public function getSource()
{
return $this->source;
}
/**
* @return AbstractIndexer
*/
public function getIndexer()
{
return $this->indexer;
}
}
+163
View File
@@ -0,0 +1,163 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Indexer;
use Amasty\Sorting\Api\IndexedMethodInterface;
use Amasty\Sorting\Model\ConfigProvider;
use Amasty\Sorting\Model\Method\IsMethodEnabled;
use Magento\Framework\Mview\ActionInterface as MviewActionInterface;
use Magento\Framework\Indexer\ActionInterface as IndexerActionInterface;
use Magento\Framework\App\Cache\TypeListInterface as CacheTypeListInterface;
use Magento\Framework\Indexer\CacheContext;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Registry;
class AbstractIndexer implements IndexerActionInterface, MviewActionInterface
{
/**
* @var IndexedMethodInterface
*/
private $indexBuilder;
/**
* @var CacheTypeListInterface
*/
private $cache;
/**
* @var CacheContext
*/
private $cacheContext;
/**
* @var ManagerInterface
*/
private $eventManager;
/**
* @var Registry
*/
private $registry;
/**
* @var ConfigProvider
*/
private $configProvider;
/**
* @var IsMethodEnabled
*/
private $isMethodEnabled;
public function __construct(
IndexedMethodInterface $indexBuilder,
CacheTypeListInterface $cache,
CacheContext $cacheContext,
ManagerInterface $eventManager,
Registry $registry,
ConfigProvider $configProvider,
IsMethodEnabled $isMethodEnabled
) {
$this->indexBuilder = $indexBuilder;
$this->cache = $cache;
$this->cacheContext = $cacheContext;
$this->eventManager = $eventManager;
$this->registry = $registry;
$this->configProvider = $configProvider;
$this->isMethodEnabled = $isMethodEnabled;
}
/**
* Execute materialization on ids entities
*
* @param int[] $ids
* @return void
*/
public function execute($ids)
{
$this->executeList($ids);
}
/**
* Execute full indexation
*
* @return void
*/
public function executeFull()
{
// do full reindex if method is not disabled
if ($this->isMethodEnabled->execute($this->indexBuilder->getMethodCode())
&& !$this->registry->registry('reindex_' . $this->indexBuilder->getMethodCode())
) {
$this->indexBuilder->reindex();
$this->cacheContext->registerTags(
['sorted_by_' . $this->indexBuilder->getMethodCode()]
);
$this->eventManager->dispatch('clean_cache_by_tags', ['object' => $this->cacheContext]);
$this->registry->register('reindex_' . $this->indexBuilder->getMethodCode(), true);
}
}
/**
* Execute partial indexation by ID list
*
* @param int[] $ids
* @throws \Magento\Framework\Exception\LocalizedException
* @return void
*/
public function executeList(array $ids)
{
if (!$ids) {
throw new \Magento\Framework\Exception\LocalizedException(
__('Could not rebuild index for empty products array')
);
}
$this->doExecuteList($ids);
}
/**
* TODO: implement partial reindex
*
* @param int[] $ids
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
//phpcs:ignore Magento2.CodeAnalysis.EmptyBlock.DetectedFunction
protected function doExecuteList($ids) : void
{
}
/**
* TODO: implement partial reindex
*
* @param int $id
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
// phpcs:ignore Magento2.CodeAnalysis.EmptyBlock.DetectedFunction
private function doExecuteRow($id): void
{
}
/**
* Execute partial indexation by ID
*
* @param int $id
* @throws \Magento\Framework\Exception\LocalizedException
* @return void
*/
public function executeRow($id)
{
if (!$id) {
throw new \Magento\Framework\Exception\LocalizedException(
__('We can\'t rebuild the index for an undefined product.')
);
}
$this->doExecuteRow($id);
}
}
@@ -0,0 +1,20 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Indexer;
use Magento\Framework\Indexer\AbstractProcessor;
abstract class AbstractSortingProcessor extends AbstractProcessor
{
public function markIndexerAsInvalid()
{
if ($this->isIndexerScheduled()) {
parent::markIndexerAsInvalid();
}
}
}
@@ -0,0 +1,18 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Indexer\Bestsellers;
use Amasty\Sorting\Model\Indexer\AbstractSortingProcessor;
class BestsellersProcessor extends AbstractSortingProcessor
{
/**
* Indexer id
*/
public const INDEXER_ID = 'amasty_sorting_bestseller';
}
@@ -0,0 +1,53 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Indexer;
use Magento\Framework\Indexer\AbstractProcessor;
class ConfigInvalidateAbstract extends \Magento\Framework\App\Config\Value
{
/**
* @var AbstractProcessor
*/
private $indexProcessor;
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
AbstractProcessor $indexProcessor,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
$this->indexProcessor = $indexProcessor;
}
/**
* {@inheritdoc}
*/
public function afterSave()
{
$this->_getResource()->addCommitCallback([$this, 'processValue']);
return parent::afterSave();
}
/**
* Invalidate index if Status or Period changed
*
* @return void
*/
public function processValue()
{
if ($this->getValue() != $this->getOldValue()) {
$this->indexProcessor->markIndexerAsInvalid();
}
}
}
@@ -0,0 +1,18 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Indexer\MostViewed;
use Amasty\Sorting\Model\Indexer\AbstractSortingProcessor;
class MostViewedProcessor extends AbstractSortingProcessor
{
/**
* Indexer id
*/
public const INDEXER_ID = 'amasty_sorting_most_viewed';
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Indexer\Revenue;
use Amasty\Sorting\Model\Indexer\AbstractSortingProcessor;
class RevenueProcessor extends AbstractSortingProcessor
{
/**
* Indexer id
*/
public const INDEXER_ID = 'amasty_sorting_revenue';
}
@@ -0,0 +1,44 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Indexer\Stock;
use Magento\ConfigurableProduct\Model\ResourceModel\Indexer\Stock\Configurable as NativeIndexer;
use Zend_Db_Expr;
use Magento\Framework\DB\Select;
class Configurable extends NativeIndexer
{
/**
* @inheritdoc
*/
protected function _getStockStatusSelect($entityIds = null, $usePrimaryTable = false)
{
$select = parent::_getStockStatusSelect($entityIds, $usePrimaryTable);
$this->calculateDependOnSimples($select);
return $select;
}
/**
* @param Select $select
*/
private function calculateDependOnSimples($select)
{
$columns = $select->getPart(Select::COLUMNS);
foreach ($columns as &$column) {
if (isset($column[2]) && $column[2] == 'qty') {
$column[1] = new Zend_Db_Expr('SUM(IF(i.stock_status > 0, i.qty, 0))');
}
// determine stock status based on simples
// if (isset($column[2]) && $column[2] == 'status') {
// $column[1] = new Zend_Db_Expr('MAX(i.stock_status = 1)');
// }
}
$select->setPart(Select::COLUMNS, $columns);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Indexer;
use Amasty\Sorting\Model\Indexer\Bestsellers\BestsellersProcessor;
use Amasty\Sorting\Model\Indexer\MostViewed\MostViewedProcessor;
use Amasty\Sorting\Model\Indexer\Revenue\RevenueProcessor;
use Amasty\Sorting\Model\Indexer\Wished\WishedProcessor;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\Indexer\Model\IndexerFactory;
class Summary
{
/**
* @var array
*/
private $indexerIds = [
BestsellersProcessor::INDEXER_ID,
RevenueProcessor::INDEXER_ID,
MostViewedProcessor::INDEXER_ID,
WishedProcessor::INDEXER_ID
];
/**
* @var IndexerRegistry
*/
private $indexerRegistry;
public function __construct(IndexerRegistry $indexerRegistry)
{
$this->indexerRegistry = $indexerRegistry;
}
/**
* @return void
*/
public function reindexAll(): void
{
foreach ($this->indexerIds as $indexerId) {
$indexer = $this->indexerRegistry->get($indexerId);
if ($indexer) {
$indexer->reindexAll();
}
}
}
}
@@ -0,0 +1,18 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Indexer\Wished;
use Amasty\Sorting\Model\Indexer\AbstractSortingProcessor;
class WishedProcessor extends AbstractSortingProcessor
{
/**
* Indexer id
*/
public const INDEXER_ID = 'amasty_sorting_wished';
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Inventory\CatalogInventory;
use Amasty\Sorting\Model\Inventory\GetQtyInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;
class GetConfigurableQty implements GetQtyInterface
{
/**
* @var StockRegistryInterface
*/
private $stockRegistry;
public function __construct(StockRegistryInterface $stockRegistry)
{
$this->stockRegistry = $stockRegistry;
}
/**
* @param string $sku
* @param string $websiteCode
* @return null|float
*/
public function execute(string $sku, string $websiteCode): ?float
{
$qty = $this->stockRegistry->getStockStatusBySku($sku, $websiteCode)->getQty();
return $qty !== null ? (float) $qty : null;
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Inventory\CatalogInventory;
use Amasty\Sorting\Model\Inventory\GetQtyInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;
class GetSimpleQty implements GetQtyInterface
{
/**
* @var StockRegistryInterface
*/
private $stockRegistry;
public function __construct(StockRegistryInterface $stockRegistry)
{
$this->stockRegistry = $stockRegistry;
}
/**
* @param string $sku
* @param string $websiteCode
* @return null|float
*/
public function execute(string $sku, string $websiteCode): ?float
{
$qty = $this->stockRegistry->getStockItemBySku($sku, $websiteCode)->getQty();
return $qty ?? null;
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Inventory;
use Magento\Framework\Module\Manager as ModuleManager;
class GetQty implements GetQtyInterface
{
/**
*
* @var array Array [
* 'website_code' => [
* 'sku' => 'qty'
* ...
* ]
* ...
* ]
*/
private $qty = [];
/**
* @var GetQtyInterface
*/
private $getCatalogInventoryQtyByType;
/**
* @var GetQtyInterface
*/
private $getMsiQtyByType;
/**
* @var ModuleManager
*/
private $moduleManager;
public function __construct(
GetQtyInterface $getCatalogInventoryQtyByType,
GetQtyInterface $getMsiQtyByType,
ModuleManager $moduleManager
) {
$this->getCatalogInventoryQtyByType = $getCatalogInventoryQtyByType;
$this->getMsiQtyByType = $getMsiQtyByType;
$this->moduleManager = $moduleManager;
}
/**
* @param string $sku
* @param string $websiteCode
* @return null|float
*/
public function execute(string $sku, string $websiteCode): ?float
{
if (!isset($this->qty[$websiteCode][$sku])) {
if ($this->moduleManager->isEnabled('Magento_Inventory')) {
$qty = $this->getMsiQtyByType->execute($sku, $websiteCode);
} else {
$qty = $this->getCatalogInventoryQtyByType->execute($sku, $websiteCode);
}
$this->qty[$websiteCode][$sku] = $qty;
}
return $this->qty[$websiteCode][$sku];
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Inventory;
use Amasty\Sorting\Model\Elasticsearch\SkuRegistry;
class GetQtyByType implements GetQtyInterface
{
/**
* @var SkuRegistry
*/
private $skuRegistry;
/**
* @var GetQtyInterface
*/
private $defaultQtyResolver;
/**
* @var GetQtyInterface[]
*/
private $resolversByType;
public function __construct(
SkuRegistry $skuRegistry,
GetQtyInterface $defaultQtyResolver,
array $resolversByType = []
) {
$this->skuRegistry = $skuRegistry;
$this->resolversByType = $resolversByType;
$this->defaultQtyResolver = $defaultQtyResolver;
}
/**
* @param string $sku
* @param string $websiteCode
* @return null|float
*/
public function execute(string $sku, string $websiteCode): ?float
{
$typeId = $this->skuRegistry->getType($sku);
$qtyResolver = $this->resolversByType[$typeId] ?? $this->defaultQtyResolver;
return $qtyResolver->execute($sku, $websiteCode);
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Inventory;
/**
* This class now works only in catalogsearch_fulltext indexation process
* for elasticsearch engine compatibility.
* @see \Amasty\Sorting\Model\Elasticsearch\Adapter\DataMapper\Stock::map
* @see \Amasty\Sorting\Model\Elasticsearch\SkuRegistry
*/
interface GetQtyInterface
{
/**
* @param string $sku
* @param string $websiteCode
* @return null|float
*/
public function execute(string $sku, string $websiteCode): ?float;
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Inventory\Msi;
use Amasty\Sorting\Model\Inventory\GetQtyInterface;
use Amasty\Sorting\Model\ResourceModel\Inventory;
use Amasty\Sorting\Model\ResourceModel\Inventory\GetConfigurableQty as GetConfigurableQtyResource;
use Amasty\Sorting\Model\ResourceModel\Inventory\GetReservationQty as GetReservationQtyResource;
class GetConfigurableQty implements GetQtyInterface
{
/**
* @var GetConfigurableQtyResource
*/
private $getConfigurableQtyResource;
/**
* @var GetReservationQtyResource
*/
private $getReservationQtyResource;
/**
* @var Inventory
*/
private $inventory;
public function __construct(
GetConfigurableQtyResource $getConfigurableQtyResource,
GetReservationQtyResource $getReservationQtyResource,
Inventory $inventory
) {
$this->getConfigurableQtyResource = $getConfigurableQtyResource;
$this->getReservationQtyResource = $getReservationQtyResource;
$this->inventory = $inventory;
}
/**
* Qty with reservation qty.
*
* @param string $sku
* @param string $websiteCode
* @return null|float
*
* @see \Magento\InventoryReservations\Model\ResourceModel\GetReservationsQuantity::execute
*/
public function execute(string $sku, string $websiteCode): ?float
{
$qty = $this->getConfigurableQtyResource->execute($sku, $websiteCode);
if ($reservationQty = $this->getReservationQtyResource->execute(
$sku,
$this->inventory->getStockId($websiteCode)
)) {
$qty += $reservationQty;
}
return $qty;
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Inventory\Msi;
use Amasty\Sorting\Model\Inventory\GetQtyInterface;
use Amasty\Sorting\Model\ResourceModel\Inventory;
use Amasty\Sorting\Model\ResourceModel\Inventory\GetReservationQty as GetReservationQtyResource;
use Amasty\Sorting\Model\ResourceModel\Inventory\GetSimpleQty as GetSimpleQtyResource;
class GetSimpleQty implements GetQtyInterface
{
/**
* @var GetSimpleQtyResource
*/
private $getSimpleQtyResource;
/**
* @var GetReservationQtyResource
*/
private $getReservationQtyResource;
/**
* @var Inventory
*/
private $inventory;
public function __construct(
GetSimpleQtyResource $getSimpleQtyResource,
GetReservationQtyResource $getReservationQtyResource,
Inventory $inventory
) {
$this->getSimpleQtyResource = $getSimpleQtyResource;
$this->getReservationQtyResource = $getReservationQtyResource;
$this->inventory = $inventory;
}
/**
* Qty with reservation qty.
*
* @param string $sku
* @param string $websiteCode
* @return null|float
*
* @see \Magento\InventoryReservations\Model\ResourceModel\GetReservationsQuantity::execute
*/
public function execute(string $sku, string $websiteCode): ?float
{
$qty = $this->getSimpleQtyResource->execute($sku, $websiteCode);
if ($reservationQty = $this->getReservationQtyResource->execute(
$sku,
$this->inventory->getStockId($websiteCode)
)) {
$qty += $reservationQty;
}
return $qty;
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model;
use Magento\Framework\App\RequestInterface;
class IsSearchPage
{
/**
* @var RequestInterface
*/
private $request;
public function __construct(RequestInterface $request)
{
$this->request = $request;
}
/**
* @return bool
*/
public function execute(): bool
{
return in_array(
$this->request->getModuleName(),
['sqli_singlesearchresult', 'catalogsearch']
);
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model;
class Logger
{
public const DEBUG_CONFIG_PATH = 'amsorting/general/debug';
public const DEBUG_REQUEST_VAR = 'amdebug';
/**
* @var \Amasty\Base\Debug\VarDump
*/
private $logger;
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var \Magento\Framework\App\RequestInterface
*/
private $request;
public function __construct(
\Amasty\Base\Debug\VarDump $logger,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\App\RequestInterface $request
) {
$this->logger = $logger;
$this->scopeConfig = $scopeConfig;
$this->request = $request;
}
/**
* @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
* @return $this
*/
public function logCollectionQuery($collection)
{
if ($this->scopeConfig->isSetFlag(self::DEBUG_CONFIG_PATH)
&& $this->request->getParam(self::DEBUG_REQUEST_VAR, false)
) {
$this->logger->amastyEcho($collection->getSelect()->__toString());
}
return $this;
}
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Method;
use Amasty\Sorting\Model\ConfigProvider;
use Amasty\Sorting\Model\MethodProvider;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
class ApplyGlobalSorting
{
private const FLAG_NAME = 'global_sorting';
/**
* @var ConfigProvider
*/
private $configProvider;
/**
* @var MethodProvider
*/
private $methodProvider;
/**
* @var IsAvailableForSorting
*/
private $isAvailableForSorting;
public function __construct(
ConfigProvider $configProvider,
MethodProvider $methodProvider,
IsAvailableForSorting $isAvailableForSorting
) {
$this->configProvider = $configProvider;
$this->methodProvider = $methodProvider;
$this->isAvailableForSorting = $isAvailableForSorting;
}
/**
* Apply global sorting if needed to collection.
* Set flag in collection for prevent repeated applying.
* Resolve custom amasty sorting methods with our plugin
* For mysql needed instantly applying with addAttributeToSort.
*
* @see \Amasty\Sorting\Plugin\Catalog\Product\Collection::beforeSetOrder
*/
public function execute(Collection $collection): void
{
$attribute = $this->configProvider->getGlobalSorting();
if (!$attribute || !$this->isAvailableForSorting->execute($attribute)) {
return;
}
if (!$collection->getFlag(self::FLAG_NAME)) {
$direction = $this->configProvider->getGlobalSortingDirection();
$collection->setOrder($attribute, $direction); // trigger resolving amasty sorting methods
if ($method = $this->methodProvider->getMethodByCode($attribute)) {
$attribute = $method->getAlias(); // resolve joined attribute for amasty sorting method
}
$collection->addAttributeToSort($attribute, $direction); // trigger instantly apply for mysql
$collection->setFlag(self::FLAG_NAME, true);
}
}
}
@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Method;
use Amasty\Sorting\Model\ConfigProvider;
use Amasty\Sorting\Model\MethodProvider;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
/**
* Provide attribute codes used for sorting by amasty sorting.
* This attributes must be added for indexation.
*/
class GetAttributeCodesForSorting
{
/**
* @var ConfigProvider
*/
private $configProvider;
/**
* @var MethodProvider
*/
private $methodProvider;
/**
* @var ProductAttributeRepositoryInterface
*/
private $productAttributeRepository;
/**
* @var string[]
*/
private $attributeCodesForSorting;
public function __construct(
ConfigProvider $configProvider,
MethodProvider $methodProvider,
ProductAttributeRepositoryInterface $productAttributeRepository
) {
$this->configProvider = $configProvider;
$this->methodProvider = $methodProvider;
$this->productAttributeRepository = $productAttributeRepository;
}
public function execute(): array
{
if ($this->attributeCodesForSorting === null) {
$this->attributeCodesForSorting = $this->getAttributeCodes();
}
return $this->attributeCodesForSorting;
}
/**
* Check if eav attribute exists.
*
* Detect if passed attribute code need be processed with magento.
* If amasty method exist with same code, amasty method more priority and processed by Sorting module.
*/
private function isEavAttribute(string $sortAttributeCode): bool
{
if ($this->methodProvider->getMethodByCode($sortAttributeCode) !== null) {
return false;
}
try {
$this->productAttributeRepository->get($sortAttributeCode);
$result = true;
} catch (NoSuchEntityException $e) {
$result = false;
}
return $result;
}
private function getAttributeCodes(): array
{
$attributes = [
'created_at',
'small_image',
$this->configProvider->getBestsellerAttributeCode(),
$this->configProvider->getRevenueAttributeCode(),
$this->configProvider->getMostviewedAttributeCode(),
$this->configProvider->getNewAttributeCode(),
$this->configProvider->getGlobalSorting()
];
return array_filter($attributes, function (?string $attribute) {
return $attribute && $this->isEavAttribute($attribute);
});
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Method;
use Magento\Catalog\Model\Config as CatalogConfig;
/**
* Check if passed code is amasty method or attribute used for sorting.
*/
class IsAvailableForSorting
{
/**
* @var CatalogConfig
*/
private $catalogConfig;
public function __construct(CatalogConfig $catalogConfig)
{
$this->catalogConfig = $catalogConfig;
}
public function execute(string $sortingCode): bool
{
return array_key_exists($sortingCode, $this->catalogConfig->getAttributesUsedForSortBy());
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Method;
use Amasty\Sorting\Model\ConfigProvider;
class IsMethodDisabledByConfig
{
/**
* @var ConfigProvider
*/
private $configProvider;
public function __construct(ConfigProvider $configProvider)
{
$this->configProvider = $configProvider;
}
/**
* Check is method disabled.
*
* @param string $methodCode
* @param int|null $storeId
* @return bool
*/
public function execute(string $methodCode, ?int $storeId = null): bool
{
$result = false;
foreach ($this->configProvider->getDisabledMethods($storeId) as $disabledCode) {
if ($disabledCode === $methodCode) {
$result = true;
break;
}
}
return $result;
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Method;
use Amasty\Sorting\Model\Plugin\Catalog\Config\DisplayAllFlag;
class IsMethodDisplayed
{
/**
* @var DisplayAllFlag
*/
private $displayAllFlag;
/**
* @var IsMethodDisabledByConfig
*/
private $isMethodDisabledByConfig;
public function __construct(
DisplayAllFlag $displayAllFlag,
IsMethodDisabledByConfig $isMethodDisabledByConfig
) {
$this->displayAllFlag = $displayAllFlag;
$this->isMethodDisabledByConfig = $isMethodDisabledByConfig;
}
/**
* @param string $methodCode
* @return bool
*/
public function execute(string $methodCode): bool
{
return $this->displayAllFlag->get()
|| !$this->isMethodDisabledByConfig->execute($methodCode);
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Method;
use Amasty\Sorting\Model\ConfigProvider;
class IsMethodEnabled
{
/**
* @var ConfigProvider
*/
private $configProvider;
/**
* @var IsMethodDisabledByConfig
*/
private $isMethodDisabledByConfig;
public function __construct(
IsMethodDisabledByConfig $isMethodDisabledByConfig,
ConfigProvider $configProvider
) {
$this->configProvider = $configProvider;
$this->isMethodDisabledByConfig = $isMethodDisabledByConfig;
}
/**
* Check is method enabled for indexation & applying.
*
* @param string $methodCode
* @param int|null $storeId
* @return bool
*/
public function execute(string $methodCode, ?int $storeId = null): bool
{
return !$this->isMethodDisabledByConfig->execute($methodCode, $storeId)
|| in_array($methodCode, $this->configProvider->getDefaultSortingSearchPages($storeId))
|| in_array($methodCode, $this->configProvider->getDefaultSortingCategoryPages($storeId))
|| $methodCode === $this->configProvider->getGlobalSorting();
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model;
use Amasty\Sorting\Api\MethodInterface;
use Amasty\Sorting\Api\IndexMethodWrapperInterface;
use Magento\Framework\Exception\LocalizedException;
class MethodProvider
{
/**
* Sorting Methods which can use index table
*
* @var IndexMethodWrapperInterface[]
*/
private $indexedMethods = [];
/**
* Sorting methods
*
* @var MethodInterface[]
*/
private $methods = [];
public function __construct(
array $indexedMethods = [],
array $methods = []
) {
$this->initMethods($indexedMethods, $methods);
}
/**
* initialize sorting method collection
*
* @param IndexMethodWrapperInterface[] $indexedMethods
* @param MethodInterface[] $methods
*
* @throws LocalizedException
*/
private function initMethods(array $indexedMethods = [], array $methods = []): void
{
foreach ($indexedMethods as $methodWrapper) {
$this->indexedMethods[$methodWrapper->getSource()->getMethodCode()] = $methodWrapper;
}
foreach ($methods as $methodObject) {
if (!$methodObject instanceof MethodInterface) {
if (is_object($methodObject)) {
throw new LocalizedException(
__('Method object ' . get_class($methodObject) .
' must be implemented by Amasty\Sorting\Api\MethodInterface')
);
} else {
throw new LocalizedException(__('$methodObject is not object'));
}
}
$this->methods[$methodObject->getMethodCode()] = $methodObject;
}
}
/**
* @param string $code
* @return MethodInterface|null
*/
public function getMethodByCode(string $code): ?MethodInterface
{
return $this->methods[$code] ?? null;
}
/**
* @return IndexMethodWrapperInterface[]
*/
public function getIndexedMethods(): array
{
return $this->indexedMethods;
}
/**
* @return MethodInterface[]
*/
public function getMethods(): array
{
return $this->methods;
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Plugin\Catalog\Config;
/**
* @see \Amasty\Sorting\Plugin\Catalog\Config
* When flag set as true - all options must be displayed by plugin
*/
class DisplayAllFlag
{
/**
* @var bool
*/
private $flag = false;
/**
* @param bool $flag
* @return void
*/
public function set(bool $flag): void
{
$this->flag = $flag;
}
/**
* @return bool
*/
public function get(): bool
{
return $this->flag;
}
}
+149
View File
@@ -0,0 +1,149 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel;
class Inventory extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* @var array
*/
private $stockIds;
/**
* @var array
*/
private $sourceCodes;
/**
* @var array
*/
private $stockStatus;
/**
* @var \Magento\Framework\Module\Manager
*/
private $moduleManager;
/**
* @var \Magento\CatalogInventory\Api\StockRegistryInterface
*/
private $stockRegistry;
public function __construct(
\Magento\Framework\Module\Manager $moduleManager,
\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
\Magento\Framework\Model\ResourceModel\Db\Context $context,
$connectionName = null
) {
parent::__construct($context, $connectionName);
$this->moduleManager = $moduleManager;
$this->stockRegistry = $stockRegistry;
}
/**
* @return void
*/
protected function _construct()
{
$this->stockIds = [];
$this->sourceCodes = [];
}
/**
* @param $productSku
* @param $websiteCode
*
* @return int
*
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getStockStatus($productSku, $websiteCode)
{
if ($this->moduleManager->isEnabled('Magento_Inventory')) {
$stockStatus = $this->getMsiStock($productSku, $websiteCode);
} else {
$stockStatus = $this->getStockItem($productSku, $websiteCode)->getIsInStock();
}
return $stockStatus;
}
/**
* @param $productSku
* @param $websiteCode
*
* @return \Magento\CatalogInventory\Api\Data\StockItemInterface
*
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function getStockItem($productSku, $websiteCode)
{
return $this->stockRegistry->getStockItemBySku($productSku, $websiteCode);
}
/**
* @param string $productSku
* @param string $websiteCode
*
* @return int
*
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getMsiStock($productSku, $websiteCode)
{
if (!isset($this->stockStatus[$websiteCode][$productSku])) {
$select = $this->getConnection()->select()
->from($this->getTable('inventory_stock_' . $this->getStockId($websiteCode)), ['is_salable'])
->where('sku = ?', $productSku)
->group('sku');
$this->stockStatus[$websiteCode][$productSku] = (int) $this->getConnection()->fetchOne($select);
}
return $this->stockStatus[$websiteCode][$productSku];
}
/**
* For MSI.
*
* @param string $websiteCode
*
* @return int
*/
public function getStockId(string $websiteCode): int
{
if (!isset($this->stockIds[$websiteCode])) {
$select = $this->getConnection()->select()
->from($this->getTable('inventory_stock_sales_channel'), ['stock_id'])
->where('type = \'website\' AND code = ?', $websiteCode);
$this->stockIds[$websiteCode] = (int)$this->getConnection()->fetchOne($select);
}
return $this->stockIds[$websiteCode];
}
/**
* For MSI.
*
* @param string $websiteCode
*
* @return array
*/
public function getSourceCodes($websiteCode)
{
if (!isset($this->sourceCodes[$websiteCode])) {
$select = $this->getConnection()->select()
->from($this->getTable('inventory_source_stock_link'), ['source_code'])
->where('stock_id = ?', $this->getStockId($websiteCode));
$this->sourceCodes[$websiteCode] = $this->getConnection()->fetchCol($select);
}
return $this->sourceCodes[$websiteCode];
}
}
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Inventory;
use Amasty\Sorting\Model\ResourceModel\Inventory;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\EntityManager\MetadataPool;
class GetConfigurableQty
{
/**
* @var ResourceConnection
*/
private $resourceConnection;
/**
* @var MetadataPool
*/
private $metadataPool;
/**
* @var Inventory
*/
private $inventory;
public function __construct(
ResourceConnection $resourceConnection,
MetadataPool $metadataPool,
Inventory $inventory
) {
$this->resourceConnection = $resourceConnection;
$this->metadataPool = $metadataPool;
$this->inventory = $inventory;
}
/**
* @param string $productSku
* @param string $websiteCode
* @return null|float
*/
public function execute(string $productSku, string $websiteCode): ?float
{
$connection = $this->resourceConnection->getConnection();
$metadata = $this->metadataPool->getMetadata(ProductInterface::class);
$linkField = $metadata->getLinkField();
$select = $connection->select()->from(
['source_item' => $this->resourceConnection->getTableName('inventory_source_item')],
['SUM(quantity)']
)->joinInner(
['product_entity' => $this->resourceConnection->getTableName('catalog_product_entity')],
'product_entity.sku = source_item.sku',
[]
)->joinInner(
['parent_link' => $this->resourceConnection->getTableName('catalog_product_super_link')],
'parent_link.product_id = product_entity.entity_id',
[]
)->joinInner(
['parent_product_entity' => $this->resourceConnection->getTableName('catalog_product_entity')],
'parent_product_entity.' . $linkField . ' = parent_link.parent_id',
[]
)->where(
'source_code IN (?)',
$this->inventory->getSourceCodes($websiteCode)
)->where(
'parent_product_entity.sku = ?',
$productSku
)->group(
'parent_product_entity.sku'
);
$qty = $connection->fetchOne($select);
return $qty ? (float) $qty : null;
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Inventory;
use Magento\Framework\App\ResourceConnection;
class GetReservationQty
{
/**
* @var ResourceConnection
*/
private $resourceConnection;
public function __construct(ResourceConnection $resourceConnection)
{
$this->resourceConnection = $resourceConnection;
}
/**
* @param string $sku
* @param int $stockId
* @return null|float
*/
public function execute(string $sku, int $stockId): ?float
{
$connection = $this->resourceConnection->getConnection();
$select = $connection->select()
->from($this->resourceConnection->getTableName('inventory_reservation'), ['quantity' => 'SUM(quantity)'])
->where('sku = ?', $sku)
->where('stock_id = ?', $stockId)
->limit(1);
$reservationQty = $connection->fetchOne($select);
return $reservationQty ? (float) $reservationQty : 0;
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Inventory;
use Amasty\Sorting\Model\ResourceModel\Inventory;
use Magento\Framework\App\ResourceConnection;
class GetSimpleQty
{
/**
* @var ResourceConnection
*/
private $resourceConnection;
/**
* @var Inventory
*/
private $inventory;
public function __construct(ResourceConnection $resourceConnection, Inventory $inventory)
{
$this->resourceConnection = $resourceConnection;
$this->inventory = $inventory;
}
/**
* @param string $productSku
* @param string $websiteCode
* @return null|float
*/
public function execute(string $productSku, string $websiteCode): ?float
{
$connection = $this->resourceConnection->getConnection();
$select = $connection->select()
->from($this->resourceConnection->getTableName('inventory_source_item'), ['SUM(quantity)'])
->where('source_code IN (?)', $this->inventory->getSourceCodes($websiteCode))
->where('sku = ?', $productSku)
->group('sku');
$qty = $connection->fetchOne($select);
return $qty ? (float) $qty : null;
}
}
@@ -0,0 +1,154 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
use Amasty\Sorting\Api\IndexedMethodInterface;
use Magento\Framework\DB\Query\BatchIteratorInterface;
use Magento\Framework\DB\Query\Generator as BatchQueryGenerator;
use Magento\Framework\DB\Select;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\CouldNotDeleteException;
abstract class AbstractIndexMethod extends AbstractMethod implements IndexedMethodInterface
{
protected function _construct()
{
// product_id can be not unique
$this->_init($this->getIndexTableName(), 'product_id');
}
abstract public function doReindex();
/**
* @return $this
* @throws CouldNotDeleteException
*/
public function beforeReindex()
{
try {
if ($this->getMethodCode() != 'rating_summary') {
$this->getConnection()->truncateTable($this->getMainTable());
}
} catch (\Exception $e) {
throw new CouldNotDeleteException(__('Error while clear index amasty sorting method: '), $e);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function reindex()
{
if ($this->getConnection()->getTransactionLevel() == 0) {
$this->beforeReindex();
try {
if ($this->indexConnection) {
$this->doReindex();
}
} catch (\Exception $e) {
$this->logger->critical(
$e,
['method_code' => $this->getMethodCode()]
);
throw $e;
}
$this->afterReindex();
}
}
/**
* @return $this
*/
public function afterReindex()
{
return $this;
}
/**
* {@inheritdoc}
*/
public function getMainTable()
{
return $this->getTable($this->getIndexTableName());
}
/**
* @return string
*/
public function getIndexTableName()
{
return 'amasty_sorting_' . $this->getMethodCode();
}
/**
* {@inheritdoc}
*/
public function getSortingColumnName()
{
return $this->getMethodCode();
}
/**
* @return string
*/
public function getAlias()
{
return $this->getMethodCode();
}
/**
* {@inheritdoc}
*/
public function apply($collection, $direction)
{
try {
$collection->joinField(
$this->getAlias(), // alias
$this->getIndexTableName(), // table
$this->getSortingColumnName(), // field
'product_id = entity_id', // bind
['store_id' => $this->storeManager->getStore()->getId()], // conditions
'left' // join type
);
} catch (LocalizedException $e) {
// A joined field with this alias is already declared.
$this->logger->warning(
'Failed on join table for amasty sorting method: ' . $e->getMessage(),
['method_code' => $this->getMethodCode()]
);
} catch (\Exception $e) {
$this->logger->critical($e, ['method_code' => $this->getMethodCode()]);
}
return $this;
}
protected function getBatchSelectIterator(string $rangeField, Select $select): BatchIteratorInterface
{
return $this->getBatchQueryGenerator()->generate(
$rangeField,
$select,
$this->getBatchSize(),
BatchIteratorInterface::NON_UNIQUE_FIELD_ITERATOR
);
}
private function getBatchSize(): int
{
return (int) ($this->getAdditionalData('batchSize') ?? 1000);
}
protected function getBatchQueryGenerator(): BatchQueryGenerator
{
return $this->getAdditionalData('batchQueryGenerator');
}
}
@@ -0,0 +1,221 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
use Amasty\Sorting\Api\MethodInterface;
use Amasty\Sorting\Model\ConfigProvider;
use Amasty\Sorting\Model\Elasticsearch\IsElasticSort;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
abstract class AbstractMethod extends AbstractDb implements MethodInterface
{
/**
* @var bool
*/
public const ENABLED = true;
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @var \Magento\Framework\App\RequestInterface
*/
protected $request;
/**
* @var string
*/
protected $methodCode;
/**
* @var string
*/
protected $methodName;
/**
* @var \Amasty\Sorting\Helper\Data
*/
protected $helper;
/**
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
protected $date;
/**
* @var AdapterInterface|null
*/
protected $indexConnection = null;
/**
* @var array
*/
private $data;
/**
* @var \Magento\Framework\Escaper
*/
private $escaper;
/**
* @var ConfigProvider
*/
protected $configProvider;
public function __construct(
Context $context,
\Magento\Framework\Escaper $escaper,
ConfigProvider $configProvider,
?IsElasticSort $isElasticSort, // @deprecated
$connectionName = null,
$methodCode = '',
$methodName = '',
AbstractDb $indexResource = null,
$data = []
) {
$this->scopeConfig = $context->getScopeConfig();
$this->storeManager = $context->getStoreManager();
$this->helper = $context->getHelper();
$this->logger = $context->getLogger();
$this->date = $context->getDate();
$this->methodCode = $methodCode;
$this->methodName = $methodName;
$this->data = $data;
$this->escaper = $escaper;
$this->configProvider = $configProvider;
if ($indexResource) {
$this->indexConnection = $indexResource->getConnection();
}
parent::__construct($context, $connectionName);
}
//@codingStandardsIgnoreStart
protected function _construct()
{
// dummy
}
//@codingStandardsIgnoreEnd
/**
* {@inheritdoc}
*/
abstract public function apply($collection, $direction);
//phpcs:ignore Magento2.CodeAnalysis.EmptyBlock.DetectedFunction
public function applyCustomAttribute(Collection $collection, string $direction): void
{
}
/**
* @param Collection $collection
* @return bool
*/
protected function isMethodAlreadyApplied($collection)
{
return (bool) $collection->getFlag($this->getFlagName());
}
/**
* @param Collection $collection
*/
protected function markApplied($collection)
{
$collection->setFlag($this->getFlagName(), true);
}
/**
* @return string
*/
protected function getFlagName()
{
return 'sorted_by_' . $this->getMethodCode();
}
/**
* @param int $storeId
* @param array|null $entityIds
* @return mixed
*/
abstract public function getIndexedValues(int $storeId, ?array $entityIds = []);
/**
* Is sorting method enabled by config
*
* @return bool
*/
public function isActive()
{
return !$this->helper->isMethodDisabled($this->getMethodCode());
}
/**
* @return string
*/
public function getMethodCode()
{
if (empty($this->methodCode)) {
$this->logger->warning('Undefined Amasty sorting method code, add method code to di.xml');
}
return $this->methodCode;
}
/**
* @return string
*/
public function getMethodName()
{
if (empty($this->methodCode)) {
$this->logger->warning('Undefined Amasty sorting method code, add method code to di.xml');
}
return $this->methodName;
}
/**
* {@inheritdoc}
*/
public function getMethodLabel($store = null)
{
$label = $this->helper->getScopeValue($this->getMethodCode() . '/label', $store);
if (!$label) {
$label = __($this->getMethodName());
}
return $this->escaper->escapeHtml($label);
}
/**
* @param string $key
*
* @return mixed
*/
protected function getAdditionalData($key)
{
$result = null;
if (isset($this->data[$key])) {
$result = $this->data[$key];
}
return $result;
}
}
@@ -0,0 +1,30 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
class Commented extends Toprated
{
/**
* Returns Sorting method Table Column name
* which is using for order collection
*
* @return string
*/
public function getSortingColumnName()
{
return 'reviews_count';
}
/**
* @return string
*/
public function getSortingFieldName()
{
return $this->helper->isYotpoEnabled() ? 'total_reviews' : 'reviews_count';
}
}
@@ -0,0 +1,115 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Model\ResourceModel\Db\ObjectRelationProcessor;
use Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterface;
use Magento\Framework\ObjectManager\ContextInterface;
use Magento\Store\Model\StoreManagerInterface;
class Context extends \Magento\Framework\Model\ResourceModel\Db\Context implements ContextInterface
{
/**
* @var ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var \Amasty\Sorting\Helper\Data
*/
private $helper;
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
private $date;
/**
* @var \Amasty\Sorting\Model\IsSearchPage
*/
private $isSearchPage;
public function __construct(
\Magento\Framework\App\ResourceConnection $resource,
TransactionManagerInterface $transactionManager,
ObjectRelationProcessor $objectRelationProcessor,
ScopeConfigInterface $scopeConfig,
StoreManagerInterface $storeManager,
\Amasty\Sorting\Helper\Data $helper,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Stdlib\DateTime\DateTime $date,
\Amasty\Sorting\Model\IsSearchPage $isSearchPage
) {
parent::__construct($resource, $transactionManager, $objectRelationProcessor);
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
$this->helper = $helper;
$this->logger = $logger;
$this->date = $date;
$this->isSearchPage = $isSearchPage;
}
/**
* @return ScopeConfigInterface
*/
public function getScopeConfig()
{
return $this->scopeConfig;
}
/**
* @return StoreManagerInterface
*/
public function getStoreManager()
{
return $this->storeManager;
}
/**
* @return \Amasty\Sorting\Helper\Data
*/
public function getHelper()
{
return $this->helper;
}
/**
* @return \Psr\Log\LoggerInterface
*/
public function getLogger()
{
return $this->logger;
}
/**
* @return \Magento\Framework\Stdlib\DateTime\DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* @return \Amasty\Sorting\Model\IsSearchPage
*/
public function getIsSearchPage(): \Amasty\Sorting\Model\IsSearchPage
{
return $this->isSearchPage;
}
}
@@ -0,0 +1,123 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
use Amasty\Sorting\Model\ConfigProvider;
use Amasty\Sorting\Model\Elasticsearch\IsElasticSort;
use Amasty\Sorting\Model\IsSearchPage;
use Amasty\Sorting\Model\Source\Image as ImageSource;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
use Magento\Framework\DB\Select;
use Magento\Framework\Escaper;
use Magento\Sitemap\Model\ResourceModel\Catalog\Product as ProductResource;
/**
* Class Image
* Method Using like additional sorting and not visible in the list of methods
*/
class Image extends AbstractMethod
{
/**
* @var IsSearchPage
*/
private $isSearchPage;
public function __construct(
Context $context,
Escaper $escaper,
ConfigProvider $configProvider,
IsElasticSort $isElasticSort,
$connectionName = null,
$methodCode = '',
$methodName = ''
) {
parent::__construct(
$context,
$escaper,
$configProvider,
$isElasticSort,
$connectionName,
$methodCode,
$methodName
);
$this->isSearchPage = $context->getIsSearchPage();
}
/**
* {@inheritdoc}
*/
public function getSortingColumnName()
{
return 'small_image';
}
/**
* {@inheritdoc}
*/
public function apply($collection, $direction = '')
{
if (!$this->isMethodActive($collection) || $this->isMethodAlreadyApplied($collection)) {
return $this;
}
$attribute = $this->getSortingColumnName();
$collection->addAttributeToSelect($attribute, 'left');
$collection->getSelect()->order($this->getSortExpression($attribute));
$orders = $collection->getSelect()->getPart(Select::ORDER);
// move from the last to the the first position
array_unshift($orders, array_pop($orders));
$collection->getSelect()->setPart(Select::ORDER, $orders);
$this->markApplied($collection);
return $this;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function isMethodActive(ProductCollection $collection): bool
{
$show = $this->helper->getNonImageLast();
if (!$show || ($show == ImageSource::SHOW_LAST_FOR_CATALOG && $this->isSearchPage->execute())) {
return false;
}
return true;
}
/**
* If image value is no_selection then drop value to down of the list
* return IF(IFNULL(e.small_image, 'no_selection')='no_selection', 1, 0)
*
* @return \Zend_Db_Expr
*/
private function getSortExpression($imageColumn)
{
$connection = $this->getConnection();
$noSelection = $connection->quote(ProductResource::NOT_SELECTED_IMAGE);
/** IFNULL(e.small_image, 'no_selection') */
$ifNull = $connection->getIfNullSql($imageColumn, $noSelection);
/** IFNULL(e.small_image, 'no_selection')='no_selection' */
$ifNull .= '=' . $noSelection;
/** IF(IFNULL(e.small_image, 'no_selection')='no_selection', 1, 0) */
return $connection->getCheckSql($ifNull, 1, 0);
}
/**
* @inheritdoc
*/
public function getIndexedValues(int $storeId, ?array $entityIds = [])
{
return [];
}
}
@@ -0,0 +1,205 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
use Amasty\Sorting\Model\ConfigProvider;
use Amasty\Sorting\Model\Elasticsearch\IsElasticSort;
use Amasty\Sorting\Model\IsSearchPage;
use Amasty\Sorting\Model\Source\Stock as StockSource;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
use Magento\Framework\DB\Select;
/**
* Class Instock
* Method Using like additional sorting and not visible in the list of methods
*/
class Instock extends AbstractMethod
{
/**
* @var \Magento\Framework\Module\Manager
*/
private $moduleManager;
/**
* @var \Magento\CatalogInventory\Helper\Stock
*/
private $stockHelper;
/**
* Used for MSI
*
* @var null|int
*/
private $stockId = null;
/**
* @var IsSearchPage
*/
private $isSearchPage;
public function __construct(
\Magento\Framework\Module\Manager $moduleManager,
\Magento\CatalogInventory\Helper\Stock $stockHelper,
Context $context,
\Magento\Framework\Escaper $escaper,
ConfigProvider $configProvider,
IsElasticSort $isElasticSort,
$connectionName = null,
$methodCode = '',
$methodName = ''
) {
parent::__construct(
$context,
$escaper,
$configProvider,
$isElasticSort,
$connectionName,
$methodCode,
$methodName
);
$this->moduleManager = $moduleManager;
$this->stockHelper = $stockHelper;
$this->isSearchPage = $context->getIsSearchPage();
}
/**
* {@inheritdoc}
*/
public function apply($collection, $direction = '')
{
if (!$this->isMethodActive($collection) || $this->isMethodAlreadyApplied($collection)) {
return $this;
}
$fromTables = $collection->getSelect()->getPart('from');
if (!isset($fromTables['stock_status_index'])) {
$this->stockHelper->addIsInStockFilterToCollection($collection);
$fromTables = $collection->getSelect()->getPart('from');
}
$catalogInventoryTable = $collection->getResource()->getTable('cataloginventory_stock_status');
if ($this->isMsiEnabled() && $fromTables['stock_status_index']['tableName'] != $catalogInventoryTable) {
$qtyColumn = 'quantity';
$salableColumn = 'is_salable';
} else {
$qtyColumn = 'qty';
$salableColumn = 'stock_status';
}
$qtyAlias = 'stock_status_index.' . $qtyColumn;
if ($this->isMsiEnabled()) {
if (!isset($fromTables['reservation'])) {
$reservedTable = $collection->getConnection()->select()
->from($this->getTable('inventory_reservation'), ['sku', 'quantity' => 'SUM(quantity)'])
->where('stock_id = ?', $this->getStockId())
->group('sku');
$collection->getSelect()->joinLeft(
['reservation' => $reservedTable],
'reservation.sku = e.sku',
['reserved_qty' => 'quantity']
);
}
$qtyAlias .= ' + IF(reserved_qty IS NOT NULL, reserved_qty, 0)';
}
/**
* join in @see \Magento\CatalogInventory\Model\AddStockStatusToCollection
* so we don't need to process join, only add sorting
*/
if ($this->helper->isOutOfStockByQty()) {
$ignoreTypes = [
'\'grouped\'',
'\'bundle\''
];
$collection->getSelect()->order(
/** in result something like this IF(qty > 0, 0, 1) . bundles and grouped not processing */
$this->getConnection()->getCheckSql(
sprintf(
'%s > %s OR e.type_id in (%s)',
$qtyAlias,
$this->helper->getQtyOutStock(),
implode(',', $ignoreTypes)
),
'0',
'1'
)
);
} else {
$collection->getSelect()->order(
'stock_status_index.' . $salableColumn . ' ' . $collection::SORT_ORDER_DESC
);
}
$orders = $collection->getSelect()->getPart(Select::ORDER);
// move from the last to the the first position
array_unshift($orders, array_pop($orders));
$collection->getSelect()->setPart(Select::ORDER, $orders);
$this->markApplied($collection);
return $this;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function isMethodActive(ProductCollection $collection): bool
{
// is out of stock is not displayed, method don't need to be applied
$isShowOutOfStock = $this->scopeConfig->getValue(
\Magento\CatalogInventory\Model\Configuration::XML_PATH_SHOW_OUT_OF_STOCK,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
if (!$isShowOutOfStock) {
return false;
}
$show = $this->helper->getOutOfStockLast();
if (!$show || ($show == StockSource::SHOW_LAST_FOR_CATALOG && $this->isSearchPage->execute())) {
return false;
}
return true;
}
/**
* @inheritdoc
*/
public function getIndexedValues(int $storeId, ?array $entityIds = [])
{
return [];
}
/**
* For MSI.
*
* @return int
*/
private function getStockId()
{
if ($this->stockId === null) {
$select = $this->getConnection()->select()
->from($this->getTable('inventory_stock_sales_channel'), ['stock_id'])
->where('type = \'website\' AND code = ?', $this->storeManager->getWebsite()->getCode());
$this->stockId = (int)$this->getConnection()->fetchOne($select);
}
return $this->stockId;
}
/**
* @return bool
*/
private function isMsiEnabled()
{
return $this->moduleManager->isEnabled('Magento_Inventory');
}
}
@@ -0,0 +1,115 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
class MostViewed extends AbstractIndexMethod
{
/**
* {@inheritdoc}
*/
public function getIndexTableName()
{
return 'amasty_sorting_most_viewed';
}
/**
* {@inheritdoc}
*/
public function getSortingColumnName()
{
return 'views_num';
}
/**
* {@inheritdoc}
*/
public function doReindex()
{
$select = $this->indexConnection->select();
$select->group(['source_table.store_id', 'source_table.object_id']);
$viewsNumExpr = new \Zend_Db_Expr('COUNT(source_table.event_id)');
$columns = [
'product_id' => 'source_table.object_id',
'store_id' => 'source_table.store_id',
'views_num' => $viewsNumExpr,
];
$select->from(
['source_table' => $this->getTable('report_event')],
$columns
)->where(
'source_table.event_type_id = ?',
\Magento\Reports\Model\Event::EVENT_PRODUCT_VIEW
);
$this->addFromDate($select);
$havingPart = $this->indexConnection->prepareSqlCondition($viewsNumExpr, ['gt' => 0]);
$select->having($havingPart);
$select->useStraightJoin();
foreach ($this->getBatchSelectIterator('object_id', $select) as $select) {
$viewedInfo = $this->indexConnection->fetchAll($select);
if ($viewedInfo) {
$this->getConnection()->insertOnDuplicate($this->getMainTable(), $viewedInfo, [
$this->getSortingColumnName()
]);
}
}
}
/**
* @param \Magento\Framework\DB\Select $select
*
* @return bool
*/
private function addFromDate($select)
{
$period = (int)$this->helper->getScopeValue('most_viewed/viewed_period');
if ($period) {
$from = $this->date->date(
\Magento\Framework\DB\Adapter\Pdo\Mysql::TIMESTAMP_FORMAT,
$this->date->timestamp() - $period * 24 * 3600
);
$select->where('source_table.logged_at >= ?', $from);
return true;
}
return false;
}
public function applyCustomAttribute(Collection $collection, string $direction): void
{
if ($attributeCode = $this->helper->getScopeValue('most_viewed/viewed_attr')) {
$collection->setOrder($attributeCode, $direction);
}
}
/**
* @inheritdoc
*/
public function getIndexedValues(int $storeId, ?array $entityIds = [])
{
$select = $this->getConnection()->select()->from(
$this->getMainTable(),
['product_id', 'value' => 'views_num']
)->where('store_id = ?', $storeId);
if (!empty($entityIds)) {
$select->where('product_id in(?)', $entityIds);
}
return $this->getConnection()->fetchPairs($select);
}
}
@@ -0,0 +1,42 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
class Newest extends AbstractMethod
{
public function getSortingColumnName()
{
$attributeCode = $this->helper->getScopeValue('new/new_attr');
if ($attributeCode) {
return $attributeCode;
}
return 'created_at';
}
/**
* @return string
*/
public function getAlias()
{
return $this->getSortingColumnName();
}
/**
* {@inheritdoc}
*/
public function apply($collection, $direction)
{
return $this;
}
public function getIndexedValues(int $storeId, ?array $entityIds = [])
{
return [];
}
}
@@ -0,0 +1,240 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Framework\DB\Adapter\Pdo\Mysql;
use Magento\Framework\Db\Select;
use Magento\GroupedProduct\Model\Product\Type\Grouped;
use Magento\Sales\Model\ResourceModel\Order\Item\Collection as OrderItemCollection;
class OrderBasedSorting extends AbstractIndexMethod
{
public const PRODUCT_ID = 'product_id';
public const STORE_ID = 'store_id';
public function getSortingColumnName(): string
{
return $this->getAdditionalData('sortingColumn');
}
public function getOrderColumnName(): string
{
return $this->getAdditionalData('orderColumn');
}
public function doReindex(): void
{
$needCalculateGrouped = !in_array(
\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE,
$this->getAdditionalData('ignoredProductTypes')
);
$select = $this->indexConnection->select();
$select->group(['source_table.store_id', 'order_item.product_id']);
$columns = [
self::PRODUCT_ID => 'order_item.product_id',
self::STORE_ID => 'source_table.store_id',
$this->getSortingColumnName() =>
new \Zend_Db_Expr(sprintf('SUM(order_item.%s)', $this->getOrderColumnName())),
];
$select->from(
['source_table' => $this->getTable('sales_order')]
)->joinInner(
['order_item' => $this->getTable('sales_order_item')],
'order_item.order_id = source_table.entity_id',
[]
)->joinLeft(
['order_item_parent' => $this->getTable('sales_order_item')],
'order_item.parent_item_id = order_item_parent.item_id',
[]
);
$this->addIgnoreProductTypes($select, $needCalculateGrouped);
$this->addIgnoreStatus($select);
$this->addFromDate($select);
$select->reset(Select::COLUMNS)->columns($columns);
$select->useStraightJoin();
foreach ($this->getBatchSelectIterator('entity_id', $select) as $select) {
$resultInfo = $this->indexConnection->fetchAll($select);
if ($resultInfo) {
$this->insertData($resultInfo);
}
}
if ($needCalculateGrouped) {
$this->calculateGrouped();
}
}
private function insertData(array $data): void
{
$this->getConnection()->insertOnDuplicate($this->getMainTable(), $data);
}
private function addIgnoreStatus(Select $select): void
{
$excludedOrderStatuses = $this->getExcludedOrderStatuses();
if ($excludedOrderStatuses) {
$select->where('source_table.status NOT IN(?)', $excludedOrderStatuses);
}
}
private function getExcludedOrderStatuses(): array
{
return $this->getSortingColumnName() === 'revenue'
? $this->configProvider->getExcludedOrderStatusesForRevenue()
: $this->configProvider->getExcludedOrderStatusesForBestsellers();
}
private function getPeriod(): int
{
return $this->getSortingColumnName() === 'revenue'
? $this->configProvider->getRevenuePeriod()
: $this->configProvider->getBestsellersPeriod();
}
private function getSortingAttributeCode(): string
{
return $this->getSortingColumnName() === 'revenue'
? $this->configProvider->getRevenueAttributeCode()
: $this->configProvider->getBestsellerAttributeCode();
}
private function addFromDate(Select $select): void
{
$period = $this->getPeriod();
if ($period) {
$from = $this->date->date(
Mysql::TIMESTAMP_FORMAT,
$this->date->timestamp() - $period * 24 * 3600
);
$select->where('source_table.created_at >= ?', $from);
}
}
/**
* Count grouped products ordered qty
* Sum of all simple qty which grouped by parent product and store
*/
private function calculateGrouped(): void
{
$collection = $this->getAdditionalData('orderItemCollectionFactory')->create();
$collection->addFieldToFilter('product_type', Grouped::TYPE_CODE);
$select = $collection->getSelect();
$select->joinLeft(
['source_table' => $this->getTable('sales_order')],
'main_table.order_id = source_table.entity_id',
[]
);
$this->addIgnoreStatus($select);
$this->addFromDate($select);
$result = $this->calculateItemsQty($collection);
if (empty($result)) {
return;
}
$insert = [];
foreach ($result as $storeId => $itemCounts) {
foreach ($itemCounts as $productId => $count) {
$insert[] = [
self::PRODUCT_ID => $productId,
self::STORE_ID => $storeId,
$this->getSortingColumnName() => $count,
];
}
}
$columns = [self::PRODUCT_ID, self::STORE_ID, $this->getSortingColumnName()];
$this->getConnection()->insertArray($this->getMainTable(), $columns, $insert);
}
private function calculateItemsQty(OrderItemCollection $collection): array
{
$result = [];
foreach ($collection->getItems() as $item) {
$config = $item->getProductOptionByCode('super_product_config');
$groupedId = $config[self::PRODUCT_ID];
$storeId = $item->getStoreId();
if (!isset($result[$storeId][$groupedId])) {
$result[$storeId][$groupedId] = 0;
}
// Sum of all simple qty which grouped by parent product
$result[$storeId][$groupedId] += $item->getQtyOrdered();
}
return $result;
}
private function addIgnoreProductTypes(
Select $select,
bool $needCalculateGrouped = false
): void {
$select->where('order_item.product_type NOT IN(?)', $this->getAdditionalData('ignoredProductTypes'));
if ($needCalculateGrouped) {
$connection = $this->getConnection();
$groupedIdsSelect = $connection->select()->from(
['main_table' => $this->getTable('catalog_product_entity')],
['entity_id']
)->where(
'main_table.type_id = ?',
\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE
);
$groupedIds = $connection->fetchCol($groupedIdsSelect);
if ($groupedIds) {
$select->where(
'order_item.product_id NOT IN (?)',
$groupedIds
);
}
}
}
public function applyCustomAttribute(Collection $collection, string $direction): void
{
if ($attributeCode = $this->getSortingAttributeCode()) {
$collection->setOrder($attributeCode, $direction);
}
}
public function getIndexedValues(int $storeId, ?array $entityIds = []): array
{
$select = $this->getConnection()->select()->from(
$this->getMainTable(),
[self::PRODUCT_ID, 'value' => $this->getSortingColumnName()]
)->where(
sprintf('%s = ?', self::STORE_ID),
$storeId
);
if (!empty($entityIds)) {
$select->where(
sprintf('%s in(?)', self::PRODUCT_ID),
$entityIds
);
}
return $this->getConnection()->fetchPairs($select);
}
}
@@ -0,0 +1,35 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
class Price extends AbstractMethod
{
/**
* {@inheritdoc}
*/
public function apply($collection, $direction)
{
return $this;
}
/**
* @inheritdoc
*/
public function getAlias()
{
return 'price';
}
/**
* @inheritdoc
*/
public function getIndexedValues(int $storeId, ?array $entityIds = [])
{
return [];
}
}
@@ -0,0 +1,115 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Framework\DB\Select;
class Saving extends AbstractMethod
{
/**
* @var bool
*/
private $limitColumns = false;
/**
* @param Collection $collection
* @param $direction
* @param bool $limitColumns
* @return $this|AbstractMethod
*/
public function apply($collection, $direction)
{
$connection = $this->getConnection();
$collection->addPriceData();
$table = $this->getPriceAlias($collection);
/** LEAST(min_price, tier_price) */
$least = $connection->getLeastSql(["$table.min_price", "$table.tier_price"]);
$price = $table . '.price';
/** tier_price IS NOT NULL */
$tpNotNull = $connection->prepareSqlCondition("$table.tier_price", ['notnull' => true]);
/** IF (tier_price IS NOT NULL, LEAST(min_price, tier_price), min_price) */
$minPrice = $connection->getCheckSql($tpNotNull, $least, "$table.min_price");
if ($this->helper->getScopeValue('saving/saving')) {
$percent = "($price - $minPrice) * 100 / $price";
$saving = $connection->getCheckSql($price, $percent, 0);
} else {
$saving = "($price - $minPrice)";
}
if ($this->isLimitColumns()) {
$collection->getSelect()->reset(Select::COLUMNS);
$collection->getSelect()->columns(['product_id' => 'e.entity_id']);
$alias = 'value';
} else {
$alias = $this->getMethodCode();
}
$collection->getSelect()->columns([$alias => new \Zend_Db_Expr($saving)]);
if (!$this->isLimitColumns()) {
$collection->addExpressionAttributeToSelect($this->getMethodCode(), $this->getMethodCode(), []);
// remove last item from columns because e.saving from addExpressionAttributeToSelect not exist
$columns = $collection->getSelect()->getPart(Select::COLUMNS);
array_pop($columns);
$collection->getSelect()->setPart(Select::COLUMNS, $columns);
}
return $this;
}
/**
* @return string
*/
public function getAlias()
{
return $this->getMethodCode();
}
/**
* @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
*
* @return string
*/
private function getPriceAlias($collection)
{
$tableAliases = array_keys($collection->getSelect()->getPart(Select::FROM));
if (in_array($collection::INDEX_TABLE_ALIAS, $tableAliases)) {
return $collection::INDEX_TABLE_ALIAS;
}
return reset($tableAliases);
}
/**
* @inheritdoc
*/
public function getIndexedValues(int $storeId, ?array $entityIds = [])
{
return [];
}
/**
* @return bool
*/
public function isLimitColumns()
{
return $this->limitColumns;
}
/**
* @param bool $limitColumns
*/
public function setLimitColumns($limitColumns)
{
$this->limitColumns = $limitColumns;
}
}
@@ -0,0 +1,182 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
use Amasty\Sorting\Model\ConfigProvider;
use Amasty\Sorting\Model\Elasticsearch\IsElasticSort;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory;
class Toprated extends AbstractMethod
{
public const MAIN_TABLE = 'review_entity_summary';
/**
* @var \Magento\Review\Model\ResourceModel\Review
*/
protected $reviewResource;
/**
* @var int|null
*/
private $entityTypeId = null;
public function __construct(
Context $context,
\Magento\Framework\Escaper $escaper,
ConfigProvider $configProvider,
IsElasticSort $isElasticSort,
\Magento\Review\Model\ResourceModel\Review $reviewResource,
$connectionName = null,
$methodCode = '',
$methodName = ''
) {
parent::__construct(
$context,
$escaper,
$configProvider,
$isElasticSort,
$connectionName,
$methodCode,
$methodName
);
$this->reviewResource = $reviewResource;
}
/**
* Returns Sorting method Table Column name
* which is using for order collection
*
* @return string
*/
public function getSortingColumnName()
{
return 'rating_summary_field';
}
/**
* @return string
*/
public function getSortingFieldName()
{
return 'rating_summary';
}
/**
* @return string
*/
public function getAlias()
{
return $this->getSortingColumnName();
}
/**
* {@inheritdoc}
* This method is also used for @see Commented
*/
public function apply($collection, $direction)
{
try {
$collection->joinField(
$this->getSortingColumnName(), // alias
$this->getIndexTableName(), // table
$this->getSortingFieldName(), // field
$this->getProductColumn() . '=entity_id', // bind
$this->getConditions(), // conditions
'left' // join type
);
} catch (LocalizedException $e) {
// A joined field with this alias is already declared.
$this->logger->warning(
'Failed on join table for amasty sorting method: ' . $e->getMessage(),
['method_code' => $this->getMethodCode()]
);
} catch (\Exception $e) {
$this->logger->critical($e, ['method_code' => $this->getMethodCode()]);
}
return $this;
}
/**
* Get Review entity type id for product
*
* @return bool|int|null
*/
private function getEntityTypeId()
{
if ($this->entityTypeId === null) {
$this->entityTypeId = $this->reviewResource->getEntityIdByCode(
\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE
);
}
return $this->entityTypeId;
}
/**
* {@inheritdoc}
*/
public function getIndexTableName()
{
if ($this->helper->isYotpoEnabled()) {
$table = \Amasty\Yotpo\Model\ResourceModel\YotpoReview::MAIN_TABLE;
} else {
$table = self::MAIN_TABLE;
}
return $table;
}
private function getConditions(?int $storeId = null): array
{
$conditions = ['store_id' => $this->getStoreId($storeId)];
if (!$this->helper->isYotpoEnabled()) {
$conditions['entity_type'] = $this->getEntityTypeId();
}
return $conditions;
}
/**
* @return string
*/
private function getProductColumn()
{
$column = $this->helper->isYotpoEnabled() ?
'product_id' :
'entity_pk_value';
return $column;
}
/**
* @inheritdoc
*/
public function getIndexedValues(int $storeId, ?array $entityIds = [])
{
$select = $this->getConnection()->select()->from(
$this->getTable($this->getIndexTableName()),
['product_id' => $this->getProductColumn(), 'value' => $this->getSortingFieldName()]
);
foreach ($this->getConditions($storeId) as $field => $value) {
$select->where($field . ' = ?', $value);
}
if (!empty($entityIds)) {
$select->where($this->getProductColumn() . ' in(?)', $entityIds);
}
return $this->getConnection()->fetchPairs($select);
}
private function getStoreId(?int $preferredStoreId = null): int
{
return $preferredStoreId ?? (int)$this->storeManager->getStore()->getId();
}
}
@@ -0,0 +1,104 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Method;
/**
* Class Wished
* Sorting adapter for wished method
*/
class Wished extends AbstractIndexMethod
{
/**
* {@inheritdoc}
*/
public function getIndexTableName()
{
return 'amasty_sorting_wished';
}
/**
* {@inheritdoc}
*/
public function getSortingColumnName()
{
return 'wished';
}
/**
* {@inheritdoc}
*/
public function doReindex()
{
$select = $this->indexConnection->select();
$select->group(['source_table.store_id', 'source_table.product_id']);
$viewsNumExpr = new \Zend_Db_Expr('COUNT(source_table.wishlist_item_id)');
$columns = [
'product_id' => 'source_table.product_id',
'store_id' => 'source_table.store_id',
'wished' => $viewsNumExpr,
];
$select->from(
['source_table' => $this->getTable('wishlist_item')],
$columns
);
$this->addFromDate($select);
$select->useStraightJoin();
foreach ($this->getBatchSelectIterator('wishlist_item_id', $select) as $select) {
$wishedInfo = $this->indexConnection->fetchAll($select);
if ($wishedInfo) {
$this->getConnection()->insertOnDuplicate($this->getMainTable(), $wishedInfo, [
$this->getSortingColumnName()
]);
}
}
}
/**
* @param \Magento\Framework\DB\Select $select
*
* @return bool
*/
private function addFromDate($select)
{
$period = (int)$this->helper->getScopeValue('wished/wished_period');
if ($period) {
$from = $this->date->date(
\Magento\Framework\DB\Adapter\Pdo\Mysql::TIMESTAMP_FORMAT,
$this->date->timestamp() - $period * 24 * 3600
);
$select->where('source_table.added_at >= ?', $from);
return true;
}
return false;
}
/**
* @inheritdoc
*/
public function getIndexedValues(int $storeId, ?array $entityIds = [])
{
$select = $this->getConnection()->select()->from(
$this->getMainTable(),
['product_id', 'value' => 'wished']
)->where('store_id = ?', $storeId);
if (!empty($entityIds)) {
$select->where('product_id in(?)', $entityIds);
}
return $this->getConnection()->fetchPairs($select);
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Product;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\App\ResourceConnection;
class LoadSkuMap
{
private const ENTITY_ID_FIELD = 'entity_id';
/**
* @var ResourceConnection
*/
private $resourceConnection;
public function __construct(ResourceConnection $resourceConnection)
{
$this->resourceConnection = $resourceConnection;
}
/**
* @param array $entityIds
* @return array
*/
public function execute(array $entityIds): array
{
$select = $this->resourceConnection->getConnection()->select()->from(
$this->resourceConnection->getTableName('catalog_product_entity'),
[self::ENTITY_ID_FIELD, ProductInterface::SKU]
)->where(
sprintf('%s IN (?)', self::ENTITY_ID_FIELD),
$entityIds
);
return $this->resourceConnection->getConnection()->fetchPairs($select);
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel\Product;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\App\ResourceConnection;
class LoadTypeMap
{
/**
* @var ResourceConnection
*/
private $resourceConnection;
public function __construct(ResourceConnection $resourceConnection)
{
$this->resourceConnection = $resourceConnection;
}
/**
* @param string[] $skus
* @return array
*/
public function execute(array $skus): array
{
$select = $this->resourceConnection->getConnection()->select()->from(
$this->resourceConnection->getTableName('catalog_product_entity'),
[ProductInterface::SKU, ProductInterface::TYPE_ID]
)->where(
sprintf('%s IN (?)', ProductInterface::SKU),
$skus
);
return $this->resourceConnection->getConnection()->fetchPairs($select);
}
}
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\ResourceModel;
use Amasty\Sorting\Api\ProductReviewLinkProcessorInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\DB\Adapter\DuplicateException;
class ProductReviewLinkProcessor implements ProductReviewLinkProcessorInterface
{
public const TABLE_NAME = 'amasty_sorting_reviews_link';
public const PRODUCT_ID = 'product_id';
public const REVIEW_ID = 'review_id';
/**
* @var ResourceConnection
*/
private $resourceConnection;
public function __construct(
ResourceConnection $resourceConnection
) {
$this->resourceConnection = $resourceConnection;
}
public function create(int $productId, int $reviewId): void
{
try {
$connection = $this->resourceConnection->getConnection();
$connection->insert(
$this->getTableName(),
[
self::PRODUCT_ID => $productId,
self::REVIEW_ID => $reviewId,
]
);
} catch (DuplicateException $e) {
$this->remove($productId, $reviewId);
}
}
public function getTableName(): string
{
return $this->resourceConnection->getTableName(self::TABLE_NAME);
}
public function remove(int $productId, int $reviewId): void
{
$connection = $this->resourceConnection->getConnection();
$connection->delete(
$this->getTableName(),
[
$connection->prepareSqlCondition(self::REVIEW_ID, $reviewId),
$connection->prepareSqlCondition(self::PRODUCT_ID, $productId)
]
);
}
}
+141
View File
@@ -0,0 +1,141 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model;
/**
* Class SortingAdapter
* adapter of @see \Magento\Eav\Model\Entity\Attribute
* used for add sorting method
*/
class SortingAdapter extends \Magento\Framework\DataObject
{
public const CACHE_TAG = 'SORTING_METHOD';
/**
* @var \Amasty\Sorting\Helper\Data
*/
private $helper;
/**
* @var \Amasty\Sorting\Api\MethodInterface
*/
private $methodModel;
public function __construct(
\Amasty\Sorting\Helper\Data $helper,
\Amasty\Sorting\Api\MethodInterface $methodModel = null,
array $data = []
) {
$this->helper = $helper;
$this->methodModel = $methodModel;
parent::__construct($data);
$this->prepareData();
}
/**
* Set Data for call object as array
*/
private function prepareData()
{
if (!$this->hasData('attribute_code')) {
$this->setData('attribute_code', $this->methodModel->getMethodCode());
}
if (!$this->hasData('frontend_label')) {
$this->setData('frontend_label', $this->methodModel->getMethodName());
}
}
public function getAttributeCode()
{
if ($this->hasData('attribute_code')) {
return $this->_getData('attribute_code');
}
return $this->methodModel->getMethodCode();
}
public function getFrontendLabel()
{
if ($this->hasData('frontend_label')) {
return $this->getData('frontend_label');
}
return $this->methodModel->getMethodName();
}
public function getDefaultFrontendLabel()
{
return $this->getFrontendLabel();
}
/**
* Return frontend label for default store
*
* @return string|null
*/
public function getStoreLabel($storeId = null)
{
if ($this->hasData('store_label')) {
return $this->getData('store_label');
}
return $this->methodModel->getMethodLabel($storeId);
}
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getAttributeCode()];
}
/**
* @param \Amasty\Sorting\Api\MethodInterface $methodModel
*
* @return $this
*/
public function setMethodModel($methodModel)
{
$this->methodModel = $methodModel;
return $this;
}
/**
* @return \Amasty\Sorting\Api\MethodInterface
*/
public function getMethodModel()
{
return $this->methodModel;
}
/**
* Frontend HTML for input element.
*
* @return string
*/
public function getFrontendInput()
{
return 'hidden';
}
/**
* Get attribute name
*
* @return string
* @codeCoverageIgnore
*/
public function getName()
{
return $this->getAttributeCode();
}
/**
* @return bool
*/
public function usesSource()
{
return false;
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
/**
* Class Stock
*/
abstract class AbstractShowLast implements \Magento\Framework\Data\OptionSourceInterface
{
public const DISABLED = 0;
public const SHOW_LAST = 1;
public const SHOW_LAST_FOR_CATALOG = 2;
/**
* @return array
*/
public function toOptionArray()
{
$options = [
[
'value' => self::DISABLED,
'label' => __('No')
],
[
'value' => self::SHOW_LAST,
'label' => __('Yes')
],
[
'value' => self::SHOW_LAST_FOR_CATALOG,
'label' => __('Yes for Catalog, No for Search')
]
];
return $options;
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
use Amasty\Sorting\Model\Plugin\Catalog\Config\DisplayAllFlag;
use Magento\Catalog\Model\Config;
use Magento\Framework\Data\OptionSourceInterface;
class AllSortingAttributes implements OptionSourceInterface
{
/**
* @var Config
*/
private $catalogConfig;
/**
* @var DisplayAllFlag
*/
private $displayAllFlag;
public function __construct(Config $catalogConfig, DisplayAllFlag $displayAllFlag)
{
$this->catalogConfig = $catalogConfig;
$this->displayAllFlag = $displayAllFlag;
}
/**
* Return array of options as value-label pairs
*
* @return array Format: array(array('value' => '<value>', 'label' => '<label>'), ...)
*/
public function toOptionArray()
{
$options = [];
$this->displayAllFlag->set(true);
$allAttributes = $this->catalogConfig->getAttributeUsedForSortByArray();
$this->displayAllFlag->set(false);
foreach ($allAttributes as $code => $label) {
$options[] = [
'label' => $label,
'value' => $code
];
}
return $options;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
class CategorySortAfter extends AllSortingAttributes
{
/**
* @return array
*/
public function toOptionArray(): array
{
$options = parent::toOptionArray();
array_unshift($options, [
'value' => '',
'label' => __('--Please Select--')
]);
return $options;
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
/**
* Class Image
*/
class Image extends AbstractShowLast
{
}
+54
View File
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
use Magento\Catalog\Model\Config\Source\ListSort as NativeListSort;
class ListSort extends NativeListSort
{
public const IGNORE_ATTRIBUTES = [
'price_asc',
'price_desc'
];
/**
* @var bool
*/
private $enabledIgnoreAttributes = true;
/**
* @return array
*/
public function toOptionArray()
{
$options = parent::toOptionArray();
foreach ($options as $key => $option) {
if (isset($option['value'])
&& $this->enabledIgnoreAttributes
&& in_array($option['value'], self::IGNORE_ATTRIBUTES)
) {
unset($options[$key]);
}
}
return $options;
}
public function getAllOptions(): array
{
$this->enabledIgnoreAttributes = false;
$options = $this->toOptionArray();
$this->enabledIgnoreAttributes = true;
return $options;
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
/**
* Class Methods
*/
class Methods implements \Magento\Framework\Data\OptionSourceInterface
{
/**
* @var \Amasty\Sorting\Model\MethodProvider
*/
private $methodProvider;
public function __construct(
\Amasty\Sorting\Model\MethodProvider $methodProvider
) {
$this->methodProvider = $methodProvider;
}
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->methodProvider->getMethods() as $methodObject) {
$options[] = [
'value' => $methodObject->getMethodCode(),
'label' => $methodObject->getMethodName()
];
}
return $options;
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
/**
* Class Price
*/
class Price implements \Magento\Framework\Data\OptionSourceInterface
{
/**
* @return array
*/
public function toOptionArray()
{
return [
[
'value' => 'min_price',
'label' => __('Minimal Price'),
],
[
'value' => 'price',
'label' => __('Price'),
],
[
'value' => 'final_price',
'label' => __('Final Price'),
],
];
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
/**
* Class ProductAttribute
*/
class ProductAttribute implements \Magento\Framework\Data\OptionSourceInterface
{
private $options;
/**
* @var \Magento\Eav\Model\Config
*/
private $eavConfig;
/**
* ProductAttribute constructor.
*
* @param \Magento\Eav\Model\Config $eavConfig
*/
public function __construct(
\Magento\Eav\Model\Config $eavConfig
) {
$this->eavConfig = $eavConfig;
}
/**
* @return array
*/
public function toOptionArray()
{
if (!$this->options) {
$this->options = [['value' => '', 'label' => ' ']];
$attributes = $this->eavConfig->getEntityType(\Magento\Catalog\Model\Product::ENTITY)
->getAttributeCollection()
->addFieldToFilter('frontend_input', ['nin' => ['multiselect', 'gallery', 'textarea']])
->addFieldToFilter('used_in_product_listing', 1)
->getItems();
foreach ($attributes as $item) {
$this->options[] = [
'value' => $item->getAttributeCode(),
'label' => __($item->getFrontendLabel()),
];
}
}
return $this->options;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
use Magento\Catalog\Model\Config\Source\ListSort;
class SearchSort extends ListSort
{
/**
* @return array
*/
public function toOptionArray()
{
$options = parent::toOptionArray();
array_shift($options);
array_unshift($options, [
'value' => 'relevance',
'label' => __('Relevance')
]);
return $options;
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
class SearchSortAfter extends AllSortingAttributes
{
/**
* @return array
*/
public function toOptionArray(): array
{
$options = parent::toOptionArray();
array_shift($options);
array_unshift($options, [
'value' => 'relevance',
'label' => __('Relevance')
]);
array_unshift($options, [
'value' => '',
'label' => __('--Please Select--')
]);
return $options;
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
use Amasty\Sorting\Model\ConfigProvider;
class SortOptions
{
/**
* @var ConfigProvider
*/
private $configProvider;
public function __construct(
ConfigProvider $configProvider
) {
$this->configProvider = $configProvider;
}
public function execute(array $options): array
{
if ($this->configProvider->getSortOrder()) {
uksort($options, [$this, "sortingRule"]);
}
return $options;
}
private function sortingRule(string $leftItem, string $rightItem): int
{
$correctSortOrder = array_flip(array_keys($this->configProvider->getSortOrder()));
$leftPos = $correctSortOrder[$leftItem] ?? 0;
$rightPos = $correctSortOrder[$rightItem] ?? 0;
return $leftPos <=> $rightPos;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
use Magento\Framework\Data\OptionSourceInterface;
class SortOrder implements OptionSourceInterface
{
public const SORT_ASC = 'asc';
public const SORT_DESC = 'desc';
/**
* @return array
*/
public function toOptionArray(): array
{
return [
[
'value' => self::SORT_DESC,
'label' => __('DESC')
],
[
'value' => self::SORT_ASC,
'label' => __('ASC')
]
];
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
class State implements \Magento\Framework\Option\ArrayInterface
{
/**
* @var array
*/
private $options;
/**
* @var \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory
*/
private $statusCollectionFactory;
/**
* @param \Magento\Framework\ObjectManagerInterface $objectManager
*/
public function __construct(
\Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory $statusCollectionFactory
) {
$this->statusCollectionFactory = $statusCollectionFactory;
}
/**
* @return array
*/
public function toOptionArray()
{
if (!$this->options) {
/** @var \Magento\Sales\Model\Order\Status[] $statusItems */
$statusItems = $this->statusCollectionFactory->create()->getItems();
foreach ($statusItems as $status) {
$this->options[] = ['value' => $status->getStatus(), 'label' => $status->getLabel()];
}
}
return $this->options;
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Model\Source;
/**
* Class Stock
*/
class Stock extends AbstractShowLast
{
}
+106
View File
@@ -0,0 +1,106 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Observer\System;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Model\Config as CatalogConfig;
class ConfigChanged implements ObserverInterface
{
/**
* @var \Magento\Framework\App\Config\Storage\WriterInterface
*/
private $configWriter;
/**
* @var \Magento\Framework\App\Config\ReinitableConfigInterface
*/
private $reinitableConfig;
/**
* @var \Amasty\Sorting\Helper\Data
*/
private $helper;
/**
* @var CatalogConfig
*/
private $catalogConfig;
public function __construct(
\Magento\Framework\App\Config\ReinitableConfigInterface $reinitableConfig,
\Magento\Framework\App\Config\Storage\WriterInterface $configWriter,
\Amasty\Sorting\Helper\Data $helper,
CatalogConfig $catalogConfig
) {
$this->reinitableConfig = $reinitableConfig;
$this->configWriter = $configWriter;
$this->helper = $helper;
$this->catalogConfig = $catalogConfig;
}
/**
* @param Observer $observer
*/
public function execute(Observer $observer)
{
$name = $observer->getEvent()->getName();
$store = (int)$observer->getEvent()->getStore() ?: null;
$defaultSortings = $this->helper->getCategorySorting($store);
$moduleValue = array_shift($defaultSortings);
$catalogValue = $this->catalogConfig->getProductListDefaultSortBy($store);
if ($catalogValue != $moduleValue) {
switch ($name) {
case 'admin_system_config_changed_section_catalog':
$this->saveAmastyValue($catalogValue, $store);
break;
case 'admin_system_config_changed_section_amsorting':
$this->saveCatalogValue($moduleValue, $store);
break;
}
}
}
/**
* @param $value
* @param $store
*/
private function saveAmastyValue($value, $store)
{
$this->saveConfig('amsorting/default_sorting/category_1', $value, $store);
}
/**
* @param $value
* @param $store
*/
private function saveCatalogValue($value, $store)
{
$this->saveConfig(CatalogConfig::XML_PATH_LIST_DEFAULT_SORT_BY, $value, $store);
}
/**
* @param string $path
* @param string $value
* @param int $store
*
* @return $this
*/
private function saveConfig($path, $value, $store)
{
if ($store) {
$this->configWriter->save($path, $value, \Magento\Store\Model\ScopeInterface::SCOPE_STORES, $store);
} else {
$this->configWriter->save($path, $value);
}
$this->reinitableConfig->reinit();
return $this;
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Plugin\Block;
use Amasty\Sorting\Helper\Data;
use Magento\CatalogSearch\Block\Result as Subject;
use Magento\Framework\Registry;
class Result
{
/**
* @var Data
*/
private $helper;
/**
* @var Registry
*/
private $registry;
public function __construct(Data $helper, Registry $registry)
{
$this->helper = $helper;
$this->registry = $registry;
}
/**
* @param Subject $result
*
* @return Subject
*/
public function afterSetListOrders(Subject $result)
{
$searchSortings = $this->helper->getSearchSorting();
// getting first default sorting
$sortBy = array_shift($searchSortings);
$result->getListBlock()->setDefaultSortBy(
$sortBy
);
$this->registry->unregister(Data::SEARCH_SORTING);
$this->registry->register(Data::SEARCH_SORTING, true);
return $result;
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Plugin\Catalog;
use Amasty\Sorting\Model\Method\IsMethodDisplayed;
use Amasty\Sorting\Model\MethodProvider;
use Amasty\Sorting\Model\Source\SortOptions;
use Amasty\Sorting\Model\SortingAdapterFactory;
use Magento\Catalog\Model\Config as CatalogEavConfig;
use Magento\Framework\View\LayoutInterface;
class Config
{
/**
* @var MethodProvider
*/
private $methodProvider;
/**
* @var SortingAdapterFactory
*/
private $adapterFactory;
/**
* @var LayoutInterface
*/
private $layout;
/**
* @var SortOptions
*/
private $sortOptions;
/**
* @var IsMethodDisplayed
*/
private $isMethodDisplayed;
public function __construct(
MethodProvider $methodProvider,
SortingAdapterFactory $adapterFactory,
LayoutInterface $layout,
SortOptions $sortOptions,
IsMethodDisplayed $isMethodDisplayed
) {
$this->methodProvider = $methodProvider;
$this->adapterFactory = $adapterFactory;
$this->layout = $layout;
$this->sortOptions = $sortOptions;
$this->isMethodDisplayed = $isMethodDisplayed;
}
/**
* Retrieve Attributes array used for sort by
*
* @param CatalogEavConfig $subject
* @param array $options
* @return array
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetAttributesUsedForSortBy(CatalogEavConfig $subject, array $options): array
{
foreach ($options as $key => $option) {
if (!$this->isMethodDisplayed->execute($key)) {
unset($options[$key]);
}
}
return $this->addNewOptions($options);
}
/**
* @param array $options
* @return array
*/
public function addNewOptions(array $options): array
{
$methods = $this->methodProvider->getMethods();
foreach ($methods as $methodObject) {
$code = $methodObject->getMethodCode();
if ($this->isMethodDisplayed->execute($code) && !isset($options[$code])) {
$options[$code] = $this->adapterFactory->create(['methodModel' => $methodObject]);
}
}
return $options;
}
/**
* Retrieve Attributes Used for Sort by as array
* key = code, value = name
*
* @param CatalogEavConfig $subject
* @param array $options
* @return array
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetAttributeUsedForSortByArray(CatalogEavConfig $subject, array $options): array
{
if (!$this->isMethodDisplayed->execute('position')) {
unset($options['position']);
}
$options = $this->sortOptions->execute($options);
if (count($options) == 0 && !$this->layout->getBlock('search.result')) {
$options[] = '';
}
return $options;
}
}
@@ -0,0 +1,56 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Plugin\Catalog\Helper\Product;
use Amasty\Sorting\Helper\Data;
use Magento\Framework\App\RequestInterface;
use Magento\Catalog\Helper\Product\ProductList as Subject;
class ProductList
{
/**
* @var Data
*/
private $helper;
/**
* @var RequestInterface
*/
private $request;
/**
* @var array
*/
private $searchModules = [
'catalogsearch'
];
public function __construct(
Data $helper,
RequestInterface $request
) {
$this->helper = $helper;
$this->request = $request;
}
/**
* @param Subject $subject
* @param $sortBy
* @return string
*/
public function afterGetDefaultSortField(Subject $subject, $sortBy)
{
if (in_array($this->request->getModuleName(), $this->searchModules)) {
$searchSortings = $this->helper->getSearchSorting();
// getting first default sorting
$sortBy = array_shift($searchSortings);
}
return $sortBy;
}
}
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Improved Sorting for Magento 2
*/
namespace Amasty\Sorting\Plugin\Catalog\Model\Category;
use Amasty\Sorting\Model\Method\IsMethodDisplayed;
use Amasty\Sorting\Model\Source\SortOptions;
use Magento\Catalog\Model\Category;
class SortAvailableOptions
{
/**
* @var SortOptions
*/
private $sortOptions;
/**
* @var IsMethodDisplayed
*/
private $isMethodDisplayed;
public function __construct(
SortOptions $sortOptions,
IsMethodDisplayed $isMethodDisplayed
) {
$this->sortOptions = $sortOptions;
$this->isMethodDisplayed = $isMethodDisplayed;
}
/**
* @param Category $subject
* @param array $options
* @return array
* @see \Magento\Catalog\Model\Category::getAvailableSortBy
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetAvailableSortBy(Category $subject, ?array $options): ?array
{
if ($options) {
if (!$this->isMethodDisplayed->execute('position')) {
unset($options['position']);
}
$options = array_flip($this->sortOptions->execute(array_flip($options)));
}
return $options;
}
}

Some files were not shown because too many files have changed in this diff Show More