addFilter example

$collection = $this->sliderResolver->collect($slot$resolverContext);
        static::assertInstanceOf(CriteriaCollection::class$collection);

        static::assertCount(1, $collection->all());
        static::assertEquals(ProductDefinition::classkey($collection->all()));

        /** @phpstan-ignore-next-line - will fail because return type of getIterator will change */
        static::assertEquals('product-slider-entity-fallback_id', key($collection->getIterator()->current()));

        $expectedCriteria = new Criteria();
        $expectedCriteria->addSorting(new FieldSorting('name', FieldSorting::ASCENDING));
        $expectedCriteria->addFilter(new MultiFilter(
            MultiFilter::CONNECTION_AND,
            [
                new EqualsAnyFilter('product.id', [Uuid::randomHex()]),
                new RangeFilter('product.width', [
                    'gte' => 120,
                    'lte' => 180,
                ]),
            ]
        ));
        $expectedCriteria->setLimit(50);

        
    public function bench_load_product_listing_route_no_criteria(): void
    {
        $this->getContainer()->get(ProductListingRoute::class)
            ->load($this->ids->get(self::CATEGORY_KEY)new Request()$this->context, new Criteria());
    }

    #[Bench\Groups(['custom-pricing'])]     #[Bench\Assert('mean(variant.time.avg) < 35ms')]     public function bench_load_product_listing_route_only_active_and_price_below_80(): void
    {
        $criteria = (new Criteria())
            ->addFilter(new RangeFilter('price', [
                RangeFilter::GTE => 0.00,
                RangeFilter::LT => 80.00,
            ]))
            ->addFilter(new EqualsFilter('active', true));
        $this->getContainer()->get(ProductListingRoute::class)
            ->load($this->ids->get(self::CATEGORY_KEY)new Request()$this->context, $criteria);
    }

    protected static function getKernel(): KernelInterface
    {
        return self::getContainer()->get('kernel');
    }
private function getThemeConfigWithLabels(): StorefrontPluginConfiguration
    {
        $factory = $this->getContainer()->get(StorefrontPluginConfigurationFactory::class);

        return $factory->createFromBundle(new ThemeWithLabels());
    }

    private function getTheme(StorefrontPluginConfiguration $bundle, bool $withChild = false): ThemeEntity
    {
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('technicalName', $bundle->getTechnicalName()));
        $criteria->addAssociation('media');
        $criteria->addAssociation('translations.language.locale');

        if ($withChild) {
            $criteria->addAssociation('dependentThemes');
        }

        $theme = $this->themeRepository->search($criteria$this->context)->getEntities()->first();
        static::assertInstanceOf(ThemeEntity::class$theme);

        return $theme;
    }
Context::createDefaultContext()
        );

        return $ruleId;
    }

    protected function getDefaultProfileId(string $entity): string
    {
        /** @var EntityRepository $profileRepository */
        $profileRepository = $this->getContainer()->get('import_export_profile.repository');
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('systemDefault', true));
        $criteria->addFilter(new EqualsFilter('sourceEntity', $entity));

        /** @var string $id */
        $id = $profileRepository->searchIds($criteria, Context::createDefaultContext())->firstId();

        return $id;
    }

    protected function cloneDefaultProfile(string $entity): ImportExportProfileEntity
    {
        /** @var EntityRepository $profileRepository */
        
return parent::ensureMyTable();
  }

  protected function opHelper() {
    if (empty($this->value)) {
      return;
    }
    // Form API returns unchecked options in the form of option_id => 0. This     // breaks the generated query for "is all of" filters so we remove them.     $this->value = array_filter($this->value, [static::class, 'arrayFilterZero']);
    $this->helper->addFilter();
  }

}
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Log\Package;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelDefinitionInterface;
use Shopware\Core\System\SalesChannel\SalesChannelContext;

#[Package('buyers-experience')] class SalesChannelNewsletterRecipientDefinition extends NewsletterRecipientDefinition implements SalesChannelDefinitionInterface
{
    public function processCriteria(Criteria $criteria, SalesChannelContext $context): void
    {
        $criteria->addFilter(new EqualsFilter('salesChannel.id', $context->getSalesChannel()->getId()));
    }
}
$this->pluginService->refreshPlugins($this->context, new NullIO());

        $pluginInstalled = $this->pluginService->getPluginByName('SwagTestTheme', $this->context);
        $this->pluginLifecycleService->installPlugin($pluginInstalled$this->context);

        $this->pluginLifecycleService->activatePlugin($pluginInstalled$this->context);
        static::assertTrue($pluginInstalled->getActive());

        $themeRepo = $this->container->get('theme.repository');

        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('technicalName', 'SwagTestTheme'));

        static::assertCount(1, $themeRepo->search($criteria$this->context)->getElements());

        $this->pluginLifecycleService->uninstallPlugin($pluginInstalled$this->context, $keepUserData);

        $pluginUninstalled = $this->getTestPlugin($this->context);
        static::assertNull($pluginUninstalled->getInstalledAt());
        static::assertFalse($pluginUninstalled->getActive());
        static::assertCount($keepUserData ? 1 : 0, $themeRepo->search($criteria$this->context)->getElements());
    }

    

    public function getLocalesListQueryBuilder($filter = null, $order = null)
    {
        $builder = $this->createQueryBuilder('l');
        $fields = [
            'locale',
        ];
        $builder->select($fields);
        $builder->from(Locale::class, 'locale');
        if ($filter !== null) {
            $builder->addFilter($filter);
        }
        if ($order !== null) {
            $builder->addOrderBy($order);
        }

        return $builder;
    }

    /** * Returns a builder-object in order to get all shops * * @param array|null $filter * @param string|array|null $order * @param int|null $offset * @param int|null $limit * @param bool $orderByShopPositionAsDefault Deprecated since 5.6.3, will be default starting with Shopware 5.8. * * @return Query<Shop> */
            $reverses = $definition->getFields()->filter(
                fn (Field $field) => $field instanceof ManyToManyAssociationField && $association->getMappingDefinition() === $field->getMappingDefinition()
            );

            // contains now the inverse side association: category.products             /** @var ManyToManyAssociationField|null $reverse */
            $reverse = $reverses->first();
            if (!$reverse) {
                throw ApiException::missingReverseAssociation($definition->getEntityName()$parentDefinition->getEntityName());
            }

            $criteria->addFilter(
                new EqualsFilter(
                    sprintf('%s.%s.id', $definition->getEntityName()$reverse->getPropertyName()),
                    $parent['value']
                )
            );

            /** @var EntityDefinition $parentDefinition */
            if ($parentDefinition->isVersionAware()) {
                $criteria->addFilter(
                    new EqualsFilter(
                        sprintf('%s.%s.versionId', $definition->getEntityName()$reverse->getPropertyName()),
                        
EntitySearchedEvent::class => 'securePrivateFolders',
        ];
    }

    public function securePrivateFolders(EntitySearchedEvent $event): void
    {
        if ($event->getContext()->getScope() === Context::SYSTEM_SCOPE) {
            return;
        }

        if ($event->getDefinition()->getEntityName() === MediaFolderDefinition::ENTITY_NAME) {
            $event->getCriteria()->addFilter(
                new MultiFilter('OR', [
                    new EqualsFilter('media_folder.configuration.private', false),
                    new EqualsFilter('media_folder.configuration.private', null),
                ])
            );

            return;
        }

        if ($event->getDefinition()->getEntityName() === MediaDefinition::ENTITY_NAME) {
            $event->getCriteria()->addFilter(
                

        }
        $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()),
            ]));

            return;
        }

        foreach ($pattern->getTokenTerms() as $terms) {
            $criteria->addFilter(new AndFilter([
                new EqualsFilter('product.searchKeywords.languageId', $context->getContext()->getLanguageId()),
                new EqualsAnyFilter('product.searchKeywords.keyword', $terms),
            ]));

    public function getList($offset = 0, $limit = 25, array $criteria = [], array $orderBy = [])
    {
        $this->checkPrivilege('read');

        $builder = $this->getRepository()->createQueryBuilder('orders')
            ->addSelect(['attribute'])
            ->leftJoin('orders.attribute', 'attribute')
            ->addFilter($criteria)
            ->addOrderBy($orderBy)
            ->setFirstResult($offset)
                ->setMaxResults($limit)
            ->addSelect(['partial customer.{id,email}'])
            ->leftJoin('orders.customer', 'customer');
        /** @var Query<OrderModel|array<string, mixed>> $query */
        $query = $builder->getQuery();

        $query->setHydrationMode($this->getResultMode());

        $paginator = $this->getManager()->createPaginator($query);

        
public function getNotifications(Context $context, int $limit, ?string $latestTimestamp): array
    {
        $source = $context->getSource();
        if (!$source instanceof AdminApiSource) {
            throw new InvalidContextSourceException(AdminApiSource::class$context->getSource()::class);
        }

        $criteria = new Criteria();
        $isAdmin = $source->isAdmin();
        if (!$isAdmin) {
            $criteria->addFilter(new EqualsFilter('adminOnly', false));
        }

        if ($latestTimestamp) {
            $criteria->addFilter(new RangeFilter('createdAt', [
                RangeFilter::GT => $latestTimestamp,
            ]));
        }

        $criteria->addSorting(new FieldSorting('createdAt', FieldSorting::ASCENDING));
        $criteria->setLimit($limit);

        
yield 'option' => [['--format', '']['txt', 'json', 'github']];
    }

    private function createCommandTester(): CommandTester
    {
        return new CommandTester($this->createCommand());
    }

    private function createCommand(): Command
    {
        $environment = new Environment(new FilesystemLoader(\dirname(__DIR__).'/Fixtures/templates/'));
        $environment->addFilter(new TwigFilter('deprecated_filter', fn ($v) => $v['deprecated' => true]));

        $command = new LintCommand($environment);

        $application = new Application();
        $application->add($command);

        return $application->find('lint:twig');
    }

    private function createFile($content): string
    {
        
'countries.forceStateInRegistration',
            'countries.displayStateInRegistration',
            'area.id as areaId',
        ]);
        $builder->from(Country::class, 'countries')
            ->leftJoin('countries.area', 'area');

        if (\is_array($filter) && $filter[0]['property'] === 'areaId') {
            $builder->where('area.id = :areaId');
            $builder->setParameter('areaId', $filter[0]['value']);
        } elseif ($filter !== null) {
            $builder->addFilter($filter);
        }

        if ($order !== null) {
            $builder->addOrderBy($order);
        }

        return $builder;
    }

    /** * @param array|null $filter * @param string|array|OrderBy|null $order * * @return QueryBuilder */
Home | Imprint | This part of the site doesn't use cookies.