ltsecurityinc安防产品在线商城代码
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\Category;
|
||||
|
||||
/**
|
||||
* Class DataProvider
|
||||
*
|
||||
* @api
|
||||
*
|
||||
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
|
||||
* @since 101.0.0
|
||||
*/
|
||||
class DataProvider extends \Magento\Catalog\Model\Category\DataProvider
|
||||
{
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @since 101.0.0
|
||||
*/
|
||||
protected function getFieldsMap()
|
||||
{
|
||||
$fields = parent::getFieldsMap();
|
||||
$fields['display_settings'][] = 'ox_nav_disable_ajax';
|
||||
return $fields;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\Config\Source;
|
||||
|
||||
|
||||
use Magento\Framework\Option\ArrayInterface;
|
||||
|
||||
class CategoryDepth implements ArrayInterface
|
||||
{
|
||||
public function toOptionArray()
|
||||
{
|
||||
return [
|
||||
['value' => 0, 'label' => __('Don\'t show nested categories')],
|
||||
['value' => 1, 'label' => __('1 level sub categories')],
|
||||
['value' => 2, 'label' => __('2 level sub categories')],
|
||||
['value' => 3, 'label' => __('3 level sub categories')],
|
||||
['value' => 4, 'label' => __('4 level sub categories')],
|
||||
['value' => 5, 'label' => __('5 level sub categories')],
|
||||
];
|
||||
}
|
||||
|
||||
public function toArray()
|
||||
{
|
||||
$array = [];
|
||||
foreach ($this->toOptionArray() as $item) {
|
||||
$array[$item['value']] = $item['label'];
|
||||
}
|
||||
return $array;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\Config\Source;
|
||||
|
||||
use Magento\Framework\Option\ArrayInterface;
|
||||
|
||||
class FiltersType implements ArrayInterface
|
||||
{
|
||||
const TYPE_CHECKBOX = 'checkbox';
|
||||
|
||||
public function toOptionArray()
|
||||
{
|
||||
return [
|
||||
['value' => '', 'label' => __('Simple Links')],
|
||||
['value' => static::TYPE_CHECKBOX, 'label' => __('Checkboxes')],
|
||||
];
|
||||
}
|
||||
|
||||
public function toArray()
|
||||
{
|
||||
$array = [];
|
||||
foreach ($this->toOptionArray() as $item) {
|
||||
$array[$item['value']] = $item['label'];
|
||||
}
|
||||
return $array;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\Config\Source;
|
||||
|
||||
use Magento\Framework\Option\ArrayInterface;
|
||||
|
||||
class LoaderType implements ArrayInterface
|
||||
{
|
||||
const TYPE_THEME = 'theme';
|
||||
const TYPE_MAGENTO = 'magento';
|
||||
const TYPE_BLOCK = 'css';
|
||||
const TYPE_IMAGE = 'image';
|
||||
|
||||
public function toOptionArray()
|
||||
{
|
||||
return [
|
||||
['value' => '', 'label' => __('Disabled')],
|
||||
['value' => static::TYPE_MAGENTO, 'label' => __('Magento Default')],
|
||||
['value' => static::TYPE_BLOCK, 'label' => __('CSS Preloader')],
|
||||
['value' => static::TYPE_THEME, 'label' => __('Theme Preloader')],
|
||||
['value' => static::TYPE_IMAGE, 'label' => __('Custom Image')]
|
||||
];
|
||||
}
|
||||
|
||||
public function toArray()
|
||||
{
|
||||
return [
|
||||
'' => __('Disabled'),
|
||||
static::TYPE_MAGENTO => __('Magento Default'),
|
||||
static::TYPE_IMAGE => __('CSS Preloader'),
|
||||
static::TYPE_THEME => __('Theme Preloader'),
|
||||
static::TYPE_IMAGE => __('Custom Image')
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\Config\Source;
|
||||
|
||||
use Magento\Config\Block\System\Config\Form\Field;
|
||||
use Magento\Framework\Data\Form\Element\AbstractElement;
|
||||
|
||||
class Spacer extends Field
|
||||
{
|
||||
protected function _decorateRowHtml(AbstractElement $element, $html)
|
||||
{
|
||||
return '<tr id="row_' . $element->getHtmlId() . '"><td></td><td colspan="2"><hr class="ox-settings-spacer"></td></tr>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\Layer;
|
||||
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
|
||||
class Filter
|
||||
{
|
||||
|
||||
protected $request;
|
||||
protected $_ids = [];
|
||||
|
||||
public function __construct(
|
||||
RequestInterface $request
|
||||
) {
|
||||
$this->request = $request;
|
||||
}
|
||||
|
||||
public function getItemUrl($item)
|
||||
{
|
||||
if ($this->isSelected($item)) {
|
||||
return $item->getRemoveUrl();
|
||||
}
|
||||
|
||||
return $item->getUrl();
|
||||
}
|
||||
|
||||
public function getFilterValue($filter, $explode = true)
|
||||
{
|
||||
$filterValue = $this->request->getParam($filter->getRequestVar());
|
||||
if (empty($filterValue)) {
|
||||
return [];
|
||||
}
|
||||
if ($explode) {
|
||||
if (is_string($filterValue)) {
|
||||
$filterValue = explode(',', $filterValue);
|
||||
}
|
||||
}
|
||||
|
||||
return $filterValue;
|
||||
}
|
||||
|
||||
public function isOptionReducesResults($filter, $optionCount, $totalSize)
|
||||
{
|
||||
$result = $optionCount <= $totalSize;
|
||||
|
||||
if ($this->isShowZero($filter)) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $optionCount && $result;
|
||||
}
|
||||
|
||||
public function isShowZero($filter)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function isMainFilter($filter)
|
||||
{
|
||||
if (empty($this->_ids)) {
|
||||
$this->_ids = $this->getStateAttributesIds($filter);
|
||||
}
|
||||
$isMulti = false;
|
||||
if (count($this->_ids) <= 1) {
|
||||
$isMulti = true;
|
||||
if (!empty($this->_ids)) {
|
||||
$isMulti = $this->isMultiselect($this->_ids[0]);
|
||||
}
|
||||
}
|
||||
|
||||
return $isMulti;
|
||||
}
|
||||
|
||||
protected function getStateAttributesIds($filter)
|
||||
{
|
||||
$layer = $filter->getLayer();
|
||||
foreach ($layer->getState()->getFilters() as $filter) {
|
||||
if ($model = $filter->getFilter()->getData('attribute_model')) {
|
||||
$this->_ids[] = $model->getId();
|
||||
}
|
||||
}
|
||||
return array_unique($this->_ids);
|
||||
}
|
||||
|
||||
public function isMultiselect($attrId)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\Layer\Filter;
|
||||
|
||||
use Amasty\ShopbyBase\Helper\FilterSetting;
|
||||
use Exception;
|
||||
use Magento\Catalog\Model\Layer;
|
||||
use Magento\Catalog\Model\Layer\Filter\Item;
|
||||
use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder;
|
||||
use Magento\Catalog\Model\Layer\Filter\ItemFactory;
|
||||
use Magento\Framework\App\ObjectManager;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Exception\StateException;
|
||||
use Magento\Framework\Filter\StripTags;
|
||||
use Magento\Framework\Message\ManagerInterface;
|
||||
use Magento\Framework\Search\Response\QueryResponse;
|
||||
use Magento\Framework\Search\ResponseInterface;
|
||||
use Magento\Search\Model\SearchEngine;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Olegnax\LayeredNavigation\Helper\Helper;
|
||||
use Olegnax\LayeredNavigation\Model\Request\Builder;
|
||||
use Olegnax\LayeredNavigation\Model\ResourceModel\Fulltext\Collection;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class Attribute extends \Magento\CatalogSearch\Model\Layer\Filter\Attribute
|
||||
{
|
||||
|
||||
/**
|
||||
* @var Helper
|
||||
*/
|
||||
protected $_helper;
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $_isFilter = false;
|
||||
/**
|
||||
* @var SearchEngine
|
||||
*/
|
||||
protected $searchEngine;
|
||||
/**
|
||||
* @var ManagerInterface
|
||||
*/
|
||||
protected $messageManager;
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $attributeValues = [];
|
||||
/**
|
||||
* @var StripTags
|
||||
*/
|
||||
private $tagFilter;
|
||||
|
||||
public function __construct(
|
||||
ItemFactory $filterItemFactory,
|
||||
StoreManagerInterface $storeManager,
|
||||
Layer $layer,
|
||||
DataBuilder $itemDataBuilder,
|
||||
StripTags $tagFilter,
|
||||
Helper $helper,
|
||||
SearchEngine $searchEngine,
|
||||
ManagerInterface $messageManager,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct(
|
||||
$filterItemFactory,
|
||||
$storeManager,
|
||||
$layer,
|
||||
$itemDataBuilder,
|
||||
$tagFilter,
|
||||
$data
|
||||
);
|
||||
$this->_helper = $helper;
|
||||
$this->searchEngine = $searchEngine;
|
||||
$this->messageManager = $messageManager;
|
||||
$this->tagFilter = $tagFilter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply filter to collection
|
||||
*
|
||||
* @param RequestInterface $request
|
||||
* @return $this
|
||||
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function apply(RequestInterface $request)
|
||||
{
|
||||
if (!$this->pluginEnable()) {
|
||||
return parent::apply($request);
|
||||
}
|
||||
|
||||
$attributeValue = $request->getParam($this->getRequestVar());
|
||||
if (empty($attributeValue)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$attributeValue = explode(',', $attributeValue);
|
||||
$this->setCurrentValue($attributeValue);
|
||||
|
||||
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
|
||||
$attribute = $this->getAttributeModel();
|
||||
$id = $attribute->getAttributeId();
|
||||
|
||||
if (!$this->isMultiselect($id) && count($attributeValue) > 1) {
|
||||
$attributeValue = array_slice($attributeValue, 0, 1);
|
||||
}
|
||||
/** @var Collection $productCollection */
|
||||
$productCollection = $this->getProductCollection();
|
||||
|
||||
$productCollection->addFieldToFilter($attribute->getAttributeCode(), $attributeValue);
|
||||
|
||||
if ($this->shouldAddState($id)) {
|
||||
$this->addState($attributeValue);
|
||||
}
|
||||
if (!$this->isVisibleWhenSelected($id)) {
|
||||
$this->setItems([]); // set items to disable show filtering
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function pluginEnable()
|
||||
{
|
||||
return (bool)$this->_helper->isEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $attributeValues
|
||||
*/
|
||||
protected function setCurrentValue(array $attributeValues)
|
||||
{
|
||||
$this->attributeValues = $attributeValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @return bool
|
||||
* @noinspection PhpUnusedParameterInspection
|
||||
*/
|
||||
protected function isMultiselect($id)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Magento\Catalog\Model\ResourceModel\Product\Collection
|
||||
*/
|
||||
protected function getProductCollection()
|
||||
{
|
||||
return $this->getLayer()->getProductCollection();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @return bool
|
||||
* @noinspection PhpUnusedParameterInspection
|
||||
*/
|
||||
public function shouldAddState($id)
|
||||
{
|
||||
return !$this->isBrandingBrand();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
protected function isBrandingBrand()
|
||||
{
|
||||
if (
|
||||
class_exists('Amasty\ShopbyBrand\Helper\Content')
|
||||
&& $contentHelper = ObjectManager::getInstance()->get('Amasty\ShopbyBrand\Helper\Content')
|
||||
) {
|
||||
$brand = $contentHelper->getCurrentBranding();
|
||||
return $brand &&
|
||||
(FilterSetting::ATTR_PREFIX . $this->getRequestVar() ==
|
||||
$brand->getFilterCode());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $values
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function addState($values)
|
||||
{
|
||||
$labels = [];
|
||||
foreach ((array)$values as $value) {
|
||||
$label = $this->getOptionText($value);
|
||||
$labels[$value] = $label;
|
||||
}
|
||||
foreach ($labels as $id => $label) {
|
||||
$item = $this->_createItem($label, $id);
|
||||
$this->getLayer()->getState()
|
||||
->addFilter(
|
||||
$item
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @return bool
|
||||
* @noinspection PhpUnusedParameterInspection
|
||||
*/
|
||||
public function isVisibleWhenSelected($id)
|
||||
{
|
||||
return !$this->isBrandingBrand();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $a
|
||||
* @param $b
|
||||
* @return int|mixed
|
||||
*/
|
||||
public function sortOption($a, $b)
|
||||
{
|
||||
$pattern = '@^(\d+)@';
|
||||
if (preg_match($pattern, $a['label'], $ma) && preg_match($pattern, $b['label'], $mb)) {
|
||||
$r = $ma[1] - $mb[1];
|
||||
if ($r != 0) {
|
||||
return $r;
|
||||
}
|
||||
}
|
||||
|
||||
return strcasecmp($a['label'], $b['label']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get data array for building filter items
|
||||
*
|
||||
* Result array should have next structure:
|
||||
* array(
|
||||
* $index => array(
|
||||
* 'label' => $label,
|
||||
* 'value' => $value,
|
||||
* 'count' => $count
|
||||
* )
|
||||
* )
|
||||
*
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function _getItemsData()
|
||||
{
|
||||
if (!$this->pluginEnable()) {
|
||||
return parent::_getItemsData();
|
||||
}
|
||||
$attribute = $this->getAttributeModel();
|
||||
if ($this->hasCurrentValue() && !$this->isVisibleWhenSelected($attribute->getAttributeId())) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$options = $this->getOptions();
|
||||
$optionsFacetedData = $this->getOptionsFacetedData();
|
||||
if (!$optionsFacetedData) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$this->addItemsToDataBuilder($options, $optionsFacetedData);
|
||||
$itemsData = $this->getItemsFromDataBuilder();
|
||||
|
||||
return $itemsData;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasCurrentValue()
|
||||
{
|
||||
return !empty($this->attributeValues);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function getOptions()
|
||||
{
|
||||
$attribute = $this->getAttributeModel();
|
||||
$options = $attribute->getFrontend()->getSelectOptions();
|
||||
|
||||
usort($options, [$this, 'sortOption']);
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function getOptionsFacetedData()
|
||||
{
|
||||
$optionsFacetedData = $this->generateOptionsFacetedData();
|
||||
|
||||
if (count($optionsFacetedData)) {
|
||||
$optionsFacetedData = $this->convertOptionsFacetedData($optionsFacetedData);
|
||||
}
|
||||
|
||||
return $optionsFacetedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
* @noinspection PhpRedundantCatchClauseInspection
|
||||
*/
|
||||
protected function generateOptionsFacetedData()
|
||||
{
|
||||
$productCollection = $this->getProductCollection();
|
||||
$attribute = $this->getAttributeModel();
|
||||
$attributeCode = $attribute->getAttributeCode();
|
||||
try {
|
||||
$optionsFacetedData = $productCollection->getFacetedData(
|
||||
$attributeCode,
|
||||
$this->getAlteredQueryResponse()
|
||||
);
|
||||
} catch (StateException $e) {
|
||||
if (!$this->messageManager->hasMessages()) {
|
||||
$this->messageManager->addErrorMessage(
|
||||
__('Make sure that "%1" attribute can be used in layered navigation', $attributeCode)
|
||||
);
|
||||
}
|
||||
$optionsFacetedData = [];
|
||||
}
|
||||
|
||||
return $optionsFacetedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return QueryResponse|ResponseInterface|null
|
||||
*/
|
||||
protected function getAlteredQueryResponse()
|
||||
{
|
||||
$alteredQueryResponse = null;
|
||||
if ($this->hasCurrentValue()) {
|
||||
try {
|
||||
$requestBuilder = $this->getRequestBuilder();
|
||||
if (!$requestBuilder) {
|
||||
return $alteredQueryResponse;
|
||||
}
|
||||
$queryRequest = $requestBuilder->create();
|
||||
$alteredQueryResponse = $this->searchEngine->search($queryRequest);
|
||||
} catch (Exception $e) {
|
||||
$alteredQueryResponse = null;
|
||||
}
|
||||
}
|
||||
return $alteredQueryResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder|null
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function getRequestBuilder()
|
||||
{
|
||||
$requestBuilder = $this->getMemRequestBuilder();
|
||||
if (!$requestBuilder) {
|
||||
return null;
|
||||
}
|
||||
$attributeCode = $this->getAttributeModel()->getAttributeCode();
|
||||
$requestBuilder->removePlaceholder($attributeCode);
|
||||
$requestBuilder->setAggregationsOnly($attributeCode);
|
||||
|
||||
return $requestBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder|null
|
||||
*/
|
||||
private function getMemRequestBuilder()
|
||||
{
|
||||
$productCollection = $this->getProductCollection();
|
||||
if (method_exists($productCollection, 'getMemRequestBuilder')) {
|
||||
return clone $productCollection->getMemRequestBuilder();
|
||||
}
|
||||
$this->_helper->_loadObject(LoggerInterface::class)
|
||||
->error(__('Invalid class for product collection: ') . get_class($productCollection));
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $optionsFacetedData
|
||||
* @return array
|
||||
*/
|
||||
protected function convertOptionsFacetedData(array $optionsFacetedData)
|
||||
{
|
||||
$values = $this->getCurrentValue();
|
||||
foreach ($values as $value) {
|
||||
if (!empty($value) && !array_key_exists($value, $optionsFacetedData)) {
|
||||
$optionsFacetedData[$value] = [
|
||||
'value' => $value,
|
||||
'count' => 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $optionsFacetedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
protected function getCurrentValue()
|
||||
{
|
||||
return $this->attributeValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $options
|
||||
* @param array $optionsFacetedData
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function addItemsToDataBuilder(array $options, array $optionsFacetedData)
|
||||
{
|
||||
if (!$options) {
|
||||
return;
|
||||
}
|
||||
foreach ($options as $option) {
|
||||
if (empty($option['value'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$isFilterableAttribute = $this->getAttributeIsFilterable($this->getAttributeModel());
|
||||
if (isset($optionsFacetedData[$option['value']])
|
||||
|| $isFilterableAttribute != static::ATTRIBUTE_OPTIONS_ONLY_WITH_RESULTS
|
||||
) {
|
||||
$count = 0;
|
||||
if (isset($optionsFacetedData[$option['value']]['count'])) {
|
||||
$count = $optionsFacetedData[$option['value']]['count'];
|
||||
}
|
||||
$this->itemDataBuilder->addItemData(
|
||||
$this->tagFilter->filter($option['label']),
|
||||
$option['value'],
|
||||
$count
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
private function getItemsFromDataBuilder()
|
||||
{
|
||||
$itemsData = $this->itemDataBuilder->build();
|
||||
if (count($itemsData) == 1
|
||||
&& !$this->isOptionReducesResults(
|
||||
$itemsData[0]['count'],
|
||||
$this->getLayer()->getProductCollection()->getSize()
|
||||
)
|
||||
) {
|
||||
$itemsData = $this->getReducedItemsData($itemsData);
|
||||
}
|
||||
|
||||
return $itemsData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $itemsData
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function getReducedItemsData(array $itemsData)
|
||||
{
|
||||
$isFilterActive = false;
|
||||
/** @var Item $filter */
|
||||
foreach ($this->getLayer()->getState()->getFilters() as $filter) {
|
||||
|
||||
if ($filter->getFilter()->getRequestVar() == $this->getRequestVar()) {
|
||||
$isFilterActive = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $isFilterActive ? $itemsData : [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,521 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\Layer\Filter;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Magento\Catalog\Api\CategoryRepositoryInterface;
|
||||
use Magento\Catalog\Model\Category as CategoryModel;
|
||||
use Magento\Catalog\Model\Layer;
|
||||
use Magento\Catalog\Model\Layer\Filter\DataProvider\CategoryFactory;
|
||||
use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder;
|
||||
use Magento\Catalog\Model\Layer\Filter\ItemFactory;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\Escaper;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Exception\NoSuchEntityException;
|
||||
use Magento\Framework\Exception\StateException;
|
||||
use Magento\Framework\Message\ManagerInterface;
|
||||
use Magento\Framework\Search\Response\QueryResponse;
|
||||
use Magento\Framework\Search\ResponseInterface;
|
||||
use Magento\Search\Model\SearchEngine;
|
||||
use Magento\Store\Api\Data\StoreInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Olegnax\LayeredNavigation\Helper\Helper;
|
||||
use Olegnax\LayeredNavigation\Model\Layer\Filter;
|
||||
use Olegnax\LayeredNavigation\Model\Request\Builder;
|
||||
use Olegnax\LayeredNavigation\Model\ResourceModel\Fulltext\Collection;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class Category extends \Magento\CatalogSearch\Model\Layer\Filter\Category
|
||||
{
|
||||
const FILTER_CODE = 'category';
|
||||
const ATTRIBUTE_CODE = 'category_ids';
|
||||
/**
|
||||
* @var Helper
|
||||
*/
|
||||
protected $_helper;
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $attributeValues;
|
||||
/**
|
||||
* @var mixed
|
||||
*/
|
||||
protected $currentId;
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $isSearch;
|
||||
/**
|
||||
* @var ManagerInterface
|
||||
*/
|
||||
protected $messageManager;
|
||||
/**
|
||||
* @var CategoryRepositoryInterface
|
||||
*/
|
||||
protected $categoryRepository;
|
||||
/**
|
||||
* @var SearchEngine
|
||||
*/
|
||||
protected $searchEngine;
|
||||
/**
|
||||
* @var Filter
|
||||
*/
|
||||
protected $layerFilter;
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $categorys = [];
|
||||
/**
|
||||
* @var CategoryModel
|
||||
*/
|
||||
protected $category;
|
||||
/**
|
||||
* @var StoreManagerInterface
|
||||
*/
|
||||
protected $storeManager;
|
||||
/**
|
||||
* @var Layer\Filter\DataProvider\Category
|
||||
*/
|
||||
private $dataProvider;
|
||||
/**
|
||||
* @var Escaper
|
||||
*/
|
||||
private $escaper;
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $maxDepth;
|
||||
|
||||
/**
|
||||
* Category constructor.
|
||||
* @param ItemFactory $filterItemFactory
|
||||
* @param StoreManagerInterface $storeManager
|
||||
* @param Layer $layer
|
||||
* @param DataBuilder $itemDataBuilder
|
||||
* @param Escaper $escaper
|
||||
* @param CategoryFactory $categoryDataProviderFactory
|
||||
* @param Helper $helper
|
||||
* @param SearchEngine $searchEngine
|
||||
* @param ManagerInterface $messageManager
|
||||
* @param Filter $layerFilter
|
||||
* @param CategoryModel $category
|
||||
* @param array $data
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function __construct(
|
||||
ItemFactory $filterItemFactory,
|
||||
StoreManagerInterface $storeManager,
|
||||
Layer $layer,
|
||||
DataBuilder $itemDataBuilder,
|
||||
Escaper $escaper,
|
||||
CategoryFactory $categoryDataProviderFactory,
|
||||
Helper $helper,
|
||||
SearchEngine $searchEngine,
|
||||
ManagerInterface $messageManager,
|
||||
Filter $layerFilter,
|
||||
CategoryModel $category,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct(
|
||||
$filterItemFactory,
|
||||
$storeManager,
|
||||
$layer,
|
||||
$itemDataBuilder,
|
||||
$escaper,
|
||||
$categoryDataProviderFactory,
|
||||
$data
|
||||
);
|
||||
$this->storeManager = $storeManager;
|
||||
$this->_helper = $helper;
|
||||
$this->dataProvider = $categoryDataProviderFactory->create(['layer' => $this->getLayer()]);
|
||||
$this->searchEngine = $searchEngine;
|
||||
$this->messageManager = $messageManager;
|
||||
$this->escaper = $escaper;
|
||||
$this->layerFilter = $layerFilter;
|
||||
$this->category = $category;
|
||||
}
|
||||
|
||||
public function getMaxDepth()
|
||||
{
|
||||
if (null == $this->maxDepth) {
|
||||
$this->maxDepth = abs((int)$this->_helper->getModuleConfig('category/depth'));
|
||||
}
|
||||
return $this->maxDepth;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param RequestInterface $request
|
||||
* @return $this|Category
|
||||
* @noinspection PhpDeprecationInspection
|
||||
*/
|
||||
public function apply(RequestInterface $request)
|
||||
{
|
||||
if (!$this->pluginEnable()) {
|
||||
return parent::apply($request);
|
||||
}
|
||||
$this->currentId = $request->getParam('id');
|
||||
$this->isSearch = (bool)$request->getParam('q');
|
||||
$categoryId = $request->getParam($this->_requestVar) ?: $this->currentId;
|
||||
if (empty($categoryId)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$categoryIds = explode(',', $categoryId);
|
||||
$categoryIds = array_unique($categoryIds);
|
||||
$this->setCurrentValue($categoryIds);
|
||||
|
||||
/** @var Collection $productCollection */
|
||||
$productCollection = $this->getProductCollection();
|
||||
if ($this->isMultiselect() && count($categoryIds) > 1) {
|
||||
$productCollection->addIndexCategoriesFilter(['in' => $categoryIds]);
|
||||
$category = $this->getLayer()->getCurrentCategory();
|
||||
$child = $category->getCollection()
|
||||
->addFieldToFilter($category->getIdFieldName(), ['in' => $categoryIds])
|
||||
->addAttributeToSelect('name');
|
||||
if ($this->shouldAddState()) {
|
||||
$this->addState($categoryIds, $child);
|
||||
}
|
||||
} else {
|
||||
$this->dataProvider->setCategoryId($categoryId);
|
||||
$productCollection->addCategoryFilter($this->dataProvider->getCategory());
|
||||
if ($this->shouldAddState()) {
|
||||
$this->addState();
|
||||
}
|
||||
}
|
||||
|
||||
if (!$this->shouldVisible()) {
|
||||
$this->setItems([]); // set items to disable show filtering
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function pluginEnable()
|
||||
{
|
||||
return (bool)$this->_helper->isEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $attributeValues
|
||||
*/
|
||||
protected function setCurrentValue(array $attributeValues)
|
||||
{
|
||||
$this->attributeValues = $attributeValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Magento\Catalog\Model\ResourceModel\Product\Collection
|
||||
*/
|
||||
protected function getProductCollection()
|
||||
{
|
||||
return $this->getLayer()->getProductCollection();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
protected function isMultiselect()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
protected function shouldAddState()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $values
|
||||
* @param null $child
|
||||
*/
|
||||
protected function addState($values = [], $child = null)
|
||||
{
|
||||
if ($child) {
|
||||
$labels = [];
|
||||
foreach ((array)$values as $value) {
|
||||
if ($currentCategory = $child->getItemById($value)) {
|
||||
$labels[$currentCategory->getId()] = $currentCategory->getName();
|
||||
}
|
||||
}
|
||||
foreach ($labels as $id => $categoryName) {
|
||||
$state = $this->_createItem($categoryName, $id);
|
||||
$this->getLayer()->getState()->addFilter($state);
|
||||
}
|
||||
} else {
|
||||
$category = $this->dataProvider->getCategory();
|
||||
if ($this->getCurrentCategoryId() != $category->getId() && $this->dataProvider->isValid()) {
|
||||
$state = $this->_createItem($category->getName(), $category->getId());
|
||||
$this->getLayer()->getState()->addFilter($state);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function getCurrentCategoryId()
|
||||
{
|
||||
return $this->currentId ?: $this->getStore()->getRootCategoryId(); //$this->getRootCategory()->getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return StoreInterface
|
||||
* @throws NoSuchEntityException
|
||||
*/
|
||||
private function getStore()
|
||||
{
|
||||
return $this->storeManager->getStore();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
protected function shouldVisible()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function _getItemsData()
|
||||
{
|
||||
if (!$this->pluginEnable()) {
|
||||
return parent::_getItemsData();
|
||||
}
|
||||
|
||||
$optionsFacetedData = $this->getOptionsFacetedData();
|
||||
$this->dataProvider->setCategoryId($this->getCurrentCategoryId());
|
||||
$categories = $this->getCategoryTree($this->dataProvider->getCategory());
|
||||
foreach ($categories as $key => $category) {
|
||||
if (isset($optionsFacetedData[$key])) {
|
||||
$categories[$key]['count'] = $optionsFacetedData[$key]['count'];
|
||||
$path = explode('/', $category['path']);
|
||||
foreach ($path as $id) {
|
||||
if (array_key_exists($id, $categories)) {
|
||||
$categories[$id]['use'] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$categories = array_filter($categories, [$this, 'filterCategory']);
|
||||
|
||||
return $categories;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize filter items
|
||||
*
|
||||
* @return \Magento\Catalog\Model\Layer\Filter\AbstractFilter
|
||||
*/
|
||||
protected function _initItems()
|
||||
{
|
||||
$data = $this->_getItemsData();
|
||||
$items = [];
|
||||
foreach ($data as $itemData) {
|
||||
$items[] = $this->_createItem(
|
||||
$itemData['label'],
|
||||
$itemData['value'],
|
||||
$itemData['count']
|
||||
)
|
||||
->setData('item_level', isset($itemData['item_level']) ? $itemData['item_level'] : 0)
|
||||
->setData('path', isset($itemData['path']) ? $itemData['path'] : '');
|
||||
}
|
||||
$this->_items = $items;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
protected function getOptionsFacetedData()
|
||||
{
|
||||
return $this->generateOptionsFacetedData();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @noinspection PhpRedundantCatchClauseInspection
|
||||
*/
|
||||
protected function generateOptionsFacetedData()
|
||||
{
|
||||
$productCollection = $this->getProductCollection();
|
||||
$attributeCode = static::FILTER_CODE;
|
||||
try {
|
||||
$optionsFacetedData = $productCollection->getFacetedData(
|
||||
$attributeCode,
|
||||
$this->getAlteredQueryResponse()
|
||||
);
|
||||
} catch (StateException $e) {
|
||||
if (!$this->messageManager->hasMessages()) {
|
||||
$this->messageManager->addErrorMessage(
|
||||
__('Make sure that "%1" attribute can be used in layered navigation', $attributeCode)
|
||||
);
|
||||
}
|
||||
$optionsFacetedData = [];
|
||||
}
|
||||
|
||||
return $optionsFacetedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return QueryResponse|ResponseInterface|null
|
||||
*/
|
||||
protected function getAlteredQueryResponse()
|
||||
{
|
||||
$alteredQueryResponse = null;
|
||||
$categoryIds = $this->getCurrentValue();
|
||||
$categoryId = !empty($categoryIds) ? $categoryIds[0] : null;
|
||||
if ($this->hasCurrentValue() && $categoryId != $this->getCurrentCategoryId()) {
|
||||
try {
|
||||
$requestBuilder = $this->getRequestBuilder();
|
||||
if (!$requestBuilder) {
|
||||
return $alteredQueryResponse;
|
||||
}
|
||||
$queryRequest = $requestBuilder->create();
|
||||
$alteredQueryResponse = $this->searchEngine->search($queryRequest);
|
||||
} catch (Exception $e) {
|
||||
$alteredQueryResponse = null;
|
||||
}
|
||||
}
|
||||
return $alteredQueryResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
protected function getCurrentValue()
|
||||
{
|
||||
return $this->attributeValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasCurrentValue()
|
||||
{
|
||||
return !empty($this->attributeValues);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder|null
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function getRequestBuilder()
|
||||
{
|
||||
$requestBuilder = $this->getMemRequestBuilder();
|
||||
if (!$requestBuilder) {
|
||||
return null;
|
||||
}
|
||||
$attributeCode = static::ATTRIBUTE_CODE;
|
||||
$requestBuilder->removePlaceholder($attributeCode);
|
||||
$requestBuilder->bind($attributeCode, $this->getCurrentCategoryId());
|
||||
$requestBuilder->setAggregationsOnly($attributeCode);
|
||||
|
||||
return $requestBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder|null
|
||||
*/
|
||||
private function getMemRequestBuilder()
|
||||
{
|
||||
$productCollection = $this->getProductCollection();
|
||||
if (method_exists($productCollection, 'getMemRequestBuilder')) {
|
||||
return clone $productCollection->getMemRequestBuilder();
|
||||
}
|
||||
$this->_helper->_loadObject(LoggerInterface::class)
|
||||
->error(__('Invalid class for product collection: ') . get_class($productCollection));
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param CategoryModel $category
|
||||
* @param int $level
|
||||
* @return array
|
||||
*/
|
||||
private function getCategoryTree($category, $level = 0)
|
||||
{
|
||||
$result = [];
|
||||
if ($category->getIsActive()) {
|
||||
$categories = $category->getChildrenCategories();
|
||||
foreach ($categories as $category) {
|
||||
if ($category->getIsActive()) {
|
||||
$id = $category->getId();
|
||||
$result[$id] = [
|
||||
'label' => $this->escaper->escapeHtml($category->getName()),
|
||||
'value' => $id,
|
||||
'item_level' => $level,
|
||||
'path' => $category->getPath(),
|
||||
'count' => 0,
|
||||
];
|
||||
if ($this->getMaxDepth() > $level) {
|
||||
$subItem = $this->getCategoryTree($category, $level + 1);
|
||||
foreach ($subItem as $key => $item) {
|
||||
$result[$key] = $item;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $item
|
||||
* @return bool
|
||||
*/
|
||||
public function filterCategory($item)
|
||||
{
|
||||
return is_array($item) && array_key_exists('use', $item);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $filterItem
|
||||
* @return bool
|
||||
*/
|
||||
public function getIsDisableAjax($filterItem)
|
||||
{
|
||||
$categoryItem = $this->getCategoryItem($filterItem);
|
||||
return $categoryItem->getData('ox_nav_disable_ajax') || !$categoryItem->getIsAnchor();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $filterItem
|
||||
* @return mixed
|
||||
*/
|
||||
private function getCategoryItem($filterItem)
|
||||
{
|
||||
$value = $filterItem->getValue();
|
||||
if (!array_key_exists($value, $this->categorys)) {
|
||||
$category = clone $this->category;
|
||||
$this->categorys[$value] = $category->load($value);
|
||||
}
|
||||
|
||||
return $this->categorys[$value];
|
||||
}
|
||||
|
||||
/** @noinspection PhpDeprecationInspection */
|
||||
|
||||
/**
|
||||
* @param $filterItem
|
||||
* @return mixed
|
||||
*/
|
||||
public function getUrlItem($filterItem)
|
||||
{
|
||||
return $this->getCategoryItem($filterItem)->getUrl();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\Layer\Filter;
|
||||
|
||||
use Exception;
|
||||
use Magento\Catalog\Model\Layer;
|
||||
use Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory;
|
||||
use Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory;
|
||||
use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder;
|
||||
use Magento\Catalog\Model\Layer\Filter\ItemFactory;
|
||||
use Magento\Catalog\Model\ResourceModel\Product\Collection;
|
||||
use Magento\Customer\Model\Session;
|
||||
use Magento\Directory\Model\Currency;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Exception\NoSuchEntityException;
|
||||
use Magento\Framework\Exception\StateException;
|
||||
use Magento\Framework\Message\ManagerInterface;
|
||||
use Magento\Framework\Pricing\PriceCurrencyInterface;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\Framework\Search\Dynamic\Algorithm;
|
||||
use Magento\Framework\Search\Response\QueryResponse;
|
||||
use Magento\Framework\Search\ResponseInterface;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Search\Model\SearchEngine;
|
||||
use Magento\Store\Model\Store;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Olegnax\LayeredNavigation\Helper\Helper;
|
||||
use Olegnax\LayeredNavigation\Model\Request\Builder;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class Price extends \Magento\CatalogSearch\Model\Layer\Filter\Price
|
||||
{
|
||||
|
||||
/**
|
||||
* @var Helper
|
||||
*/
|
||||
protected $_helper;
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $attributeValues = [];
|
||||
/**
|
||||
* @var Registry
|
||||
*/
|
||||
protected $coreRegistry;
|
||||
/**
|
||||
* @var ManagerInterface
|
||||
*/
|
||||
protected $messageManager;
|
||||
/**
|
||||
* @var SearchEngine
|
||||
*/
|
||||
protected $searchEngine;
|
||||
/**
|
||||
* @var ScopeConfigInterface
|
||||
*/
|
||||
protected $scopeConfig;
|
||||
/**
|
||||
* @var Json
|
||||
*/
|
||||
protected $json;
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $currencySymbol;
|
||||
/**
|
||||
* @var Layer\Filter\DataProvider\Price
|
||||
*/
|
||||
private $dataProvider;
|
||||
|
||||
/**
|
||||
* Price constructor.
|
||||
* @param ItemFactory $filterItemFactory
|
||||
* @param StoreManagerInterface $storeManager
|
||||
* @param Layer $layer
|
||||
* @param DataBuilder $itemDataBuilder
|
||||
* @param \Magento\Catalog\Model\ResourceModel\Layer\Filter\Price $resource
|
||||
* @param Session $customerSession
|
||||
* @param Algorithm $priceAlgorithm
|
||||
* @param PriceCurrencyInterface $priceCurrency
|
||||
* @param AlgorithmFactory $algorithmFactory
|
||||
* @param PriceFactory $dataProviderFactory
|
||||
* @param Helper $helper
|
||||
* @param Registry $coreRegistry
|
||||
* @param SearchEngine $searchEngine
|
||||
* @param ManagerInterface $messageManager
|
||||
* @param ScopeConfigInterface $scopeConfig
|
||||
* @param Json $json
|
||||
* @param array $data
|
||||
* @noinspection PhpDeprecationInspection
|
||||
*/
|
||||
public function __construct(
|
||||
ItemFactory $filterItemFactory,
|
||||
StoreManagerInterface $storeManager,
|
||||
Layer $layer,
|
||||
DataBuilder $itemDataBuilder,
|
||||
\Magento\Catalog\Model\ResourceModel\Layer\Filter\Price $resource,
|
||||
Session $customerSession,
|
||||
Algorithm $priceAlgorithm,
|
||||
PriceCurrencyInterface $priceCurrency,
|
||||
AlgorithmFactory $algorithmFactory,
|
||||
PriceFactory $dataProviderFactory,
|
||||
Helper $helper,
|
||||
Registry $coreRegistry,
|
||||
SearchEngine $searchEngine,
|
||||
ManagerInterface $messageManager,
|
||||
ScopeConfigInterface $scopeConfig,
|
||||
Json $json,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct(
|
||||
$filterItemFactory,
|
||||
$storeManager,
|
||||
$layer,
|
||||
$itemDataBuilder,
|
||||
$resource,
|
||||
$customerSession,
|
||||
$priceAlgorithm,
|
||||
$priceCurrency,
|
||||
$algorithmFactory,
|
||||
$dataProviderFactory,
|
||||
$data
|
||||
);
|
||||
$this->_helper = $helper;
|
||||
$this->dataProvider = $dataProviderFactory->create(['layer' => $layer]);
|
||||
$this->coreRegistry = $coreRegistry;
|
||||
$this->searchEngine = $searchEngine;
|
||||
$this->messageManager = $messageManager;
|
||||
$this->scopeConfig = $scopeConfig;
|
||||
$this->json = $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param RequestInterface $request
|
||||
* @return $this|Price
|
||||
*/
|
||||
public function apply(RequestInterface $request)
|
||||
{
|
||||
if (!$this->pluginEnable()) {
|
||||
return parent::apply($request);
|
||||
}
|
||||
|
||||
$filter = $request->getParam($this->getRequestVar());
|
||||
if (empty($filter)) {
|
||||
return $this;
|
||||
}
|
||||
if (is_string($filter)) {
|
||||
$filter = explode(',', $filter);
|
||||
}
|
||||
$filterParams = $filter;
|
||||
|
||||
$filter = $this->dataProvider->validateFilter($filterParams[0]);
|
||||
if (!$filter) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->setCurrentValue($filter);
|
||||
$this->dataProvider->setInterval($filter);
|
||||
$priorFilters = $this->dataProvider->getPriorFilters($filterParams);
|
||||
if ($priorFilters) {
|
||||
$this->dataProvider->setPriorIntervals($priorFilters);
|
||||
}
|
||||
|
||||
[$from, $to] = $filter;
|
||||
|
||||
$this->getProductCollection()->addFieldToFilter(
|
||||
'price',
|
||||
[
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
]
|
||||
);
|
||||
if ($this->shouldAddState()) {
|
||||
$this->addState($filter);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function pluginEnable()
|
||||
{
|
||||
return (bool)$this->_helper->isEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $attributeValues
|
||||
*/
|
||||
protected function setCurrentValue(array $attributeValues)
|
||||
{
|
||||
$this->attributeValues = $attributeValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection
|
||||
*/
|
||||
protected function getProductCollection()
|
||||
{
|
||||
return $this->getLayer()->getProductCollection();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function shouldAddState()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $values
|
||||
*/
|
||||
protected function addState($values)
|
||||
{
|
||||
[$from, $to] = $values;
|
||||
$label = $this->_renderRangeLabel(empty($from) ? 0 : $from, $to);
|
||||
$item = $this->_createItem($label, $values);
|
||||
$this->getLayer()->getState()
|
||||
->addFilter(
|
||||
$item
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function getIsSlider()
|
||||
{
|
||||
return $this->pluginEnable() && $this->_helper->isPriceSlider();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool|false|string
|
||||
* @throws LocalizedException
|
||||
* @throws NoSuchEntityException
|
||||
*/
|
||||
public function getSliderConfig()
|
||||
{
|
||||
/** @var Collection $productCollection */
|
||||
$productCollection = $this->getProductCollection();
|
||||
$format = explode('%s', $this->getOutputFormat());
|
||||
if (2 != count($format)) {
|
||||
$format = [
|
||||
$this->getCurrencySymbol(),
|
||||
''
|
||||
];
|
||||
}
|
||||
$config = [
|
||||
"min" => $productCollection->getMinPrice(),
|
||||
"max" => $productCollection->getMaxPrice(),
|
||||
"step" => 1,
|
||||
"formatMoney" => [
|
||||
"prefix" => $format[0] ?: '',
|
||||
"suffix" => $format[1] ?: '',
|
||||
],
|
||||
];
|
||||
|
||||
return $this->json->serialize($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws LocalizedException
|
||||
* @throws NoSuchEntityException
|
||||
*/
|
||||
public function getCurrencySymbol()
|
||||
{
|
||||
if (empty($this->currencySymbol)) {
|
||||
$this->currencySymbol = $this->getCurrentCurrency()->getCurrencySymbol();
|
||||
}
|
||||
|
||||
return $this->currencySymbol;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Currency
|
||||
* @throws LocalizedException
|
||||
* @throws NoSuchEntityException
|
||||
*/
|
||||
public function getCurrentCurrency()
|
||||
{
|
||||
/** @var Store $store */
|
||||
$store = $this->_storeManager->getStore();
|
||||
/** @var Currency $currentCurrency */
|
||||
$currentCurrency = $store->getCurrentCurrency();
|
||||
return $currentCurrency;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws LocalizedException
|
||||
* @throws NoSuchEntityException
|
||||
*/
|
||||
public function getOutputFormat()
|
||||
{
|
||||
return $this->getCurrentCurrency()->getOutputFormat();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
protected function getCurrentValue()
|
||||
{
|
||||
return $this->attributeValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function _getItemsData()
|
||||
{
|
||||
if (!$this->_helper->isEnabled()) {
|
||||
return parent::_getItemsData();
|
||||
}
|
||||
|
||||
if ($this->hasCurrentValue() && !$this->shouldVisible()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$facets = $this->getFacetedData();
|
||||
|
||||
$data = [];
|
||||
if (count($facets) > 1) { // two range minimum
|
||||
$lastFacet = array_key_last($facets);
|
||||
foreach ($facets as $key => $aggregation) {
|
||||
$count = $aggregation['count'];
|
||||
if (strpos($key, '_') === false) {
|
||||
continue;
|
||||
}
|
||||
$isLast = $lastFacet === $key;
|
||||
$data[] = $this->prepareData($key, $count, $isLast);
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasCurrentValue()
|
||||
{
|
||||
return !empty($this->attributeValues);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
protected function shouldVisible()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
* @noinspection PhpDeprecationInspection
|
||||
*/
|
||||
protected function getFacetedData()
|
||||
{
|
||||
$key = 'facet_price_' . $this->getRequestVar();
|
||||
if ($this->coreRegistry->registry($key) === null) {
|
||||
$this->coreRegistry->register($key, $this->generateFacetedData());
|
||||
}
|
||||
|
||||
return $this->coreRegistry->registry($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
* @noinspection PhpRedundantCatchClauseInspection
|
||||
*/
|
||||
protected function generateFacetedData()
|
||||
{
|
||||
$productCollection = $this->getProductCollection();
|
||||
$attribute = $this->getAttributeModel();
|
||||
$attributeCode = $attribute->getAttributeCode();
|
||||
try {
|
||||
$facetedData = $productCollection->getFacetedData(
|
||||
$attributeCode,
|
||||
$this->getAlteredQueryResponse()
|
||||
);
|
||||
} catch (StateException $e) {
|
||||
if (!$this->messageManager->hasMessages()) {
|
||||
$this->messageManager->addErrorMessage(
|
||||
__('Make sure that "%1" attribute can be used in layered navigation', $attributeCode)
|
||||
);
|
||||
}
|
||||
$facetedData = [];
|
||||
}
|
||||
|
||||
return $facetedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return QueryResponse|ResponseInterface|null
|
||||
*/
|
||||
protected function getAlteredQueryResponse()
|
||||
{
|
||||
$alteredQueryResponse = null;
|
||||
if ($this->hasCurrentValue() &&
|
||||
$this->scopeConfig->getValue(AlgorithmFactory::XML_PATH_RANGE_CALCULATION) !=
|
||||
AlgorithmFactory::RANGE_CALCULATION_IMPROVED) {
|
||||
try {
|
||||
$requestBuilder = $this->getRequestBuilder();
|
||||
if (!$requestBuilder) {
|
||||
return $alteredQueryResponse;
|
||||
}
|
||||
$queryRequest = $requestBuilder->create();
|
||||
$alteredQueryResponse = $this->searchEngine->search($queryRequest);
|
||||
} catch (Exception $e) {
|
||||
$alteredQueryResponse = null;
|
||||
}
|
||||
}
|
||||
return $alteredQueryResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder|null
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function getRequestBuilder()
|
||||
{
|
||||
$requestBuilder = $this->getMemRequestBuilder();
|
||||
if (!$requestBuilder) {
|
||||
return null;
|
||||
}
|
||||
$attributeCode = $this->getAttributeModel()->getAttributeCode();
|
||||
$requestBuilder->removePlaceholder($attributeCode . '.from');
|
||||
$requestBuilder->removePlaceholder($attributeCode . '.to');
|
||||
$requestBuilder->setAggregationsOnly($attributeCode);
|
||||
|
||||
return $requestBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder|null
|
||||
*/
|
||||
private function getMemRequestBuilder()
|
||||
{
|
||||
$productCollection = $this->getProductCollection();
|
||||
if (method_exists($productCollection, 'getMemRequestBuilder')) {
|
||||
return clone $productCollection->getMemRequestBuilder();
|
||||
}
|
||||
$this->_helper->_loadObject(LoggerInterface::class)
|
||||
->error(__('Invalid class for product collection: ') . get_class($productCollection));
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param int $count
|
||||
* @return array
|
||||
*/
|
||||
private function prepareData($key, $count, $isLast = false)
|
||||
{
|
||||
[$from, $to] = explode('_', $key);
|
||||
$label = $this->_renderRangeLabel(
|
||||
empty($from) ? 0 : $from * $this->getCurrencyRate(), // @todo may need to be removed * $this->getCurrencyRate()
|
||||
$to * $this->getCurrencyRate(), // @todo may need to be removed * $this->getCurrencyRate()
|
||||
$isLast
|
||||
);
|
||||
$value = $from . '-' . $to . $this->dataProvider->getAdditionalRequestData();
|
||||
|
||||
$data = [
|
||||
'label' => $label,
|
||||
'value' => $value,
|
||||
'count' => $count,
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
];
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\Request;
|
||||
|
||||
|
||||
use Magento\Framework\App\Request\Http;
|
||||
use Magento\Framework\ObjectManagerInterface;
|
||||
use Magento\Framework\Search\Request\Binder;
|
||||
use Magento\Framework\Search\Request\Cleaner;
|
||||
use Magento\Framework\Search\Request\Config;
|
||||
use Magento\Framework\Search\RequestInterface;
|
||||
use ReflectionClass;
|
||||
|
||||
class Builder extends \Magento\Framework\Search\Request\Builder
|
||||
{
|
||||
/**
|
||||
* @var Http
|
||||
*/
|
||||
protected $requestHttp;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $dataPlaceholders = [];
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $baseCategory;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $aggregationsOnly = [];
|
||||
|
||||
public function __construct(
|
||||
ObjectManagerInterface $objectManager,
|
||||
Config $config,
|
||||
Binder $binder,
|
||||
Cleaner $cleaner,
|
||||
Http $requestHttp
|
||||
) {
|
||||
$this->requestHttp = $requestHttp;
|
||||
parent::__construct($objectManager, $config, $binder, $cleaner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $placeholder
|
||||
* @param mixed $value
|
||||
* @return Builder
|
||||
*/
|
||||
public function bind($placeholder, $value)
|
||||
{
|
||||
$this->dataPlaceholders[$placeholder] = $placeholder == 'category_ids'
|
||||
? $this->getPlaceholderCategory($placeholder, $value)
|
||||
: $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $placeholder
|
||||
* @param $value
|
||||
* @return array
|
||||
*/
|
||||
public function getPlaceholderCategory($placeholder, $value)
|
||||
{
|
||||
if (!$this->baseCategory) {
|
||||
$this->baseCategory = $this->requestHttp->getParam('id') ?: $value;
|
||||
}
|
||||
|
||||
if (isset($this->dataPlaceholders[$placeholder])
|
||||
&& $this->dataPlaceholders[$placeholder] !== $value) {
|
||||
$value = $this->getPlaceholderCategoryList($this->dataPlaceholders[$placeholder], $value);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $placeholders
|
||||
* @param $value
|
||||
* @return array
|
||||
*/
|
||||
public function getPlaceholderCategoryList($placeholders, $value)
|
||||
{
|
||||
$placeholders = array_merge((array)$placeholders, (array)$value);
|
||||
$placeholders = array_unique($placeholders);
|
||||
$placeholders = array_diff($placeholders, (array)$this->baseCategory);
|
||||
$placeholders = array_values($placeholders);
|
||||
|
||||
return $placeholders;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return RequestInterface
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function create()
|
||||
{
|
||||
$this->applyPlaceholders();
|
||||
$request = parent::create();
|
||||
$this->removeAggregations($request);
|
||||
return $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
protected function applyPlaceholders()
|
||||
{
|
||||
foreach ($this->dataPlaceholders as $key => $value) {
|
||||
parent::bind($key, $value);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $request
|
||||
* @return $this
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
private function removeAggregations($request)
|
||||
{
|
||||
if (!empty($this->aggregationsOnly)) {
|
||||
$buckets = $request->getAggregation();
|
||||
foreach ($buckets as $key => $bucket) {
|
||||
if (!in_array($bucket->getField(), $this->aggregationsOnly)) {
|
||||
unset($buckets[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
$reflection = new ReflectionClass($request);
|
||||
$bucketProperty = $reflection->getProperty('buckets');
|
||||
$bucketProperty->setAccessible(true);
|
||||
$bucketProperty->setValue($request, $buckets);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $code
|
||||
* @return $this
|
||||
*/
|
||||
public function setAggregationsOnly($code)
|
||||
{
|
||||
if (!is_array($code)) {
|
||||
$code = [$code];
|
||||
}
|
||||
$this->aggregationsOnly = $code;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $placeholder
|
||||
* @return $this
|
||||
*/
|
||||
public function removePlaceholder($placeholder)
|
||||
{
|
||||
if (array_key_exists($placeholder, $this->dataPlaceholders)) {
|
||||
unset($this->dataPlaceholders[$placeholder]);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $placeholder
|
||||
* @return bool
|
||||
*/
|
||||
public function hasPlaceholder($placeholder)
|
||||
{
|
||||
return array_key_exists($placeholder, $this->dataPlaceholders);
|
||||
}
|
||||
|
||||
}
|
||||
+478
@@ -0,0 +1,478 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\ResourceModel\Fulltext;
|
||||
|
||||
use Magento\Catalog\Model\Category;
|
||||
use Magento\Catalog\Model\Indexer\Product\Flat\State;
|
||||
use Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory;
|
||||
use Magento\Catalog\Model\Product\OptionFactory;
|
||||
use Magento\Catalog\Model\ResourceModel\Helper;
|
||||
use Magento\Catalog\Model\ResourceModel\Url;
|
||||
use Magento\CatalogInventory\Helper\Stock;
|
||||
use Magento\Customer\Api\GroupManagementInterface;
|
||||
use Magento\Customer\Model\Session;
|
||||
use Magento\Eav\Model\Config;
|
||||
use Magento\Eav\Model\EntityFactory;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\App\ProductMetadataInterface;
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Data\Collection\Db\FetchStrategyInterface;
|
||||
use Magento\Framework\DB\Select;
|
||||
use Magento\Framework\Event\ManagerInterface;
|
||||
use Magento\Framework\Exception\StateException;
|
||||
use Magento\Framework\Module\Manager;
|
||||
use Magento\Framework\Phrase;
|
||||
use Magento\Framework\Search\Adapter\Mysql\TemporaryStorage;
|
||||
use Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory;
|
||||
use Magento\Framework\Search\Response\QueryResponse;
|
||||
use Magento\Framework\Stdlib\DateTime;
|
||||
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
|
||||
use Magento\Framework\Validator\UniversalFactory;
|
||||
use Magento\Search\Model\QueryFactory;
|
||||
use Magento\Search\Model\SearchEngine;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Olegnax\LayeredNavigation\Model\Request\Builder;
|
||||
use Olegnax\LayeredNavigation\Model\Request\BuilderFactory;
|
||||
//use Magento\Framework\Search\Request\Builder;
|
||||
//use Magento\Framework\Search\Request\BuilderFactory;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Fulltext Collection
|
||||
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
|
||||
*/
|
||||
class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection
|
||||
{
|
||||
/**
|
||||
* @var QueryResponse
|
||||
*/
|
||||
private $queryResponse;
|
||||
|
||||
/**
|
||||
* Catalog search data
|
||||
*
|
||||
* @var QueryFactory
|
||||
*/
|
||||
private $queryFactory = null;
|
||||
|
||||
/**
|
||||
* @var Builder
|
||||
*/
|
||||
private $requestBuilder;
|
||||
|
||||
/**
|
||||
* @var SearchEngine
|
||||
*/
|
||||
private $searchEngine;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $queryText;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
private $relevanceOrderDirection;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $searchRequestName;
|
||||
|
||||
/**
|
||||
* @var TemporaryStorageFactory
|
||||
*/
|
||||
private $temporaryStorageFactory;
|
||||
|
||||
/**
|
||||
* @var Stock
|
||||
*/
|
||||
private $stockHelper;
|
||||
|
||||
/**
|
||||
* @var Builder
|
||||
*/
|
||||
private $memRequestBuilder;
|
||||
|
||||
/**
|
||||
* @var ProductMetadataInterface
|
||||
*/
|
||||
private $productMetadata;
|
||||
|
||||
/**
|
||||
* Collection constructor.
|
||||
* @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory
|
||||
* @param LoggerInterface $logger
|
||||
* @param FetchStrategyInterface $fetchStrategy
|
||||
* @param ManagerInterface $eventManager
|
||||
* @param Config $eavConfig
|
||||
* @param ResourceConnection $resource
|
||||
* @param EntityFactory $eavEntityFactory
|
||||
* @param Helper $resourceHelper
|
||||
* @param UniversalFactory $universalFactory
|
||||
* @param StoreManagerInterface $storeManager
|
||||
* @param Manager $moduleManager
|
||||
* @param State $catalogProductFlatState
|
||||
* @param ScopeConfigInterface $scopeConfig
|
||||
* @param OptionFactory $productOptionFactory
|
||||
* @param Url $catalogUrl
|
||||
* @param TimezoneInterface $localeDate
|
||||
* @param Session $customerSession
|
||||
* @param DateTime $dateTime
|
||||
* @param GroupManagementInterface $groupManagement
|
||||
* @param QueryFactory $queryFactory
|
||||
* @param BuilderFactory $requestBuilderFactory
|
||||
* @param SearchEngine $searchEngine
|
||||
* @param TemporaryStorageFactory $temporaryStorageFactory
|
||||
* @param ProductMetadataInterface $productMetadata
|
||||
* @param Stock $stockHelper
|
||||
* @param null $connection
|
||||
* @param string $searchRequestName
|
||||
*/
|
||||
public function __construct(
|
||||
\Magento\Framework\Data\Collection\EntityFactory $entityFactory,
|
||||
LoggerInterface $logger,
|
||||
FetchStrategyInterface $fetchStrategy,
|
||||
ManagerInterface $eventManager,
|
||||
Config $eavConfig,
|
||||
ResourceConnection $resource,
|
||||
EntityFactory $eavEntityFactory,
|
||||
Helper $resourceHelper,
|
||||
UniversalFactory $universalFactory,
|
||||
StoreManagerInterface $storeManager,
|
||||
Manager $moduleManager,
|
||||
State $catalogProductFlatState,
|
||||
ScopeConfigInterface $scopeConfig,
|
||||
OptionFactory $productOptionFactory,
|
||||
Url $catalogUrl,
|
||||
TimezoneInterface $localeDate,
|
||||
Session $customerSession,
|
||||
DateTime $dateTime,
|
||||
GroupManagementInterface $groupManagement,
|
||||
QueryFactory $queryFactory,
|
||||
BuilderFactory $requestBuilderFactory,
|
||||
SearchEngine $searchEngine,
|
||||
TemporaryStorageFactory $temporaryStorageFactory,
|
||||
ProductMetadataInterface $productMetadata,
|
||||
Stock $stockHelper,
|
||||
$connection = null,
|
||||
$searchRequestName = 'catalog_view_container'
|
||||
) {
|
||||
$this->queryFactory = $queryFactory;
|
||||
$this->searchRequestName = $searchRequestName;
|
||||
parent::__construct(
|
||||
$entityFactory,
|
||||
$logger,
|
||||
$fetchStrategy,
|
||||
$eventManager,
|
||||
$eavConfig,
|
||||
$resource,
|
||||
$eavEntityFactory,
|
||||
$resourceHelper,
|
||||
$universalFactory,
|
||||
$storeManager,
|
||||
$moduleManager,
|
||||
$catalogProductFlatState,
|
||||
$scopeConfig,
|
||||
$productOptionFactory,
|
||||
$catalogUrl,
|
||||
$localeDate,
|
||||
$customerSession,
|
||||
$dateTime,
|
||||
$groupManagement,
|
||||
$connection
|
||||
);
|
||||
|
||||
$this->requestBuilder = $requestBuilderFactory->create();
|
||||
$this->searchEngine = $searchEngine;
|
||||
$this->temporaryStorageFactory = $temporaryStorageFactory;
|
||||
$this->stockHelper = $stockHelper;
|
||||
$this->productMetadata = $productMetadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add search query filter
|
||||
*
|
||||
* @param string $query
|
||||
* @return $this
|
||||
*/
|
||||
public function addSearchFilter($query)
|
||||
{
|
||||
$this->queryText = trim($this->queryText . ' ' . $query);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function setRequestData($builder)
|
||||
{
|
||||
$this->_select->reset();
|
||||
$this->requestBuilder = $builder;
|
||||
$this->queryResponse = null;
|
||||
$this->_isFiltersRendered = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder
|
||||
*/
|
||||
public function getMemRequestBuilder()
|
||||
{
|
||||
if ($this->memRequestBuilder === null) {
|
||||
$this->memRequestBuilder = clone $this->requestBuilder;
|
||||
$this->memRequestBuilder->bindDimension('scope', $this->getStoreId());
|
||||
if ($this->queryText) {
|
||||
$this->memRequestBuilder->bind('search_term', $this->queryText);
|
||||
}
|
||||
|
||||
$priceRangeCalculation = $this->_scopeConfig->getValue(
|
||||
AlgorithmFactory::XML_PATH_RANGE_CALCULATION,
|
||||
ScopeInterface::SCOPE_STORE
|
||||
);
|
||||
if (is_null($priceRangeCalculation)) {
|
||||
$priceRangeCalculation = '';
|
||||
}
|
||||
if ($priceRangeCalculation) {
|
||||
$this->memRequestBuilder->bind('price_dynamic_algorithm', $priceRangeCalculation);
|
||||
}
|
||||
|
||||
$this->memRequestBuilder->setRequestName($this->searchRequestName);
|
||||
}
|
||||
return $this->memRequestBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stub method for compatibility with other search engines
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setGeneralDefaultQuery()
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field
|
||||
* @param QueryResponse|null $response
|
||||
* @return array
|
||||
*/
|
||||
public function getFacetedData($field, QueryResponse $response = null)
|
||||
{
|
||||
if (!$response) {
|
||||
$this->_renderFilters();
|
||||
$response = $this->queryResponse;
|
||||
}
|
||||
|
||||
$aggregations = $response->getAggregations();
|
||||
$bucket = $aggregations->getBucket($field . '_bucket');
|
||||
$result = [];
|
||||
if (!$bucket) {
|
||||
throw new StateException(__('Bucket does not exist'));
|
||||
}
|
||||
|
||||
foreach ($bucket->getValues() as $value) {
|
||||
$metrics = $value->getMetrics();
|
||||
$result[$metrics['value']] = $metrics;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
protected function _renderFilters()
|
||||
{
|
||||
$this->_filters = [];
|
||||
return parent::_renderFilters();
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify category filter for product collection
|
||||
*
|
||||
* @param Category $category
|
||||
* @return $this
|
||||
*/
|
||||
public function addCategoryFilter(Category $category)
|
||||
{
|
||||
$this->addFieldToFilter('category_ids', $category->getId());
|
||||
return parent::addCategoryFilter($category);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply attribute filter to facet collection
|
||||
*
|
||||
* @param string $field
|
||||
* @param null $condition
|
||||
* @return $this
|
||||
*/
|
||||
public function addFieldToFilter($field, $condition = null)
|
||||
{
|
||||
if ($this->queryResponse !== null) {
|
||||
throw new RuntimeException('Illegal state');
|
||||
}
|
||||
|
||||
if (!is_array($condition) || !in_array(key($condition), ['from', 'to'], true)) {
|
||||
// See app/code/Magento/Catalog/Model/ResourceModel/Product/Indexer/Eav/AbstractEav::_getIndexableAttributesCondition()
|
||||
// Visibility filter wasn't in index before 2.2
|
||||
if ($field != 'visibility'
|
||||
|| version_compare($this->productMetadata->getVersion(), '2.2.0', '>=')) {
|
||||
$this->requestBuilder->bind($field, $condition);
|
||||
}
|
||||
} else {
|
||||
if (!empty($condition['from'])) {
|
||||
$this->requestBuilder->bind("{$field}.from", $condition['from']);
|
||||
}
|
||||
if (!empty($condition['to'])) {
|
||||
$this->requestBuilder->bind("{$field}.to", $condition['to']);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set product visibility filter for enabled products
|
||||
*
|
||||
* @param array $visibility
|
||||
* @return $this
|
||||
*/
|
||||
public function setVisibility($visibility)
|
||||
{
|
||||
$this->addFieldToFilter('visibility', $visibility);
|
||||
return parent::setVisibility($visibility);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter Product by Categories using index table
|
||||
*
|
||||
* @param array $categoriesFilter
|
||||
* @return $this
|
||||
*/
|
||||
public function addIndexCategoriesFilter(array $categoriesFilter)
|
||||
{
|
||||
foreach ($categoriesFilter as $conditionType => $values) {
|
||||
$categorySelect = $this->getConnection()->select()->from(
|
||||
['cat' => $this->getTable('catalog_category_product_index')],
|
||||
'cat.product_id'
|
||||
)->where($this->getConnection()->prepareSqlCondition('cat.category_id', ['in' => $values]));
|
||||
$selectCondition = [
|
||||
$this->mapConditionType($conditionType) => $categorySelect,
|
||||
];
|
||||
$whereCondition = $this->getConnection()->prepareSqlCondition('e.entity_id', $selectCondition);
|
||||
$this->getSelect()->where($whereCondition);
|
||||
$this->requestBuilder->bind('category_ids', $values);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map equal and not equal conditions to in and not in
|
||||
*
|
||||
* @param string $conditionType
|
||||
* @return mixed
|
||||
*/
|
||||
private function mapConditionType($conditionType)
|
||||
{
|
||||
$conditionsMap = [
|
||||
'eq' => 'in',
|
||||
'neq' => 'nin',
|
||||
];
|
||||
return isset($conditionsMap[$conditionType]) ? $conditionsMap[$conditionType] : $conditionType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load product collection before filters rendering
|
||||
*/
|
||||
protected function _renderFiltersBefore()
|
||||
{
|
||||
$this->requestBuilder->bindDimension('scope', $this->getStoreId());
|
||||
if ($this->queryText) {
|
||||
$this->requestBuilder->bind('search_term', $this->queryText);
|
||||
}
|
||||
|
||||
$priceRangeCalculation = $this->_scopeConfig->getValue(
|
||||
AlgorithmFactory::XML_PATH_RANGE_CALCULATION,
|
||||
ScopeInterface::SCOPE_STORE
|
||||
);
|
||||
if ($priceRangeCalculation) {
|
||||
$this->requestBuilder->bind('price_dynamic_algorithm', $priceRangeCalculation);
|
||||
}
|
||||
|
||||
$this->requestBuilder->setRequestName($this->searchRequestName);
|
||||
$this->memRequestBuilder = clone $this->requestBuilder;
|
||||
$queryRequest = $this->requestBuilder->create();
|
||||
$this->queryResponse = $this->searchEngine->search($queryRequest);
|
||||
|
||||
$temporaryStorage = $this->temporaryStorageFactory->create();
|
||||
$table = $temporaryStorage->storeApiDocuments($this->queryResponse->getIterator());
|
||||
|
||||
$this->getSelect()->joinInner(
|
||||
[
|
||||
'search_result' => $table->getName(),
|
||||
],
|
||||
'e.entity_id = search_result.' . TemporaryStorage::FIELD_ENTITY_ID,
|
||||
[]
|
||||
);
|
||||
|
||||
return parent::_renderFiltersBefore();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
protected function _beforeLoad()
|
||||
{
|
||||
$this->setOrder('entity_id');
|
||||
$this->stockHelper->addIsInStockFilterToCollection($this);
|
||||
|
||||
return parent::_beforeLoad();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Order field
|
||||
*
|
||||
* @param string $attribute
|
||||
* @param string $dir
|
||||
* @return $this
|
||||
*/
|
||||
public function setOrder($attribute, $dir = Select::SQL_DESC)
|
||||
{
|
||||
if ($attribute === 'relevance') {
|
||||
$this->relevanceOrderDirection = $dir;
|
||||
} else {
|
||||
parent::setOrder($attribute, $dir);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add order by entity_id
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
protected function _renderOrders()
|
||||
{
|
||||
if (!$this->_isOrdersRendered) {
|
||||
if ($this->relevanceOrderDirection) {
|
||||
$this->getSelect()->order(
|
||||
'search_result.' . TemporaryStorage::FIELD_SCORE . ' ' . $this->relevanceOrderDirection
|
||||
);
|
||||
}
|
||||
|
||||
parent::_renderOrders();
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\ResourceModel\Layer\Filter;
|
||||
|
||||
use Magento\Catalog\Model\Layer\Filter\FilterInterface;
|
||||
use Magento\Catalog\Model\Layer\Search;
|
||||
use Magento\Framework\DB\Select;
|
||||
use Zend_Db_Expr;
|
||||
|
||||
class Attribute extends \Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute
|
||||
{
|
||||
|
||||
public function getCount(FilterInterface $filter)
|
||||
{
|
||||
$layer = $filter->getLayer();
|
||||
if ($layer instanceof Search) {
|
||||
$collectionSelect = $layer->getProductCollection()->getSelect();
|
||||
} else {
|
||||
$collectionSelect = $layer->getCurrentCategory()->getProductCollection()->getSelect();
|
||||
}
|
||||
|
||||
$select = clone $collectionSelect;
|
||||
$select->reset(Select::COLUMNS);
|
||||
$select->reset(Select::ORDER);
|
||||
$select->reset(Select::LIMIT_COUNT);
|
||||
$select->reset(Select::LIMIT_OFFSET);
|
||||
|
||||
$connection = $this->getConnection();
|
||||
$attribute = $filter->getAttributeModel();
|
||||
$tableAlias = sprintf('%s_idx', $attribute->getAttributeCode());
|
||||
$conditions = [
|
||||
"{$tableAlias}.entity_id = e.entity_id",
|
||||
$connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
|
||||
$connection->quoteInto("{$tableAlias}.store_id = ?", $filter->getStoreId()),
|
||||
];
|
||||
|
||||
$select->join(
|
||||
[$tableAlias => $this->getMainTable()], join(' AND ', $conditions),
|
||||
['value', 'count' => new Zend_Db_Expr("COUNT({$tableAlias}.entity_id)")]
|
||||
)->group(
|
||||
"{$tableAlias}.value"
|
||||
);
|
||||
|
||||
return $connection->fetchPairs($select);
|
||||
}
|
||||
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\ResourceModel\Search;
|
||||
|
||||
use Magento\Framework\Api\FilterBuilder;
|
||||
use Magento\Framework\Api\ObjectFactory;
|
||||
use Magento\Framework\Api\Search\FilterGroup as SourceFilterGroup;
|
||||
use Magento\Framework\Api\Search\FilterGroupBuilder as SourceFilterGroupBuilder;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
|
||||
class FilterGroupBuilder extends SourceFilterGroupBuilder
|
||||
{
|
||||
|
||||
protected $_request;
|
||||
|
||||
public function __construct(
|
||||
ObjectFactory $objectFactory,
|
||||
FilterBuilder $filterBuilder,
|
||||
RequestInterface $request
|
||||
) {
|
||||
parent::__construct($objectFactory, $filterBuilder);
|
||||
|
||||
$this->_request = $request;
|
||||
}
|
||||
|
||||
public function cloneObject()
|
||||
{
|
||||
$cloneObject = clone $this;
|
||||
$cloneObject->setFilterBuilder(clone $this->_filterBuilder);
|
||||
|
||||
return $cloneObject;
|
||||
}
|
||||
|
||||
public function setFilterBuilder($filterBuilder)
|
||||
{
|
||||
$this->_filterBuilder = $filterBuilder;
|
||||
}
|
||||
|
||||
public function removeFilter($attributeCode)
|
||||
{
|
||||
if (isset($this->data[SourceFilterGroup::FILTERS])) {
|
||||
foreach ($this->data[SourceFilterGroup::FILTERS] as $key => $filter) {
|
||||
if ($filter->getField() == $attributeCode) {
|
||||
if (($attributeCode == 'category_ids') && ($filter->getValue() == $this->_request->getParam('id'))) {
|
||||
continue;
|
||||
}
|
||||
unset($this->data[SourceFilterGroup::FILTERS][$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected function _getDataObjectType()
|
||||
{
|
||||
return 'Magento\Framework\Api\Search\FilterGroup';
|
||||
}
|
||||
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
/**
|
||||
* @author Olegnax
|
||||
* @package Olegnax_LayeredNavigation
|
||||
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
|
||||
* @license Proprietary License https://olegnax.com/license/
|
||||
*/
|
||||
|
||||
namespace Olegnax\LayeredNavigation\Model\ResourceModel\Search;
|
||||
|
||||
use Magento\Framework\Api\ObjectFactory;
|
||||
use Magento\Framework\Api\Search\SearchCriteriaBuilder as SourceSearchCriteriaBuilder;
|
||||
use Magento\Framework\Api\SortOrderBuilder;
|
||||
|
||||
class SearchCriteriaBuilder extends SourceSearchCriteriaBuilder
|
||||
{
|
||||
|
||||
public function __construct(
|
||||
ObjectFactory $objectFactory,
|
||||
FilterGroupBuilder $filterGroupBuilder,
|
||||
SortOrderBuilder $sortOrderBuilder
|
||||
) {
|
||||
parent::__construct($objectFactory, $filterGroupBuilder, $sortOrderBuilder);
|
||||
}
|
||||
|
||||
public function removeFilter($attributeCode)
|
||||
{
|
||||
$this->filterGroupBuilder->removeFilter($attributeCode);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function cloneObject()
|
||||
{
|
||||
$cloneObject = clone $this;
|
||||
$cloneObject->setFilterGroupBuilder($this->filterGroupBuilder->cloneObject());
|
||||
|
||||
return $cloneObject;
|
||||
}
|
||||
|
||||
public function setFilterGroupBuilder($filterGroupBuilder)
|
||||
{
|
||||
$this->filterGroupBuilder = $filterGroupBuilder;
|
||||
}
|
||||
|
||||
protected function _getDataObjectType()
|
||||
{
|
||||
return 'Magento\Framework\Api\Search\SearchCriteria';
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user