Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Neom\CategoryLanding\Block\Widget\Bestsellers;
- use Magento\Catalog\Block\Product\AbstractProduct;
- use Magento\Catalog\Block\Product\Context;
- use Magento\Catalog\Block\Product\ImageBlockBuilder;
- use Magento\Catalog\Model\Product;
- use Magento\Catalog\Block\Widget\Link as CatalogLink;
- use Neom\CategoryLanding\Provider\Widget\Bestsellers\Product\CollectionProvider;
- /**
- * @author Diego Cabrejas <diego@wearejh.com>
- */
- class ProductList extends AbstractProduct
- {
- /**
- * @var CollectionProvider
- */
- private $collectionProvider;
- /**
- * @var ProductLink
- */
- private $productLink;
- public function __construct(
- Context $context,
- CollectionProvider $collectionProvider,
- CatalogLink $productLink,
- array $data = [],
- ImageBlockBuilder $imageBlockBuilder = null,
- string $var = ''
- ) {
- $this->collectionProvider = $collectionProvider;
- parent::__construct($context, $data, $imageBlockBuilder);
- $this->setTemplate('widget/bestsellers/product-list.phtml');
- $this->productLink = $productLink;
- }
- public function getProducts() : array
- {
- $products = $this->collectionProvider->getCollection($this->getProductIds())->getItems();
- usort($products, [$this, 'sortProducts']);
- //mark first item as Nicola's pick
- if (count($products)) {
- reset($products)->setIsNicolasPick(true);
- }
- return $products;
- }
- private function getProductIds() : array
- {
- $ids = [];
- foreach ($this->getProductIdPaths() as $idPath) {
- $ids[] = $this->getProductIdByPath($idPath);
- }
- return $ids;
- }
- private function getProductIdPaths() : array
- {
- return $this->getData('product_id_paths') ?? [];
- }
- private function getProductIdByPath(string $idPath) : string
- {
- $parts = explode('/', $idPath);
- if (!isset($parts[0]) || !isset($parts[1])) {
- throw new \RuntimeException('Wrong id_path structure.');
- }
- return $parts[1];
- }
- private function getProductPathByProductId(int $id) : string
- {
- foreach ($this->getProductIdPaths() as $idPath) {
- $productId = $this->getProductIdByPath($idPath);
- if ($productId === $id) {
- return $idPath;
- }
- }
- return '';
- }
- private function sortProducts(Product $productA, Product $productB)
- {
- $productIds = $this->getProductIds();
- return array_search($productA->getId(), $productIds) <=> array_search($productB->getId(), $productIds);
- }
- public function getProductLink(Product $product) : string
- {
- $idPath = $this->getProductPathByProductId($product->getId());
- $this->productLink->setData('id_path', $idPath);
- return $this->productLink->getHref();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement