This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,50 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model;
class AttributeOptions extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface
{
const CACHE_TAG = 'weltpixel_ln_attribute_options';
const DISPLAY_OPTION_DEF_VAL = 0;
const DISPLAY_OPTION_OPEN_VAL = 1;
const VISIBLE_OPTIONS_DEF_VAL = 99;
const VISIBLE_OPTIONS_STEP_DEF_VAL = 99;
/**
* @var string
*/
protected $_cacheTag = 'weltpixel_ln_attribute_options';
/**
* @var string
*/
protected $_eventPrefix = 'weltpixel_ln_attribute_options';
protected function _construct()
{
$this->_init('WeltPixel\LayeredNavigation\Model\ResourceModel\AttributeOptions');
}
/**
* @return array|string[]
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
/**
* @param $attributeId
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getDisplayOptionsByAttribute($attributeId) {
$this->_getResource()->loadDisplayOptionsByAttribute($this, $attributeId);
return $this;
}
}
@@ -0,0 +1,42 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class FilterButton
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class FilterButton implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
0 => 'Icon Only',
1 => 'Icon + Label',
2 => 'Label Only',
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
return $options;
}
}
@@ -0,0 +1,42 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class FilterDisplay
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class FilterDisplay implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
0 => 'Close',
1 => 'Open',
2 => 'Expand',
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
return $options;
}
}
@@ -0,0 +1,41 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class SidebarStyle
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class SidebarStyle implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
'0' => 'Default',
'1' => 'Slide In',
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
return $options;
}
}
@@ -0,0 +1,41 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class SortBy
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class SortBy implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
'position' => 'Position',
'name' => 'Name'
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
return $options;
}
}
+152
View File
@@ -0,0 +1,152 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Layer;
use Magento\Framework\App\RequestInterface;
use WeltPixel\LayeredNavigation\Model\AttributeOptions;
/**
* Class Filter
* @package WeltPixel\LayeredNavigation\Model\Layer
*/
class Filter
{
/** @var \Magento\Framework\App\RequestInterface */
protected $request;
/**
* @var AttributeOptions
*/
protected $_wpAttributeOptions;
/**
* @var array
*/
protected $_ids = [];
/**
* Filter constructor.
* @param RequestInterface $request
* @param AttributeOptions $attributeOptions
*/
public function __construct(
RequestInterface $request,
AttributeOptions $attributeOptions
)
{
$this->request = $request;
$this->_wpAttributeOptions = $attributeOptions;
}
/**
* Get option url. If it has been filtered, return removed url. Else return filter url
*
* @param \Magento\Catalog\Model\Layer\Filter\Item $item
* @return mixed
*/
public function getItemUrl($item)
{
if ($this->isSelected($item)) {
return $item->getRemoveUrl();
}
return $item->getUrl();
}
/**
* @param \Magento\Catalog\Model\Layer\Filter\AbstractFilter $filter
* @param bool|true $explode
* @return array|mixed
*/
public function getFilterValue($filter, $explode = true)
{
$filterValue = $this->request->getParam($filter->getRequestVar());
if (empty($filterValue)) {
return [];
}
return $explode ? explode(',', $filterValue) : $filterValue;
}
/**
* Checks whether the option reduces the number of results
*
* @param \Magento\Catalog\Model\Layer\Filter\AbstractFilter $filter
* @param int $optionCount Count of search results with this option
* @param int $totalSize Current search results count
* @return bool
*/
public function isOptionReducesResults($filter, $optionCount, $totalSize)
{
$result = $optionCount <= $totalSize;
if ($this->isShowZero($filter)) {
return $result;
}
return $optionCount && $result;
}
/**
* @param \Magento\Catalog\Model\Layer\Filter\AbstractFilter $filter
* @return bool
*/
public function isShowZero($filter)
{
return false;
}
/**
* @param $filter
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
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;
}
/**
* @param $attrId
*/
public function isMultiselect($attrId) {
$wpLnAttributeOptions = ($attrId) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attrId) : false;
$isMultiselect = ($wpLnAttributeOptions) ? $wpLnAttributeOptions->getIsMultiselect() : false;
return $isMultiselect;
}
/**
* @param Layer $layer
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
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);
}
}
@@ -0,0 +1,271 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Layer\Filter;
use Magento\Catalog\Model\Layer\Filter\AbstractFilter;
use WeltPixel\LayeredNavigation\Helper\Data as LayerHelper;
use WeltPixel\LayeredNavigation\Model\Layer\Filter as LayerFilter;
use WeltPixel\LayeredNavigation\Model\AttributeOptions;
/**
* Class Attribute
* @package WeltPixel\LayeredNavigation\Model\Layer\Filter
*/
class Attribute extends AbstractFilter
{
/**
* @var LayerHelper
*/
protected $_moduleHelper;
/**
* @var bool
*/
protected $_isFilter = true;
/**
* @var \Magento\Framework\Filter\StripTags
*/
protected $tagFilter;
/**
* @var LayerFilter
*/
protected $_layerFilter;
/**
* @var AttributeOptions
*/
protected $_wpAttributeOptions;
/**
* @var
*/
protected $_requestParamVal;
/**
* Resource instance
*
* @var \Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute
*/
protected $_resource;
/**
* @var
*/
protected $_originalCollection;
/**
* Attribute constructor.
* @param \Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Catalog\Model\Layer $layer
* @param \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder
* @param \Magento\Framework\Filter\StripTags $tagFilter
* @param \Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory $filterAttributeFactory
* @param LayerHelper $moduleHelper
* @param LayerFilter $layerFilter
* @param AttributeOptions $attributeOptions
* @param array $data
*/
public function __construct(
\Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Layer $layer,
\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder,
\Magento\Framework\Filter\StripTags $tagFilter,
\Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory $filterAttributeFactory,
LayerHelper $moduleHelper,
LayerFilter $layerFilter,
AttributeOptions $attributeOptions,
array $data = []
)
{
parent::__construct(
$filterItemFactory,
$storeManager,
$layer,
$itemDataBuilder,
$data
);
$this->_resource = $filterAttributeFactory->create();
$this->tagFilter = $tagFilter;
$this->_moduleHelper = $moduleHelper;
$this->_layerFilter = $layerFilter;
$this->_wpAttributeOptions = $attributeOptions;
}
/**
* @inheritdoc
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
if (!$this->_moduleHelper->isEnabled()) {
return parent::apply($request);
}
$attribute = $this->getAttributeModel();
$attributeValue = $request->getParam($this->_requestVar);
if (empty($attributeValue)) {
$this->_isFilter = false;
return $this;
}
$this->_requestParamVal = $this->_requestVar;
$attributeValue = explode(',', $attributeValue);
$state = $this->getLayer()->getState();
foreach ($attributeValue as $value) {
$label = $this->getOptionText($value);
$state->addFilter($this->_createItem($label, $value));
}
if (!$this->isMultiselect($attribute->getId()) && count($attributeValue) > 1) {
$attributeValue = array_slice($attributeValue, 0, 1);
}
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()->getProductCollection();
if(!$this->_originalCollection) {
$this->_originalCollection = $productCollection->getCollectionClone();
}
if (count($attributeValue) > 1) {
if ($this->_moduleHelper->isElasticOrOpenSearchEngine()) {
$productCollection->addFieldToFilter($attribute->getAttributeCode(), $attributeValue);
} else {
$productCollection->addFieldToFilter($attribute->getAttributeCode(), ['in' => $attributeValue]);
}
} else {
$productCollection->addFieldToFilter($attribute->getAttributeCode(), $attributeValue[0]);
}
return $this;
}
/**
* Retrieve resource instance
*
* @return \Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute
*/
protected function _getResource()
{
return $this->_resource;
}
/**
* @inheritdoc
*/
protected function _getItemsData()
{
if (!$this->_moduleHelper->isEnabled()) {
return parent::_getItemsData();
}
$logger = \Magento\Framework\App\ObjectManager::getInstance()->get(\Psr\Log\LoggerInterface::class);
$attribute = $this->getAttributeModel();
$wpLnAttributeOptions = ($attribute->getId()) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attribute->getId()) : false;
if(!$wpLnAttributeOptions->getIsMultiselect() && $this->_isFilter && $attribute->getAttributeCode() != 'category_option') {
return [];
}
/** @var \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()->getProductCollection();
if ($this->_isFilter && ( $this->_layerFilter->isMainFilter($this) || $wpLnAttributeOptions->getIsMultiselect())) {
$productCollection = $productCollection->getCollectionClone()
->removeAttributeSearch($attribute->getAttributeCode());
}
$optionsFacetedData = $productCollection->getFacetedData($attribute->getAttributeCode());
if (count($optionsFacetedData) === 0
&& $this->getAttributeIsFilterable($attribute) !== static::ATTRIBUTE_OPTIONS_ONLY_WITH_RESULTS
) {
return $this->itemDataBuilder->build();
}
$productSize = $productCollection->getSize();
$itemData = [];
$checkCount = false;
$options = $attribute->getFrontend()->getSelectOptions();
$counter = false;
foreach ($options as $option) {
$sorted = false;
if (empty($option['value'])) {
continue;
}
$value = $option['value'];
if($counter) {
$count = isset($counter[$value]) ? (int)$counter[$value] : 0;
} else {
$count = isset($optionsFacetedData[$value]['count']) ? (int)$optionsFacetedData[$value]['count'] : 0;
}
// Check filter type
if ($this->getAttributeIsFilterable($attribute) == static::ATTRIBUTE_OPTIONS_ONLY_WITH_RESULTS && (!$this->_layerFilter->isOptionReducesResults($this, $count, $productSize)) && $count == 0) {
continue;
}
if ($count > 0) {
$checkCount = true;
}
$itemData[] = [
'label' => $this->tagFilter->filter($option['label']),
'value' => $value,
'count' => $count
];
}
if ($checkCount) {
if ($wpLnAttributeOptions->getSortBy() == 2) {
usort($itemData, [$this, '_compareAz']);
$sorted = true;
}
foreach ($itemData as $item) {
$this->itemDataBuilder->addItemData($item['label'], $item['value'], $item['count']);
}
}
if ($wpLnAttributeOptions->getSortBy() == 2 && !$sorted) {
usort($options, [$this, '_compareAz']);
}
return $this->itemDataBuilder->build();
}
/**
* return attribute custom 'is_multiselect' option
*
* @param $attrId
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function isMultiselect($attrId)
{
$wpLnAttributeOptions = ($attrId) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attrId) : false;
$isMultiselect = ($wpLnAttributeOptions) ? $wpLnAttributeOptions->getIsMultiselect() : false;
return $isMultiselect;
}
/**
* @param $a
* @param $b
* @return int
*/
protected function _compareAz($a, $b)
{
return strcmp($a["label"], $b["label"]);
}
}
@@ -0,0 +1,152 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Layer\Filter;
use Magento\CatalogSearch\Model\Layer\Filter\Category as AbstractFilter;
use WeltPixel\LayeredNavigation\Helper\Data as LayerHelper;
use WeltPixel\LayeredNavigation\Model\Layer\Filter as LayerFilter;
/**
* Class Category
* @package WeltPixel\LayeredNavigation\Model\Layer\Filter
*/
class Category extends AbstractFilter
{
/** @var \WeltPixel\LayeredNavigation\Helper\Data */
protected $_moduleHelper;
/** @var bool Is Filterable Flag */
protected $_isFilter = false;
/** @var \Magento\Framework\Escaper */
private $escaper;
/** @var \Magento\Catalog\Model\Layer\Filter\DataProvider\Category */
private $dataProvider;
/**
* Category constructor.
* @param \Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Catalog\Model\Layer $layer
* @param \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder
* @param \Magento\Framework\Escaper $escaper
* @param \Magento\Catalog\Model\Layer\Filter\DataProvider\CategoryFactory $categoryDataProviderFactory
* @param LayerHelper $moduleHelper
* @param LayerFilter $layerFilter
* @param array $data
*/
public function __construct(
\Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Layer $layer,
\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder,
\Magento\Framework\Escaper $escaper,
\Magento\Catalog\Model\Layer\Filter\DataProvider\CategoryFactory $categoryDataProviderFactory,
LayerHelper $moduleHelper,
LayerFilter $layerFilter,
array $data = []
)
{
parent::__construct(
$filterItemFactory,
$storeManager,
$layer,
$itemDataBuilder,
$escaper,
$categoryDataProviderFactory,
$data
);
$this->escaper = $escaper;
$this->_moduleHelper = $moduleHelper;
$this->_layerFilter = $layerFilter;
$this->dataProvider = $categoryDataProviderFactory->create(['layer' => $this->getLayer()]);
}
/**
* @inheritdoc
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
if (!$this->_moduleHelper->isEnabled()) {
return parent::apply($request);
}
$categoryId = $request->getParam($this->_requestVar);
if (empty($categoryId)) {
return $this;
}
$categoryIds = [];
foreach (explode(',', $categoryId) as $key => $id) {
$this->dataProvider->setCategoryId($id);
if ($this->dataProvider->isValid()) {
$category = $this->dataProvider->getCategory();
if ($request->getParam('id') != $id) {
$categoryIds[] = $id;
$this->getLayer()->getState()->addFilter($this->_createItem($category->getName(), $id));
}
}
}
if (sizeof($categoryIds)) {
$this->_isFilter = true;
$this->getLayer()->getProductCollection()->addLayerCategoryFilter($categoryIds);
}
if ($parentCategoryId = $request->getParam('id')) {
$this->dataProvider->setCategoryId($parentCategoryId);
}
return $this;
}
/**
* @return array
* @throws \Magento\Framework\Exception\StateException
*/
protected function _getItemsData()
{
if (!$this->_moduleHelper->isEnabled()) {
return parent::_getItemsData();
}
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()->getProductCollection();
if ($this->_isFilter) {
$productCollection = $productCollection->getCollectionClone()
->removeAttributeSearch('category_ids');
}
$optionsFacetedData = $productCollection->getFacetedData('category');
$category = $this->dataProvider->getCategory();
$categories = $category->getChildrenCategories();
$collectionSize = $productCollection->getSize();
if ($category->getIsActive()) {
foreach ($categories as $category) {
$count = isset($optionsFacetedData[$category->getId()]) ? $optionsFacetedData[$category->getId()]['count'] : 0;
if ($category->getIsActive()
&& $this->_layerFilter->isOptionReducesResults($this, $count, $collectionSize)
) {
$this->itemDataBuilder->addItemData(
$this->escaper->escapeHtml($category->getName()),
$category->getId(),
$count
);
}
}
}
return $this->itemDataBuilder->build();
}
}
@@ -0,0 +1,157 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayerdNavigation\Model\Layer\Filter;
use Magento\Catalog\Model\Layer\Filter\AbstractFilter;
/**
* Class Decimal
* @package WeltPixel\LayerdNavigation\Model\Layer\Filter
*/
class Decimal extends AbstractFilter
{
/**
* @var \Magento\Framework\Pricing\PriceCurrencyInterface
*/
private $priceCurrency;
/**
* @var \Magento\Catalog\Model\ResourceModel\Layer\Filter\Decimal
*/
private $resource;
/**
* @param \Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Catalog\Model\Layer $layer
* @param \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder
* @param \Magento\Catalog\Model\ResourceModel\Layer\Filter\DecimalFactory $filterDecimalFactory
* @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency
* @param array $data
*/
public function __construct(
\Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Layer $layer,
\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder,
\Magento\Catalog\Model\ResourceModel\Layer\Filter\DecimalFactory $filterDecimalFactory,
\Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency,
array $data = []
) {
parent::__construct(
$filterItemFactory,
$storeManager,
$layer,
$itemDataBuilder,
$data
);
$this->resource = $filterDecimalFactory->create();
$this->priceCurrency = $priceCurrency;
}
/**
* Apply price range filter
*
* @param \Magento\Framework\App\RequestInterface $request
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
/**
* Filter must be string: $fromPrice-$toPrice
*/
$filter = $request->getParam($this->getRequestVar());
if (!$filter || is_array($filter)) {
return $this;
}
list($from, $to) = explode('-', $filter);
$this->getLayer()
->getProductCollection()
->addFieldToFilter(
$this->getAttributeModel()->getAttributeCode(),
['from' => $from, 'to' => $to]
);
$this->getLayer()->getState()->addFilter(
$this->_createItem($this->renderRangeLabel(empty($from) ? 0 : $from, $to), $filter)
);
return $this;
}
/**
* Get data array for building attribute filter items
*
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function _getItemsData()
{
$attribute = $this->getAttributeModel();
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()->getProductCollection();
$productSize = $productCollection->getSize();
$facets = $productCollection->getFacetedData($attribute->getAttributeCode());
$data = [];
foreach ($facets as $key => $aggregation) {
$count = $aggregation['count'];
if (!$this->isOptionReducesResults($count, $productSize)) {
continue;
}
list($from, $to) = explode('_', $key);
if ($from == '*') {
$from = '';
}
if ($to == '*') {
$to = '';
}
$label = $this->renderRangeLabel(
empty($from) ? 0 : $from,
empty($to) ? $to : $to
);
$value = $from . '-' . $to;
$data[] = [
'label' => $label,
'value' => $value,
'count' => $count,
'from' => $from,
'to' => $to
];
}
return $data;
}
/**
* Prepare text of range label
*
* @param float|string $fromPrice
* @param float|string $toPrice
* @return \Magento\Framework\Phrase
*/
protected function renderRangeLabel($fromPrice, $toPrice)
{
$formattedFromPrice = $this->priceCurrency->format($fromPrice);
if ($toPrice === '') {
return __('%1 and above', $formattedFromPrice);
} else {
if ($fromPrice != $toPrice) {
$toPrice -= .01;
}
return __('%1 - %2', $formattedFromPrice, $this->priceCurrency->format($toPrice));
}
}
}
@@ -0,0 +1,255 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Layer\Filter;
use Magento\CatalogSearch\Model\Layer\Filter\Price as AbstractFilter;
use WeltPixel\LayeredNavigation\Helper\Data as LayerHelper;
/**
* Class Price
* @package WeltPixel\LayeredNavigation\Model\Layer\Filter
*/
class Price extends AbstractFilter
{
/** @var \WeltPixel\LayeredNavigation\Helper\Data */
protected $_moduleHelper;
/** @var array|null Filter value */
protected $_filterVal = null;
/** @var \Magento\Tax\Helper\Data */
protected $_taxHelper;
/** @var \Magento\Catalog\Model\Layer\Filter\DataProvider\Price */
private $dataProvider;
/** @var \Magento\Framework\Pricing\PriceCurrencyInterface */
private $priceCurrency;
/**
* @param \Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Catalog\Model\Layer $layer
* @param \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder
* @param \Magento\Catalog\Model\ResourceModel\Layer\Filter\Price $resource
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Framework\Search\Dynamic\Algorithm $priceAlgorithm
* @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency
* @param \Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory $algorithmFactory
* @param \Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory $dataProviderFactory
* @param \Magento\Tax\Helper\Data $taxHelper
* @param \WeltPixel\LayeredNavigation\Helper\Data $moduleHelper
* @param array $data
*/
public function __construct(
\Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\Layer $layer,
\Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder,
\Magento\Catalog\Model\ResourceModel\Layer\Filter\Price $resource,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\Search\Dynamic\Algorithm $priceAlgorithm,
\Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency,
\Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory $algorithmFactory,
\Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory $dataProviderFactory,
\Magento\Tax\Helper\Data $taxHelper,
LayerHelper $moduleHelper,
array $data = []
)
{
parent::__construct(
$filterItemFactory,
$storeManager,
$layer,
$itemDataBuilder,
$resource,
$customerSession,
$priceAlgorithm,
$priceCurrency,
$algorithmFactory,
$dataProviderFactory,
$data
);
$this->priceCurrency = $priceCurrency;
$this->dataProvider = $dataProviderFactory->create(['layer' => $this->getLayer()]);
$this->_moduleHelper = $moduleHelper;
$this->_taxHelper = $taxHelper;
}
/**
* @inheritdoc
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
if (!$this->_moduleHelper->isEnabled()) {
return parent::apply($request);
}
/**
* Filter must be string: $fromPrice-$toPrice
*/
$filter = $request->getParam($this->getRequestVar());
if (!$filter || is_array($filter)) {
return $this;
}
$filterParams = explode(',', $filter);
$filter = $this->dataProvider->validateFilter($filterParams[0]);
if (!$filter) {
return $this;
}
$this->dataProvider->setInterval($filter);
$priorFilters = $this->dataProvider->getPriorFilters($filterParams);
if ($priorFilters) {
$this->dataProvider->setPriorIntervals($priorFilters);
}
list($from, $to) = $this->_filterVal = $filter;
$this->getLayer()->getProductCollection()->addFieldToFilter(
'price',
['from' => $from, 'to' => $to]
);
$this->getLayer()->getState()->addFilter(
$this->_createItem($this->_renderRangeLabel(empty($from) ? 0 : $from, $to), $filter)
);
return $this;
}
/**
* @inheritdoc
*/
protected function _renderRangeLabel($fromPrice, $toPrice, $isLast = false)
{
if (!$this->_moduleHelper->isEnabled()) {
return parent::_renderRangeLabel($fromPrice, $toPrice, $isLast = false);
}
$formattedFromPrice = $this->priceCurrency->format($fromPrice);
if ($toPrice === '' || $isLast) {
return __('%1 and above', $formattedFromPrice);
} elseif ($fromPrice == $toPrice && $this->dataProvider->getOnePriceIntervalValue()) {
return $formattedFromPrice;
} else {
return __('%1 - %2', $formattedFromPrice, $this->priceCurrency->format($toPrice));
}
}
/**
* Price Slider Configuration
*
* @return array
*/
public function getSliderConfig()
{
/** @var \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()->getProductCollection();
if ($this->_filterVal) {
/** @type \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection $productCollectionClone */
$productCollection = $productCollection->getCollectionClone()
->removeAttributeSearch(['price.from', 'price.to']);
}
$min = $productCollection->getMinPrice();
$max = $productCollection->getMaxPrice();
list($from, $to) = $this->_filterVal ?: [$min, $max];
$from = ($from < $min) ? $min : $from;
$to = ($to > $max) ? $max : $to;
$item = $this->getItems()[0];
return [
"selectedFrom" => $from,
"selectedTo" => $to,
"minValue" => $min,
"maxValue" => $max,
"priceFormat" => $this->_taxHelper->getPriceFormat(),
"ajaxUrl" => $item->getUrl()
];
}
/**
* Get data array for building attribute filter items
*
* @return array
*
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function _getItemsData()
{
if (!$this->_moduleHelper->isEnabled()) {
return parent::_getItemsData();
}
$attribute = $this->getAttributeModel();
$this->_requestVar = $attribute->getAttributeCode();
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()->getProductCollection();
if ($this->_filterVal) {
/** @type \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection $productCollectionClone */
$productCollection = $productCollection->getCollectionClone()
->removeAttributeSearch(['price.from', 'price.to']);
}
$facets = $productCollection->getFacetedData($attribute->getAttributeCode());
$data = [];
if (count($facets) > 1) {
$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;
}
/**
* @param string $key
* @param int $count
* @param boolean $isLast
* @return array
*/
private function prepareData($key, $count, $isLast = false)
{
list($from, $to) = explode('_', $key);
if ($from == '*') {
$from = $this->getFrom($to);
}
if ($to == '*') {
$to = $this->getTo($to);
}
$label = $this->_renderRangeLabel(
empty($from) ? 0 : $from * $this->getCurrencyRate(),
empty($to) ? $to : $to * $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,75 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel;
/**
* Class AttributeOptions
* @package WeltPixel\LayeredNavigation\Model\ResourceModel
*/
class AttributeOptions extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* @var array
*/
protected $loadedAttributes = [];
/**
* AttributeOptions constructor.
* @param \Magento\Framework\Model\ResourceModel\Db\Context $context
*/
public function __construct(
\Magento\Framework\Model\ResourceModel\Db\Context $context
)
{
parent::__construct($context);
}
protected function _construct()
{
$this->_init('weltpixel_ln_attribute_options', 'id');
}
/**
* Load Attribute display option by attribute_id & store_id
*
* @param \WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions
* @param $attributeId
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function loadDisplayOptionsByAttribute(
\WeltPixel\LayeredNavigation\Model\AttributeOptions $attributeOptions,
$attributeId
) {
if (isset($this->loadedAttributes[$attributeId])) {
$attributeOptions->setData($this->loadedAttributes[$attributeId]->getData());
return $this;
}
$connection = $this->getConnection();
$bind = [
'attribute_id' => $attributeId
];
$select = $connection->select()->from(
$this->getMainTable(),
[$this->getIdFieldName()]
)->where(
'attribute_id = :attribute_id'
);
$lineId = $connection->fetchOne($select, $bind);
if ($lineId) {
$this->load($attributeOptions, $lineId);
} else {
$attributeOptions->setData([]);
}
$this->loadedAttributes[$attributeId] = clone $attributeOptions;
}
}
@@ -0,0 +1,31 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\AttributeOptions;
/**
* Class Collection
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\AttributeOptions
*/
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'id';
protected $_eventPrefix = 'weltpixel_ln_atribute_options_collection';
protected $_eventObject = 'attribute_options_collection';
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('WeltPixel\LayeredNavigation\Model\AttributeOptions', 'WeltPixel\LayeredNavigation\Model\ResourceModel\AttributeOptions');
}
}
@@ -0,0 +1,588 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext;
use Magento\CatalogSearch\Model\Search\RequestGenerator;
use Magento\Framework\Api\Search\FilterGroup as SourceFilterGroup;
use Magento\Framework\Api\Search\SearchCriteria;
use Magento\Framework\Api\Search\SearchResultFactory;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DB\Select;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Search\Adapter\Mysql\TemporaryStorage;
use Magento\Framework\Search\Request\EmptyRequestDataException;
use Magento\Store\Model\ScopeInterface;
use Magento\CatalogSearch\Model\ResourceModel\EngineInterface;
/**
* Class Collection
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext
*/
class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection
{
/** @var \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection|null Clone collection */
public $collectionClone = null;
/** @var string */
private $queryText;
/** @var string|null */
private $order = null;
/** @var string */
private $searchRequestName;
/** @var \Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory */
private $temporaryStorageFactory;
/** @var \Magento\Search\Api\SearchInterface */
private $search;
/** @var \WeltPixel\LayeredNavigation\Model\ResourceModel\Search\SearchCriteriaBuilder */
private $searchCriteriaBuilder;
/** @var \Magento\Framework\Api\Search\SearchResultInterface */
private $searchResult;
/** @var \Magento\Framework\Api\FilterBuilder */
private $filterBuilder;
/* @var \Magento\Framework\App\Config\ScopeConfigInterface */
protected $_scopeConfig;
/** @var \Magento\Framework\App\ProductMetadataInterface */
protected $_productMetadata;
/** @var */
protected $_categoryId;
/** @var */
protected $_isTwoOne;
/**
* @var SearchResultFactory
*/
protected $searchResultFactory;
/**
* Collection constructor.
* @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory
* @param \Psr\Log\LoggerInterface $logger
* @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
* @param \Magento\Framework\Event\ManagerInterface $eventManager
* @param \Magento\Eav\Model\Config $eavConfig
* @param \Magento\Framework\App\ResourceConnection $resource
* @param \Magento\Eav\Model\EntityFactory $eavEntityFactory
* @param \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper
* @param \Magento\Framework\Validator\UniversalFactory $universalFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\Module\Manager $moduleManager
* @param \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory
* @param \Magento\Catalog\Model\ResourceModel\Url $catalogUrl
* @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Framework\Stdlib\DateTime $dateTime
* @param \Magento\Customer\Api\GroupManagementInterface $groupManagement
* @param \Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory $temporaryStorageFactory
* @param \Magento\Framework\App\ProductMetadataInterface $productMetadata
* @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection
* @param string $searchRequestName
* @param SearchResultFactory|null $searchResultFactory
*/
public function __construct(
\Magento\Framework\Data\Collection\EntityFactory $entityFactory,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
\Magento\Framework\Event\ManagerInterface $eventManager,
\Magento\Eav\Model\Config $eavConfig,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Eav\Model\EntityFactory $eavEntityFactory,
\Magento\Catalog\Model\ResourceModel\Helper $resourceHelper,
\Magento\Framework\Validator\UniversalFactory $universalFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Module\Manager $moduleManager,
\Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Catalog\Model\Product\OptionFactory $productOptionFactory,
\Magento\Catalog\Model\ResourceModel\Url $catalogUrl,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\Stdlib\DateTime $dateTime,
\Magento\Customer\Api\GroupManagementInterface $groupManagement,
\Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory $temporaryStorageFactory,
\Magento\Framework\App\ProductMetadataInterface $productMetadata,
\Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
$searchRequestName = 'catalog_view_container',
SearchResultFactory $searchResultFactory = null
)
{
$this->searchResultFactory = $searchResultFactory ?? ObjectManager::getInstance()->get(SearchResultFactory::class);
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$eavConfig,
$resource,
$eavEntityFactory,
$resourceHelper,
$universalFactory,
$storeManager,
$moduleManager,
$catalogProductFlatState,
$scopeConfig,
$productOptionFactory,
$catalogUrl,
$localeDate,
$customerSession,
$dateTime,
$groupManagement,
$connection
);
$this->temporaryStorageFactory = $temporaryStorageFactory;
$this->searchRequestName = $searchRequestName;
$this->_scopeConfig = $scopeConfig;
$this->_productMetadata = $productMetadata;
$this->_isMTwoOneVersion();
}
/**
* WeltPixel LayeredNavigation Clone collection
*
* @return \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection|null
*/
public function getCollectionClone()
{
if ($this->collectionClone === null) {
$this->collectionClone = clone $this;
$this->collectionClone->setSearchCriteriaBuilder($this->searchCriteriaBuilder->cloneObject());
}
$searchCriterialBuilder = $this->collectionClone->getSearchCriteriaBuilder()->cloneObject();
/** @var \WeltPixel\LayeredNavigation\Model\ResourceModel\Fulltext\Collection $collectionClone */
$collectionClone = clone $this->collectionClone;
$collectionClone->setSearchCriteriaBuilder($searchCriterialBuilder);
return $collectionClone;
}
/**
* WeltPixel LayeredNavigation Add multi-filter categories
*
* @param $categories
* @return $this
*/
public function addLayerCategoryFilter($categories)
{
$this->addFieldToFilter('category_ids', implode(',', $categories));
return $this;
}
/**
* WeltPixel LayeredNavigation remove filter to load option item data
*
* @param $attributeCode
* @return $this
*/
public function removeAttributeSearch($attributeCode)
{
if (is_array($attributeCode)) {
foreach ($attributeCode as $attCode) {
$this->searchCriteriaBuilder->removeFilter($attCode);
}
} else {
$this->searchCriteriaBuilder->removeFilter($attributeCode);
}
$this->_isFiltersRendered = false;
return $this->loadWithFilter();
}
/**
* WeltPixel LayeredNavigation Get attribute condition sql
*
* @param $attribute
* @param $condition
* @param string $joinType
* @return string
*/
public function getAttributeConditionSql($attribute, $condition, $joinType = 'inner')
{
return $this->_getAttributeConditionSql($attribute, $condition, $joinType);
}
/**
* WeltPixel LayeredNavigation Reset Total records
*
* @return $this
*/
public function resetTotalRecords($collectionCount = null)
{
$this->_totalRecords = $collectionCount;
return $this;
}
/**
* @return int|void
*/
public function getSize() {
return sizeof($this->getAllIds());
}
/**
* @return \Magento\Search\Api\SearchInterface|mixed
*/
private function getSearch()
{
if ($this->search === null) {
$this->search = ObjectManager::getInstance()->get('\Magento\Search\Api\SearchInterface');
}
return $this->search;
}
/**
* @param \Magento\Search\Api\SearchInterface $object
*/
public function setSearch(\Magento\Search\Api\SearchInterface $object)
{
$this->search = $object;
}
/**
* @return mixed|\WeltPixel\LayeredNavigation\Model\ResourceModel\Search\SearchCriteriaBuilder
*/
public function getSearchCriteriaBuilder()
{
if ($this->searchCriteriaBuilder === null) {
$this->searchCriteriaBuilder = ObjectManager::getInstance()
->get('\WeltPixel\LayeredNavigation\Model\ResourceModel\Search\SearchCriteriaBuilder');
}
return $this->searchCriteriaBuilder;
}
/**
* @param \WeltPixel\LayeredNavigation\Model\ResourceModel\Search\SearchCriteriaBuilder $object
*/
public function setSearchCriteriaBuilder(\WeltPixel\LayeredNavigation\Model\ResourceModel\Search\SearchCriteriaBuilder $object)
{
$this->searchCriteriaBuilder = $object;
}
/**
* @return \Magento\Framework\Api\FilterBuilder|mixed
*/
private function getFilterBuilder()
{
if ($this->filterBuilder === null) {
$this->filterBuilder = ObjectManager::getInstance()->get('\Magento\Framework\Api\FilterBuilder');
}
return $this->filterBuilder;
}
/**
* @param \Magento\Framework\Api\FilterBuilder $object
*/
public function setFilterBuilder(\Magento\Framework\Api\FilterBuilder $object)
{
$this->filterBuilder = $object;
}
/**
* Apply attribute filter to facet collection
*
* @param string $field
* @param null $condition
* @return $this
*/
public function addFieldToFilter($field, $condition = null)
{
if ($this->searchResult !== null) {
throw new \RuntimeException('Illegal state');
}
$this->getSearchCriteriaBuilder();
$this->getFilterBuilder();
if (is_array($condition) && $this->_isElasticOrOpenSearchEngine()) {
$this->filterBuilder->setField($field);
$this->filterBuilder->setValue($condition);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
} elseif (!is_array($condition) || !in_array(key($condition), ['from', 'to'])) {
$this->filterBuilder->setField($field);
$this->filterBuilder->setValue($condition);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
} else {
if (!empty($condition['from'])) {
$this->filterBuilder->setField("{$field}.from");
$this->filterBuilder->setValue($condition['from']);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
}
if (!empty($condition['to'])) {
$this->filterBuilder->setField("{$field}.to");
$this->filterBuilder->setValue($condition['to']);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
}
}
return $this;
}
/**
* Add search query filter
*
* @param string $query
* @return $this
*/
public function addSearchFilter($query)
{
$this->queryText = trim($this->queryText . ' ' . $query);
return $this;
}
/**
* @inheritdoc
*/
protected function _renderFiltersBefore()
{
$this->getCollectionClone();
$this->getSearchCriteriaBuilder();
$this->getFilterBuilder();
$this->getSearch();
if ($this->queryText) {
$this->filterBuilder->setField('search_term');
$this->filterBuilder->setValue($this->queryText);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
}
$priceRangeCalculation = $this->_scopeConfig->getValue(
\Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory::XML_PATH_RANGE_CALCULATION,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
if ($priceRangeCalculation) {
$this->filterBuilder->setField('price_dynamic_algorithm');
$this->filterBuilder->setValue($priceRangeCalculation);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
}
if ($this->_isTwoOne) {
$this->filterBuilder->setField('category_ids');
$this->filterBuilder->setValue($this->_categoryId);
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
}
$searchCriteria = $this->searchCriteriaBuilder->create();
$searchCriteria->setRequestName($this->searchRequestName);
if ($this->_isElasticOrOpenSearchEngine()) {
if ($this->order && isset($this->order['field'])) {
$fieldValue = explode("~", $this->order['field']);
} else {
$fieldValue = [];
$fieldValue[0]=null;
}
if (!$fieldValue[0]) {
$searchCriteria->setSortOrders([
'entity_id' => 'DESC'
]);
} else {
$searchCriteria->setSortOrders([
$fieldValue[0] => $this->order['dir']
]);
}
}
try {
$this->searchResult = $this->getSearch()->search($searchCriteria);
} catch (EmptyRequestDataException $e) {
/** @var \Magento\Framework\Api\Search\SearchResultInterface $searchResult */
$this->searchResult = $this->searchResultFactory->create()->setItems([]);
} catch (\Exception $e) {
throw new LocalizedException(__('Something went wrong, check and test your Search Engine configurations, reindex catalog and clear cache. Thrown error: %1', $e->getMessage()));
}
try {
$temporaryStorage = $this->temporaryStorageFactory->create();
$table = $temporaryStorage->storeDocuments($this->searchResult->getItems());
$this->getSelect()->joinInner(
[
'search_result' => $table->getName(),
],
'e.entity_id = search_result.' . TemporaryStorage::FIELD_ENTITY_ID,
[]
);
if ($this->order && 'relevance' === $this->order['field']) {
$this->getSelect()->order('search_result.' . TemporaryStorage::FIELD_SCORE . ' ' . $this->order['dir']);
}
} catch (\Exception $ex) {
$this->_logger->error($ex->getMessage());
}
parent::_renderFiltersBefore();
}
/**
* @return $this
*/
protected function _renderFilters()
{
$this->_filters = [];
return parent::_renderFilters();
}
/**
* Set Order field
*
* @param string $attribute
* @param string $dir
* @return $this
*/
public function setOrder($attribute, $dir = Select::SQL_DESC)
{
$this->order = ['field' => $attribute, 'dir' => $dir];
if ($attribute != 'relevance') {
parent::setOrder($attribute, $dir);
}
return $this;
}
/**
* Stub method for compatibility with other search engines
*
* @return $this
*/
public function setGeneralDefaultQuery()
{
return $this;
}
/**
* Return field faceted data from faceted search result
*
* @param string $field
* @return array
* @throws StateException
*/
public function getFacetedData($field)
{
$this->_renderFilters();
$result = [];
$aggregations = $this->searchResult->getAggregations();
if (null !== $aggregations) {
$bucketName = $field . RequestGenerator::BUCKET_SUFFIX;
$bucket = $aggregations->getBucket($bucketName);
if ($bucket) {
foreach ($bucket->getValues() as $value) {
$metrics = $value->getMetrics();
$result[$metrics['value']] = $metrics;
}
}
}
return $result;
}
/**
* Specify category filter for product collection
*
* @param \Magento\Catalog\Model\Category $category
* @return $this
*/
public function addCategoryFilter(\Magento\Catalog\Model\Category $category)
{
$this->_categoryId = $category->getId();
$this->addFieldToFilter('category_ids', $category->getId());
return parent::addCategoryFilter($category);
}
/**
* Set product visibility filter for enabled products
*
* @param array $visibility
* @return $this
*/
public function setVisibility($visibility)
{
$this->addFieldToFilter('visibility', $visibility);
return parent::setVisibility($visibility);
}
/**
* Check the engine provider is 'elasticsearch'
* @deprecated
*
* @return bool
*/
protected function _isElasticSearchEngine()
{
$currentEngine = $this->_scopeConfig->getValue(EngineInterface::CONFIG_ENGINE_PATH, ScopeInterface::SCOPE_STORE);
if ($currentEngine == 'elasticsearch' || $currentEngine == 'elasticsearch5'
|| $currentEngine == 'elasticsearch6' || $currentEngine == 'elasticsearch7' ) {
return true;
}
return false;
}
/**
* Check the engine provider is 'elasticsearch' or 'opensearch'
*
* @return bool
*/
protected function _isElasticOrOpenSearchEngine()
{
$currentEngine = $this->_scopeConfig->getValue(EngineInterface::CONFIG_ENGINE_PATH, ScopeInterface::SCOPE_STORE);
if ($currentEngine == 'elasticsearch' || $currentEngine == 'elasticsearch5'
|| $currentEngine == 'elasticsearch6' || $currentEngine == 'elasticsearch7' || $currentEngine == 'opensearch' ) {
return true;
}
return false;
}
/**
* check magento version
* @return bool
*/
protected function _isMTwoOneVersion()
{
$version = $this->_productMetadata->getVersion();
$pos = strpos($version, '2.1');
if ($pos === false) {
$this->_isTwoOne = false;
} else {
$this->_isTwoOne = true;
}
return $this->_isTwoOne;
}
}
@@ -0,0 +1,61 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Layer\Filter;
/**
* Class Attribute
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Layer\Filter
*/
class Attribute extends \Magento\Catalog\Model\ResourceModel\Layer\Filter\Attribute
{
/**
* Retrieve array with products counts per attribute option
*
* @param \Magento\Catalog\Model\Layer\Filter\FilterInterface $filter
* @throws \Magento\Framework\Exception\LocalizedException
* @return array
*/
public function getCount(\Magento\Catalog\Model\Layer\Filter\FilterInterface $filter)
{
// clone select from collection with filters
$layer = $filter->getLayer();
if($layer instanceof \Magento\Catalog\Model\Layer\Search) {
$collectionSelect = $layer->getProductCollection()->getSelect();
} else {
$collectionSelect = $layer->getCurrentCategory()->getProductCollection()->getSelect();
}
$select = clone $collectionSelect;
// reset columns, order and limitation conditions
$select->reset(\Magento\Framework\DB\Select::COLUMNS);
$select->reset(\Magento\Framework\DB\Select::ORDER);
$select->reset(\Magento\Framework\DB\Select::LIMIT_COUNT);
$select->reset(\Magento\Framework\DB\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);
}
}
@@ -0,0 +1,19 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Search;
use Magento\Framework\Api\Search\FilterGroup as SourceFilterGroup;
/**
* Class FilterGroup
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Search
*/
class FilterGroup extends SourceFilterGroup
{
}
@@ -0,0 +1,92 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\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
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Search
*/
class FilterGroupBuilder extends SourceFilterGroupBuilder
{
/** @var \Magento\Framework\App\RequestInterface */
protected $_request;
/**
* FilterGroupBuilder constructor.
* @param \Magento\Framework\Api\ObjectFactory $objectFactory
* @param \Magento\Framework\Api\FilterBuilder $filterBuilder
* @param \Magento\Framework\App\RequestInterface $request
*/
public function __construct(
ObjectFactory $objectFactory,
FilterBuilder $filterBuilder,
RequestInterface $request
)
{
parent::__construct($objectFactory, $filterBuilder);
$this->_request = $request;
}
/**
* @return FilterGroupBuilder
*/
public function cloneObject()
{
$cloneObject = clone $this;
$cloneObject->setFilterBuilder(clone $this->_filterBuilder);
return $cloneObject;
}
/**
* @param $filterBuilder
*/
public function setFilterBuilder($filterBuilder)
{
$this->_filterBuilder = $filterBuilder;
}
/**
* @param $attributeCode
*
* @return $this
*/
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;
}
/**
* Return the Data type class name
*
* @return string
*/
protected function _getDataObjectType()
{
return 'Magento\Framework\Api\Search\FilterGroup';
}
}
@@ -0,0 +1,19 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Search;
use Magento\Framework\Api\Search\SearchCriteria as SourceSearchCriteria;
/**
* Class SearchCriteria
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Search
*/
class SearchCriteria extends SourceSearchCriteria
{
}
@@ -0,0 +1,73 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\ResourceModel\Search;
use Magento\Framework\Api\ObjectFactory;
use Magento\Framework\Api\Search\SearchCriteriaBuilder as SourceSearchCriteriaBuilder;
use Magento\Framework\Api\SortOrderBuilder;
/**
* Class SearchCriteriaBuilder
* @package WeltPixel\LayeredNavigation\Model\ResourceModel\Search
*/
class SearchCriteriaBuilder extends SourceSearchCriteriaBuilder
{
/**
* @param ObjectFactory $objectFactory
* @param FilterGroupBuilder $filterGroupBuilder
* @param SortOrderBuilder $sortOrderBuilder
*/
public function __construct(
ObjectFactory $objectFactory,
FilterGroupBuilder $filterGroupBuilder,
SortOrderBuilder $sortOrderBuilder
)
{
parent::__construct($objectFactory, $filterGroupBuilder, $sortOrderBuilder);
}
/**
* @param $attributeCode
*
* @return $this
*/
public function removeFilter($attributeCode)
{
$this->filterGroupBuilder->removeFilter($attributeCode);
return $this;
}
/**
* @return SearchCriteriaBuilder
*/
public function cloneObject()
{
$cloneObject = clone $this;
$cloneObject->setFilterGroupBuilder($this->filterGroupBuilder->cloneObject());
return $cloneObject;
}
/**
* @param $filterGroupBuilder
*/
public function setFilterGroupBuilder($filterGroupBuilder)
{
$this->filterGroupBuilder = $filterGroupBuilder;
}
/**
* @return string
*/
protected function _getDataObjectType()
{
return 'Magento\Framework\Api\Search\SearchCriteria';
}
}