This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 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,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 CategoryShowAs
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class CategoryShowAs implements ArrayInterface
{
/**
* @var array
*/
protected $_showAs = array(
0 => 'Closed',
1 => 'Fully Opened'
);
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
foreach ($this->_showAs as $id => $showAs) :
$options[] = array(
'value' => $id,
'label' => $showAs
);
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 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 FilterShowHideState
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class FilterShowHideState implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = [
'open' => 'Open',
'closed' => 'Closed',
];
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->_styles as $id => $style) :
$options[] = [
'value' => $id,
'label' => $style
];
endforeach;
return $options;
}
}
@@ -0,0 +1,73 @@
<?php
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface;
use Magento\Framework\Data\OptionSourceInterface;
class HorizontalSidebarDesignVersion implements SourceInterface, OptionSourceInterface
{
/**
* block type
*/
const VERSION_1 = 'v1';
const VERSION_2 = 'v2';
const VERSION_3 = 'v3';
/**
* Prepare display options.
*
* @return array
*/
public function getAvailableModes()
{
return [
self::VERSION_1 => __('Version 1'),
self::VERSION_2 => __('Version 2'),
self::VERSION_3 => __('Version 3'),
];
}
/**
* Retrieve All options
*
* @return array
*/
public function getAllOptions()
{
$result = [];
foreach ($this->getAvailableModes() as $index => $value) {
$result[] = ['value' => $index, 'label' => $value];
}
return $result;
}
/**
* Retrieve Option value text
*
* @param string $value
* @return mixed
*/
public function getOptionText($value)
{
$options = $this->getAvailableModes();
return isset($options[$value]) ? $options[$value] : null;
}
/**
* Return array of options as value-label pairs
*
* @return array Format: array(array('value' => '<value>', 'label' => '<label>'), ...)
*/
public function toOptionArray()
{
return $this->getAllOptions();
}
}
@@ -0,0 +1,71 @@
<?php
namespace WeltPixel\LayeredNavigation\Model\Config\Source;
use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface;
use Magento\Framework\Data\OptionSourceInterface;
class HorizontalSidebarFilterPosition implements SourceInterface, OptionSourceInterface
{
/**
* block type
*/
const LEFT = 'left';
const CENTER = 'center';
/**
* Prepare display options.
*
* @return array
*/
public function getAvailableModes()
{
return [
self::LEFT => __('Left'),
self::CENTER => __('Center')
];
}
/**
* Retrieve All options
*
* @return array
*/
public function getAllOptions()
{
$result = [];
foreach ($this->getAvailableModes() as $index => $value) {
$result[] = ['value' => $index, 'label' => $value];
}
return $result;
}
/**
* Retrieve Option value text
*
* @param string $value
* @return mixed
*/
public function getOptionText($value)
{
$options = $this->getAvailableModes();
return isset($options[$value]) ? $options[$value] : null;
}
/**
* Return array of options as value-label pairs
*
* @return array Format: array(array('value' => '<value>', 'label' => '<label>'), ...)
*/
public function toOptionArray()
{
return $this->getAllOptions();
}
}
@@ -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 PriceFilter
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class PriceFilter implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
'1' => 'Default',
'2' => 'Slider'
);
/**
* @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 RatingFilterDisplay
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class RatingFilterDisplay implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
0 => 'Close',
1 => 'Open'
);
/**
* @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,43 @@
<?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',
'2' => 'Slide Down',
'3' => 'Horizontal View'
);
/**
* @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,120 @@
<?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;
use \Magento\Store\Model\StoreManagerInterface;
use \Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\View\Design\Theme\ThemeProviderInterface;
/**
* Class SlideDownFilterColumns
* @package WeltPixel\LayeredNavigation\Model\Config\Source
*/
class SlideDownFilterColumns implements ArrayInterface
{
/**
* @var array
*/
protected $_styles = array(
'99%' => '1 column',
'48.5%' => '2 columns',
'31.9%' => '3 columns',
'23.4%' => '4 columns',
'18.4%' => '5 columns',
'15.2%' => '6 columns',
);
/**
* @var array
*/
protected $_pearl_styles = array(
'99%' => '1 column',
'49%' => '2 columns',
'32.33%' => '3 columns',
'24%' => '4 columns',
'19%' => '5 columns',
'16.33%' => '6 columns',
);
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/** @var ThemeProviderInterface */
protected $themeProvider;
public function __construct(
StoreManagerInterface $storeManager,
ScopeConfigInterface $scopeConfig,
ThemeProviderInterface $themeProvider
)
{
$this->storeManager = $storeManager;
$this->scopeConfig = $scopeConfig;
$this->themeProvider = $themeProvider;
}
/**
* @return array
*/
public function toOptionArray()
{
$options = array();
if($this->_isPearlTheamActive()) {
foreach ($this->_pearl_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
} else {
foreach ($this->_styles as $id => $style) :
$options[] = array(
'value' => $id,
'label' => $style
);
endforeach;
}
return $options;
}
/**
* @return bool
* @throws \Exception
*/
protected function _isPearlTheamActive()
{
try {
$store = $this->storeManager->getStore();
$themeId = $this->scopeConfig->getValue(
\Magento\Framework\View\DesignInterface::XML_PATH_THEME_ID,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$store->getId()
);
$theme = $this->themeProvider->getThemeById($themeId);
$themePath = $theme->getThemePath();
if (strpos($themePath, 'Pearl') !== false) {
return true;
}
return false;
} catch (\Exception $ex) {
throw new \Exception('Store with id or code ' . $store->getId() . ' not found.');
}
}
}
@@ -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,361 @@
<?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;
/**
* @var \Magento\Framework\Stdlib\StringUtils
*/
protected $string;
/**
* @var int
*/
protected $selectedOptionsCounter = 0;
/**
* 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 \Magento\Framework\Stdlib\StringUtils $string
* @param array $data
* @throws \Magento\Framework\Exception\LocalizedException
*/
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,
\Magento\Framework\Stdlib\StringUtils $string,
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;
$this->string = $string;
}
/**
* @inheritdoc
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
if (!$this->_moduleHelper->isEnabled()) {
return $this->_getBaseApply($request);
}
$attributeValue = $request->getParam($this->_requestVar);
if (empty($attributeValue)) {
$this->_isFilter = false;
return $this;
}
$this->_requestParamVal = $this->_requestVar;
$attributeValue = explode(',', $attributeValue);
$this->selectedOptionsCounter = count($attributeValue);
$state = $this->getLayer()->getState();
foreach ($attributeValue as $value) {
$label = $this->getOptionText($value);
$state->addFilter($this->_createItem($label, $value));
}
$attribute = $this->getAttributeModel();
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 $this->_getBaseItemsData();
}
$attribute = $this->getAttributeModel();
$wpLnAttributeOptions = ($attribute->getId()) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attribute->getId()) : false;
if(!$wpLnAttributeOptions->getIsMultiselect() && $this->_isFilter) {
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"]);
}
/**
* @param $request
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _getBaseApply($request){
$attributeValue = $request->getParam($this->_requestVar);
if (empty($attributeValue) && !is_numeric($attributeValue)) {
return $this;
}
$attribute = $this->getAttributeModel();
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$productCollection = $this->getLayer()
->getProductCollection();
$productCollection->addFieldToFilter($attribute->getAttributeCode(), $attributeValue);
$label = $this->getOptionText($attributeValue);
$this->getLayer()
->getState()
->addFilter($this->_createItem($label, $attributeValue));
$this->setItems([]); // set items to disable show filtering
return $this;
}
/**
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _getBaseItemsData(){
$attribute = $this->getAttributeModel();
$this->_requestVar = $attribute->getAttributeCode();
$options = $attribute->getFrontend()->getSelectOptions();
$optionsCount = $this->_getResource()->getCount($this);
foreach ($options as $option) {
if (is_array($option['value'])) {
continue;
}
if ($this->string->strlen($option['value'])) {
// Check filter type
if ($this->getAttributeIsFilterable($attribute) == self::ATTRIBUTE_OPTIONS_ONLY_WITH_RESULTS) {
if (!empty($optionsCount[$option['value']])) {
$this->itemDataBuilder->addItemData(
$this->tagFilter->filter($option['label']),
$option['value'],
$optionsCount[$option['value']]
);
}
} else {
$this->itemDataBuilder->addItemData(
$this->tagFilter->filter($option['label']),
$option['value'],
isset($optionsCount[$option['value']]) ? $optionsCount[$option['value']] : 0
);
}
}
}
return $this->itemDataBuilder->build();
}
/**
* @return int
*/
public function getSelectedOptionsCounter()
{
return $this->selectedOptionsCounter;
}
}
@@ -0,0 +1,148 @@
<?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);
$categoryIds[] = $id;
if ($this->dataProvider->isValid()) {
$category = $this->dataProvider->getCategory();
if ($request->getParam('id') != $id) {
$this->getLayer()->getState()->addFilter($this->_createItem($category->getName(), $id));
}
}
}
if (sizeof($categoryIds)) {
$this->_isFilter = true;
$this->getLayer()->getProductCollection()->addLayerCategoryFilter($categoryIds);
}
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,341 @@
<?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;
use WeltPixel\LayeredNavigation\Model\AttributeOptions;
/**
* 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;
/** @var \Magento\Framework\Registry */
protected $_registry;
protected $_scopeConfig;
/**
* @var AttributeOptions
*/
protected $_wpAttributeOptions;
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @var int
*/
protected $selectedOptionsCounter = 0;
/**
* Price 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\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 LayerHelper $moduleHelper
* @param AttributeOptions $attributeOptions
* @param \WeltPixel\LayeredNavigation\Helper\Data $wpHelper
* @param \Magento\Framework\Registry $registry
* @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\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Tax\Helper\Data $taxHelper,
LayerHelper $moduleHelper,
AttributeOptions $attributeOptions,
\WeltPixel\LayeredNavigation\Helper\Data $wpHelper,
\Magento\Framework\Registry $registry,
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;
$this->_registry = $registry;
$this->_scopeConfig = $scopeConfig;
$this->_wpAttributeOptions = $attributeOptions;
$this->_wpHelper = $wpHelper;
}
/**
* @inheritdoc
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
$priceRangeCalculation = $this->_scopeConfig->getValue(
\Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory::XML_PATH_RANGE_CALCULATION,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
if($priceRangeCalculation != 'auto') {
return parent::apply($request);
}
$filterEntry = [];
if (!$this->_moduleHelper->isEnabled()) {
return parent::apply($request);
}
/**
* Filter must be string: $fromPrice-$toPrice
*/
$filter = $strFilter = $request->getParam($this->getRequestVar());
if (!$filter || is_array($filter)) {
return $this;
}
$collection = $this->getLayer()->getProductCollection();
$baseCollection = clone $collection;
$currentCatId = $this->_registry->registry('current_category') ? $this->_registry->registry('current_category')->getId() : false;
$priceFilter = $this->_registry->registry('price_filter') ?: [];
if ($currentCatId) {
if (!array_key_exists($currentCatId, $priceFilter)) {
$basePriceData = [
'min' => $baseCollection->getMinPrice(),
'max' => $baseCollection->getMaxPrice()
];
$filterEntry = [
$currentCatId => $basePriceData
];
$this->_registry->register('price_filter', $filterEntry);
}
}
$filterParams = explode(',', $filter);
$this->selectedOptionsCounter = count($filterParams);
$attribute = $this->getAttributeModel();
$wpLnAttributeOptions = ($attribute->getId()) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attribute->getId()) : false;
if (!$this->_wpHelper->getPriceIsSliderMode() && $wpLnAttributeOptions->getIsMultiselect()) {
$filterConditions = [];
foreach ($filterParams as $filterParam) {
$filter = $this->dataProvider->validateFilter($filterParam);
if (!$filter) {
continue;
}
$this->dataProvider->setInterval($filter);
$priorFilters = $this->dataProvider->getPriorFilters($filterParams);
if ($priorFilters) {
$this->dataProvider->setPriorIntervals($filterParams);
}
list($from, $to) = $this->_filterVal = $filter;
$filterConditions[] = [
'attribute' => 'price',
['from' => $from, 'to' => $to]
];
$this->getLayer()->getState()->addFilter(
$this->_createItem($this->_renderRangeLabel(empty($from) ? 0 : $from, $to), $filter)
);
}
$this->getLayer()->getProductCollection()->addAttributeToFilter(
$filterConditions
);
} else {
$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);
}
$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));
}
}
/**
* 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();
$wpLnAttributeOptions = ($attribute->getId()) ? $this->_wpAttributeOptions->getDisplayOptionsByAttribute($attribute->getId()) : false;
if (!$this->_wpHelper->getPriceIsSliderMode() && !$wpLnAttributeOptions->getIsMultiselect() && $this->_filterVal) {
return [];
}
/** @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, $wpLnAttributeOptions->getIsMultiselect(), $isLast);
}
}
return $data;
}
/**
* @param string $key
* @param int $count
* @param bool $isMultiSelect
* @param boolean $isLast
* @return array
*/
private function prepareData($key, $count, $isMultiSelect, $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;
if (!$isMultiSelect) {
$value .= $this->dataProvider->getAdditionalRequestData();
}
$data = [
'label' => $label,
'value' => $value,
'count' => $count,
'from' => $from,
'to' => $to,
];
return $data;
}
/**
* @return int
*/
public function getSelectedOptionsCounter()
{
return $this->selectedOptionsCounter;
}
}
@@ -0,0 +1,236 @@
<?php
/**
* @category WeltPixel
* @package WeltPixel_LayeredNavigation
* @copyright Copyright (c) 2018 Weltpixel
* @author Nagy Attila @ Weltpixel TEAM
*/
namespace WeltPixel\LayeredNavigation\Model\Layer\Filter;
use Magento\Catalog\Model\Layer;
use WeltPixel\LayeredNavigation\Helper\Data as LayerHelper;
/**
* Layer category filter
*
* @author Magento Core Team <core@magentocommerce.com>
*/
class Rating extends \Magento\Catalog\Model\Layer\Filter\AbstractFilter
{
/**
* Active Category Id
*
* @var int
*/
protected $_categoryId;
/**
* Applied Category
*
* @var \Magento\Catalog\Model\Category
*/
protected $_appliedCategory;
/**
* Core data
*
* @var \Magento\Framework\Escaper
*/
protected $_escaper;
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry;
/**
* @var CategoryDataProvider
*/
private $dataProvider;
/**
* @var \WeltPixel\LayeredNavigation\Helper\Data
*/
protected $_wpHelper;
/**
* @var int
*/
protected $selectedOptionsCounter = 0;
/**
* Rating constructor.
* @param \Magento\Framework\Registry $coreRegistry
* @param Layer\Filter\ItemFactory $filterItemFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param Layer $layer
* @param Layer\Filter\Item\DataBuilder $itemDataBuilder
* @param \Magento\Framework\Escaper $escaper
* @param LayerHelper $moduleHelper
* @param array $data
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function __construct(
\Magento\Framework\Registry $coreRegistry,
\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,
LayerHelper $moduleHelper,
array $data = []
) {
parent::__construct($filterItemFactory, $storeManager, $layer, $itemDataBuilder, $data);
$this->_escaper = $escaper;
$this->_wpHelper = $moduleHelper;
$this->_requestVar = $this->_wpHelper->getRatingParamLabel();
$this->_coreRegistry = $coreRegistry;
}
/**
* Apply category filter to layer
*
* @param \Magento\Framework\App\RequestInterface $request
* @return $this
*/
public function apply(\Magento\Framework\App\RequestInterface $request)
{
/**
* Filter must be string: $fromPrice-$toPrice
*/
$filter = $request->getParam($this->getRequestVar());
if (!$filter) {
return $this;
}
$filters = explode(',',$filter);
$this->selectedOptionsCounter = count($filters);
$collection = $this->getLayer()->getProductCollection();
$noRatingCollection = $collection->getCollectionClone();
$this->_coreRegistry->register('no_rating_coll', $noRatingCollection);
$collection->getSelect()->joinLeft(array('rating'=> 'rating_option_vote_aggregated'),'e.entity_id =rating.entity_pk_value',array("percent"))
->where("rating.store_id = ?", $this->_storeManager->getStore()->getId())
->group('e.entity_id');
foreach($filters as $reqFilter){
list($from,$to) = explode('-', $reqFilter);
$conditionArr[] = new \Zend_Db_Expr("rating.percent BETWEEN ".$from." AND ".$to);
}
$condString = '';
foreach($conditionArr as $condition) {
$condString .= " {$condition} OR";
}
$collection->getSelect()->where(substr($condString, 0, -2));
foreach($filters as $reqFilter) {
$state = $this->_createItem($this->getLabelHtml($reqFilter), $reqFilter)
->setVar($this->_requestVar);
$this->getLayer()->getState()->addFilter($state);
}
$collection->getSize();
return $this;
}
/**
* @return \Magento\Framework\Phrase|string
*/
public function getName()
{
$name = ($this->_wpHelper->getRatingFilterName()) ? $this->_wpHelper->getRatingFilterName() : 'Rating';
return __($name);
}
/**
* Get data array for building attribute filter items
*
* @throws \Magento\Framework\Exception\LocalizedException
* @return array
*/
protected function _getItemsData()
{
$collection = $this->_coreRegistry->registry('no_rating_coll');
if (!$this->_wpHelper->isRatingFilterMultiselect() && isset($collection) ) {
return [];
}
$facets = array(
'0-20' => $this->_getRatingLabelHtml(1),
'21-40' => $this->_getRatingLabelHtml(2),
'41-60' => $this->_getRatingLabelHtml(3),
'61-80' => $this->_getRatingLabelHtml(4),
'81-100' => $this->_getRatingLabelHtml(5),
);
if (count($facets) > 1) { // two range minimum
$i=1;
foreach ($facets as $key => $label) {
if (!$collection) {
$collection = $this->getLayer()->getProductCollection();
}
$clonedCollection = clone $collection;
$count = $this->prepareData($key, $clonedCollection, $i);
$i++;
if($count > 0) {
$this->itemDataBuilder->addItemData(
$label,
$key,
$count
);
}
}
}
return $this->itemDataBuilder->build();
}
/**
* @param string $key
* @param int $count
* @return array
*/
private function prepareData($filter,$collection,$i)
{
$filter = explode('-', $filter);
list($from, $to) = $filter;
$collection->clear();
/** @var \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $productCollection */
$collection->getSelect()->joinLeft(array('rating'.$i=> 'rating_option_vote_aggregated'),'e.entity_id =rating'.$i.'.entity_pk_value',array("percent"))
->where("rating".$i.".percent between ".$from." and ".$to)
->where("rating".$i.".store_id = ?", $this->_storeManager->getStore()->getId())
->group('e.entity_id');
return $collection->getSize();
}
/**
* @param $countStars
* @return string
*/
protected function _getRatingLabelHtml($countStars)
{
$html = '<div class="rating-summary" style="display: inline-block;margin-top: -5px;">
<div class="rating-result" title="up to '.$countStars*20 .'%"">
<span style="width:'.$countStars*20 .'%"></span>
</div>
</div>';
return $html;
}
/**
* @return int
*/
public function getSelectedOptionsCounter()
{
return $this->selectedOptionsCounter;
}
}
@@ -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,587 @@
<?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\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) {
$bucket = $aggregations->getBucket($field . RequestGenerator::BUCKET_SUFFIX);
if ($bucket) {
foreach ($bucket->getValues() as $value) {
$metrics = $value->getMetrics();
$result[$metrics['value']] = $metrics;
}
} else {
throw new StateException(__('Bucket does not exist'));
}
}
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' || $currentEngine == 'elasticsearch8') {
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';
}
}