Skip to content

Instantly share code, notes, and snippets.

@nttan
Forked from Vinai/or-example.php
Created July 27, 2018 02:49
Show Gist options
  • Save nttan/b2b14abe3b3df4c7b681a22a05fbf05d to your computer and use it in GitHub Desktop.
Save nttan/b2b14abe3b3df4c7b681a22a05fbf05d to your computer and use it in GitHub Desktop.
SearchCriteria OR Example for Magento 2
<?php
declare(strict_types = 1);
namespace Training5\VendorRepository\Controller\Test;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\Filter;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\Raw as RawResult;
use Magento\Framework\Controller\ResultFactory;
class OrExample extends Action
{
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @var FilterBuilder
*/
private $filterBuilder;
/**
* @var ResultFactory
*/
private $pageResultFactory;
public function __construct(
Context $context,
ProductRepositoryInterface $productRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
FilterBuilder $filterBuilder,
ResultFactory $pageResultFactory
) {
parent::__construct($context);
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->filterBuilder = $filterBuilder;
$this->pageResultFactory = $pageResultFactory;
}
public function execute(): RawResult
{
$skusToMatch = ['24-MB01', '24-MB04'];
$this->searchCriteriaBuilder->addFilters(array_map(function (string $sku): Filter {
return $this->filterBuilder->setField('sku')->setValue($sku)->create();
}, $skusToMatch));
$searchResult = $this->productRepository->getList($this->searchCriteriaBuilder->create());
$content = implode(PHP_EOL, array_map(function (ProductInterface $product): string {
return sprintf('%s (%s)', $product->getName(), $product->getSku());
}, $searchResult->getItems()));
return $this->createRawResultPage($content);
}
private function createRawResultPage(string $content): RawResult
{
/** @var RawResult $page */
$page = $this->pageResultFactory->create(ResultFactory::TYPE_RAW);
$page->setHeader('Content-Type', 'text/plain');
$page->setContents($content);
return $page;
}
}
Joust Duffle Bag (24-MB01)
Strive Shoulder Pack (24-MB04)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment