ContainsFilter example

use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter;

/** * @internal * * @covers \Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter */
class ContainsFilterTest extends TestCase
{
    public function testEncode(): void
    {
        $filter = new ContainsFilter('foo', 'bar');

        static::assertEquals(
            [
                'field' => 'foo',
                'value' => 'bar',
                'isPrimary' => false,
                'resolved' => null,
                'extensions' => [],
                '_class' => ContainsFilter::class,
            ],
            $filter->jsonSerialize()
        );
->expects(static::never())
            ->method('addOrderBy');

        $builder = $this->getContainer()->get(CriteriaQueryBuilder::class);
        $builder->build($queryMock$productDefinition$criteria, Context::createDefaultContext());
    }

    public function testSortByScoreIfScoreQueryIsSet(): void
    {
        $productDefinition = $this->getContainer()->get(ProductDefinition::class);
        $criteria = new Criteria();
        $criteria->addQuery(new ScoreQuery(new ContainsFilter('name', 'test matching'), 1000));
        $queryMock = $this->createTestProxy(QueryBuilder::class[$this->createMock(Connection::class)]);
        $queryMock
            ->expects(static::once())
            ->method('addOrderBy')
            ->with('_score', 'DESC');

        $builder = $this->getContainer()->get(CriteriaQueryBuilder::class);
        $builder->build($queryMock$productDefinition$criteria, Context::createDefaultContext());
    }

    public function testSortByScoreIfSearchTermIsSet(): void
    {

                        [
                            'terms' => [
                                'name.' . Defaults::LANGUAGE_SYSTEM => ['foo', 'bar'],
                            ],
                        ],
                    ],
                ],
            ],
        ];
        yield 'ContainsFilter field' => [
            new ContainsFilter('productNumber', 'foo'),
            [
                'wildcard' => [
                    'productNumber' => [
                        'value' => '*foo*',
                    ],
                ],
            ],
        ];
        yield 'ContainsFilter translated field' => [
            new ContainsFilter('name', 'foo'),
            [
                


                continue;
            }

            $queries[] = new ScoreQuery(
                new EqualsFilter($select$term->getOriginal()->getTerm()),
                $ranking * $term->getOriginal()->getScore()
            );

            $queries[] = new ScoreQuery(
                new ContainsFilter($select$term->getOriginal()->getTerm()),
                $ranking * $term->getOriginal()->getScore() * 0.5
            );

            if ($flag && !$flag->tokenize()) {
                continue;
            }

            foreach ($term->getTerms() as $part) {
                $queries[] = new ScoreQuery(
                    new EqualsFilter($select$part->getTerm()),
                    $ranking * $part->getScore()
                );
$store,
            ApiProtectionException::class,
        ];

        yield 'Test aggregation order line item access in store api' => [
            (new Criteria())->addAggregation(new TermsAggregation('agg', 'orderLineItems.id')),
            $store,
            ApiProtectionException::class,
        ];

        yield 'Test filter for runtime field' => [
            (new Criteria())->addFilter(new ContainsFilter('variation', Uuid::randomHex())),
            $admin,
            RuntimeFieldInCriteriaException::class,
        ];

        yield 'Test aggregate for runtime field' => [
            (new Criteria())->addAggregation(new TermsAggregation('agg', 'variation')),
            $admin,
            RuntimeFieldInCriteriaException::class,
        ];
    }
}
$productId2 = Uuid::randomHex();

        $this->productRepository->upsert([
            ['id' => $productId1, 'productNumber' => Uuid::randomHex(), 'stock' => 1, 'name' => 'test_product 1', 'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 9, 'linked' => false]], 'tax' => ['name' => 'test', 'taxRate' => 5], 'manufacturer' => ['name' => 'test']],
            ['id' => $productId2, 'productNumber' => Uuid::randomHex(), 'stock' => 2, 'name' => 'test_product 2', 'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 9, 'linked' => false]], 'tax' => ['name' => 'test', 'taxRate' => 5], 'manufacturer' => ['name' => 'test']],
            ['id' => Uuid::randomHex(), 'productNumber' => Uuid::randomHex(), 'stock' => 1, 'name' => 'notmatch', 'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 9, 'linked' => false]], 'tax' => ['name' => 'notmatch', 'taxRate' => 5], 'manufacturer' => ['name' => 'notmatch']],
            ['id' => Uuid::randomHex(), 'productNumber' => Uuid::randomHex(), 'stock' => 1, 'name' => 'notmatch', 'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 9, 'linked' => false]], 'tax' => ['name' => 'notmatch', 'taxRate' => 5], 'manufacturer' => ['name' => 'notmatch']],
        ]$this->context);

        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('stock', 1));
        $criteria->addQuery(new ScoreQuery(new ContainsFilter('manufacturer.name', 'test'), 500));
        $criteria->addQuery(new ScoreQuery(new ContainsFilter('name', 'test'), 2500));

        $queries = new CriteriaCollection([
            'product' => $criteria,
        ]);

        $result = $this->searcher->search($queries$this->context);

        static::assertCount(1, $result);

        static::assertNotEmpty($result['product']);

        
$criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_NONE);

        /** @var CategoryCollection $missing */
        $missing = $this->categoryRepository->search($criteria$context)->getEntities();

        return $missing;
    }

    private function loadLevels(string $rootId, int $rootLevel, SalesChannelContext $context, Criteria $criteria, int $depth = 2): CategoryCollection
    {
        $criteria->addFilter(
            new ContainsFilter('path', '|' . $rootId . '|'),
            new RangeFilter('level', [
                RangeFilter::GT => $rootLevel,
                RangeFilter::LTE => $rootLevel + $depth + 1,
            ])
        );

        $criteria->addAssociation('media');

        $criteria->setLimit(null);
        $criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_NONE);

        
foreach ($pattern->getTerms() as $searchTerm) {
            $criteria->addQuery(
                new ScoreQuery(
                    new EqualsFilter('product.searchKeywords.keyword', $searchTerm->getTerm()),
                    $searchTerm->getScore(),
                    'product.searchKeywords.ranking'
                )
            );
        }
        $criteria->addQuery(
            new ScoreQuery(
                new ContainsFilter('product.searchKeywords.keyword', $pattern->getOriginal()->getTerm()),
                $pattern->getOriginal()->getScore(),
                'product.searchKeywords.ranking'
            )
        );

        if ($pattern->getBooleanClause() !== SearchPattern::BOOLEAN_CLAUSE_AND) {
            $criteria->addFilter(new AndFilter([
                new EqualsAnyFilter('product.searchKeywords.keyword', array_values($pattern->getAllTerms())),
                new EqualsFilter('product.searchKeywords.languageId', $context->getContext()->getLanguageId()),
            ]));

            
$pattern = new SearchPattern(
            new SearchTerm($dateTerm, 1),
            'product'
        );

        $queries = $builder->buildScoreQueries($pattern$this->onlyDateFieldDefinition, 'test', $this->context);

        static::assertEquals(
            [
                new ScoreQuery(new EqualsFilter('test.dateTime', $dateTerm), 100),
                new ScoreQuery(new ContainsFilter('test.dateTime', $dateTerm), 50),
            ],
            $queries
        );
    }

    /** * @dataProvider inValidDateTerms */
    public function testInValidDateTerms(string $dateTerm): void
    {
        $builder = new EntityScoreQueryBuilder();

        
return null;
    }

    private function getSalesChannelFilter(SalesChannelContext $context): MultiFilter
    {
        $ids = array_filter([
            $context->getSalesChannel()->getNavigationCategoryId(),
            $context->getSalesChannel()->getServiceCategoryId(),
            $context->getSalesChannel()->getFooterCategoryId(),
        ]);

        return new OrFilter(array_map(static fn (string $id) => new ContainsFilter('path', '|' . $id . '|')$ids));
    }

    private function getMainCategory(ProductEntity $product, SalesChannelContext $context): ?CategoryEntity
    {
        $criteria = new Criteria();
        $criteria->setLimit(1);
        $criteria->setTitle('breadcrumb-builder::main-category');

        if (($product->getMainCategories() === null || $product->getMainCategories()->count() <= 0) && $product->getParentId() !== null) {
            $criteria->addFilter($this->getMainCategoryFilter($product->getParentId()$context));
        } else {
            

        $io = new ShopwareStyle($input$output);
        $context = Context::createDefaultContext();

        $criteria = new Criteria();
        $criteria->addSorting(new FieldSorting('name', FieldSorting::ASCENDING));
        $filter = $input->getOption('filter');
        if ($filter) {
            $criteria->addFilter(new MultiFilter(
                MultiFilter::CONNECTION_OR,
                [
                    new ContainsFilter('name', $filter),
                    new ContainsFilter('label', $filter),
                ]
            ));
        }
        /** @var PluginCollection $plugins */
        $plugins = $this->pluginRepo->search($criteria$context)->getEntities();

        if ($input->getOption('json')) {
            $output->write(json_encode($plugins, \JSON_THROW_ON_ERROR));

            return self::SUCCESS;
        }
return new MultiFilter($operator$queries);
            case 'contains':
                if (empty($query['field'])) {
                    throw DataAbstractionLayerException::invalidFilterQuery('Parameter "field" for contains filter is missing.', $path . '/field');
                }

                if (!isset($query['value']) || $query['value'] === '') {
                    throw DataAbstractionLayerException::invalidFilterQuery('Parameter "value" for contains filter is missing.', $path . '/value');
                }

                return new ContainsFilter(self::buildFieldName($definition$query['field'])$query['value']);
            case 'prefix':
                if (empty($query['field'])) {
                    throw DataAbstractionLayerException::invalidFilterQuery('Parameter "field" for prefix filter is missing.', $path . '/field');
                }

                if (!isset($query['value']) || $query['value'] === '') {
                    throw DataAbstractionLayerException::invalidFilterQuery('Parameter "value" for prefix filter is missing.', $path . '/value');
                }

                return new PrefixFilter(self::buildFieldName($definition$query['field'])$query['value']);
            case 'suffix':
                

        $criteria = (new Criteria($ids))
            ->addFilter($notGreenFilter);

        $notGreenIds = $productRepository->searchIds($criteria, Context::createDefaultContext())->getIds();
        static::assertContains($noTagsId$notGreenIds);
        static::assertContains($redId$notGreenIds);
        static::assertContains($blueId$notGreenIds);
        static::assertCount(3, $notGreenIds);

        $extendedNotGreenFilter = new MultiFilter('AND', [
            new ContainsFilter('name', 'green'),
            $notGreenFilter,
        ]);

        $criteria = (new Criteria($ids))->addFilter($extendedNotGreenFilter);

        $notGreenExtendedIds = $productRepository->searchIds($criteria, Context::createDefaultContext())->getIds();

        static::assertContains($noTagsId$notGreenExtendedIds);
        static::assertCount(1, $notGreenExtendedIds);

        $notGreenFilter = new NotFilter('OR', [
            

        ];

        $this->getContainer()->get('product_stream.repository')
            ->create([$stream], Context::createDefaultContext());

        $filters = $this->getContainer()->get(ProductStreamBuilder::class)
            ->buildFilters($ids->get('stream'), Context::createDefaultContext());

        $expected = new MultiFilter(MultiFilter::CONNECTION_OR, [
            new MultiFilter(MultiFilter::CONNECTION_AND, [
                new ContainsFilter('product.name', 'Awesome'),
                new NotFilter(MultiFilter::CONNECTION_AND, [
                    new ContainsFilter('product.name', 'Copper'),
                ]),
            ]),
        ]);

        $filter = array_shift($filters);
        static::assertInstanceOf(MultiFilter::class$filter);

        static::assertEquals($expected$filter);
    }

    
class RepositoryIteratorTest extends TestCase
{
    use IntegrationTestBehaviour;

    public function testIteratedSearch(): void
    {
        $context = Context::createDefaultContext();
        /** @var EntityRepository<SystemConfigCollection> $systemConfigRepository */
        $systemConfigRepository = $this->getContainer()->get('system_config.repository');

        $criteria = new Criteria();
        $criteria->addFilter(new ContainsFilter('configurationKey', 'core'));
        $criteria->setLimit(1);

        /** @var RepositoryIterator<SystemConfigCollection> $iterator */
        $iterator = new RepositoryIterator($systemConfigRepository$context$criteria);

        $offset = 1;
        while (($result = $iterator->fetch()) !== null) {
            static::assertNotEmpty($result->getEntities()->first()?->getId());
            static::assertEquals(
                [new ContainsFilter('configurationKey', 'core')],
                $criteria->getFilters()
            );
Home | Imprint | This part of the site doesn't use cookies.