/**
  * {@inheritdoc}
  */
 public function apply(DatasourceInterface $datasource, $field, $direction)
 {
     $attribute = $this->attributeRepository->findOneByCode($field);
     $qb = $datasource->getQueryBuilder();
     $pqb = $this->productRepository->getProductQueryBuilder($qb);
     $pqb->addAttributeSorter($attribute, $direction);
 }
 /**
  * Update product association export date for the given product.
  *
  * @param JobInstance $jobInstance
  * @param string      $identifier
  */
 public function updateProductAssociationExport(JobInstance $jobInstance, $identifier)
 {
     $product = $this->productRepository->findByReference((string) $identifier);
     if ($product) {
         $this->updateExport($product, $jobInstance, $this->tableNameBuilder->getTableName('pim_magento_connector.entity.delta_product_association_export.class'));
     }
 }
 function it_checks_value_existence(ProductRepositoryInterface $productRepository, ProductValueInterface $value)
 {
     $productRepository->valueExists($value)->willReturn(true);
     $this->valueExists($value)->shouldReturn(true);
     $productRepository->valueExists($value)->willReturn(false);
     $this->valueExists($value)->shouldReturn(false);
 }
 /**
  * Display the products of a group
  *
  * @param string $identifier
  *
  * @return JsonResponse
  *
  * @AclAncestor("pim_enrich_product_index")
  */
 public function listProductsAction($identifier)
 {
     $group = $this->groupRepository->findOneBy(['code' => $identifier]);
     if (!$group) {
         throw new NotFoundHttpException(sprintf('Group with code "%s" not found', $identifier));
     }
     return new JsonResponse($this->normalizer->normalize(['products' => $this->productRepository->getProductsByGroup($group, self::MAX_PRODUCTS), 'productCount' => $this->productRepository->getProductCountByGroup($group)], 'internal_api'));
 }
 /**
  * Find a product by its id or return a 404 response
  *
  * @param string $id the product id
  *
  * @throws NotFoundHttpException
  *
  * @return ProductInterface
  */
 protected function findProductOr404($id)
 {
     $product = $this->productRepository->findOneByWithValues($id);
     if (!$product) {
         throw new NotFoundHttpException(sprintf('Product with id %s could not be found.', (string) $id));
     }
     return $product;
 }
 /**
  * Displays completeness for a product
  *
  * @param int $id
  *
  * @return Response
  */
 public function completenessAction($id)
 {
     $product = $this->productRepository->getFullProduct($id);
     $channels = $this->channelManager->getFullChannels();
     $locales = $this->userContext->getUserLocales();
     $completenesses = $this->completenessManager->getProductCompleteness($product, $channels, $locales, $this->userContext->getCurrentLocale()->getCode());
     return $this->templating->renderResponse('PimEnrichBundle:Completeness:_completeness.html.twig', ['product' => $product, 'channels' => $channels, 'locales' => $locales, 'completenesses' => $completenesses]);
 }
 /**
  * Find a product by its id or return a 404 response
  *
  * @param int $id the product id
  *
  * @throws NotFoundHttpException
  *
  * @return ProductInterface
  */
 protected function findProductOr404($id)
 {
     $product = $this->productRepository->findOneById($id);
     if (!$product) {
         throw new NotFoundHttpException(sprintf('Product with id %s could not be found.', $id));
     }
     $this->productBuilder->addMissingAssociations($product);
     return $product;
 }
 /**
  * Get completeness for a product
  *
  * @param int $id
  *
  * @return JSONResponse
  */
 public function getAction($id)
 {
     $product = $this->productRepository->getFullProduct($id);
     $this->completenessManager->generateMissingForProduct($product);
     $channels = $this->channelRepository->getFullChannels();
     $locales = $this->userContext->getUserLocales();
     $filteredLocales = $this->collectionFilter->filterCollection($locales, 'pim.internal_api.locale.view');
     $completenesses = $this->completenessManager->getProductCompleteness($product, $channels, $filteredLocales, $this->userContext->getCurrentLocale()->getCode());
     return new JsonResponse($this->completenessNormalizer->normalize($completenesses, 'internal_api'));
 }
 /**
  * {@inheritdoc}
  */
 public function apply(DatasourceInterface $datasource, $field, $direction)
 {
     $qb = $datasource->getQueryBuilder();
     $groupId = $this->requestParams->get('currentGroup', null);
     if (!$groupId) {
         throw new \LogicException('The current product group must be configured');
     }
     $field = 'in_group_' . $groupId;
     $pqb = $this->repository->getProductQueryBuilder($qb);
     $pqb->addFieldSorter($field, $direction);
 }
 /**
  * @return array
  */
 protected function prepareParameters()
 {
     $queryParameters = parent::prepareParameters();
     $variantGroupId = $queryParameters['currentGroup'];
     if (null !== $variantGroupId) {
         $productIds = $this->productRepository->getEligibleProductIdsForVariantGroup($variantGroupId);
         if (count($productIds) === 0) {
             $productIds = [0];
         }
     } else {
         $productIds = [0];
     }
     $queryParameters['productIds'] = $productIds;
     return $queryParameters;
 }
 /**
  * Inject current product in the datagrid configuration
  */
 protected function addCurrentProduct()
 {
     $path = $this->getSourcePath(self::CURRENT_PRODUCT_KEY);
     $id = $this->requestParams->get('product', null);
     $product = null !== $id ? $this->productRepository->findOneByWithValues($id) : null;
     $this->configuration->offsetSetByPath($path, $product);
 }
 /**
  * {@inheritdoc}
  */
 protected function findEntity($class, array $data)
 {
     if (!$this->identifierAttribute) {
         throw new MissingIdentifierException();
     }
     return $this->productRepository->findOneByIdentifier($data[$this->identifierAttribute->getCode()]);
 }
 /**
  * {@inheritdoc}
  */
 public function read()
 {
     $this->documentManager->clear();
     if (!$this->executed) {
         $this->executed = true;
         if (!is_object($this->channel)) {
             $this->channel = $this->channelManager->getChannelByCode($this->channel);
         }
         if ($this->missingCompleteness) {
             $this->completenessManager->generateMissingForChannel($this->channel);
         }
         $this->query = $this->repository->buildByChannelAndCompleteness($this->channel)->getQuery();
         $this->products = $this->getQuery()->execute();
         // MongoDB Cursor are not positioned on first element (whereas ArrayIterator is)
         // as long as getNext() hasn't be called
         $this->products->getNext();
     }
     $result = $this->products->current();
     if ($result) {
         $this->metricConverter->convert($result, $this->channel);
         $this->stepExecution->incrementSummaryInfo('read');
         $this->products->next();
     }
     return $result;
 }
 /**
  * Get matching products for variant group
  *
  * @param GroupInterface $variantGroup the variant group
  *
  * @return ProductInterface[]
  */
 protected function getMatchingProductsForVariantGroup(GroupInterface $variantGroup)
 {
     if (!$variantGroup->getId()) {
         return [];
     }
     return $this->repository->findAllForVariantGroup($variantGroup);
 }
 /**
  * {@inheritdoc}
  */
 protected function quickExport()
 {
     $productIds = $this->massActionDispatcher->dispatch($this->request);
     $fieldsList = $this->fieldsBuilder->getFieldsList($productIds);
     $attributeIds = $this->fieldsBuilder->getAttributeIds();
     $context = $this->getContext() + ['fields' => $fieldsList];
     // batch output to avoid memory leak
     $offset = 0;
     $batchSize = 100;
     while ($productsList = array_slice($productIds, $offset, $batchSize)) {
         $results = $this->productRepository->getFullProducts($productsList, $attributeIds);
         echo $this->serializer->serialize($results, $this->getFormat(), $context);
         $offset += $batchSize;
         flush();
     }
 }
 /**
  * Find previous sequential edit entity
  *
  * @param SequentialEdit $sequentialEdit
  * @param int            $currentKey
  *
  * @return null|ProductInterface
  */
 protected function findPrevious(SequentialEdit $sequentialEdit, $currentKey)
 {
     $previous = null;
     $objectSet = $sequentialEdit->getObjectSet();
     while ($currentKey-- > 0 && null === $previous) {
         $previous = $this->productRepository->findOneByWithValues($objectSet[$currentKey]);
     }
     return $previous;
 }
 /**
  * @return ProductInterface
  */
 protected function getCurrentProduct()
 {
     $productId = $this->extractor->getDatagridParameter('product');
     if (!$productId) {
         throw new \LogicException('The current product type must be configured');
     }
     $product = $this->productRepository->findOneByWithValues($productId);
     return $product;
 }
 /**
  * @param array $configuration
  */
 public function execute(array $configuration)
 {
     $actions = $configuration['actions'];
     $variantGroupCode = $actions['value'];
     $variantGroup = $this->groupRepository->findOneByIdentifier($variantGroupCode);
     $axisAttributeCodes = $this->getAxisAttributeCodes($variantGroup);
     $eligibleProductIds = $this->productRepository->getEligibleProductIdsForVariantGroup($variantGroup->getId());
     $cursor = $this->getProductsCursor($configuration['filters']);
     $paginator = $this->paginatorFactory->createPaginator($cursor);
     list($productAttributeAxis, $acceptedIds) = $this->filterDuplicateAxisCombinations($paginator, $eligibleProductIds, $axisAttributeCodes);
     $excludedIds = $this->addSkippedMessageForDuplicatedProducts($productAttributeAxis);
     $acceptedIds = array_diff($acceptedIds, $excludedIds);
     $configuration['filters'] = [['field' => 'id', 'operator' => 'IN', 'value' => $acceptedIds]];
     if (0 === count($acceptedIds)) {
         $configuration = null;
     }
     $this->setJobConfiguration(json_encode($configuration));
 }
 /**
  * Find a product by its id or return a 404 response
  *
  * @param string $id the product id
  *
  * @throws NotFoundHttpException
  *
  * @return ProductInterface
  */
 protected function findProductOr404($id)
 {
     $product = $this->productRepository->findOneByWithValues($id);
     $product = $this->objectFilter->filterObject($product, 'pim.internal_api.product.view') ? null : $product;
     if (!$product) {
         throw new NotFoundHttpException(sprintf('Product with id %s could not be found.', $id));
     }
     return $product;
 }
 /**
  * {@inheritdoc}
  */
 public function process($group)
 {
     $this->form->setData($group);
     if ($this->request->isMethod('POST')) {
         // TODO : how to fix this ? Load products when ODM storage is used to enable validation
         if (null === $group->getProducts()) {
             $products = $this->productRepository->findAllForGroup($group)->toArray();
             $group->setProducts($products);
         }
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             $this->onSuccess($group);
             return true;
         } elseif ($group->getType()->isVariant() && $group->getId()) {
             $products = $this->productRepository->findAllForVariantGroup($group);
             $group->setProducts($products);
         }
     }
     return false;
 }
 /**
  * Find a product by its id or return a 404 response
  *
  * @param int $id the product id
  *
  * @throws NotFoundHttpException
  *
  * @return ProductInterface
  */
 protected function findProductOr404($id)
 {
     $product = $this->productRepository->findOneByWithValues($id);
     if (!$product) {
         throw $this->createNotFoundException(sprintf('Product with id %s could not be found.', (string) $id));
     }
     // With this version of the form we need to add missing values from family
     $this->productBuilder->addMissingProductValues($product);
     $this->productBuilder->addMissingAssociations($product);
     return $product;
 }
 /**
  * Get matching products
  *
  * @param GroupInterface   $variantGroup the variant group
  * @param ProductInterface $entity       the product
  * @param array            $criteria     query criterias
  *
  * @return ProductInterface[]
  */
 protected function getMatchingProducts(GroupInterface $variantGroup, ProductInterface $entity = null, array $criteria = [])
 {
     if (!$variantGroup->getId()) {
         return [];
     }
     $matchingProducts = $this->repository->findAllForVariantGroup($variantGroup, $criteria);
     if ($entity) {
         $matchingProducts = array_filter($matchingProducts, function ($product) use($entity) {
             return $product->getId() !== $entity->getId();
         });
     }
     return $matchingProducts;
 }
 /**
  * Get next products batch from DB
  *
  * @return \ArrayIterator
  */
 protected function getNextProducts()
 {
     $this->entityManager->clear();
     $products = null;
     if (null === $this->ids) {
         $this->ids = $this->getIds();
     }
     $currentIds = array_slice($this->ids, $this->offset, $this->limit);
     if (!empty($currentIds)) {
         $items = $this->repository->findByIds($currentIds);
         $products = new \ArrayIterator($items);
         $this->offset += $this->limit;
     }
     return $products;
 }
 /**
  * Checks the uniqueness of product values that should be unique
  * As the uniqueness check is normally executed against the database
  * and imported products have not been persisted yet, this effectively
  * checks that the items in the current batch don't contain duplicate values
  * for unique attributes.
  *
  * @param object $entity
  * @param array  $columnsInfo
  * @param array  $data
  *
  * @throws DuplicateProductValueException When duplicate values are encountered
  */
 protected function checkUniqueValues($entity, array $columnsInfo, array $data)
 {
     foreach ($columnsInfo as $columnInfo) {
         if ($columnInfo->getAttribute()) {
             $value = $this->getProductValue($entity, $columnInfo);
             if ($value->getAttribute()->isUnique()) {
                 $code = $value->getAttribute()->getCode();
                 $valueData = (string) $value;
                 if ($valueData !== '') {
                     if ($this->productRepository->valueExists($value)) {
                         throw new DuplicateProductValueException($code, $valueData, $data);
                     }
                     $this->uniqueValues[$code] = isset($this->uniqueValues[$code]) ? $this->uniqueValues[$code] : [];
                     if (isset($this->uniqueValues[$code][$valueData])) {
                         throw new DuplicateProductValueException($code, $valueData, $data);
                     } else {
                         $this->uniqueValues[$code][$valueData] = "";
                     }
                 }
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function collect()
 {
     return ['nb_channels' => $this->channelRepository->countAll(), 'nb_products' => $this->productRepository->countAll(), 'nb_attributes' => $this->attributeRepository->countAll(), 'nb_locales' => $this->localeRepository->countAllActivated(), 'nb_families' => $this->familyRepository->countAll(), 'nb_users' => $this->userRepository->countAll()];
 }
 /**
  * Prepare available attribute ids
  *
  * @param array $productIds
  */
 protected function prepareAvailableAttributeIds($productIds)
 {
     $this->attributeIds = $this->productRepository->getAvailableAttributeIdsToExport($productIds);
 }
 /**
  * Returns an array containing a limited number of product groups, and the total number of products
  *
  * @param GroupInterface $group
  * @param int            $maxResults
  *
  * @deprecated will be removed in 1.5
  *
  * @return array
  */
 public function getProductList(GroupInterface $group, $maxResults)
 {
     $products = $this->productRepository->getProductsByGroup($group, $maxResults);
     $count = $this->productRepository->getProductCountByGroup($group);
     return ['products' => $products, 'productCount' => $count];
 }
 /**
  * {@inheritdoc}
  */
 public function apply(DatasourceInterface $datasource, $field, $direction)
 {
     $qb = $datasource->getQueryBuilder();
     $pqb = $this->repository->getProductQueryBuilder($qb);
     $pqb->addFieldSorter('family', $direction);
 }
 /**
  * Check if a product value with a specific value already exists
  *
  * @param ProductValueInterface $value
  *
  * @return bool
  *
  * @deprecated will be removed in 1.5, please use ProductRepositoryInterface::valueExists
  */
 public function valueExists(ProductValueInterface $value)
 {
     return $this->productRepository->valueExists($value);
 }
 function it_does_not_validate_with_empty_value(ProductRepositoryInterface $productRepository, ProductValueInterface $value, ExecutionContextInterface $context, Constraint $constraint)
 {
     $productRepository->valueExists($value)->shouldNotBeCalled();
     $context->buildViolation(Argument::any())->shouldNotBeCalled();
     $this->validate("", $constraint)->shouldReturn(null);
 }