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
@@ -0,0 +1,74 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Elasticsearch\Catalog\Controller\Adminhtml\Product\Attribute;
use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save\AbstractSaveAttributeTest;
/**
* Test cases related to creating attribute and search engine.
*/
class SaveTest extends AbstractSaveAttributeTest
{
/**
* Default POST data for create attribute.
*
* @var array
*/
private const DEFAULT_ATTRIBUTE_POST_DATA = [
'active_tab' => 'main',
'frontend_label' => [
'0' => 'Test attribute name',
],
'frontend_input' => 'select',
'is_required' => '0',
'attribute_code' => 'filtrable_attribute',
'is_global' => '1',
'default_value_yesno' => '0',
'is_unique' => '0',
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
'is_filterable' => '1',
'is_filterable_in_search' => '0',
'is_searchable' => '0',
'is_comparable' => '0',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '0',
'used_in_product_listing' => '0',
];
/**
* @param array $data
* @param string $errorMessage
* @dataProvider createAttributeWithErrorDataProvider
*/
public function testCreateAttributeWithError(array $data, string $errorMessage): void
{
$this->createAttributeUsingDataWithErrorAndAssert(
array_merge(self::DEFAULT_ATTRIBUTE_POST_DATA, $data),
$errorMessage
);
}
/**
* @return array
*/
public function createAttributeWithErrorDataProvider(): array
{
return [
'should not create attribute with reserved code "category_name"' => [
[
'attribute_code' => 'category_name'
],
'The attribute code &#039;category_name&#039; is reserved by system. ' .
'Please try another attribute code'
]
];
}
}
@@ -0,0 +1,149 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Elasticsearch\Catalog\Model\Indexer\Category\Product\Action;
use Magento\Catalog\Api\CategoryListInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Helper\DefaultCategory;
use Magento\Catalog\Model\Indexer\Category\Product\Action\Rows;
use Magento\CatalogSearch\Model\ResourceModel\Fulltext\SearchCollectionFactory;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\TestModuleCatalogSearch\Model\SearchEngineVersionReader;
use Magento\Framework\Search\EngineResolverInterface;
/**
* Test for Magento\Catalog\Model\Indexer\Category\Product\Action\Rows class.
* This test executable with any configuration of ES and should not be deleted with removal of ES2.
*
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class RowsTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var Rows
*/
private $rowsIndexer;
/**
* @var DefaultCategory
*/
private $defaultCategoryHelper;
/**
* @var SearchCollectionFactory
*/
private $fulltextSearchCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->rowsIndexer = $this->objectManager->get(Rows::class);
$this->defaultCategoryHelper = $this->objectManager->get(DefaultCategory::class);
$this->fulltextSearchCollectionFactory = $this->objectManager->get(SearchCollectionFactory::class);
}
/**
* @inheritdoc
*/
protected function assertPreConditions(): void
{
$currentEngine = $this->objectManager->get(EngineResolverInterface::class)->getCurrentSearchEngine();
$installedEngine = $this->objectManager->get(SearchEngineVersionReader::class)->getFullVersion();
$this->assertEquals(
$installedEngine,
$currentEngine,
sprintf(
'Search engine configuration "%s" is not compatible with the installed version',
$currentEngine
)
);
}
/**
* @magentoDataFixture Magento/Catalog/_files/category_tree_with_products.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
* @magentoDataFixtureBeforeTransaction Magento/Catalog/_files/enable_reindex_schedule.php
* @return void
*/
public function testLoadWithFilterCatalogView()
{
$categoryA = $this->getCategory('Category A');
$categoryB = $this->getCategory('Category B');
$categoryC = $this->getCategory('Category C');
/** Move $categoryB to $categoryA */
$categoryB->move($categoryA->getId(), null);
$this->rowsIndexer->execute(
[
$this->defaultCategoryHelper->getId(),
$categoryA->getId(),
$categoryB->getId(),
$categoryC->getId(),
],
true
);
$fulltextCollection = $this->fulltextSearchCollectionFactory->create()
->addCategoryFilter($categoryA);
$this->assertProductsArePresentInCollection($fulltextCollection->getAllIds());
}
/**
* Assert that expected products are present in collection.
*
* @param array $productIds
*
* @return void
*/
private function assertProductsArePresentInCollection(array $productIds): void
{
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$firstProductId = $productRepository->get('simpleB')->getId();
$secondProductId = $productRepository->get('simpleC')->getId();
$this->assertCount(2, $productIds);
$this->assertContains($secondProductId, $productIds);
$this->assertContains($firstProductId, $productIds);
}
/**
* Gets category by name.
*
* @param string $name
* @return CategoryInterface
*/
private function getCategory(string $name): CategoryInterface
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('name', $name)
->create();
/** @var CategoryListInterface $repository */
$repository = $this->objectManager->get(CategoryListInterface::class);
$items = $repository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
}
@@ -0,0 +1,165 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Elasticsearch\Controller\Adminhtml\Category;
use Magento\Catalog\Api\CategoryListInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Indexer\Category\Product as CategoryIndexer;
use Magento\CatalogSearch\Model\Indexer\Fulltext as FulltextIndexer;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Indexer\IndexerInterface;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class SaveTest extends AbstractBackendController
{
private $indexerSchedule = [];
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->changeIndexerSchedule(FulltextIndexer::INDEXER_ID, true);
$this->changeIndexerSchedule(CategoryIndexer::INDEXER_ID, true);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->changeIndexerSchedule(FulltextIndexer::INDEXER_ID, $this->indexerSchedule[FulltextIndexer::INDEXER_ID]);
$this->changeIndexerSchedule(CategoryIndexer::INDEXER_ID, $this->indexerSchedule[CategoryIndexer::INDEXER_ID]);
parent::tearDown();
}
/**
* Checks a case when indexers are invalidated if products for category were changed.
*
* @magentoConfigFixture current_store catalog/frontend/flat_catalog_category true
* @magentoDataFixture Magento/Catalog/_files/category_product.php
* @magentoDataFixture Magento/Catalog/_files/multiple_products.php
*/
public function testExecute()
{
$fulltextIndexer = $this->getIndexer(FulltextIndexer::INDEXER_ID);
self::assertTrue($fulltextIndexer->isValid(), 'Fulltext indexer should be valid.');
$categoryIndexer = $this->getIndexer(CategoryIndexer::INDEXER_ID);
self::assertTrue($categoryIndexer->isValid(), 'Category indexer should be valid.');
$category = $this->getCategory('Category 1');
$productIdList = $this->getProductIdList(['simple1', 'simple2', 'simple3']);
$inputData = [
'category_products' => json_encode(array_fill_keys($productIdList, [0, 1, 2])),
'entity_id' => $category->getId(),
'default_sort_by' => 'position'
];
$this->getRequest()->setPostValue($inputData);
$this->getRequest()->setMethod('POST');
$this->dispatch('backend/catalog/category/save');
$this->assertSessionMessages(
self::equalTo(['You saved the category.']),
MessageInterface::TYPE_SUCCESS
);
$fulltextIndexer = $this->getIndexer(FulltextIndexer::INDEXER_ID);
self::assertTrue($fulltextIndexer->isInvalid(), 'Fulltext indexer should be invalidated.');
$categoryIndexer = $this->getIndexer(CategoryIndexer::INDEXER_ID);
self::assertTrue($categoryIndexer->isInvalid(), 'Category indexer should be invalidated.');
}
/**
* Gets indexer from registry by ID.
*
* @param string $indexerId
* @return IndexerInterface
*/
private function getIndexer(string $indexerId): IndexerInterface
{
/** @var IndexerRegistry $indexerRegistry */
$indexerRegistry = $this->_objectManager->get(IndexerRegistry::class);
return $indexerRegistry->get($indexerId);
}
/**
* Changes the scheduled state of indexer.
*
* @param string $indexerId
* @param bool $isScheduled
* @return void
*/
private function changeIndexerSchedule(string $indexerId, bool $isScheduled): void
{
$indexer = $this->getIndexer($indexerId);
if (!isset($this->indexerSchedule[$indexerId])) {
$this->indexerSchedule[$indexerId] = $indexer->isScheduled();
$indexer->reindexAll();
}
$indexer->setScheduled($isScheduled);
}
/**
* Gets category by name.
*
* @param string $name
* @return CategoryInterface
*/
private function getCategory(string $name): CategoryInterface
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('name', $name)
->create();
/** @var CategoryListInterface $repository */
$repository = $this->_objectManager->get(CategoryListInterface::class);
$items = $repository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
/**
* Gets list of product ID by SKU.
*
* @param array $skuList
* @return array
*/
private function getProductIdList(array $skuList): array
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('sku', $skuList, 'in')
->create();
/** @var ProductRepositoryInterface $repository */
$repository = $this->_objectManager->get(ProductRepositoryInterface::class);
$items = $repository->getList($searchCriteria)
->getItems();
$idList = array_map(
function (ProductInterface $item) {
return $item->getId();
},
$items
);
return $idList;
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Elasticsearch\Controller;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\TestCase\AbstractController;
class QuickSearchTest extends AbstractController
{
/**
* Tests quick search with "Price Navigation Step Calculation" sets to "Automatic (equalize product counts)".
*
* @magentoAppArea frontend
* @magentoDbIsolation disabled
* @magentoConfigFixture fixturestore_store catalog/layered_navigation/price_range_calculation improved
* @magentoConfigFixture fixturestore_store catalog/layered_navigation/one_price_interval 1
* @magentoConfigFixture fixturestore_store catalog/layered_navigation/interval_division_limit 1
* @magentoDataFixture Magento/Catalog/_files/products_for_search.php
* @magentoDataFixture Magento/Store/_files/core_fixturestore.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
*/
public function testQuickSearchWithImprovedPriceRangeCalculation()
{
$storeManager = $this->_objectManager->get(StoreManagerInterface::class);
$secondStore = $storeManager->getStore('fixturestore');
$storeManager->setCurrentStore($secondStore);
try {
$this->dispatch('/catalogsearch/result/?q=search+product');
$responseBody = $this->getResponse()->getBody();
} finally {
$defaultStore = $storeManager->getStore('default');
$storeManager->setCurrentStore($defaultStore);
}
$this->assertStringContainsString('search product 1', $responseBody);
}
/**
* Tests quick search with "Minimum Terms to Match" sets to "100%".
*
* @magentoAppArea frontend
* @magentoDbIsolation disabled
* @magentoConfigFixture current_store catalog/search/elasticsearch7_minimum_should_match 100%
* @magentoConfigFixture current_store catalog/search/elasticsearch8_minimum_should_match 100%
* @magentoConfigFixture current_store catalog/search/opensearch_minimum_should_match 100%
* @magentoDataFixture Magento/Elasticsearch/_files/products_for_search.php
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
*/
public function testQuickSearchWithMinimumTermsToMatch()
{
$this->dispatch('/catalogsearch/result/?q=24+MB04');
$responseBody = $this->getResponse()->getBody();
$this->assertStringContainsString('search product 2', $responseBody);
$this->assertStringNotContainsString('search product 1', $responseBody);
}
}
@@ -0,0 +1,106 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Elasticsearch\Elasticsearch5\SearchAdapter;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class AdapterTest to test Elasticsearch search adapter
*/
class AdapterTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Adapter
*/
private $adapter;
/**
* @var \Magento\AdvancedSearch\Model\Client\ClientInterface|\PHPUnit\Framework\MockObject\MockObject
*/
private $clientMock;
/**
* @var \Magento\Framework\Search\Request\Builder
*/
private $requestBuilder;
/**
* @var \Psr\Log\LoggerInterface|\PHPUnit\Framework\MockObject\MockObject
*/
private $loggerMock;
/**
* @return void
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$contentManager = $this->getMockBuilder(\Magento\Elasticsearch\SearchAdapter\ConnectionManager::class)
->disableOriginalConstructor()
->getMock();
$this->clientMock = $this->getMockBuilder(\Magento\AdvancedSearch\Model\Client\ClientInterface::class)
->setMethods(['query', 'testConnection'])
->disableOriginalConstructor()
->getMock();
$contentManager
->expects($this->any())
->method('getConnection')
->willReturn($this->clientMock);
/** @var \Magento\Framework\Search\Request\Config\Converter $converter */
$converter = $objectManager->create(\Magento\Framework\Search\Request\Config\Converter::class);
$document = new \DOMDocument();
$document->load($this->getRequestConfigPath());
$requestConfig = $converter->convert($document);
/** @var \Magento\Framework\Search\Request\Config $config */
$config = $objectManager->create(\Magento\Framework\Search\Request\Config::class);
$config->merge($requestConfig);
$this->requestBuilder = $objectManager->create(
\Magento\Framework\Search\Request\Builder::class,
['config' => $config]
);
$this->loggerMock = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class);
$this->adapter = $objectManager->create(
\Magento\Elasticsearch\Elasticsearch5\SearchAdapter\Adapter::class,
[
'connectionManager' => $contentManager,
'logger' => $this->loggerMock
]
);
}
/**
* @magentoAppIsolation enabled
* @return void
*/
public function testQuery()
{
$this->requestBuilder->bind('fulltext_search_query', 'socks');
$this->requestBuilder->setRequestName('one_match');
$queryRequest = $this->requestBuilder->create();
$exception = new \Exception('Test Message');
$this->loggerMock->expects($this->once())->method('critical')->with($exception);
$this->clientMock->expects($this->once())->method('query')->willThrowException($exception);
$actualResponse = $this->adapter->query($queryRequest);
$this->assertEmpty($actualResponse->getAggregations()->getBuckets());
$this->assertEquals(0, $actualResponse->count());
}
/**
* Get request config path
*
* @return string
*/
private function getRequestConfigPath()
{
return __DIR__ . '/../../_files/requests.xml';
}
}
@@ -0,0 +1,256 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Elasticsearch\Model\Adapter;
use Magento\AdvancedSearch\Model\Client\ClientInterface;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
use Magento\Catalog\Setup\CategorySetup;
use Magento\CatalogSearch\Model\Indexer\IndexerHandlerFactory;
use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend;
use Magento\Elasticsearch\Model\Adapter\Index\BuilderInterface;
use Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver;
use Magento\Elasticsearch\Model\Indexer\IndexerHandler;
use Magento\Elasticsearch\SearchAdapter\ConnectionManager;
use Magento\Framework\Indexer\DimensionFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Stdlib\ArrayManager;
use Magento\Indexer\Model\Indexer;
use Magento\Store\Model\StoreDimensionProvider;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Elasticsearch adapter model test class
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ElasticsearchTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var IndexNameResolver
*/
private $indexNameResolver;
/**
* @var ClientInterface
*/
private $client;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var Elasticsearch
*/
private $adapter;
/**
* @var BuilderInterface
*/
private $indexBuilder;
/**
* @var ArrayManager
*/
private $arrayManager;
/**
* @var string
*/
private $newIndex;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->indexNameResolver = $this->objectManager->get(IndexNameResolver::class);
$this->adapter = $this->objectManager->get(Elasticsearch::class);
$this->storeManager = $this->objectManager->create(StoreManagerInterface::class);
$connectionManager = $this->objectManager->create(ConnectionManager::class);
$this->client = $connectionManager->getConnection();
$this->indexBuilder = $this->objectManager->get(BuilderInterface::class);
$this->arrayManager = $this->objectManager->get(ArrayManager::class);
}
/**
* @inheritdoc
*/
public function tearDown(): void
{
if ($this->newIndex) {
$this->deleteIndex($this->newIndex);
}
}
/**
* Tests possibility to create mapping if adapter has obsolete index name in cache
*
* @magentoDataFixture Magento/Elasticsearch/_files/select_attribute.php
* @return void
*/
public function testRetryOnIndexNotFoundException(): void
{
$this->reindex();
$this->updateElasticsearchIndex();
$this->createNewAttribute();
$mapping = $this->client->getMapping(['index' => $this->newIndex]);
$pathField = $this->arrayManager->findPath('properties', $mapping);
$attributes = $this->arrayManager->get($pathField, $mapping, []);
$this->assertArrayHasKey('multiselect_attribute', $attributes);
}
/**
* Test that new fields are not added during document indexing that were not explicitly defined in the mapping
*
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDataFixture Magento/Store/_files/second_store.php
* @magentoDbIsolation disabled
*/
public function testMappingShouldNotChangeAfterReindex(): void
{
$index = 'catalogsearch_fulltext';
$storeId = (int) $this->storeManager->getStore('fixture_second_store')->getId();
// Create empty index and save the initial mapping
$dimensionFactory = $this->objectManager->get(DimensionFactory::class);
$dimensions = [
StoreDimensionProvider::DIMENSION_NAME => $dimensionFactory->create(
StoreDimensionProvider::DIMENSION_NAME,
(string) $storeId
)
];
$indexHandlerFactory = $this->objectManager->get(IndexerHandlerFactory::class);
/** @var IndexerHandler $indexHandler */
$indexHandler = $indexHandlerFactory->create(
[
'data' => [
'indexer_id' => $index
]
]
);
$indexHandler->cleanIndex($dimensions);
$indexHandler->saveIndex($dimensions, new \ArrayIterator([]));
$propertiesBefore = $this->getIndexMapping($storeId);
$this->reindex();
$propertiesAfter = $this->getIndexMapping($storeId);
$this->assertEquals($propertiesBefore, $propertiesAfter);
}
/**
* Prepare and save new attribute
*
* @return void
*/
public function createNewAttribute(): void
{
/** @var CategorySetup $installer */
$installer = $this->objectManager->get(CategorySetup::class);
/** @var Attribute $attribute */
$multiselectAttribute = $this->objectManager->get(Attribute::class);
$multiselectAttribute->setData(
[
'attribute_code' => 'multiselect_attribute',
'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
'is_global' => 1,
'is_user_defined' => 1,
'frontend_input' => 'multiselect',
'is_unique' => 0,
'is_required' => 0,
'is_searchable' => 1,
'is_visible_in_advanced_search' => 0,
'is_comparable' => 0,
'is_filterable' => 1,
'is_filterable_in_search' => 0,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 0,
'used_in_product_listing' => 0,
'used_for_sort_by' => 0,
'frontend_label' => ['Multiselect Attribute'],
'backend_type' => 'text',
'backend_model' => ArrayBackend::class,
'option' => [
'value' => [
'dog' => ['Dog'],
'cat' => ['Cat'],
],
'order' => [
'dog' => 1,
'cat' => 2,
],
],
]
);
$multiselectAttribute->save();
}
/**
* Prepare new index and delete old. Keep cache alive.
*
* @return void
*/
private function updateElasticsearchIndex(): void
{
$storeId = (int)$this->storeManager->getDefaultStoreView()->getId();
$mappedIndexerId = 'product';
$this->adapter->updateIndexMapping($storeId, $mappedIndexerId, 'select_attribute');
$oldIndex = $this->indexNameResolver->getIndexFromAlias($storeId, $mappedIndexerId);
$this->newIndex = $oldIndex . '1';
$this->deleteIndex($this->newIndex);
$this->indexBuilder->setStoreId($storeId);
$this->client->createIndex($this->newIndex, ['settings' => $this->indexBuilder->build()]);
$this->client->updateAlias(
$this->indexNameResolver->getIndexNameForAlias($storeId, $mappedIndexerId),
$this->newIndex,
$oldIndex
);
$this->client->deleteIndex($oldIndex);
}
/**
* Delete index by name if exists
*
* @param $newIndex
*/
private function deleteIndex($newIndex): void
{
if ($this->client->indexExists($newIndex)) {
$this->client->deleteIndex($newIndex);
}
}
/**
* @return void
*/
private function reindex(): void
{
$indexer = $this->objectManager->create(Indexer::class);
$indexer->load('catalogsearch_fulltext');
$indexer->reindexAll();
}
/**
* @param int $storeId
* @return array
*/
private function getIndexMapping(int $storeId): array
{
$indexName = $this->indexNameResolver->getIndexName($storeId, 'product', []);
$mapping = $this->client->getMapping(['index' => $indexName]);
$pathField = $this->arrayManager->findPath('properties', $mapping);
return $this->arrayManager->get($pathField, $mapping, []);
}
}
@@ -0,0 +1,100 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Elasticsearch\Model\CatalogSearch;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\CatalogSearch\Model\Advanced;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Check catalog Advanced Search
*/
class AdvancedTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Registry
*/
private $registry;
/**
* @var Visibility
*/
private $productVisibility;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->productVisibility = $this->objectManager->get(Visibility::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
}
/**
* Check that Advanced Search does NOT return products that do NOT have search visibility.
*
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_product_with_two_child_products.php
* @return void
*/
public function testAddFilters(): void
{
$this->assertResultsAfterRequest(1);
/** @var ProductInterface $configurableProductOption */
$configurableProductOption = $this->productRepository->get('Simple option 1');
$configurableProductOption->setVisibility(Visibility::VISIBILITY_IN_SEARCH);
$this->productRepository->save($configurableProductOption);
$this->registry->unregister('advanced_search_conditions');
$this->assertResultsAfterRequest(2);
}
/**
* Do search query and assert results.
*
* @param int $count
* @return void
*/
private function assertResultsAfterRequest(int $count): void
{
/** @var Advanced $advancedSearch */
$advancedSearch = $this->objectManager->create(Advanced::class);
$advancedSearch->addFilters(['name' => 'Configurable']);
/** @var ProductInterface[] $itemsResult */
$itemsResult = $advancedSearch->getProductCollection()
->addAttributeToSelect(ProductInterface::VISIBILITY)
->getItems();
$this->assertCount($count, $itemsResult);
foreach ($itemsResult as $product) {
$this->assertStringContainsString('Configurable', $product->getName());
$this->assertContains((int)$product->getVisibility(), $this->productVisibility->getVisibleInSearchIds());
}
}
}
@@ -0,0 +1,158 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Elasticsearch\Model\Client;
use Magento\AdvancedSearch\Model\Client\ClientInterface;
use Magento\Indexer\Model\Indexer;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Elasticsearch\SearchAdapter\ConnectionManager;
use Magento\Elasticsearch\Model\Config;
use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver;
use Magento\TestModuleCatalogSearch\Model\SearchEngineVersionReader;
use Magento\Framework\Search\EngineResolverInterface;
/**
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Elasticsearch/_files/configurable_products.php
*/
class ElasticsearchTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ConnectionManager
*/
private $connectionManager;
/**
* @var ClientInterface
*/
private $client;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var Config
*/
private $clientConfig;
/**
* @var SearchIndexNameResolver
*/
private $searchIndexNameResolver;
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->connectionManager = $objectManager->create(ConnectionManager::class);
$this->client = $this->connectionManager->getConnection();
$this->storeManager = $objectManager->create(StoreManagerInterface::class);
$this->clientConfig = $objectManager->create(Config::class);
$this->searchIndexNameResolver = $objectManager->create(SearchIndexNameResolver::class);
$indexer = $objectManager->create(Indexer::class);
$indexer->load('catalogsearch_fulltext');
$indexer->reindexAll();
}
/**
* Make sure that correct engine is set
*/
protected function assertPreConditions(): void
{
$objectManager = Bootstrap::getObjectManager();
$currentEngine = $objectManager->get(EngineResolverInterface::class)->getCurrentSearchEngine();
$installedEngine = $objectManager->get(SearchEngineVersionReader::class)->getFullVersion();
$this->assertEquals(
$installedEngine,
$currentEngine,
sprintf(
'Search engine configuration "%s" is not compatible with the installed version',
$currentEngine
)
);
}
/**
* @param string $text
* @return array
*/
private function search($text)
{
$storeId = $this->storeManager->getDefaultStoreView()->getId();
$searchQuery = [
'index' => $this->searchIndexNameResolver->getIndexName($storeId, 'catalogsearch_fulltext'),
'type' => $this->clientConfig->getEntityType(),
'body' => [
'query' => [
'bool' => [
'minimum_should_match' => 1,
'should' => [
[
'match' => [
'_all' => $text,
],
],
],
],
],
],
];
$queryResult = $this->client->query($searchQuery);
return isset($queryResult['hits']['hits']) ? $queryResult['hits']['hits'] : [];
}
/**
* @return void
*/
public function testSearchConfigurableProductBySimpleProductName()
{
$this->assertProductWithSkuFound('configurable', $this->search('Configurable Option'));
}
/**
* @return void
*/
public function testSearchConfigurableProductBySimpleProductAttributeMultiselect()
{
$this->assertProductWithSkuFound('configurable', $this->search('dog'));
}
/**
* @return void
*/
public function testSearchConfigurableProductBySimpleProductAttributeSelect()
{
$this->assertProductWithSkuFound('configurable', $this->search('chair'));
}
/**
* @return void
*/
public function testSearchConfigurableProductBySimpleProductAttributeShortDescription()
{
$this->assertProductWithSkuFound('configurable', $this->search('simpledescription'));
}
/**
* Assert that product with SKU is present in response
*
* @param string $sku
* @param array $result
* @return bool
*/
private function assertProductWithSkuFound($sku, array $result)
{
foreach ($result as $item) {
if ($item['_source']['sku'] == $sku) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,194 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Elasticsearch\Model\Indexer\Fulltext\Plugin\Category\Product;
use Magento\AdvancedSearch\Model\Client\ClientInterface;
use Magento\Catalog\Api\Data\EavAttributeInterface;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory;
use Magento\Catalog\Setup\CategorySetup;
use Magento\CatalogSearch\Model\Indexer\Fulltext\Processor;
use Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver;
use Magento\Elasticsearch\SearchAdapter\ConnectionManager;
use Magento\Framework\Stdlib\ArrayManager;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Check Search engine indexer mapping when working with attributes.
*/
class AttributeTest extends TestCase
{
/**
* @var ClientInterface
*/
private $client;
/**
* @var ArrayManager
*/
private $arrayManager;
/**
* @var IndexNameResolver
*/
private $indexNameResolver;
/**
* @var Processor
*/
private $indexerProcessor;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var CategorySetup
*/
private $installer;
/**
* @var AttributeFactory
*/
private $attributeFactory;
/**
* @var ProductAttributeRepositoryInterface
*/
private $attributeRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$connectionManager = Bootstrap::getObjectManager()->get(ConnectionManager::class);
$this->client = $connectionManager->getConnection();
$this->arrayManager = Bootstrap::getObjectManager()->get(ArrayManager::class);
$this->indexNameResolver = Bootstrap::getObjectManager()->get(IndexNameResolver::class);
$this->indexerProcessor = Bootstrap::getObjectManager()->get(Processor::class);
$this->storeManager = Bootstrap::getObjectManager()->get(StoreManagerInterface::class);
$this->installer = Bootstrap::getObjectManager()->get(CategorySetup::class);
$this->attributeFactory = Bootstrap::getObjectManager()->get(AttributeFactory::class);
$this->attributeRepository = Bootstrap::getObjectManager()->get(ProductAttributeRepositoryInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
parent::tearDown();
/** @var ProductAttributeInterface $attribute */
$attribute = $this->attributeRepository->get('dropdown_attribute');
$this->attributeRepository->delete($attribute);
}
/**
* Check Search engine indexer mapping is updated after creating attribute.
*
* @return void
* @magentoDataFixture Magento/CatalogSearch/_files/full_reindex.php
*/
public function testCheckElasticsearchMappingAfterUpdateAttributeToSearchable(): void
{
$mappedAttributesBefore = $this->getMappingProperties();
$expectedResult = [
'dropdown_attribute' => [
'type' => 'integer',
'index' => false,
],
'dropdown_attribute_value' => [
'type' => 'text',
'copy_to' => ['_search'],
],
];
/** @var ProductAttributeInterface $dropDownAttribute */
$dropDownAttribute = $this->attributeFactory->create();
$dropDownAttribute->setData($this->getAttributeData());
$this->attributeRepository->save($dropDownAttribute);
$this->assertTrue($this->indexerProcessor->getIndexer()->isValid());
$mappedAttributesAfter = $this->getMappingProperties();
$this->assertEquals($expectedResult, array_diff_key($mappedAttributesAfter, $mappedAttributesBefore));
$dropDownAttribute->setData(EavAttributeInterface::IS_SEARCHABLE, true);
$this->attributeRepository->save($dropDownAttribute);
$this->assertTrue($this->indexerProcessor->getIndexer()->isInvalid());
$this->assertEquals($mappedAttributesAfter, $this->getMappingProperties());
}
/**
* Retrieve Search engine indexer mapping.
*
* @return array
*/
private function getMappingProperties(): array
{
$storeId = $this->storeManager->getStore()->getId();
$mappedIndexerId = $this->indexNameResolver->getIndexMapping(Processor::INDEXER_ID);
$indexName = $this->indexNameResolver->getIndexFromAlias($storeId, $mappedIndexerId);
$mappedAttributes = $this->client->getMapping(['index' => $indexName]);
$pathField = $this->arrayManager->findPath('properties', $mappedAttributes);
return $this->arrayManager->get($pathField, $mappedAttributes, []);
}
/**
* Retrieve drop-down attribute data.
*
* @return array
*/
private function getAttributeData(): array
{
$entityTypeId = $this->installer->getEntityTypeId(ProductAttributeInterface::ENTITY_TYPE_CODE);
return [
'attribute_code' => 'dropdown_attribute',
'entity_type_id' => $entityTypeId,
'is_global' => 0,
'is_user_defined' => 1,
'frontend_input' => 'select',
'is_unique' => 0,
'is_required' => 0,
'is_searchable' => 0,
'is_visible_in_advanced_search' => 0,
'is_comparable' => 0,
'is_filterable' => 0,
'is_filterable_in_search' => 0,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 1,
'used_in_product_listing' => 1,
'used_for_sort_by' => 0,
'frontend_label' => ['Drop-Down Attribute'],
'backend_type' => 'varchar',
'option' => [
'value' => [
'option_1' => ['Option 1'],
'option_2' => ['Option 2'],
'option_3' => ['Option 3'],
],
'order' => [
'option_1' => 1,
'option_2' => 2,
'option_3' => 3,
],
],
];
}
}
@@ -0,0 +1,297 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Elasticsearch\Model\Indexer;
use Magento\AdvancedSearch\Model\Client\ClientInterface;
use Magento\Catalog\Model\Product\Action as ProductAction;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\CatalogInventory\Api\StockItemRepositoryInterface;
use Magento\CatalogSearch\Model\Indexer\Fulltext as CatalogSearchFulltextIndexer;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Elasticsearch\SearchAdapter\ConnectionManager;
use Magento\Elasticsearch\Model\Config;
use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver;
use Magento\Indexer\Model\Indexer;
use Magento\Framework\Search\EngineResolverInterface;
use Magento\TestModuleCatalogSearch\Model\SearchEngineVersionReader;
use PHPUnit\Framework\TestCase;
/**
* Important: Please make sure that each integration test file works with unique search index. In order to
* achieve this, use @magentoConfigFixture to pass unique value for index_prefix for every test
* method. E.g. '@magentoConfigFixture current_store catalog/search/elasticsearch7_index_prefix indexerhandlertest'
*
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Elasticsearch/_files/indexer.php
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class IndexHandlerTest extends TestCase
{
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ClientInterface
*/
private $client;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var int[]
*/
private $storeIds;
/**
* @var string
*/
private $entityType;
/**
* @var Indexer
*/
private $indexer;
/**
* @var SearchIndexNameResolver
*/
private $searchIndexNameResolver;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
$connectionManager = Bootstrap::getObjectManager()->create(ConnectionManager::class);
$this->client = $connectionManager->getConnection();
$this->storeManager = Bootstrap::getObjectManager()->create(StoreManagerInterface::class);
$this->storeIds = array_keys($this->storeManager->getStores());
$clientConfig = Bootstrap::getObjectManager()->create(Config::class);
$this->entityType = $clientConfig->getEntityType();
$this->indexer = Bootstrap::getObjectManager()->create(Indexer::class);
$this->indexer->load(CatalogSearchFulltextIndexer::INDEXER_ID);
$this->indexer->reindexAll();
$this->searchIndexNameResolver = Bootstrap::getObjectManager()->create(SearchIndexNameResolver::class);
$this->productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class);
}
/**
* Make sure that correct engine is set
*/
protected function assertPreConditions(): void
{
$objectManager = Bootstrap::getObjectManager();
$currentEngine = $objectManager->get(EngineResolverInterface::class)->getCurrentSearchEngine();
$installedEngine = $objectManager->get(SearchEngineVersionReader::class)->getFullVersion();
$this->assertEquals(
$installedEngine,
$currentEngine,
sprintf(
'Search engine configuration "%s" is not compatible with the installed version',
$currentEngine
)
);
}
/**
* @return void
*/
public function testReindexAll(): void
{
$productApple = $this->productRepository->get('fulltext-1');
foreach ($this->storeIds as $storeId) {
$products = $this->searchByName('Apple', $storeId);
$this->assertCount(1, $products);
$this->assertEquals($productApple->getId(), $products[0]['_id']);
$products = $this->searchByName('Simple Product', $storeId);
$this->assertCount(5, $products);
$this->assertCount(2, $this->searchByBoolAttribute(0, $storeId));
$this->assertCount(3, $this->searchByBoolAttribute(1, $storeId));
}
}
/**
* @magentoAppIsolation enabled
* @return void
*/
public function testReindexRowAfterEdit(): void
{
$this->storeManager->setCurrentStore('admin');
$productApple = $this->productRepository->get('fulltext-1');
$productApple->setName('Simple Product Cucumber');
$this->productRepository->save($productApple);
foreach ($this->storeIds as $storeId) {
$products = $this->searchByName('Apple', $storeId);
$this->assertCount(0, $products);
$products = $this->searchByName('Cucumber', $storeId);
$this->assertCount(1, $products);
$this->assertEquals($productApple->getId(), $products[0]['_id']);
$products = $this->searchByName('Simple Product', $storeId);
$this->assertCount(5, $products);
}
}
/**
* @return void
*/
public function testReindexRowAfterMassAction(): void
{
$productApple = $this->productRepository->get('fulltext-1');
$productBanana = $this->productRepository->get('fulltext-2');
$productIds = [
$productApple->getId(),
$productBanana->getId(),
];
$attrData = [
'name' => 'Simple Product Common',
];
/** @var ProductAction $action */
$action = Bootstrap::getObjectManager()->get(ProductAction::class);
foreach ($this->storeIds as $storeId) {
$action->updateAttributes($productIds, $attrData, $storeId);
$products = $this->searchByName('Apple', $storeId);
$this->assertCount(0, $products);
$products = $this->searchByName('Banana', $storeId);
$this->assertCount(0, $products);
$products = $this->searchByName('Unknown', $storeId);
$this->assertCount(0, $products);
$products = $this->searchByName('Common', $storeId);
$this->assertCount(2, $products);
$products = $this->searchByName('Simple Product', $storeId);
$this->assertCount(5, $products);
}
}
/**
* @magentoAppArea adminhtml
* @return void
*/
public function testReindexRowAfterDelete(): void
{
$productBanana = $this->productRepository->get('fulltext-2');
$this->productRepository->delete($productBanana);
foreach ($this->storeIds as $storeId) {
$products = $this->searchByName('Banana', $storeId);
$this->assertEmpty($products);
$products = $this->searchByName('Simple Product', $storeId);
$this->assertCount(4, $products);
}
}
/**
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Elasticsearch/_files/configurable_products.php
* @return void
*/
public function testReindexRowAfterUpdateStockStatus(): void
{
foreach ($this->storeIds as $storeId) {
$products = $this->searchByName('ProductOption1', $storeId);
$this->assertNotEmpty($products);
}
$product = $this->productRepository->get('simple_10');
/** @var StockRegistryInterface $stockRegistry */
$stockRegistry = Bootstrap::getObjectManager()->create(StockRegistryInterface::class);
$stockItem = $stockRegistry->getStockItem($product->getId());
$stockItem->setIsInStock(false);
/** @var StockItemRepositoryInterface $stockRepository */
$stockRepository = Bootstrap::getObjectManager()->create(StockItemRepositoryInterface::class);
$stockRepository->save($stockItem);
foreach ($this->storeIds as $storeId) {
$products = $this->searchByName('ProductOption1', $storeId);
$this->assertEmpty($products);
$products = $this->searchByName('Configurable', $storeId);
$this->assertNotEmpty($products);
}
}
/**
* Search docs in search engine by name.
*
* @param string $text
* @param int $storeId
* @return array
*/
private function searchByName(string $text, int $storeId): array
{
$index = $this->searchIndexNameResolver->getIndexName($storeId, $this->indexer->getId());
$searchQuery = [
'index' => $index,
'type' => $this->entityType,
'body' => [
'query' => [
'bool' => [
'minimum_should_match' => 1,
'should' => [
[
'match' => [
'name' => $text,
],
],
],
],
],
],
];
$queryResult = $this->client->query($searchQuery);
$products = isset($queryResult['hits']['hits']) ? $queryResult['hits']['hits'] : [];
return $products;
}
/**
* Search docs in search engine by boolean attribute.
*
* @param int $value
* @param int $storeId
* @return array
*/
private function searchByBoolAttribute(int $value, int $storeId): array
{
$index = $this->searchIndexNameResolver->getIndexName($storeId, $this->indexer->getId());
$searchQuery = [
'index' => $index,
'type' => $this->entityType,
'body' => [
'query' => [
'query_string' => [
'query' => $value,
'default_field' => 'boolean_attribute',
],
],
],
];
$queryResult = $this->client->query($searchQuery);
return isset($queryResult['hits']['hits']) ? $queryResult['hits']['hits'] : [];
}
}
@@ -0,0 +1,271 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Elasticsearch\Model\Indexer;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Indexer\Model\Indexer;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Elasticsearch\SearchAdapter\ConnectionManager;
use Magento\AdvancedSearch\Model\Client\ClientInterface as ElasticsearchClient;
use Magento\Elasticsearch\Model\Config;
use Magento\Elasticsearch\SearchAdapter\SearchIndexNameResolver;
use Magento\Framework\Search\EngineResolverInterface;
use Magento\TestModuleCatalogSearch\Model\SearchEngineVersionReader;
/**
* Important: Please make sure that each integration test file works with unique search index. In order to
* achieve this, use @magentoConfigFixture to pass unique value for index_prefix for every test
* method.
* E.g. '@magentoConfigFixture current_store catalog/search/elasticsearch7_index_prefix indexerhandlertest_configurable'
*
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ReindexAllTest extends \PHPUnit\Framework\TestCase
{
/**
* @var ConnectionManager
*/
private $connectionManager;
/**
* @var ElasticsearchClient
*/
private $client;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var Config
*/
private $clientConfig;
/**
* @var SearchIndexNameResolver
*/
private $searchIndexNameResolver;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
protected function setUp(): void
{
$this->connectionManager = Bootstrap::getObjectManager()->create(ConnectionManager::class);
$this->client = $this->connectionManager->getConnection();
$this->storeManager = Bootstrap::getObjectManager()->create(StoreManagerInterface::class);
$this->clientConfig = Bootstrap::getObjectManager()->create(Config::class);
$this->searchIndexNameResolver = Bootstrap::getObjectManager()->create(SearchIndexNameResolver::class);
$this->productRepository = Bootstrap::getObjectManager()->create(ProductRepositoryInterface::class);
}
/**
* Make sure that correct engine is set
*/
protected function assertPreConditions(): void
{
$objectManager = Bootstrap::getObjectManager();
$currentEngine = $objectManager->get(EngineResolverInterface::class)->getCurrentSearchEngine();
$installedEngine = $objectManager->get(SearchEngineVersionReader::class)->getFullVersion();
$this->assertEquals(
$installedEngine,
$currentEngine,
sprintf(
'Search engine configuration "%s" is not compatible with the installed version',
$currentEngine
)
);
}
/**
* Test search of all products after full reindex
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_products.php
*/
public function testSearchAll()
{
$this->reindexAll();
$result = $this->searchByName('Configurable Product');
self::assertGreaterThanOrEqual(2, $result);
}
/**
* Test sorting of all products after full reindex
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_products.php
*/
public function testSort()
{
/** @var $productFifth \Magento\Catalog\Model\Product */
$productSimple = Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
$productSimple->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('ABC')
->setSku('abc-first-in-sort')
->setPrice(20)
->setMetaTitle('meta title')
->setMetaKeyword('meta keyword')
->setMetaDescription('meta description')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->save();
$productConfigurableOption = $this->productRepository->get('simple_10');
$productConfigurableOption->setName('1ABC');
$this->productRepository->save($productConfigurableOption);
$this->reindexAll();
$productSimple = $this->productRepository->get('abc-first-in-sort');
$result = $this->sortByName();
$firstInSearchResults = (int) $result[0]['_id'];
$productSimpleId = (int) $productSimple->getId();
$this->assertEquals($productSimpleId, $firstInSearchResults);
}
/**
* Test sorting of products with lower and upper case names after full reindex
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Elasticsearch/_files/case_sensitive.php
*/
public function testSortCaseSensitive(): void
{
$productFirst = $this->productRepository->get('fulltext-1');
$productSecond = $this->productRepository->get('fulltext-2');
$productThird = $this->productRepository->get('fulltext-3');
$productFourth = $this->productRepository->get('fulltext-4');
$productFifth = $this->productRepository->get('fulltext-5');
$this->reindexAll();
$result = $this->sortByName();
$firstInSearchResults = (int) $result[0]['_id'];
$secondInSearchResults = (int) $result[1]['_id'];
$thirdInSearchResults = (int) $result[2]['_id'];
$fourthInSearchResults = (int) $result[3]['_id'];
$fifthInSearchResults = (int) $result[4]['_id'];
self::assertCount(5, $result);
self::assertEqualsCanonicalizing(
[$productFirst->getId(), $productFourth->getId()],
[$firstInSearchResults, $secondInSearchResults]
);
self::assertEqualsCanonicalizing(
[$productSecond->getId(), $productFifth->getId()],
[$thirdInSearchResults, $fourthInSearchResults]
);
self::assertEquals($productThird->getId(), $fifthInSearchResults);
}
/**
* Test search of specific product after full reindex
*
* @magentoDataFixture Magento/ConfigurableProduct/_files/configurable_products.php
* @magentoDataFixture Magento/Catalog/_files/products.php
* @dataProvider searchSpecificProductDataProvider
* @param string $searchName
* @param string $sku
* @param int $expectedCount
*/
public function testSearchSpecificProduct(string $searchName, string $sku, int $expectedCount)
{
$this->reindexAll();
$result = $this->searchByName($searchName);
self::assertCount($expectedCount, $result);
$specificProduct = $this->productRepository->get($sku);
self::assertEquals($specificProduct->getId(), $result[0]['_id']);
}
public function searchSpecificProductDataProvider(): array
{
return [
'search by numeric name' => ['12345', 'configurable_12345', 1],
'search by name with diacritics' => ['Cùstöm Dèsign', 'custom-design-simple-product', 1],
];
}
/**
* @param string $text
* @return array
*/
private function searchByName($text)
{
$storeId = $this->storeManager->getDefaultStoreView()->getId();
$searchQuery = [
'index' => $this->searchIndexNameResolver->getIndexName($storeId, 'catalogsearch_fulltext'),
'type' => $this->clientConfig->getEntityType(),
'body' => [
'query' => [
'bool' => [
'minimum_should_match' => 1,
'should' => [
[
'match' => [
'name' => $text,
],
],
],
],
],
],
];
$queryResult = $this->client->query($searchQuery);
return isset($queryResult['hits']['hits']) ? $queryResult['hits']['hits'] : [];
}
/**
* @return array
*/
private function sortByName()
{
$storeId = $this->storeManager->getDefaultStoreView()->getId();
$searchQuery = [
'index' => $this->searchIndexNameResolver->getIndexName($storeId, 'catalogsearch_fulltext'),
'type' => $this->clientConfig->getEntityType(),
'body' => [
'sort' => [
'name.sort_name' => [
'order' => 'asc'
],
],
'query' => [
'bool' => [
'must' => [
[
'terms' => [
'visibility' => [2, 4],
],
],
],
],
],
],
];
$queryResult = $this->client->query($searchQuery);
return isset($queryResult['hits']['hits']) ? $queryResult['hits']['hits'] : [];
}
/**
* Make fulltext catalog search reindex
*
* @return void
*/
private function reindexAll()
{
// Perform full reindex
/** @var Indexer $indexer */
$indexer = Bootstrap::getObjectManager()->create(Indexer::class);
$indexer->load('catalogsearch_fulltext');
$indexer->reindexAll();
}
}
@@ -0,0 +1,712 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Elasticsearch\SearchAdapter;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection;
use Magento\Framework\Search\EngineResolverInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestModuleCatalogSearch\Model\SearchEngineVersionReader;
/**
* Class AdapterTest
*
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Framework/Search/_files/products.php
*
* Important: Please make sure that each integration test file works with unique elastic search index. In order to
* achieve this, use @ magentoConfigFixture to pass unique value for index_prefix for every test
* method. E.g. '@ magentoConfigFixture current_store catalog/search/elasticsearch7_index_prefix adaptertest'
*
* In ElasticSearch, a reindex is required if the test includes a new data fixture with new items to search, see
* testAdvancedSearchDateField().
* phpstan:ignore
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AdapterTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\Search\AdapterInterface
*/
private $adapter;
/**
* @var \Magento\Framework\Search\Request\Builder
*/
private $requestBuilder;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Framework\Search\Request\Config\Converter $converter */
$converter = $this->objectManager->create(\Magento\Framework\Search\Request\Config\Converter::class);
$document = new \DOMDocument();
$document->load($this->getRequestConfigPath());
$requestConfig = $converter->convert($document);
/** @var \Magento\Framework\Search\Request\Config $config */
$config = $this->objectManager->create(\Magento\Framework\Search\Request\Config::class);
$config->merge($requestConfig);
$this->requestBuilder = $this->objectManager->create(
\Magento\Framework\Search\Request\Builder::class,
['config' => $config]
);
$this->adapter = $this->createAdapter();
$indexer = $this->objectManager->create(\Magento\Indexer\Model\Indexer::class);
$indexer->load('catalogsearch_fulltext');
$indexer->reindexAll();
}
/**
* Get request config path
*
* @return string
*/
protected function getRequestConfigPath()
{
return __DIR__ . '/../_files/requests.xml';
}
/**
* @return \Magento\Framework\Search\AdapterInterface
*/
protected function createAdapter()
{
return $this->objectManager->create(\Magento\Search\Model\AdapterFactory::class)->create();
}
/**
* Make sure that correct engine is set
*/
protected function assertPreConditions(): void
{
$currentEngine = $this->objectManager->get(EngineResolverInterface::class)->getCurrentSearchEngine();
$installedEngine = $this->objectManager->get(SearchEngineVersionReader::class)->getFullVersion();
$this->assertEquals(
$installedEngine,
$currentEngine,
sprintf(
'Search engine configuration "%s" is not compatible with the installed version',
$currentEngine
)
);
}
/**
* @return \Magento\Framework\Search\Response\QueryResponse
*/
private function executeQuery()
{
/** @var \Magento\Framework\Search\RequestInterface $queryRequest */
$queryRequest = $this->requestBuilder->create();
$queryResponse = $this->adapter->query($queryRequest);
return $queryResponse;
}
/**
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testMatchQuery()
{
$this->requestBuilder->bind('fulltext_search_query', 'socks');
$this->requestBuilder->setRequestName('one_match');
$queryResponse = $this->executeQuery();
$this->assertEquals(1, $queryResponse->count());
}
/**
* @magentoAppIsolation enabled
*/
public function testMatchOrderedQuery()
{
$this->markTestSkipped(
'Elasticsearch not expected to order results by default. Test is skipped intentionally.'
);
$expectedIds = [8, 7, 6, 5, 2];
//Verify that MySql randomized result of equal-weighted results
//consistently ordered by entity_id after multiple calls
$this->requestBuilder->bind('fulltext_search_query', 'shorts');
$this->requestBuilder->setRequestName('one_match');
$queryResponse = $this->executeQuery();
$this->assertEquals(5, $queryResponse->count());
$this->assertOrderedProductIds($queryResponse, $expectedIds);
}
/**
* @param \Magento\Framework\Search\Response\QueryResponse $queryResponse
* @param array $expectedIds
*/
private function assertOrderedProductIds($queryResponse, $expectedIds)
{
$actualIds = [];
foreach ($queryResponse as $document) {
/** @var \Magento\Framework\Api\Search\Document $document */
$actualIds[] = $document->getId();
}
$this->assertEquals($expectedIds, $actualIds);
}
/**
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testMatchQueryFilters()
{
$this->requestBuilder->bind('fulltext_search_query', 'socks');
$this->requestBuilder->bind('pidm_from', 11);
$this->requestBuilder->bind('pidm_to', 17);
$this->requestBuilder->bind('pidsh', 18);
$this->requestBuilder->setRequestName('one_match_filters');
$queryResponse = $this->executeQuery();
$this->assertEquals(1, $queryResponse->count());
}
/**
* Range filter test with all fields filled
*
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testRangeFilterWithAllFields()
{
$this->requestBuilder->bind('range_filter_from', 11);
$this->requestBuilder->bind('range_filter_to', 17);
$this->requestBuilder->setRequestName('range_filter');
$queryResponse = $this->executeQuery();
$this->assertEquals(3, $queryResponse->count());
}
/**
* Range filter test with all fields filled
*
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testRangeFilterWithoutFromField()
{
$this->requestBuilder->bind('range_filter_to', 18);
$this->requestBuilder->setRequestName('range_filter_without_from_field');
$queryResponse = $this->executeQuery();
$this->assertEquals(4, $queryResponse->count());
}
/**
* Range filter test with all fields filled
*
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testRangeFilterWithoutToField()
{
$this->requestBuilder->bind('range_filter_from', 14);
$this->requestBuilder->setRequestName('range_filter_without_to_field');
$queryResponse = $this->executeQuery();
$this->assertEquals(4, $queryResponse->count());
}
/**
* Term filter test
*
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testTermFilter()
{
$this->requestBuilder->bind('request.price', 18);
$this->requestBuilder->setRequestName('term_filter');
$queryResponse = $this->executeQuery();
$this->assertEquals(1, $queryResponse->count());
$this->assertEquals(4, $queryResponse->getIterator()->offsetGet(0)->getId());
}
/**
* Term filter test
*
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testTermFilterArray()
{
$this->requestBuilder->bind('request.price', [17, 18]);
$this->requestBuilder->setRequestName('term_filter');
$queryResponse = $this->executeQuery();
$this->assertEquals(2, $queryResponse->count());
}
/**
* @param \Magento\Framework\Search\Response\QueryResponse $queryResponse
* @param array $expectedIds
*/
private function assertProductIds($queryResponse, $expectedIds)
{
$actualIds = [];
foreach ($queryResponse as $document) {
/** @var \Magento\Framework\Api\Search\Document $document */
$actualIds[] = $document->getId();
}
sort($actualIds);
sort($expectedIds);
$this->assertEquals($expectedIds, $actualIds);
}
/**
* Term filter test
*
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testWildcardFilter()
{
$expectedIds = [1, 3, 5];
$this->requestBuilder->bind('wildcard_filter', 're');
$this->requestBuilder->setRequestName('one_wildcard');
$queryResponse = $this->executeQuery();
$this->assertEquals(3, $queryResponse->count());
$this->assertProductIds($queryResponse, $expectedIds);
}
/**
* Request limits test
*
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testSearchLimit()
{
$this->requestBuilder->bind('wildcard_filter', 're');
$this->requestBuilder->setFrom(1);
$this->requestBuilder->setSize(2);
$this->requestBuilder->setRequestName('one_wildcard');
$queryResponse = $this->executeQuery();
$this->assertEquals(2, $queryResponse->count());
}
/**
* Bool filter test
*
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testBoolFilter()
{
$expectedIds = [2, 3];
$this->requestBuilder->bind('must_range_filter1_from', 13);
$this->requestBuilder->bind('must_range_filter1_to', 22);
$this->requestBuilder->bind('should_term_filter1', 13);
$this->requestBuilder->bind('should_term_filter2', 15);
$this->requestBuilder->bind('should_term_filter3', 17);
$this->requestBuilder->bind('should_term_filter4', 18);
$this->requestBuilder->bind('not_term_filter1', 13);
$this->requestBuilder->bind('not_term_filter2', 18);
$this->requestBuilder->setRequestName('bool_filter');
$queryResponse = $this->executeQuery();
$this->assertEquals(count($expectedIds), $queryResponse->count());
$this->assertProductIds($queryResponse, $expectedIds);
}
/**
* Test bool filter with nested negative bool filter
*
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testBoolFilterWithNestedNegativeBoolFilter()
{
$expectedIds = [1];
$this->requestBuilder->bind('not_range_filter_from', 14);
$this->requestBuilder->bind('not_range_filter_to', 20);
$this->requestBuilder->bind('nested_not_term_filter', 13);
$this->requestBuilder->setRequestName('bool_filter_with_nested_bool_filter');
$queryResponse = $this->executeQuery();
$this->assertEquals(count($expectedIds), $queryResponse->count());
$this->assertProductIds($queryResponse, $expectedIds);
}
/**
* Test range inside nested negative bool filter
*
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testBoolFilterWithNestedRangeInNegativeBoolFilter()
{
$expectedIds = [1, 5];
$this->requestBuilder->bind('nested_must_range_filter_from', 14);
$this->requestBuilder->bind('nested_must_range_filter_to', 18);
$this->requestBuilder->setRequestName('bool_filter_with_range_in_nested_negative_filter');
$queryResponse = $this->executeQuery();
$this->assertEquals(count($expectedIds), $queryResponse->count());
$this->assertProductIds($queryResponse, $expectedIds);
}
/**
* Sample Advanced search request test
*
* @dataProvider elasticSearchAdvancedSearchDataProvider
* @magentoAppIsolation enabled
* @param string $nameQuery
* @param string $descriptionQuery
* @param array $rangeFilter
* @param int $expectedRecordsCount
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testSimpleAdvancedSearch(
$nameQuery,
$descriptionQuery,
$rangeFilter,
$expectedRecordsCount
) {
$this->requestBuilder->bind('name_query', $nameQuery);
$this->requestBuilder->bind('description_query', $descriptionQuery);
$this->requestBuilder->bind('request.from_price', $rangeFilter['from']);
$this->requestBuilder->bind('request.to_price', $rangeFilter['to']);
$this->requestBuilder->setRequestName('advanced_search_test');
$queryResponse = $this->executeQuery();
$this->assertEquals($expectedRecordsCount, $queryResponse->count());
}
/**
* Elastic Search specific data provider for advanced search test.
*
* The expected array is for Elastic Search is different that the one for MySQL
* because sometimes more matches are returned. For instance, 3rd index below
* will return 3 matches instead of 1 (which is what MySQL returns).
*
* @return array
*/
public function elasticSearchAdvancedSearchDataProvider()
{
return [
['white', 'shorts', ['from' => '16', 'to' => '18'], 0],
['white', 'shorts',['from' => '12', 'to' => '18'], 1],
['black', 'tshirts', ['from' => '12', 'to' => '20'], 0],
['shorts', 'green', ['from' => '12', 'to' => '22'], 3],
//Search with empty fields/values
['white', ' ', ['from' => '12', 'to' => '22'], 1],
[' ', 'green', ['from' => '12', 'to' => '22'], 2]
];
}
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Framework/Search/_files/filterable_attribute.php
*/
public function testCustomFilterableAttribute()
{
// Reindex Elastic Search since filterable_attribute data fixture added new fields to be indexed
$this->reindexAll();
/** @var Attribute $attribute */
$attribute = $this->objectManager->get(Attribute::class)
->loadByCode(Product::ENTITY, 'select_attribute');
/** @var Collection $selectOptions */
$selectOptions = $this->objectManager
->create(Collection::class)
->setAttributeFilter($attribute->getId());
$attribute->loadByCode(Product::ENTITY, 'multiselect_attribute');
/** @var Collection $multiselectOptions */
$multiselectOptions = $this->objectManager
->create(Collection::class)
->setAttributeFilter($attribute->getId());
$this->requestBuilder->bind('select_attribute', $selectOptions->getLastItem()->getId());
$this->requestBuilder->bind('multiselect_attribute', $multiselectOptions->getLastItem()->getId());
$this->requestBuilder->bind('price.from', 98);
$this->requestBuilder->bind('price.to', 100);
$this->requestBuilder->bind('category_ids', 2);
$this->requestBuilder->setRequestName('filterable_custom_attributes');
$queryResponse = $this->executeQuery();
$this->assertEquals(1, $queryResponse->count());
}
/**
* Test filtering by two attributes.
*
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Framework/Search/_files/filterable_attributes.php
* @dataProvider filterByAttributeValuesDataProvider
* @param string $requestName
* @param array $additionalData
* @return void
*/
public function testFilterByAttributeValues($requestName, $additionalData)
{
// Reindex Elastic Search since filterable_attribute data fixture added new fields to be indexed
$this->reindexAll();
/** @var Attribute $attribute */
$attribute = $this->objectManager->get(Attribute::class)
->loadByCode(Product::ENTITY, 'select_attribute_1');
/** @var Collection $selectOptions1 */
$selectOptions1 = $this->objectManager
->create(Collection::class)
->setAttributeFilter($attribute->getId());
$attribute->loadByCode(Product::ENTITY, 'select_attribute_2');
/** @var Collection $selectOptions2 */
$selectOptions2 = $this->objectManager
->create(Collection::class)
->setAttributeFilter($attribute->getId());
$this->requestBuilder->bind('select_attribute_1', $selectOptions1->getLastItem()->getId());
$this->requestBuilder->bind('select_attribute_2', $selectOptions2->getLastItem()->getId());
// Binds for specific containers.
foreach ($additionalData as $key => $value) {
$this->requestBuilder->bind($key, $value);
}
$this->requestBuilder->setRequestName($requestName);
$queryResponse = $this->executeQuery();
$this->assertEquals(1, $queryResponse->count());
}
/**
* Advanced search request using date product attribute
*
* @param $rangeFilter
* @param $expectedRecordsCount
* @magentoDataFixture Magento/Framework/Search/_files/date_attribute.php
* @magentoAppIsolation enabled
* @dataProvider dateDataProvider
*/
public function testAdvancedSearchDateField($rangeFilter, $expectedRecordsCount)
{
// Reindex Elastic Search since date_attribute data fixture added new fields to be indexed
$this->reindexAll();
$this->requestBuilder->bind('date.from', $rangeFilter['from']);
$this->requestBuilder->bind('date.to', $rangeFilter['to']);
$this->requestBuilder->setRequestName('advanced_search_date_field');
$queryResponse = $this->executeQuery();
$this->assertEquals($expectedRecordsCount, $queryResponse->count());
}
/**
* @magentoDataFixture Magento/Framework/Search/_files/product_configurable.php
* @magentoAppIsolation enabled
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
*/
public function testAdvancedSearchCompositeProductWithOutOfStockOption()
{
/** @var Attribute $attribute */
$attribute = $this->objectManager->get(Attribute::class)
->loadByCode(Product::ENTITY, 'test_configurable');
/** @var Collection $selectOptions */
$selectOptions = $this->objectManager
->create(Collection::class)
->setAttributeFilter($attribute->getId());
$visibility = [
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_IN_SEARCH,
\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH,
];
$firstOption = $selectOptions->getFirstItem();
$firstOptionId = $firstOption->getId();
$this->requestBuilder->bind('test_configurable', $firstOptionId);
$this->requestBuilder->bind('visibility', $visibility);
$this->requestBuilder->setRequestName('filter_out_of_stock_child');
$queryResponse = $this->executeQuery();
$this->assertEquals(0, $queryResponse->count());
$secondOption = $selectOptions->getLastItem();
$secondOptionId = $secondOption->getId();
$this->requestBuilder->bind('test_configurable', $secondOptionId);
$this->requestBuilder->bind('visibility', $visibility);
$this->requestBuilder->setRequestName('filter_out_of_stock_child');
$queryResponse = $this->executeQuery();
$this->assertEquals(1, $queryResponse->count());
}
/**
* @magentoDataFixture Magento/Framework/Search/_files/product_configurable_with_disabled_child.php
* @magentoAppIsolation enabled
*/
public function testAdvancedSearchCompositeProductWithDisabledChild()
{
// Reindex Elastic Search since date_attribute data fixture added new fields to be indexed
$this->reindexAll();
/** @var Attribute $attribute */
$attribute = $this->objectManager->get(Attribute::class)
->loadByCode(Product::ENTITY, 'test_configurable');
/** @var Collection $selectOptions */
$selectOptions = $this->objectManager
->create(Collection::class)
->setAttributeFilter($attribute->getId());
$firstOption = $selectOptions->getFirstItem();
$firstOptionId = $firstOption->getId();
$this->requestBuilder->bind('test_configurable', $firstOptionId);
$this->requestBuilder->setRequestName('filter_out_of_stock_child');
$queryResponse = $this->executeQuery();
$this->assertEquals(0, $queryResponse->count());
$secondOption = $selectOptions->getLastItem();
$secondOptionId = $secondOption->getId();
$this->requestBuilder->bind('test_configurable', $secondOptionId);
$this->requestBuilder->setRequestName('filter_out_of_stock_child');
$queryResponse = $this->executeQuery();
$this->assertEquals(0, $queryResponse->count());
}
/**
* @magentoDataFixture Magento/Framework/Search/_files/search_weight_products.php
* @magentoAppIsolation enabled
*/
public function testSearchQueryBoost()
{
// Reindex Elastic Search since date_attribute data fixture added new fields to be indexed
$this->reindexAll();
$this->requestBuilder->bind('query', 'antarctica');
$this->requestBuilder->setRequestName('search_boost');
$queryResponse = $this->executeQuery();
$this->assertEquals(2, $queryResponse->count());
/** @var \Magento\Framework\Api\Search\DocumentInterface $products */
$products = iterator_to_array($queryResponse);
/*
* Products now contain search query in two attributes which are boosted with the same value: 1
* The search keyword (antarctica) is mentioned twice only in one of the products.
* And, as both attributes have the same search weight and boost, we expect that
* the product with doubled keyword should be prioritized by a search engine as a most relevant
* and therefore will be first in the search result.
*/
$firstProduct = reset($products);
$this->assertEquals(1222, $firstProduct->getId());
$secondProduct = end($products);
$this->assertEquals(1221, $secondProduct->getId());
/** @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $this->objectManager->get(
\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class
);
/**
* Now we're going to change search weight of one of the attributes to ensure that it will affect
* how products are ordered in the search result
*/
/** @var Attribute $attribute */
$attribute = $productAttributeRepository->get('name');
$attribute->setSearchWeight(20);
$productAttributeRepository->save($attribute);
$this->requestBuilder->bind('query', 'antarctica');
$this->requestBuilder->setRequestName('search_boost_name');
$queryResponse = $this->executeQuery();
$this->assertEquals(2, $queryResponse->count());
/** @var \Magento\Framework\Api\Search\DocumentInterface $products */
$products = iterator_to_array($queryResponse);
/*
* As for the first case, we have two the same products.
* One of them has search keyword mentioned twice in the field which has search weight 1.
* However, we've changed the search weight of another attribute
* which has only one mention of the search keyword in another product.
*
* The case is mostly the same but search weight has been changed and we expect that
* less relevant (with only one mention) but more boosted (search weight = 20) product
* will be prioritized higher than more relevant, but less boosted product.
*/
$firstProduct = reset($products);
$this->assertEquals(1221, $firstProduct->getId());
//$firstProduct
$secondProduct = end($products);
$this->assertEquals(1222, $secondProduct->getId());
}
/**
* Perform full reindex
*
* @return void
*/
private function reindexAll()
{
$indexer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Indexer\Model\Indexer::class
);
$indexer->load('catalogsearch_fulltext');
$indexer->reindexAll();
}
/**
* Date data provider
*
* @return array
*/
public function dateDataProvider()
{
return [
[['from' => '1999-12-31T00:00:00Z', 'to' => '2000-01-01T00:00:00Z'], 1],
[['from' => '2000-02-01T00:00:00Z', 'to' => ''], 0],
];
}
public function filterByAttributeValuesDataProvider()
{
return [
'quick_search_container' => [
'quick_search_container',
[
// Make sure search uses "should" cause.
'search_term' => 'Simple Product',
],
],
'advanced_search_container' => [
'advanced_search_container',
[
// Make sure "wildcard" feature works.
'sku' => 'simple_product',
]
],
'catalog_view_container' => [
'catalog_view_container',
[
'category_ids' => 2
]
],
'quick search by date' => [
'quick_search_container',
[
'search_term' => '2000-10-30',
],
],
];
}
}
@@ -0,0 +1,126 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/product_boolean_attribute.php');
/** @var $objectManager \Magento\Framework\ObjectManagerInterface */
$objectManager = Bootstrap::getObjectManager();
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
try {
$productRepository->get('fulltext-1');
} catch (NoSuchEntityException $e) {
/** @var $productFirst Product */
$productFirst = $objectManager->create(Product::class);
$productFirst->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('A')
->setSku('fulltext-1')
->setPrice(10)
->setMetaTitle('first meta title')
->setMetaKeyword('first meta keyword')
->setMetaDescription('first meta description')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->setBooleanAttribute(1)
->save();
}
try {
$productRepository->get('fulltext-2');
} catch (NoSuchEntityException $e) {
/** @var $productSecond Product */
$productSecond = $objectManager->create(Product::class);
$productSecond->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('B')
->setSku('fulltext-2')
->setPrice(20)
->setMetaTitle('second meta title')
->setMetaKeyword('second meta keyword')
->setMetaDescription('second meta description')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->setBooleanAttribute(1)
->save();
}
try {
$productRepository->get('fulltext-3');
} catch (NoSuchEntityException $e) {
/** @var $productThird Product */
$productThird = $objectManager->create(Product::class);
$productThird->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('C')
->setSku('fulltext-3')
->setPrice(20)
->setMetaTitle('third meta title')
->setMetaKeyword('third meta keyword')
->setMetaDescription('third meta description')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->setBooleanAttribute(1)
->save();
}
try {
$productRepository->get('fulltext-4');
} catch (NoSuchEntityException $e) {
/** @var $productFourth Product */
$productFourth = $objectManager->create(Product::class);
$productFourth->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('a')
->setSku('fulltext-4')
->setPrice(20)
->setMetaTitle('fourth meta title')
->setMetaKeyword('fourth meta keyword')
->setMetaDescription('fourth meta description')
->setUrlKey('aa')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->setBooleanAttribute(0)
->save();
}
try {
$productRepository->get('fulltext-5');
} catch (NoSuchEntityException $e) {
/** @var $productFifth Product */
$productFifth = $objectManager->create(Product::class);
$productFifth->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('b')
->setSku('fulltext-5')
->setPrice(20)
->setMetaTitle('fifth meta title')
->setMetaKeyword('fifth meta keyword')
->setMetaDescription('fifth meta description')
->setUrlKey('bb')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->setBooleanAttribute(0)
->save();
}
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/product_boolean_attribute_rollback.php');
/** @var $objectManager \Magento\Framework\ObjectManagerInterface */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Framework\Registry $registry */
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
$collection = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Product\Collection::class);
$collection->addAttributeToSelect('id')->load();
if ($collection->count() > 0) {
$collection->delete();
}
/** @var \Magento\Store\Model\Store $store */
$store = $objectManager->create(\Magento\Store\Model\Store::class);
$storeCode = 'secondary';
$store->load($storeCode);
if ($store->getId()) {
$store->delete();
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,62 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Eav\Api\AttributeRepositoryInterface;
$eavConfig = Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class);
$attribute = $eavConfig->getAttribute('catalog_product', 'test_configurable');
$eavConfig->clear();
/** @var $installer \Magento\Catalog\Setup\CategorySetup */
$installer = Bootstrap::getObjectManager()->create(\Magento\Catalog\Setup\CategorySetup::class);
if (!$attribute->getId()) {
/** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
$attribute = Bootstrap::getObjectManager()->create(
\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class
);
/** @var AttributeRepositoryInterface $attributeRepository */
$attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepositoryInterface::class);
$attribute->setData(
[
'attribute_code' => 'test_configurable',
'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
'is_global' => 1,
'is_user_defined' => 1,
'frontend_input' => 'select',
'is_unique' => 0,
'is_required' => 0,
'is_searchable' => 0,
'is_visible_in_advanced_search' => 0,
'is_comparable' => 0,
'is_filterable' => 0,
'is_filterable_in_search' => 0,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 0,
'used_in_product_listing' => 0,
'used_for_sort_by' => 0,
'frontend_label' => ['Test Configurable'],
'backend_type' => 'int',
'option' => [
'value' => ['option_0' => ['Option 1'], 'option_1' => ['Option 2']],
'order' => ['option_0' => 1, 'option_1' => 2],
],
]
);
$attributeRepository->save($attribute);
/* Assign attribute to attribute set */
$installer->addAttributeToGroup('catalog_product', 'Default', 'General', $attribute->getId());
}
$eavConfig->clear();
@@ -0,0 +1,24 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
/** @var \Magento\Framework\Registry $registry */
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class);
$attribute = $eavConfig->getAttribute('catalog_product', 'test_configurable');
if ($attribute instanceof \Magento\Eav\Model\Entity\Attribute\AbstractAttribute
&& $attribute->getId()
) {
$attribute->delete();
}
$eavConfig->clear();
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,116 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Setup\CategorySetup;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
use Magento\Eav\Model\Config;
Resolver::getInstance()->requireDataFixture('Magento/Elasticsearch/_files/select_attribute.php');
Resolver::getInstance()->requireDataFixture('Magento/Elasticsearch/_files/multiselect_attribute.php');
Resolver::getInstance()->requireDataFixture('Magento/Elasticsearch/_files/configurable_attribute.php');
$objectManager = Bootstrap::getObjectManager();
$eavConfig = Bootstrap::getObjectManager()->get(Config::class);
$attribute = $eavConfig->getAttribute(Product::ENTITY, 'test_configurable');
$selectAttribute = $eavConfig->getAttribute(Product::ENTITY, 'select_attribute');
$multiselectAttribute = $eavConfig->getAttribute(Product::ENTITY, 'test_configurable');
/** @var CategorySetup $installer */
$installer = $objectManager->create(CategorySetup::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$attributeSetId = $installer->getAttributeSetId('catalog_product', 'Default');
/** @var AttributeOptionInterface[] $options */
$options = $attribute->getOptions();
$selectOptionsIds = $objectManager->create(Collection::class)
->setAttributeFilter($selectAttribute->getId())
->getAllIds();
$multiselectOptionsIds = $objectManager->create(Collection::class)
->setAttributeFilter($multiselectAttribute->getId())
->getAllIds();
$attributeValues = [];
$attributeSetId = $installer->getAttributeSetId('catalog_product', 'Default');
$associatedProductIds = [];
$productIds = [10, 20];
array_shift($options);
foreach ($options as $option) {
/** @var Product $product */
$product = $objectManager->create(Product::class);
$productId = array_shift($productIds);
$product->setTypeId(Type::TYPE_SIMPLE)
->setId($productId)
->setAttributeSetId($attributeSetId)
->setWebsiteIds([1])
->setName('Configurable Option Product' . str_replace(' ', '', $option->getLabel()))
->setSku('simple_' . $productId)
->setPrice($productId)
->setTestConfigurable($option->getValue())
->setShortDescription('simpledescription')
->setMultiselectAttribute([$multiselectOptionsIds[0]])
->setSelectAttribute([$selectOptionsIds[0]])
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(Status::STATUS_ENABLED)
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1
]
);
$product = $productRepository->save($product);
$attributeValues[] = [
'label' => 'test',
'attribute_id' => $attribute->getId(),
'value_index' => $option->getValue(),
];
$associatedProductIds[] = $product->getId();
}
/** @var Product $product */
$product = $objectManager->create(Product::class);
/** @var Factory $optionsFactory */
$optionsFactory = $objectManager->create(Factory::class);
$configurableAttributesData = [
[
'attribute_id' => $attribute->getId(),
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel(),
'position' => '0',
'values' => $attributeValues,
],
];
$configurableOptions = $optionsFactory->create($configurableAttributesData);
$extensionConfigurableAttributes = $product->getExtensionAttributes();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds);
$product->setExtensionAttributes($extensionConfigurableAttributes);
$product->setTypeId(Configurable::TYPE_CODE)
->setId(1)
->setAttributeSetId($attributeSetId)
->setWebsiteIds([1])
->setName('Configurable Product')
->setSku('configurable')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 1, 'is_in_stock' => 1]);
$productRepository->cleanCache();
$productRepository->save($product);
@@ -0,0 +1,33 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Framework\Registry $registry */
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
foreach (['simple_10', 'simple_20', 'configurable'] as $sku) {
try {
$product = $productRepository->get($sku, false, null, true);
$productRepository->delete($product);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
}
}
Resolver::getInstance()->requireDataFixture('Magento/Elasticsearch/_files/configurable_attribute_rollback.php');
Resolver::getInstance()->requireDataFixture('Magento/Elasticsearch/_files/select_attribute_rollback.php');
Resolver::getInstance()->requireDataFixture('Magento/Elasticsearch/_files/multiselect_attribute_rollback.php');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,153 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Framework\App\MutableScopeConfig;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/product_boolean_attribute.php');
/** @var $objectManager \Magento\Framework\ObjectManagerInterface */
$objectManager = Bootstrap::getObjectManager();
/** @var StoreManagerInterface $storeManager */
$storeManager = $objectManager->get(StoreManagerInterface::class);
/** @var Store $store */
$store = $objectManager->create(Store::class);
$storeCode = 'secondary';
if (!$store->load($storeCode)->getId()) {
$store->setCode($storeCode)
->setWebsiteId($storeManager->getWebsite()->getId())
->setGroupId($storeManager->getWebsite()->getDefaultGroupId())
->setName('Secondary Store View')
->setSortOrder(10)
->setIsActive(1);
$store->save();
/** @var MutableScopeConfig $scopeConfig */
$scopeConfig = $objectManager->get(MutableScopeConfig::class);
$scopeConfig->setValue(
'general/locale/code',
'de_DE',
ScopeInterface::SCOPE_STORES,
$store->getId()
);
}
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
try {
$productRepository->get('fulltext-1');
} catch (NoSuchEntityException $e) {
/** @var $productFirst Product */
$productFirst = $objectManager->create(Product::class);
$productFirst->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product Apple')
->setSku('fulltext-1')
->setPrice(10)
->setMetaTitle('first meta title')
->setMetaKeyword('first meta keyword')
->setMetaDescription('first meta description')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->setBooleanAttribute(1)
->save();
}
try {
$productRepository->get('fulltext-2');
} catch (NoSuchEntityException $e) {
/** @var $productSecond Product */
$productSecond = $objectManager->create(Product::class);
$productSecond->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product Banana')
->setSku('fulltext-2')
->setPrice(20)
->setMetaTitle('second meta title')
->setMetaKeyword('second meta keyword')
->setMetaDescription('second meta description')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->setBooleanAttribute(1)
->save();
}
try {
$productRepository->get('fulltext-3');
} catch (NoSuchEntityException $e) {
/** @var $productThird Product */
$productThird = $objectManager->create(Product::class);
$productThird->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product Orange')
->setSku('fulltext-3')
->setPrice(20)
->setMetaTitle('third meta title')
->setMetaKeyword('third meta keyword')
->setMetaDescription('third meta description')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->setBooleanAttribute(1)
->save();
}
try {
$productRepository->get('fulltext-4');
} catch (NoSuchEntityException $e) {
/** @var $productFourth Product */
$productFourth = $objectManager->create(Product::class);
$productFourth->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product Papaya')
->setSku('fulltext-4')
->setPrice(20)
->setMetaTitle('fourth meta title')
->setMetaKeyword('fourth meta keyword')
->setMetaDescription('fourth meta description')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->setBooleanAttribute(0)
->save();
}
try {
$productRepository->get('fulltext-5');
} catch (NoSuchEntityException $e) {
/** @var $productFifth Product */
$productFifth = $objectManager->create(Product::class);
$productFifth->setTypeId('simple')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setName('Simple Product Cherry')
->setSku('fulltext-5')
->setPrice(20)
->setMetaTitle('fifth meta title')
->setMetaKeyword('fifth meta keyword')
->setMetaDescription('fifth meta description')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 0])
->setBooleanAttribute(0)
->save();
}
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/product_boolean_attribute_rollback.php');
/** @var $objectManager \Magento\Framework\ObjectManagerInterface */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Framework\Registry $registry */
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
$collection = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Product\Collection::class);
$collection->addAttributeToSelect('id')->load();
if ($collection->count() > 0) {
$collection->delete();
}
/** @var \Magento\Store\Model\Store $store */
$store = $objectManager->create(\Magento\Store\Model\Store::class);
$storeCode = 'secondary';
$store->load($storeCode);
if ($store->getId()) {
$store->delete();
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,58 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Catalog\Setup\CategorySetup $installer */
$installer = Bootstrap::getObjectManager()->create(\Magento\Catalog\Setup\CategorySetup::class);
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
$multiselectAttribute = $objectManager->create(
\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class
);
$multiselectAttribute->setData(
[
'attribute_code' => 'multiselect_attribute',
'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
'is_global' => 1,
'is_user_defined' => 1,
'frontend_input' => 'multiselect',
'is_unique' => 0,
'is_required' => 0,
'is_searchable' => 1,
'is_visible_in_advanced_search' => 0,
'is_comparable' => 0,
'is_filterable' => 1,
'is_filterable_in_search' => 0,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 0,
'used_in_product_listing' => 0,
'used_for_sort_by' => 0,
'frontend_label' => ['Multiselect Attribute'],
'backend_type' => 'text',
'backend_model' => \Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend::class,
'option' => [
'value' => [
'dog' => ['Dog'],
'cat' => ['Cat'],
],
'order' => [
'dog' => 1,
'cat' => 2,
],
],
]
);
$multiselectAttribute->save();
$installer->addAttributeToGroup(
'catalog_product',
'Default',
'General',
$multiselectAttribute->getId()
);
@@ -0,0 +1,20 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
$attribute = $objectManager->create(
\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class
);
$attribute->load('multiselect_attribute', 'attribute_code');
$attribute->delete();
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,109 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Visibility;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/category.php');
$categoryId = 333;
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$attributeSet = $objectManager->create(\Magento\Eav\Model\Entity\Attribute\Set::class);
$entityType = $objectManager->create(\Magento\Eav\Model\Entity\Type::class)->loadByCode('catalog_product');
$defaultSetId = $objectManager->create(\Magento\Catalog\Model\Product::class)->getDefaultAttributeSetid();
$products = [
[
'type' => 'simple',
'name' => 'search product 1',
'sku' => '24 MB06',
'status' => Status::STATUS_ENABLED,
'visibility' => Visibility::VISIBILITY_BOTH,
'attribute_set' => $defaultSetId,
'website_ids' => [\Magento\Store\Model\Store::DISTRO_STORE_ID],
'price' => 10,
'category_id' => $categoryId,
'meta_title' => 'Key Title',
'meta_keyword' => 'meta keyword',
'meta_description' => 'meta description',
],
[
'type' => 'simple',
'name' => 'search product 2',
'sku' => '24 MB04',
'status' => Status::STATUS_ENABLED,
'visibility' => Visibility::VISIBILITY_BOTH,
'attribute_set' => $defaultSetId,
'website_ids' => [\Magento\Store\Model\Store::DISTRO_STORE_ID],
'price' => 10,
'category_id' => $categoryId,
'meta_title' => 'Last Title',
'meta_keyword' => 'meta keyword',
'meta_description' => 'meta description',
],
[
'type' => 'simple',
'name' => 'search product 3',
'sku' => '24 MB02',
'status' => Status::STATUS_ENABLED,
'visibility' => Visibility::VISIBILITY_BOTH,
'attribute_set' => $defaultSetId,
'website_ids' => [\Magento\Store\Model\Store::DISTRO_STORE_ID],
'price' => 20,
'category_id' => $categoryId,
'meta_title' => 'First Title',
'meta_keyword' => 'meta keyword',
'meta_description' => 'meta description',
],
[
'type' => 'simple',
'name' => 'search product 4',
'sku' => '24 MB01',
'status' => Status::STATUS_ENABLED,
'visibility' => Visibility::VISIBILITY_BOTH,
'attribute_set' => $defaultSetId,
'website_ids' => [\Magento\Store\Model\Store::DISTRO_STORE_ID],
'price' => 30,
'category_id' => $categoryId,
'meta_title' => 'A title',
'meta_keyword' => 'meta keyword',
'meta_description' => 'meta description',
],
];
/** @var CategoryLinkManagementInterface $categoryLinkManagement */
$categoryLinkManagement = $objectManager->create(CategoryLinkManagementInterface::class);
$categoriesToAssign = [];
foreach ($products as $data) {
/** @var $product Product */
$product = $objectManager->create(Product::class);
$product
->setTypeId($data['type'])
->setAttributeSetId($data['attribute_set'])
->setWebsiteIds($data['website_ids'])
->setName($data['name'])
->setSku($data['sku'])
->setPrice($data['price'])
->setMetaTitle($data['meta_title'])
->setMetaKeyword($data['meta_keyword'])
->setMetaDescription($data['meta_keyword'])
->setVisibility($data['visibility'])
->setStatus($data['status'])
->setStockData(['use_config_manage_stock' => 0])
->save();
$categoriesToAssign[$data['sku']][] = $data['category_id'];
}
foreach ($categoriesToAssign as $sku => $categoryIds) {
$categoryLinkManagement->assignProductToCategories($sku, $categoryIds);
}
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Bootstrap::getInstance()->getInstance()->reinitialize();
/** @var Registry $registry */
$registry = Bootstrap::getObjectManager()->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
$productSkus = ['24 MB06', '24 MB04', '24 MB02', '24 MB01'];
foreach ($productSkus as $sku) {
try {
$product = $productRepository->get($sku, false, null, true);
$productRepository->delete($product);
} catch (NoSuchEntityException $e) {
}
}
Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/category_rollback.php');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,454 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<requests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Search/etc/search_request_merged.xsd">
<request query="one_match" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="boolQuery" name="one_match" boost="2">
<queryReference clause="must" ref="fulltext_search_query"/>
</query>
<query xsi:type="matchQuery" name="fulltext_search_query" value="$fulltext_search_query$" boost="5">
<match field="description" boost="2"/>
</query>
</queries>
<from>0</from>
<size>10</size>
</request>
<request query="one_aggregations" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="boolQuery" name="one_aggregations" boost="2">
<queryReference clause="must" ref="fulltext_search_query"/>
</query>
<query xsi:type="matchQuery" name="fulltext_search_query" value="$fulltext_search_query$" boost="5">
<match field="description" boost="2"/>
</query>
</queries>
<aggregations>
<bucket xsi:type="termBucket" name="weight_bucket" field="weight">
<metrics>
<metric type="count"/>
</metrics>
</bucket>
<bucket xsi:type="rangeBucket" name="price_bucket" field="price">
<metrics>
<metric type="count"/>
</metrics>
<ranges>
<range from="" to="14"/>
<range from="14" to="18"/>
<range from="18" to=""/>
</ranges>
</bucket>
<bucket xsi:type="dynamicBucket" method="manual" name="dynamic_price" field="price" />
</aggregations>
<from>0</from>
<size>10</size>
</request>
<request query="one_wildcard" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="filteredQuery" name="one_wildcard" boost="2">
<filterReference clause="must" ref="wildcard_filter"/>
</query>
</queries>
<filters>
<filter xsi:type="wildcardFilter" name="wildcard_filter" value="$wildcard_filter$" field="name"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="one_match_filters" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="boolQuery" name="one_match_filters" boost="2">
<queryReference clause="must" ref="fulltext_search_query"/>
<queryReference clause="must" ref="filtered_query"/>
<queryReference clause="must" ref="filtered_query_rm"/>
<queryReference clause="must" ref="filtered_query_filter_rm"/>
</query>
<query xsi:type="matchQuery" name="fulltext_search_query" value="$fulltext_search_query$" boost="5">
<match field="description" boost="2"/>
</query>
<query xsi:type="filteredQuery" name="filtered_query">
<filterReference clause="must" ref="pid"/>
</query>
<query xsi:type="filteredQuery" name="filtered_query_rm">
<queryReference clause="must" ref="fulltext_search_query_rm"/>
</query>
<query xsi:type="filteredQuery" name="filtered_query_filter_rm">
<filterReference clause="must" ref="bool_filter_rm"/>
</query>
<query xsi:type="matchQuery" value="$not_bind$" name="fulltext_search_query_rm">
<match field="some"/>
</query>
</queries>
<filters>
<filter xsi:type="boolFilter" name="bool_filter_rm">
<filterReference clause="must" ref="term_rm"/>
<filterReference clause="must" ref="range_rm"/>
</filter>
<filter name="range_rm" xsi:type="rangeFilter" field="price" from="$not_bind$" to="$not_bind$"/>
<filter name="term_rm" xsi:type="termFilter" field="price" value="$not_bind$"/>
<filter xsi:type="boolFilter" name="pid">
<filterReference clause="should" ref="pidm"/>
<filterReference clause="should" ref="pidsh"/>
</filter>
<filter name="pidm" xsi:type="rangeFilter" field="price" from="$pidm_from$" to="$pidm_to$"/>
<filter name="pidsh" xsi:type="termFilter" field="price" value="$pidsh$"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="range_filter" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="filteredQuery" name="range_filter">
<filterReference clause="must" ref="range_filter"/>
</query>
</queries>
<filters>
<filter name="range_filter"
xsi:type="rangeFilter"
field="price"
from="$range_filter_from$"
to="$range_filter_to$"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="range_filter_without_from_field" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="filteredQuery" name="range_filter_without_from_field">
<filterReference clause="must" ref="range_filter_without_from_field"/>
</query>
</queries>
<filters>
<filter name="range_filter_without_from_field"
xsi:type="rangeFilter"
field="price"
to="$range_filter_to$"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="range_filter_without_to_field" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="filteredQuery" name="range_filter_without_to_field">
<filterReference clause="must" ref="range_filter_without_to_field"/>
</query>
</queries>
<filters>
<filter name="range_filter_without_to_field"
xsi:type="rangeFilter"
field="price"
from="$range_filter_from$"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="term_filter" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="filteredQuery" name="term_filter">
<filterReference clause="must" ref="term_filter"/>
</query>
</queries>
<filters>
<filter name="term_filter" xsi:type="termFilter" field="price" value="$request.price$"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="bool_filter" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="filteredQuery" name="bool_filter">
<filterReference clause="must" ref="bool_filter"/>
</query>
</queries>
<filters>
<filter xsi:type="boolFilter" name="bool_filter">
<filterReference clause="must" ref="must_range_filter1"/>
<filterReference clause="should" ref="should_term_filter1"/>
<filterReference clause="should" ref="should_term_filter2"/>
<filterReference clause="should" ref="should_term_filter3"/>
<filterReference clause="should" ref="should_term_filter4"/>
<filterReference clause="not" ref="not_term_filter1"/>
<filterReference clause="not" ref="not_term_filter2"/>
</filter>
<filter name="must_range_filter1"
xsi:type="rangeFilter"
field="price"
from="$must_range_filter1_from$"
to="$must_range_filter1_to$"/>
<filter name="should_term_filter1"
xsi:type="termFilter"
field="price"
value="$should_term_filter1$"/>
<filter name="should_term_filter2"
xsi:type="termFilter"
field="price"
value="$should_term_filter2$"/>
<filter name="should_term_filter3"
xsi:type="termFilter"
field="price"
value="$should_term_filter3$"/>
<filter name="should_term_filter4"
xsi:type="termFilter"
field="price"
value="$should_term_filter4$"/>
<filter name="not_term_filter1"
xsi:type="termFilter"
field="price"
value="$not_term_filter1$"/>
<filter name="not_term_filter2"
xsi:type="termFilter"
field="price"
value="$not_term_filter2$"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="bool_filter_with_nested_bool_filter" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="filteredQuery" name="bool_filter_with_nested_bool_filter">
<filterReference clause="must" ref="bool_filter_with_nested_bool_filter"/>
</query>
</queries>
<filters>
<filter xsi:type="boolFilter" name="bool_filter_with_nested_bool_filter">
<filterReference clause="not" ref="not_range_filter"/>
<filterReference clause="not" ref="not_bool_filter"/>
</filter>
<filter xsi:type="boolFilter" name="not_bool_filter">
<filterReference clause="not" ref="nested_not_term_filter"/>
</filter>
<filter name="not_range_filter"
xsi:type="rangeFilter"
field="price"
from="$not_range_filter_from$"
to="$not_range_filter_to$"/>
<filter name="nested_not_term_filter"
xsi:type="termFilter"
field="price"
value="$nested_not_term_filter$"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="bool_filter_with_range_in_nested_negative_filter" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="filteredQuery" name="bool_filter_with_range_in_nested_negative_filter">
<filterReference clause="must" ref="bool_filter_with_range_in_nested_negative_filter"/>
</query>
</queries>
<filters>
<filter xsi:type="boolFilter" name="bool_filter_with_range_in_nested_negative_filter">
<filterReference clause="not" ref="not_bool_filter"/>
</filter>
<filter xsi:type="boolFilter" name="not_bool_filter">
<filterReference clause="must" ref="nested_must_range_filter"/>
</filter>
<filter name="nested_must_range_filter"
xsi:type="rangeFilter"
field="price"
from="$nested_must_range_filter_from$"
to="$nested_must_range_filter_to$"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="advanced_search_test" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="boolQuery" name="advanced_search_test" boost="1">
<queryReference clause="should" ref="name_query"/>
<queryReference clause="should" ref="description_query"/>
<queryReference clause="should" ref="query_filter"/>
</query>
<query xsi:type="matchQuery" name="name_query" value="$name_query$">
<match field="name" boost="1"/>
</query>
<query xsi:type="matchQuery" name="description_query" value="$description_query$">
<match field="description" boost="1"/>
</query>
<query xsi:type="filteredQuery" name="query_filter">
<filterReference clause="must" ref="filter"/>
</query>
</queries>
<filters>
<filter xsi:type="boolFilter" name="filter">
<filterReference clause="must" ref="price_filter"/>
</filter>
<filter name="price_filter" xsi:type="rangeFilter" field="price" from="$request.from_price$" to="$request.to_price$"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="filterable_custom_attributes" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="boolQuery" name="filterable_custom_attributes" boost="1">
<queryReference clause="must" ref="category"/>
<queryReference clause="must" ref="price"/>
<queryReference clause="must" ref="select_attribute"/>
<queryReference clause="must" ref="multiselect_attribute"/>
</query>
<query xsi:type="filteredQuery" name="category">
<filterReference clause="must" ref="category_filter"/>
</query>
<query xsi:type="filteredQuery" name="price">
<filterReference clause="must" ref="price_filter"/>
</query>
<query xsi:type="filteredQuery" name="select_attribute">
<filterReference clause="must" ref="select_attribute_filter"/>
</query>
<query xsi:type="filteredQuery" name="multiselect_attribute">
<filterReference clause="must" ref="multiselect_attribute_filter"/>
</query>
</queries>
<filters>
<filter xsi:type="termFilter" name="category_filter" field="category_ids" value="$category_ids$"/>
<filter xsi:type="rangeFilter" name="price_filter" field="price" from="$price.from$" to="$price.to$"/>
<filter xsi:type="termFilter" name="select_attribute_filter" field="select_attribute" value="$select_attribute$"/>
<filter xsi:type="termFilter" name="multiselect_attribute_filter" field="multiselect_attribute" value="$multiselect_attribute$"/>
</filters>
<aggregations>
<bucket name="price_bucket" field="price" xsi:type="dynamicBucket" method="$price_dynamic_algorithm$">
<metrics>
<metric type="count"/>
</metrics>
</bucket>
<bucket name="category_bucket" field="category_ids" xsi:type="termBucket">
<metrics>
<metric type="count"/>
</metrics>
</bucket>
</aggregations>
<from>0</from>
<size>10</size>
</request>
<request query="advanced_search_date_field" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="boolQuery" name="advanced_search_date_field" boost="1">
<queryReference clause="should" ref="query_filter"/>
</query>
<query xsi:type="filteredQuery" name="query_filter">
<filterReference clause="must" ref="filter"/>
</query>
</queries>
<filters>
<filter xsi:type="boolFilter" name="filter">
<filterReference clause="must" ref="date_filter"/>
</filter>
<filter name="date_filter" xsi:type="rangeFilter" field="date_attribute" from="$date.from$" to="$date.to$"/>
</filters>
<from>0</from>
<size>10</size>
</request>
<request query="filter_out_of_stock_child" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="boolQuery" name="filter_out_of_stock_child" boost="1">
<queryReference clause="must" ref="test_configurable"/>
<queryReference clause="must" ref="visibility"/>
</query>
<query xsi:type="filteredQuery" name="test_configurable">
<filterReference clause="must" ref="test_configurable_filter"/>
</query>
<query xsi:type="filteredQuery" name="visibility">
<filterReference clause="must" ref="visibility_filter"/>
</query>
</queries>
<filters>
<filter xsi:type="termFilter" name="test_configurable_filter" field="test_configurable" value="$test_configurable$"/>
<filter xsi:type="termFilter" name="visibility_filter" field="visibility" value="$visibility$"/>
</filters>
<aggregations/>
<from>0</from>
<size>10</size>
</request>
<request query="search_boost" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="boolQuery" name="search_boost" boost="1">
<queryReference clause="should" ref="search_boost_name_query"/>
<queryReference clause="should" ref="search_boost_description_query"/>
</query>
<query xsi:type="matchQuery" name="search_boost_name_query" value="$query$" boost="1">
<match field="name"/>
</query>
<query xsi:type="matchQuery" name="search_boost_description_query" value="$query$" boost="1">
<match field="description"/>
</query>
</queries>
<from>0</from>
<size>10</size>
</request>
<request query="search_boost_name" index="catalogsearch_fulltext">
<dimensions>
<dimension name="scope" value="default"/>
</dimensions>
<queries>
<query xsi:type="boolQuery" name="search_boost_name" boost="1">
<queryReference clause="should" ref="search_boost_name_query"/>
<queryReference clause="should" ref="search_boost_description_query"/>
</query>
<query xsi:type="matchQuery" name="search_boost_name_query" value="$query$" boost="20">
<match field="name"/>
</query>
<query xsi:type="matchQuery" name="search_boost_description_query" value="$query$" boost="1">
<match field="description"/>
</query>
</queries>
<from>0</from>
<size>10</size>
</request>
</requests>
@@ -0,0 +1,56 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Catalog\Setup\CategorySetup $installer */
$installer = $objectManager->create(\Magento\Catalog\Setup\CategorySetup::class);
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
$selectAttribute = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);
$selectAttribute->setData(
[
'attribute_code' => 'select_attribute',
'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
'is_global' => 1,
'is_user_defined' => 1,
'frontend_input' => 'select',
'is_unique' => 0,
'is_required' => 0,
'is_searchable' => 1,
'is_visible_in_advanced_search' => 0,
'is_comparable' => 0,
'is_filterable' => 1,
'is_filterable_in_search' => 0,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 0,
'used_in_product_listing' => 0,
'used_for_sort_by' => 0,
'frontend_label' => ['Select Attribute'],
'backend_type' => 'varchar',
'backend_model' => \Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend::class,
'option' => [
'value' => [
'chair' => ['Chair'],
'table' => ['Table'],
],
'order' => [
'chair' => 1,
'table' => 2,
],
],
]
);
$selectAttribute->save();
$installer->addAttributeToGroup(
'catalog_product',
'Default',
'General',
$selectAttribute->getId()
);
@@ -0,0 +1,20 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
$attribute = $objectManager->create(
\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class
);
$attribute->load('select_attribute', 'attribute_code');
$attribute->delete();
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,71 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/**
* @var StoreManagerInterface $storeManager
*/
$storeManager = $objectManager->get(StoreManagerInterface::class);
$option = [
'value' => [
'chair' => ['Chair'],
'table' => ['Table'],
],
'order' => [
'chair' => 1,
'table' => 2,
],
];
foreach ($option['value'] as $value => $labels) {
foreach ($storeManager->getStores() as $store) {
$labels[$store->getId()] = $labels[0] . '_' . $store->getCode();
}
$option['value'][$value] = $labels;
}
/** @var \Magento\Catalog\Setup\CategorySetup $installer */
$installer = $objectManager->create(\Magento\Catalog\Setup\CategorySetup::class);
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
$selectAttribute = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);
$selectAttribute->setData(
[
'attribute_code' => 'select_attribute',
'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
'is_global' => 1,
'is_user_defined' => 1,
'frontend_input' => 'select',
'is_unique' => 0,
'is_required' => 0,
'is_searchable' => 1,
'is_visible_in_advanced_search' => 0,
'is_comparable' => 0,
'is_filterable' => 1,
'is_filterable_in_search' => 0,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 0,
'used_in_product_listing' => 0,
'used_for_sort_by' => 0,
'frontend_label' => ['Select Attribute'],
'backend_type' => 'varchar',
'backend_model' => \Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend::class,
'option' => $option,
]
);
$selectAttribute->save();
$installer->addAttributeToGroup(
'catalog_product',
'Default',
'General',
$selectAttribute->getId()
);
@@ -0,0 +1,10 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Elasticsearch/_files/select_attribute_rollback.php');