ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
+97
View File
@@ -0,0 +1,97 @@
<?php
/**
* @author Olegnax
* @package Olegnax_LayeredNavigation
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
* @license Proprietary License https://olegnax.com/license/
*/
namespace Olegnax\LayeredNavigation\Model\Layer;
use Magento\Framework\App\RequestInterface;
class Filter
{
protected $request;
protected $_ids = [];
public function __construct(
RequestInterface $request
) {
$this->request = $request;
}
public function getItemUrl($item)
{
if ($this->isSelected($item)) {
return $item->getRemoveUrl();
}
return $item->getUrl();
}
public function getFilterValue($filter, $explode = true)
{
$filterValue = $this->request->getParam($filter->getRequestVar());
if (empty($filterValue)) {
return [];
}
if ($explode) {
if (is_string($filterValue)) {
$filterValue = explode(',', $filterValue);
}
}
return $filterValue;
}
public function isOptionReducesResults($filter, $optionCount, $totalSize)
{
$result = $optionCount <= $totalSize;
if ($this->isShowZero($filter)) {
return $result;
}
return $optionCount && $result;
}
public function isShowZero($filter)
{
return false;
}
public function isMainFilter($filter)
{
if (empty($this->_ids)) {
$this->_ids = $this->getStateAttributesIds($filter);
}
$isMulti = false;
if (count($this->_ids) <= 1) {
$isMulti = true;
if (!empty($this->_ids)) {
$isMulti = $this->isMultiselect($this->_ids[0]);
}
}
return $isMulti;
}
protected function getStateAttributesIds($filter)
{
$layer = $filter->getLayer();
foreach ($layer->getState()->getFilters() as $filter) {
if ($model = $filter->getFilter()->getData('attribute_model')) {
$this->_ids[] = $model->getId();
}
}
return array_unique($this->_ids);
}
public function isMultiselect($attrId)
{
return true;
}
}
@@ -0,0 +1,490 @@
<?php
/**
* @author Olegnax
* @package Olegnax_LayeredNavigation
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
* @license Proprietary License https://olegnax.com/license/
*/
namespace Olegnax\LayeredNavigation\Model\Layer\Filter;
use Amasty\ShopbyBase\Helper\FilterSetting;
use Exception;
use Magento\Catalog\Model\Layer;
use Magento\Catalog\Model\Layer\Filter\Item;
use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder;
use Magento\Catalog\Model\Layer\Filter\ItemFactory;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Filter\StripTags;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Search\Response\QueryResponse;
use Magento\Framework\Search\ResponseInterface;
use Magento\Search\Model\SearchEngine;
use Magento\Store\Model\StoreManagerInterface;
use Olegnax\LayeredNavigation\Helper\Helper;
use Olegnax\LayeredNavigation\Model\Request\Builder;
use Olegnax\LayeredNavigation\Model\ResourceModel\Fulltext\Collection;
use Psr\Log\LoggerInterface;
class Attribute extends \Magento\CatalogSearch\Model\Layer\Filter\Attribute
{
/**
* @var Helper
*/
protected $_helper;
/**
* @var bool
*/
protected $_isFilter = false;
/**
* @var SearchEngine
*/
protected $searchEngine;
/**
* @var ManagerInterface
*/
protected $messageManager;
/**
* @var array
*/
protected $attributeValues = [];
/**
* @var StripTags
*/
private $tagFilter;
public function __construct(
ItemFactory $filterItemFactory,
StoreManagerInterface $storeManager,
Layer $layer,
DataBuilder $itemDataBuilder,
StripTags $tagFilter,
Helper $helper,
SearchEngine $searchEngine,
ManagerInterface $messageManager,
array $data = []
) {
parent::__construct(
$filterItemFactory,
$storeManager,
$layer,
$itemDataBuilder,
$tagFilter,
$data
);
$this->_helper = $helper;
$this->searchEngine = $searchEngine;
$this->messageManager = $messageManager;
$this->tagFilter = $tagFilter;
}
/**
* Apply filter to collection
*
* @param RequestInterface $request
* @return $this
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @throws LocalizedException
*/
public function apply(RequestInterface $request)
{
if (!$this->pluginEnable()) {
return parent::apply($request);
}
$attributeValue = $request->getParam($this->getRequestVar());
if (empty($attributeValue)) {
return $this;
}
$attributeValue = explode(',', $attributeValue);
$this->setCurrentValue($attributeValue);
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
$attribute = $this->getAttributeModel();
$id = $attribute->getAttributeId();
if (!$this->isMultiselect($id) && count($attributeValue) > 1) {
$attributeValue = array_slice($attributeValue, 0, 1);
}
/** @var Collection $productCollection */
$productCollection = $this->getProductCollection();
$productCollection->addFieldToFilter($attribute->getAttributeCode(), $attributeValue);
if ($this->shouldAddState($id)) {
$this->addState($attributeValue);
}
if (!$this->isVisibleWhenSelected($id)) {
$this->setItems([]); // set items to disable show filtering
}
return $this;
}
/**
* @return bool
*/
public function pluginEnable()
{
return (bool)$this->_helper->isEnabled();
}
/**
* @param array $attributeValues
*/
protected function setCurrentValue(array $attributeValues)
{
$this->attributeValues = $attributeValues;
}
/**
* @param $id
* @return bool
* @noinspection PhpUnusedParameterInspection
*/
protected function isMultiselect($id)
{
return true;
}
/**
* @return \Magento\Catalog\Model\ResourceModel\Product\Collection
*/
protected function getProductCollection()
{
return $this->getLayer()->getProductCollection();
}
/**
* @param $id
* @return bool
* @noinspection PhpUnusedParameterInspection
*/
public function shouldAddState($id)
{
return !$this->isBrandingBrand();
}
/**
* @return bool
*/
protected function isBrandingBrand()
{
if (
class_exists('Amasty\ShopbyBrand\Helper\Content')
&& $contentHelper = ObjectManager::getInstance()->get('Amasty\ShopbyBrand\Helper\Content')
) {
$brand = $contentHelper->getCurrentBranding();
return $brand &&
(FilterSetting::ATTR_PREFIX . $this->getRequestVar() ==
$brand->getFilterCode());
}
return false;
}
/**
* @param $values
* @throws LocalizedException
*/
protected function addState($values)
{
$labels = [];
foreach ((array)$values as $value) {
$label = $this->getOptionText($value);
$labels[$value] = $label;
}
foreach ($labels as $id => $label) {
$item = $this->_createItem($label, $id);
$this->getLayer()->getState()
->addFilter(
$item
);
}
}
/**
* @param $id
* @return bool
* @noinspection PhpUnusedParameterInspection
*/
public function isVisibleWhenSelected($id)
{
return !$this->isBrandingBrand();
}
/**
* @param $a
* @param $b
* @return int|mixed
*/
public function sortOption($a, $b)
{
$pattern = '@^(\d+)@';
if (preg_match($pattern, $a['label'], $ma) && preg_match($pattern, $b['label'], $mb)) {
$r = $ma[1] - $mb[1];
if ($r != 0) {
return $r;
}
}
return strcasecmp($a['label'], $b['label']);
}
/**
* Get data array for building filter items
*
* Result array should have next structure:
* array(
* $index => array(
* 'label' => $label,
* 'value' => $value,
* 'count' => $count
* )
* )
*
* @return array
* @throws LocalizedException
*/
protected function _getItemsData()
{
if (!$this->pluginEnable()) {
return parent::_getItemsData();
}
$attribute = $this->getAttributeModel();
if ($this->hasCurrentValue() && !$this->isVisibleWhenSelected($attribute->getAttributeId())) {
return [];
}
$options = $this->getOptions();
$optionsFacetedData = $this->getOptionsFacetedData();
if (!$optionsFacetedData) {
return [];
}
$this->addItemsToDataBuilder($options, $optionsFacetedData);
$itemsData = $this->getItemsFromDataBuilder();
return $itemsData;
}
/**
* @return bool
*/
protected function hasCurrentValue()
{
return !empty($this->attributeValues);
}
/**
* @return array
* @throws LocalizedException
*/
protected function getOptions()
{
$attribute = $this->getAttributeModel();
$options = $attribute->getFrontend()->getSelectOptions();
usort($options, [$this, 'sortOption']);
return $options;
}
/**
* @return array
* @throws LocalizedException
*/
protected function getOptionsFacetedData()
{
$optionsFacetedData = $this->generateOptionsFacetedData();
if (count($optionsFacetedData)) {
$optionsFacetedData = $this->convertOptionsFacetedData($optionsFacetedData);
}
return $optionsFacetedData;
}
/**
* @return array
* @throws LocalizedException
* @noinspection PhpRedundantCatchClauseInspection
*/
protected function generateOptionsFacetedData()
{
$productCollection = $this->getProductCollection();
$attribute = $this->getAttributeModel();
$attributeCode = $attribute->getAttributeCode();
try {
$optionsFacetedData = $productCollection->getFacetedData(
$attributeCode,
$this->getAlteredQueryResponse()
);
} catch (StateException $e) {
if (!$this->messageManager->hasMessages()) {
$this->messageManager->addErrorMessage(
__('Make sure that "%1" attribute can be used in layered navigation', $attributeCode)
);
}
$optionsFacetedData = [];
}
return $optionsFacetedData;
}
/**
* @return QueryResponse|ResponseInterface|null
*/
protected function getAlteredQueryResponse()
{
$alteredQueryResponse = null;
if ($this->hasCurrentValue()) {
try {
$requestBuilder = $this->getRequestBuilder();
if (!$requestBuilder) {
return $alteredQueryResponse;
}
$queryRequest = $requestBuilder->create();
$alteredQueryResponse = $this->searchEngine->search($queryRequest);
} catch (Exception $e) {
$alteredQueryResponse = null;
}
}
return $alteredQueryResponse;
}
/**
* @return Builder|null
* @throws LocalizedException
*/
protected function getRequestBuilder()
{
$requestBuilder = $this->getMemRequestBuilder();
if (!$requestBuilder) {
return null;
}
$attributeCode = $this->getAttributeModel()->getAttributeCode();
$requestBuilder->removePlaceholder($attributeCode);
$requestBuilder->setAggregationsOnly($attributeCode);
return $requestBuilder;
}
/**
* @return Builder|null
*/
private function getMemRequestBuilder()
{
$productCollection = $this->getProductCollection();
if (method_exists($productCollection, 'getMemRequestBuilder')) {
return clone $productCollection->getMemRequestBuilder();
}
$this->_helper->_loadObject(LoggerInterface::class)
->error(__('Invalid class for product collection: ') . get_class($productCollection));
return null;
}
/**
* @param array $optionsFacetedData
* @return array
*/
protected function convertOptionsFacetedData(array $optionsFacetedData)
{
$values = $this->getCurrentValue();
foreach ($values as $value) {
if (!empty($value) && !array_key_exists($value, $optionsFacetedData)) {
$optionsFacetedData[$value] = [
'value' => $value,
'count' => 0,
];
}
}
return $optionsFacetedData;
}
/**
* @return array
*/
protected function getCurrentValue()
{
return $this->attributeValues;
}
/**
* @param array $options
* @param array $optionsFacetedData
* @throws LocalizedException
*/
protected function addItemsToDataBuilder(array $options, array $optionsFacetedData)
{
if (!$options) {
return;
}
foreach ($options as $option) {
if (empty($option['value'])) {
continue;
}
$isFilterableAttribute = $this->getAttributeIsFilterable($this->getAttributeModel());
if (isset($optionsFacetedData[$option['value']])
|| $isFilterableAttribute != static::ATTRIBUTE_OPTIONS_ONLY_WITH_RESULTS
) {
$count = 0;
if (isset($optionsFacetedData[$option['value']]['count'])) {
$count = $optionsFacetedData[$option['value']]['count'];
}
$this->itemDataBuilder->addItemData(
$this->tagFilter->filter($option['label']),
$option['value'],
$count
);
}
}
}
/**
* @return array
* @throws LocalizedException
*/
private function getItemsFromDataBuilder()
{
$itemsData = $this->itemDataBuilder->build();
if (count($itemsData) == 1
&& !$this->isOptionReducesResults(
$itemsData[0]['count'],
$this->getLayer()->getProductCollection()->getSize()
)
) {
$itemsData = $this->getReducedItemsData($itemsData);
}
return $itemsData;
}
/**
* @param array $itemsData
* @return array
* @throws LocalizedException
*/
protected function getReducedItemsData(array $itemsData)
{
$isFilterActive = false;
/** @var Item $filter */
foreach ($this->getLayer()->getState()->getFilters() as $filter) {
if ($filter->getFilter()->getRequestVar() == $this->getRequestVar()) {
$isFilterActive = true;
break;
}
}
return $isFilterActive ? $itemsData : [];
}
}
@@ -0,0 +1,521 @@
<?php
/**
* @author Olegnax
* @package Olegnax_LayeredNavigation
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
* @license Proprietary License https://olegnax.com/license/
*/
namespace Olegnax\LayeredNavigation\Model\Layer\Filter;
use Exception;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Model\Category as CategoryModel;
use Magento\Catalog\Model\Layer;
use Magento\Catalog\Model\Layer\Filter\DataProvider\CategoryFactory;
use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder;
use Magento\Catalog\Model\Layer\Filter\ItemFactory;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Escaper;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Search\Response\QueryResponse;
use Magento\Framework\Search\ResponseInterface;
use Magento\Search\Model\SearchEngine;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Model\StoreManagerInterface;
use Olegnax\LayeredNavigation\Helper\Helper;
use Olegnax\LayeredNavigation\Model\Layer\Filter;
use Olegnax\LayeredNavigation\Model\Request\Builder;
use Olegnax\LayeredNavigation\Model\ResourceModel\Fulltext\Collection;
use Psr\Log\LoggerInterface;
class Category extends \Magento\CatalogSearch\Model\Layer\Filter\Category
{
const FILTER_CODE = 'category';
const ATTRIBUTE_CODE = 'category_ids';
/**
* @var Helper
*/
protected $_helper;
/**
* @var array
*/
protected $attributeValues;
/**
* @var mixed
*/
protected $currentId;
/**
* @var bool
*/
protected $isSearch;
/**
* @var ManagerInterface
*/
protected $messageManager;
/**
* @var CategoryRepositoryInterface
*/
protected $categoryRepository;
/**
* @var SearchEngine
*/
protected $searchEngine;
/**
* @var Filter
*/
protected $layerFilter;
/**
* @var array
*/
protected $categorys = [];
/**
* @var CategoryModel
*/
protected $category;
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var Layer\Filter\DataProvider\Category
*/
private $dataProvider;
/**
* @var Escaper
*/
private $escaper;
/**
* @var int
*/
protected $maxDepth;
/**
* Category constructor.
* @param ItemFactory $filterItemFactory
* @param StoreManagerInterface $storeManager
* @param Layer $layer
* @param DataBuilder $itemDataBuilder
* @param Escaper $escaper
* @param CategoryFactory $categoryDataProviderFactory
* @param Helper $helper
* @param SearchEngine $searchEngine
* @param ManagerInterface $messageManager
* @param Filter $layerFilter
* @param CategoryModel $category
* @param array $data
* @throws LocalizedException
*/
public function __construct(
ItemFactory $filterItemFactory,
StoreManagerInterface $storeManager,
Layer $layer,
DataBuilder $itemDataBuilder,
Escaper $escaper,
CategoryFactory $categoryDataProviderFactory,
Helper $helper,
SearchEngine $searchEngine,
ManagerInterface $messageManager,
Filter $layerFilter,
CategoryModel $category,
array $data = []
) {
parent::__construct(
$filterItemFactory,
$storeManager,
$layer,
$itemDataBuilder,
$escaper,
$categoryDataProviderFactory,
$data
);
$this->storeManager = $storeManager;
$this->_helper = $helper;
$this->dataProvider = $categoryDataProviderFactory->create(['layer' => $this->getLayer()]);
$this->searchEngine = $searchEngine;
$this->messageManager = $messageManager;
$this->escaper = $escaper;
$this->layerFilter = $layerFilter;
$this->category = $category;
}
public function getMaxDepth()
{
if (null == $this->maxDepth) {
$this->maxDepth = abs((int)$this->_helper->getModuleConfig('category/depth'));
}
return $this->maxDepth;
}
/**
* @param RequestInterface $request
* @return $this|Category
* @noinspection PhpDeprecationInspection
*/
public function apply(RequestInterface $request)
{
if (!$this->pluginEnable()) {
return parent::apply($request);
}
$this->currentId = $request->getParam('id');
$this->isSearch = (bool)$request->getParam('q');
$categoryId = $request->getParam($this->_requestVar) ?: $this->currentId;
if (empty($categoryId)) {
return $this;
}
$categoryIds = explode(',', $categoryId);
$categoryIds = array_unique($categoryIds);
$this->setCurrentValue($categoryIds);
/** @var Collection $productCollection */
$productCollection = $this->getProductCollection();
if ($this->isMultiselect() && count($categoryIds) > 1) {
$productCollection->addIndexCategoriesFilter(['in' => $categoryIds]);
$category = $this->getLayer()->getCurrentCategory();
$child = $category->getCollection()
->addFieldToFilter($category->getIdFieldName(), ['in' => $categoryIds])
->addAttributeToSelect('name');
if ($this->shouldAddState()) {
$this->addState($categoryIds, $child);
}
} else {
$this->dataProvider->setCategoryId($categoryId);
$productCollection->addCategoryFilter($this->dataProvider->getCategory());
if ($this->shouldAddState()) {
$this->addState();
}
}
if (!$this->shouldVisible()) {
$this->setItems([]); // set items to disable show filtering
}
return $this;
}
/**
* @return bool
*/
public function pluginEnable()
{
return (bool)$this->_helper->isEnabled();
}
/**
* @param array $attributeValues
*/
protected function setCurrentValue(array $attributeValues)
{
$this->attributeValues = $attributeValues;
}
/**
* @return \Magento\Catalog\Model\ResourceModel\Product\Collection
*/
protected function getProductCollection()
{
return $this->getLayer()->getProductCollection();
}
/**
* @return bool
*/
protected function isMultiselect()
{
return true;
}
/**
* @return bool
*/
protected function shouldAddState()
{
return true;
}
/**
* @param array $values
* @param null $child
*/
protected function addState($values = [], $child = null)
{
if ($child) {
$labels = [];
foreach ((array)$values as $value) {
if ($currentCategory = $child->getItemById($value)) {
$labels[$currentCategory->getId()] = $currentCategory->getName();
}
}
foreach ($labels as $id => $categoryName) {
$state = $this->_createItem($categoryName, $id);
$this->getLayer()->getState()->addFilter($state);
}
} else {
$category = $this->dataProvider->getCategory();
if ($this->getCurrentCategoryId() != $category->getId() && $this->dataProvider->isValid()) {
$state = $this->_createItem($category->getName(), $category->getId());
$this->getLayer()->getState()->addFilter($state);
}
}
}
public function getCurrentCategoryId()
{
return $this->currentId ?: $this->getStore()->getRootCategoryId(); //$this->getRootCategory()->getId();
}
/**
* @return StoreInterface
* @throws NoSuchEntityException
*/
private function getStore()
{
return $this->storeManager->getStore();
}
/**
* @return bool
*/
protected function shouldVisible()
{
return true;
}
/**
* @return array
*/
public function _getItemsData()
{
if (!$this->pluginEnable()) {
return parent::_getItemsData();
}
$optionsFacetedData = $this->getOptionsFacetedData();
$this->dataProvider->setCategoryId($this->getCurrentCategoryId());
$categories = $this->getCategoryTree($this->dataProvider->getCategory());
foreach ($categories as $key => $category) {
if (isset($optionsFacetedData[$key])) {
$categories[$key]['count'] = $optionsFacetedData[$key]['count'];
$path = explode('/', $category['path']);
foreach ($path as $id) {
if (array_key_exists($id, $categories)) {
$categories[$id]['use'] = true;
}
}
}
}
$categories = array_filter($categories, [$this, 'filterCategory']);
return $categories;
}
/**
* Initialize filter items
*
* @return \Magento\Catalog\Model\Layer\Filter\AbstractFilter
*/
protected function _initItems()
{
$data = $this->_getItemsData();
$items = [];
foreach ($data as $itemData) {
$items[] = $this->_createItem(
$itemData['label'],
$itemData['value'],
$itemData['count']
)
->setData('item_level', isset($itemData['item_level']) ? $itemData['item_level'] : 0)
->setData('path', isset($itemData['path']) ? $itemData['path'] : '');
}
$this->_items = $items;
return $this;
}
/**
* @return array
*/
protected function getOptionsFacetedData()
{
return $this->generateOptionsFacetedData();
}
/**
* @return array
* @noinspection PhpRedundantCatchClauseInspection
*/
protected function generateOptionsFacetedData()
{
$productCollection = $this->getProductCollection();
$attributeCode = static::FILTER_CODE;
try {
$optionsFacetedData = $productCollection->getFacetedData(
$attributeCode,
$this->getAlteredQueryResponse()
);
} catch (StateException $e) {
if (!$this->messageManager->hasMessages()) {
$this->messageManager->addErrorMessage(
__('Make sure that "%1" attribute can be used in layered navigation', $attributeCode)
);
}
$optionsFacetedData = [];
}
return $optionsFacetedData;
}
/**
* @return QueryResponse|ResponseInterface|null
*/
protected function getAlteredQueryResponse()
{
$alteredQueryResponse = null;
$categoryIds = $this->getCurrentValue();
$categoryId = !empty($categoryIds) ? $categoryIds[0] : null;
if ($this->hasCurrentValue() && $categoryId != $this->getCurrentCategoryId()) {
try {
$requestBuilder = $this->getRequestBuilder();
if (!$requestBuilder) {
return $alteredQueryResponse;
}
$queryRequest = $requestBuilder->create();
$alteredQueryResponse = $this->searchEngine->search($queryRequest);
} catch (Exception $e) {
$alteredQueryResponse = null;
}
}
return $alteredQueryResponse;
}
/**
* @return array
*/
protected function getCurrentValue()
{
return $this->attributeValues;
}
/**
* @return bool
*/
protected function hasCurrentValue()
{
return !empty($this->attributeValues);
}
/**
* @return Builder|null
* @throws LocalizedException
*/
protected function getRequestBuilder()
{
$requestBuilder = $this->getMemRequestBuilder();
if (!$requestBuilder) {
return null;
}
$attributeCode = static::ATTRIBUTE_CODE;
$requestBuilder->removePlaceholder($attributeCode);
$requestBuilder->bind($attributeCode, $this->getCurrentCategoryId());
$requestBuilder->setAggregationsOnly($attributeCode);
return $requestBuilder;
}
/**
* @return Builder|null
*/
private function getMemRequestBuilder()
{
$productCollection = $this->getProductCollection();
if (method_exists($productCollection, 'getMemRequestBuilder')) {
return clone $productCollection->getMemRequestBuilder();
}
$this->_helper->_loadObject(LoggerInterface::class)
->error(__('Invalid class for product collection: ') . get_class($productCollection));
return null;
}
/**
* @param CategoryModel $category
* @param int $level
* @return array
*/
private function getCategoryTree($category, $level = 0)
{
$result = [];
if ($category->getIsActive()) {
$categories = $category->getChildrenCategories();
foreach ($categories as $category) {
if ($category->getIsActive()) {
$id = $category->getId();
$result[$id] = [
'label' => $this->escaper->escapeHtml($category->getName()),
'value' => $id,
'item_level' => $level,
'path' => $category->getPath(),
'count' => 0,
];
if ($this->getMaxDepth() > $level) {
$subItem = $this->getCategoryTree($category, $level + 1);
foreach ($subItem as $key => $item) {
$result[$key] = $item;
}
}
}
}
}
return $result;
}
/**
* @param array $item
* @return bool
*/
public function filterCategory($item)
{
return is_array($item) && array_key_exists('use', $item);
}
/**
* @param $filterItem
* @return bool
*/
public function getIsDisableAjax($filterItem)
{
$categoryItem = $this->getCategoryItem($filterItem);
return $categoryItem->getData('ox_nav_disable_ajax') || !$categoryItem->getIsAnchor();
}
/**
* @param $filterItem
* @return mixed
*/
private function getCategoryItem($filterItem)
{
$value = $filterItem->getValue();
if (!array_key_exists($value, $this->categorys)) {
$category = clone $this->category;
$this->categorys[$value] = $category->load($value);
}
return $this->categorys[$value];
}
/** @noinspection PhpDeprecationInspection */
/**
* @param $filterItem
* @return mixed
*/
public function getUrlItem($filterItem)
{
return $this->getCategoryItem($filterItem)->getUrl();
}
}
@@ -0,0 +1,488 @@
<?php
/**
* @author Olegnax
* @package Olegnax_LayeredNavigation
* @copyright Copyright (c) 2019 Olegnax (http://olegnax.com/). All rights reserved.
* @license Proprietary License https://olegnax.com/license/
*/
namespace Olegnax\LayeredNavigation\Model\Layer\Filter;
use Exception;
use Magento\Catalog\Model\Layer;
use Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory;
use Magento\Catalog\Model\Layer\Filter\Dynamic\AlgorithmFactory;
use Magento\Catalog\Model\Layer\Filter\Item\DataBuilder;
use Magento\Catalog\Model\Layer\Filter\ItemFactory;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Customer\Model\Session;
use Magento\Directory\Model\Currency;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\Registry;
use Magento\Framework\Search\Dynamic\Algorithm;
use Magento\Framework\Search\Response\QueryResponse;
use Magento\Framework\Search\ResponseInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Search\Model\SearchEngine;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Olegnax\LayeredNavigation\Helper\Helper;
use Olegnax\LayeredNavigation\Model\Request\Builder;
use Psr\Log\LoggerInterface;
class Price extends \Magento\CatalogSearch\Model\Layer\Filter\Price
{
/**
* @var Helper
*/
protected $_helper;
/**
* @var array
*/
protected $attributeValues = [];
/**
* @var Registry
*/
protected $coreRegistry;
/**
* @var ManagerInterface
*/
protected $messageManager;
/**
* @var SearchEngine
*/
protected $searchEngine;
/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var Json
*/
protected $json;
/**
* @var string
*/
protected $currencySymbol;
/**
* @var Layer\Filter\DataProvider\Price
*/
private $dataProvider;
/**
* Price constructor.
* @param ItemFactory $filterItemFactory
* @param StoreManagerInterface $storeManager
* @param Layer $layer
* @param DataBuilder $itemDataBuilder
* @param \Magento\Catalog\Model\ResourceModel\Layer\Filter\Price $resource
* @param Session $customerSession
* @param Algorithm $priceAlgorithm
* @param PriceCurrencyInterface $priceCurrency
* @param AlgorithmFactory $algorithmFactory
* @param PriceFactory $dataProviderFactory
* @param Helper $helper
* @param Registry $coreRegistry
* @param SearchEngine $searchEngine
* @param ManagerInterface $messageManager
* @param ScopeConfigInterface $scopeConfig
* @param Json $json
* @param array $data
* @noinspection PhpDeprecationInspection
*/
public function __construct(
ItemFactory $filterItemFactory,
StoreManagerInterface $storeManager,
Layer $layer,
DataBuilder $itemDataBuilder,
\Magento\Catalog\Model\ResourceModel\Layer\Filter\Price $resource,
Session $customerSession,
Algorithm $priceAlgorithm,
PriceCurrencyInterface $priceCurrency,
AlgorithmFactory $algorithmFactory,
PriceFactory $dataProviderFactory,
Helper $helper,
Registry $coreRegistry,
SearchEngine $searchEngine,
ManagerInterface $messageManager,
ScopeConfigInterface $scopeConfig,
Json $json,
array $data = []
) {
parent::__construct(
$filterItemFactory,
$storeManager,
$layer,
$itemDataBuilder,
$resource,
$customerSession,
$priceAlgorithm,
$priceCurrency,
$algorithmFactory,
$dataProviderFactory,
$data
);
$this->_helper = $helper;
$this->dataProvider = $dataProviderFactory->create(['layer' => $layer]);
$this->coreRegistry = $coreRegistry;
$this->searchEngine = $searchEngine;
$this->messageManager = $messageManager;
$this->scopeConfig = $scopeConfig;
$this->json = $json;
}
/**
* @param RequestInterface $request
* @return $this|Price
*/
public function apply(RequestInterface $request)
{
if (!$this->pluginEnable()) {
return parent::apply($request);
}
$filter = $request->getParam($this->getRequestVar());
if (empty($filter)) {
return $this;
}
if (is_string($filter)) {
$filter = explode(',', $filter);
}
$filterParams = $filter;
$filter = $this->dataProvider->validateFilter($filterParams[0]);
if (!$filter) {
return $this;
}
$this->setCurrentValue($filter);
$this->dataProvider->setInterval($filter);
$priorFilters = $this->dataProvider->getPriorFilters($filterParams);
if ($priorFilters) {
$this->dataProvider->setPriorIntervals($priorFilters);
}
[$from, $to] = $filter;
$this->getProductCollection()->addFieldToFilter(
'price',
[
'from' => $from,
'to' => $to,
]
);
if ($this->shouldAddState()) {
$this->addState($filter);
}
return $this;
}
/**
* @return bool
*/
public function pluginEnable()
{
return (bool)$this->_helper->isEnabled();
}
/**
* @param array $attributeValues
*/
protected function setCurrentValue(array $attributeValues)
{
$this->attributeValues = $attributeValues;
}
/**
* @return Collection
*/
protected function getProductCollection()
{
return $this->getLayer()->getProductCollection();
}
/**
* @return bool
*/
public function shouldAddState()
{
return true;
}
/**
* @param $values
*/
protected function addState($values)
{
[$from, $to] = $values;
$label = $this->_renderRangeLabel(empty($from) ? 0 : $from, $to);
$item = $this->_createItem($label, $values);
$this->getLayer()->getState()
->addFilter(
$item
);
}
/**
* @return bool
*/
public function getIsSlider()
{
return $this->pluginEnable() && $this->_helper->isPriceSlider();
}
/**
* @return bool|false|string
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function getSliderConfig()
{
/** @var Collection $productCollection */
$productCollection = $this->getProductCollection();
$format = explode('%s', $this->getOutputFormat());
if (2 != count($format)) {
$format = [
$this->getCurrencySymbol(),
''
];
}
$config = [
"min" => $productCollection->getMinPrice(),
"max" => $productCollection->getMaxPrice(),
"step" => 1,
"formatMoney" => [
"prefix" => $format[0] ?: '',
"suffix" => $format[1] ?: '',
],
];
return $this->json->serialize($config);
}
/**
* @return string
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function getCurrencySymbol()
{
if (empty($this->currencySymbol)) {
$this->currencySymbol = $this->getCurrentCurrency()->getCurrencySymbol();
}
return $this->currencySymbol;
}
/**
* @return Currency
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function getCurrentCurrency()
{
/** @var Store $store */
$store = $this->_storeManager->getStore();
/** @var Currency $currentCurrency */
$currentCurrency = $store->getCurrentCurrency();
return $currentCurrency;
}
/**
* @return string
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function getOutputFormat()
{
return $this->getCurrentCurrency()->getOutputFormat();
}
/**
* @return array
*/
protected function getCurrentValue()
{
return $this->attributeValues;
}
/**
* @return array
* @throws LocalizedException
*/
protected function _getItemsData()
{
if (!$this->_helper->isEnabled()) {
return parent::_getItemsData();
}
if ($this->hasCurrentValue() && !$this->shouldVisible()) {
return [];
}
$facets = $this->getFacetedData();
$data = [];
if (count($facets) > 1) { // two range minimum
$lastFacet = array_key_last($facets);
foreach ($facets as $key => $aggregation) {
$count = $aggregation['count'];
if (strpos($key, '_') === false) {
continue;
}
$isLast = $lastFacet === $key;
$data[] = $this->prepareData($key, $count, $isLast);
}
}
return $data;
}
/**
* @return bool
*/
protected function hasCurrentValue()
{
return !empty($this->attributeValues);
}
/**
* @return bool
*/
protected function shouldVisible()
{
return true;
}
/**
* @return array
* @throws LocalizedException
* @noinspection PhpDeprecationInspection
*/
protected function getFacetedData()
{
$key = 'facet_price_' . $this->getRequestVar();
if ($this->coreRegistry->registry($key) === null) {
$this->coreRegistry->register($key, $this->generateFacetedData());
}
return $this->coreRegistry->registry($key);
}
/**
* @return array
* @throws LocalizedException
* @noinspection PhpRedundantCatchClauseInspection
*/
protected function generateFacetedData()
{
$productCollection = $this->getProductCollection();
$attribute = $this->getAttributeModel();
$attributeCode = $attribute->getAttributeCode();
try {
$facetedData = $productCollection->getFacetedData(
$attributeCode,
$this->getAlteredQueryResponse()
);
} catch (StateException $e) {
if (!$this->messageManager->hasMessages()) {
$this->messageManager->addErrorMessage(
__('Make sure that "%1" attribute can be used in layered navigation', $attributeCode)
);
}
$facetedData = [];
}
return $facetedData;
}
/**
* @return QueryResponse|ResponseInterface|null
*/
protected function getAlteredQueryResponse()
{
$alteredQueryResponse = null;
if ($this->hasCurrentValue() &&
$this->scopeConfig->getValue(AlgorithmFactory::XML_PATH_RANGE_CALCULATION) !=
AlgorithmFactory::RANGE_CALCULATION_IMPROVED) {
try {
$requestBuilder = $this->getRequestBuilder();
if (!$requestBuilder) {
return $alteredQueryResponse;
}
$queryRequest = $requestBuilder->create();
$alteredQueryResponse = $this->searchEngine->search($queryRequest);
} catch (Exception $e) {
$alteredQueryResponse = null;
}
}
return $alteredQueryResponse;
}
/**
* @return Builder|null
* @throws LocalizedException
*/
protected function getRequestBuilder()
{
$requestBuilder = $this->getMemRequestBuilder();
if (!$requestBuilder) {
return null;
}
$attributeCode = $this->getAttributeModel()->getAttributeCode();
$requestBuilder->removePlaceholder($attributeCode . '.from');
$requestBuilder->removePlaceholder($attributeCode . '.to');
$requestBuilder->setAggregationsOnly($attributeCode);
return $requestBuilder;
}
/**
* @return Builder|null
*/
private function getMemRequestBuilder()
{
$productCollection = $this->getProductCollection();
if (method_exists($productCollection, 'getMemRequestBuilder')) {
return clone $productCollection->getMemRequestBuilder();
}
$this->_helper->_loadObject(LoggerInterface::class)
->error(__('Invalid class for product collection: ') . get_class($productCollection));
return null;
}
/**
* @param string $key
* @param int $count
* @return array
*/
private function prepareData($key, $count, $isLast = false)
{
[$from, $to] = explode('_', $key);
$label = $this->_renderRangeLabel(
empty($from) ? 0 : $from * $this->getCurrencyRate(), // @todo may need to be removed * $this->getCurrencyRate()
$to * $this->getCurrencyRate(), // @todo may need to be removed * $this->getCurrencyRate()
$isLast
);
$value = $from . '-' . $to . $this->dataProvider->getAdditionalRequestData();
$data = [
'label' => $label,
'value' => $value,
'count' => $count,
'from' => $from,
'to' => $to,
];
return $data;
}
}