Find all products by filters

@param Category $category
@param array    $options
@param bool     $getResults

@return ArrayCollection|Query
425140
public function findAllByFilters($category, Array $options, $getResults = true)
    {
        $qb = $this->getQueryBuilder()
            ->select('p');

        if (is_null($category) && array_key_exists('s-with-dashes', $options)) {
            // searching
            $orX = $qb->expr()->orX();
            $orX->add('p.name LIKE :searchWithDashes')
                ->add('p.name LIKE :searchWithSpaces');
            $qb->andWhere($orX)
                ->setParameter('searchWithDashes', '%'.$options['s-with-dashes'].'%')
                ->setParameter('searchWithSpaces', '%'.$options['s-with-spaces'].'%');
        } elseif (!is_null($category)) {
            if (!is_null($category->getParentCategory())) {
                // listing by subcategory (put in 'where' as it is)
                $qb->andWhere('p.category = :category')
                    ->setParameter('category', $category);
            } else {
                // listing by category (put its subcategories in a chained 'or')
                $orX = $qb->expr()->orX();

                foreach ($category->getSubcategories() as $subcategory) {
                    $orX->add('IDENTITY(p.category) = '.$subcategory->getId());
                }

                $qb->andWhere($orX);
            }
        }

        // sort filter
        if (false === array_key_exists('sort', $options)) {
            $options['sort'] = 'price-asc';
        }

        switch ($options['sort']) {
            case 'newest':
                $qb->orderBy('p.createdAt', 'desc');
                break;
            case 'oldest':
                $qb->orderBy('p.createdAt', 'asc');
                break;
            case 'price-asc':
                $qb->orderBy('p.price', 'asc');
                break;
            case 'price-desc':
                $qb->orderBy('p.price', 'desc');
                break;
        }

        // brands filter
        if (array_key_exists('brands', $options)) {
            $orX = $qb->expr()->orX();

            foreach ($options['brands'] as $brand) {
                $orX->add('IDENTITY(p.brand) = '.$brand);
            }

            $qb->andWhere($orX);
        }

        // attributes filter
        if (array_key_exists('attributes', $options)) {
            $qb->join('p.attributeValues', 'av');

            $orX = $qb->expr()->orX();

            foreach ($options['attributes'] as $attribute) {
                $orX->add('av.id = '.$attribute);
            }

            $qb->andWhere($orX);
        }

        // features filter
        if (array_key_exists('features', $options)) {
            $qb->join('p.featureValues', 'fv');

            $orX = $qb->expr()->orX();

            foreach ($options['features'] as $feature) {
                $orX->add('fv.id = '.$feature);
            }

            $qb->andWhere($orX);
            $qb->having('count(p.id) >= :num_features');
            $numFeatures = count($options['features']);
            $qb->setParameter('num_features', $numFeatures);
        }
        $qb->groupBy('p.id');

        // attribute ranges filter
/*        if (array_key_exists('attribute-min', $options) && array_key_exists('attribute-max', $options)) {
            if (false === array_key_exists('attributes', $options)) {
                $qb->join('p.attributeValues', 'av');
            }

            $andX = $qb->expr()->andX();

            foreach ($options['attribute-min'] as $value) {
                $andX->add('av.name >= '.$value);
            }

            foreach ($options['attribute-max'] as $value) {
                $andX->add('av.name <= '.$value);
            }

            $qb->andWhere($andX);
        }*/

        // feature ranges filter
/*        if (array_key_exists('feature-min', $options) && array_key_exists('feature-max', $options)) {
            if (false === array_key_exists('features', $options)) {
                $qb->join('p.featureValues', 'fv');
            }

            $andX = $qb->expr()->andX();

            foreach ($options['feature-min'] as $value) {
                $andX->add('fv.name >= '.$value);
            }

            foreach ($options['feature-max'] as $value) {
                $andX->add('fv.name <= '.$value);
            }

            $qb->andWhere($andX);
        }*/

        $query = $qb->getQuery();

        return $getResults ? $query->getResult() : $query;
    }
377732
public function findEntitiesByCategoryId($categoryId, $locale)
    {
        $products = $this->productRepository->findByCategoryId($categoryId, $locale);

        return $products;
    }
319322
public function getChoices(Options $options)
    {
        if (!$options['category'] instanceof CategoryInterface) {
            return [];
        }

        if (null === $options['context']) {
            $categories = $this->manager->getAllRootCategories();
        } else {
            $categories = $this->manager->getRootCategoriesForContext($options['context']);
        }

        $choices = [];

        foreach ($categories as $category) {
            $choices[$category->getId()] = sprintf('%s (%s)', $category->getName(), $category->getContext()->getId());

            $this->childWalker($category, $options, $choices);
        }

        return $choices;
    }
577630
public function searchSpecifications(array $filters = [], array $options = [])
    {
        $data = [
            'body' => ['query' => $filters]
        ];

        $response = $this->kuzzle->query(
            $this->kuzzle->buildQueryArgs('collection', 'searchSpecifications'),
            $data,
            $options
        );

        return $response['result'];
    }
175701
public function getCategoryProductWithFilter($categoryId, $filters = [])
    {
        $prefix = env('DB_TABLE_PREFIX', 'avored_');

        $propetryInnerJoinFlag = false;
        $attributeInnerJoinFlag = false;

        $sql = "Select p.id
                FROM {$prefix}products as p 
                INNER JOIN {$prefix}category_product as cp on p.id = cp.product_id ";

        foreach ($filters as $type => $filterArray) {
            if ('property' == $type) {
                foreach ($filterArray as $identifier => $value) {
                    $property = Property::whereIdentifier($identifier)->first();

                    if ('INTEGER' == $property->data_type) {
                        if (false === $propetryInnerJoinFlag) {
                            $propetryInnerJoinFlag = true;
                            $sql .= "INNER JOIN {$prefix}product_property_integer_values as ppiv ON p.id = ppiv.product_id ";
                        }
                    }
                }
            }

            if ('attribute' == $type) {
                foreach ($filterArray as $identifier => $value) {
                    $attribute = Attribute::whereIdentifier($identifier)->first();
                    if (false === $attributeInnerJoinFlag) {
                        $attributeInnerJoinFlag = true;
                        $sql .= "INNER JOIN {$prefix}product_attribute_integer_values as paiv ON p.id = paiv.product_id ";
                    }
                }
            }
        }

        $sql .= "WHERE p.type != 'VARIABLE_PRODUCT' AND  cp.category_id = ? ";

        foreach ($filters as $type => $filterArray) {
            if ('property' == $type) {
                foreach ($filterArray as $identifier => $value) {
                    $property = Property::whereIdentifier($identifier)->first();

                    if ('INTEGER' == $property->data_type) {
                        $sql .= "AND ppiv.property_id = {$property->id} AND ppiv.value={$value} ";
                    }
                }
            }
        }

        foreach ($filters as $type => $filterArray) {
            if ('attribute' == $type) {
                foreach ($filterArray as $identifier => $value) {
                    $attribute = Attribute::whereIdentifier($identifier)->first();
                    $sql .= "AND paiv.attribute_id = {$attribute->id} AND paiv.value={$value} ";
                }
            }
        }

        $products = DB::select($sql, [$categoryId]);
        $collect = Collection::make([]);

        foreach ($products as $productArray) {
            $product = Product::find($productArray->id);

            if ($product->type == 'VARIABLE_PRODUCT') {
                $collect->push(($product->getVariableMainProduct()));
            } else {
                $collect->push(Product::find($productArray->id));
            }
        }

        return $collect;
    }
28743
public function getList(array $options = array())
    {
        $result = null;
        $this->hook->attach('product.class.list.before', $options, $result, $this);

        if (isset($result)) {
            return $result;
        }

        $sql = 'SELECT pc.*';

        if (!empty($options['count'])) {
            $sql = 'SELECT COUNT(pc.product_class_id)';
        }

        $sql .= ' FROM product_class pc WHERE pc.product_class_id IS NOT NULL';

        $conditions = array();

        if (isset($options['title'])) {
            $sql .= ' AND pc.title LIKE ?';
            $conditions[] = "%{$options['title']}%";
        }

        if (isset($options['status'])) {
            $sql .= ' AND pc.status=?';
            $conditions[] = (int) $options['status'];
        }

        $allowed_order = array('asc', 'desc');
        $allowed_sort = array('title', 'status', 'product_class_id');

        $sql .= ' GROUP BY pc.product_class_id';

        if (isset($options['sort'])
            && in_array($options['sort'], $allowed_sort)
            && isset($options['order'])
            && in_array($options['order'], $allowed_order)) {
            $sql .= " ORDER BY pc.{$options['sort']} {$options['order']}";
        } else {
            $sql .= ' ORDER BY pc.title ASC';
        }

        if (!empty($options['limit'])) {
            $sql .= ' LIMIT ' . implode(',', array_map('intval', $options['limit']));
        }

        if (empty($options['count'])) {
            $result = $this->db->fetchAll($sql, $conditions, array('index' => 'product_class_id'));
        } else {
            $result = (int) $this->db->fetchColumn($sql, $conditions);
        }

        $this->hook->attach('product.class.list.after', $options, $result, $this);
        return $result;
    }
454607
public function getWhereArray(array $clauses, array $options = [])
    {
        $query = $this->createBaseBuilder($options);

        $this->applyWhereArray($query, $clauses);

        return $query->get();
    }
611758
public function getQueryFilter(CategoryInterface $category)
    {
        $queryParams       = ['field' => 'category.category_id', 'value' => $category->getId()];
        $query             = $this->queryFactory->create(QueryInterface::TYPE_TERM, $queryParams);
        $nestedQueryParams = ['query' => $query, 'path' => 'category'];

        return $this->queryFactory->create(QueryInterface::TYPE_NESTED, $nestedQueryParams);
    }
277640
public function addFileTypeSetsToCategory(\Category $category, $dbResultCategory)
  {
    $arrFileTypesOfSets = array();
    $arrFileTypeSetIds = deserialize($dbResultCategory->file_type_sets);
    if (!empty($arrFileTypeSetIds))
    {
      foreach($arrFileTypeSetIds as $arrFileTypeSetId)
      {
        $arrFileTypesOfSets = array_merge($arrFileTypesOfSets, explode(",", $this->arrPublishedFileTypeSets[$arrFileTypeSetId]));
      }
    
    }
    
    $arrFileTypes = \DmsUtils::getUniqueFileTypes($category->fileTypes, $arrFileTypesOfSets);
    
    $category->fileTypes = implode(",", $arrFileTypes);
    return $category;
  }
98973
public function getResults(array $options = []) : ?SavedSearch
    {
        $this->setContainerId($options['entity']);

        $table = TableRegistry::get('Search.SavedSearches');

        /** @var \Search\Model\Entity\SavedSearch|null */
        $savedSearch = $table->find()
            ->where(['id' => $this->widget->get('widget_id')])
            ->enableHydration(true)
            ->first();

        if (null === $savedSearch) {
            $this->errors[] = 'No data found for this entity';

            return null;
        }

        /** @var \Cake\Datasource\RepositoryInterface */
        $table = TableRegistry::get($savedSearch->get('model'));

        $search = new Search($table, $options['user']);
        // keeps backward compatibility
        $entity = $search->reset($savedSearch);
        if (null === $entity) {
            $this->errors[] = 'Failed to reset entity';

            return null;
        }
        $content = $entity->get('content');
        $content['saved'] = Validator::validateData($table, $content['saved'], $options['user']);
        $entity->set('content', $content);

        $this->options['fields'] = Utility::instance()->getSearchableFields($table, $options['user']);
        $this->options['associationLabels'] = Utility::instance()->getAssociationLabels($table);

        $this->data = $entity;

        return $this->data;
    }
541509
public function findBy(array $wheres, array $options = [])
    {
        $query = $this->getSqlObject()->select();

        $this->setColumns($query, $options);

        $wheres = $this->addJoins($query, $wheres, $options);

        $this->addWheres($query, $wheres, $options);

        if (Arr::get($options, 'order')) {
            $this->setOrder($query, $options['order']);
        }

        return $this->executeAndGetResultsAsEntity($query);
    }
719848
static function fetchCountByCategory( $categories )
    {
        $db = eZDB::instance();

        $query = "SELECT COUNT(*) AS count FROM ezvatrule vr, ezvatrule_product_category vrpc " .
                 "WHERE vr.id=vrpc.vatrule_id AND ";

        if ( is_array( $categories ) )
        {
            $query .= $db->generateSQLINStatement( $categories, 'vrpc.product_category_id', false, false, 'int' );
        }
        else
        {
            $query .= "vrpc.product_category_id =" . (int) $categories;
        }

        $rows = $db->arrayQuery( $query );

        return $rows[0]['count'];
    }
209955
public function getQuery(array $options = array())
    {
        $query = $this->query;
        $query['query'] = $this->expr->getQuery();
        $query['newObj'] = $this->expr->getNewObj();
        return new Query($this->collection, $query, $options);
    }
179812
public function get($filters = [], $sorts = [], $fields = [], $embeds = [])
	{
		$query = $this->model;

		foreach($filters as $filter)
		{
			if($filter['or'])
			{
				$query = $query->orWhere($filter['field'], $filter['operator'], $filter['value']);
			}
			else
			{
				$query = $query->where($filter['field'], $filter['operator'], $filter['value']);
			}
		}

		foreach($embeds as $embed)
		{
			$this->eagerLoad($embed);
		}

		foreach($sorts as $key => $sort)
		{
			$query = $query->orderBy($sort['field'], $sort['direction']);
		}

		// @todo: implement fields

		$retrieved = $this->retrieve($query);

		if($retrieved->isEmpty())
		{
			return new Payload($retrieved, 'not_found');
		}

		return new Payload($retrieved, 'found');
	}
416624
public function getCategoryOptions($category_model, array $options)
    {
        $options += array(
            'status' => 1,
            'parent_id' => 0,
            'hierarchy' => true
        );

        $categories = $category_model->getTree($options);

        if (empty($categories)) {
            return array();
        }

        $list = array();
        foreach ($categories as $category) {

            $title = $category['title'];

            if (!empty($options['hierarchy'])) {
                $title = str_repeat('— ', $category['depth']) . $title;
            }

            $list[$category['category_id']] = $title;
        }

        return $list;
    }
524536
public static function getList(array $options = array())
    {
        $api = new Api\GetService();
        $result = $api->doRequest();
        $paymentMethods = self::reorderOutput($result);

        if (isset($options['country'])) {
            $paymentMethods = self::filterCountry($paymentMethods, $options['country']);
        }

        return $paymentMethods;
    }
231895
protected function buildFieldResultsArray(
        array $validationResults,
        array $options = []
    ): array {
        $results = [];
        /** @var ValidationResult $validationResult */
        foreach ($validationResults as $fieldName => $validationResult) {
            if ($validationResult instanceof ValidationResultFields) {
                $results[$fieldName] = $this->__invoke(
                    $validationResult,
                    $options
                );
                continue;
            }

            $results[$fieldName] = $this->validationResultToArray->__invoke(
                $validationResult,
                $options
            );
        }

        return $results;
    }