Skip to content

Instantly share code, notes, and snippets.

@jalogut
Last active January 28, 2016 08:30
Show Gist options
  • Save jalogut/4bf660d894dfeafd69d2 to your computer and use it in GitHub Desktop.
Save jalogut/4bf660d894dfeafd69d2 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment