diff --git a/src/Model/Layer/Filter/Price.php b/src/Model/Layer/Filter/Price.php new file mode 100644 index 0000000..f89781c --- /dev/null +++ b/src/Model/Layer/Filter/Price.php @@ -0,0 +1,127 @@ + [ + 'request_name' => 'price', + 'label' => 'Price' + ], + ]; + + /** + * @param LayerFormatter $layerFormatter + */ + public function __construct( + LayerFormatter $layerFormatter, + StoreManagerInterface $storeManager + ) + { + $this->layerFormatter = $layerFormatter; + $this->storeManager = $storeManager; + } + + /** + * @inheritdoc + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function build(AggregationInterface $aggregation, ?int $storeId): array + { + $bucket = $aggregation->getBucket(self::PRICE_BUCKET); + if ($this->isBucketEmpty($bucket)) { + return []; + } + + $result = $this->layerFormatter->buildLayer( + self::$bucketMap[self::PRICE_BUCKET]['label'], + \count($bucket->getValues()), + self::$bucketMap[self::PRICE_BUCKET]['request_name'] + ); + + // Gets cuurrent currency rate + $currencyRate = $this->storeManager->getStore()->getCurrentCurrencyRate(); + + // Loops through-out each price range option + foreach ($bucket->getValues() as $value) { + $metrics = $value->getMetrics(); + + // Updates to correct currency + $priceRange = [ + 'from' => $this->getMetricValue($metrics['from'], $currencyRate), + 'to' => $this->getMetricValue($metrics['to'], $currencyRate) + ]; + + // Builds graph-ql response + $result['options'][] = $this->layerFormatter->buildItem( + $priceRange['from'] . '~' . $priceRange['to'], + $metrics['value'], + $metrics['count'] + ); + } + + return [$result]; + } + + /** + * Converts price to correct currency base, + * if notehing is set, then changes it to wildcard. + * + * @param $base + * @param $rate + * @return float|int|string + */ + private function getMetricValue($base, $rate) { + return (!is_null($base) && is_numeric($base)) ? $base * $rate : '*'; + } + + /** + * Check that bucket contains data + * + * @param BucketInterface|null $bucket + * @return bool + */ + private function isBucketEmpty(?BucketInterface $bucket): bool + { + return null === $bucket || !$bucket->getValues(); + } +} diff --git a/src/etc/di.xml b/src/etc/di.xml index 189cc4f..8e5dbcb 100755 --- a/src/etc/di.xml +++ b/src/etc/di.xml @@ -76,4 +76,7 @@ + +