public function process($item)
 {
     $sku = (string) $item['sku'];
     $attribute = $this->productManager->getIdentifierAttribute();
     $product = $this->productManager->findByIdentifier($sku);
     // if (!$product) {
     //     $product = $this->productManager->createProduct();
     //     $value   = $this->productManager->createProductValue();
     //     $value->setAttribute($attribute);
     //     $value->setData($sku);
     //     $product->addValue($value);
     //     $this->stepExecution->incrementSummaryInfo('create');
     //     return $product;
     // } else {
     if (!$product) {
         $data = current((array) $item);
         $this->stepExecution->incrementSummaryInfo('skip');
         throw new InvalidItemException(sprintf('Skip the existing %s product', $sku), $data);
     } else {
         $product_tab = array();
         $product_tab[] = $product;
         $this->productUpdater->setValue($product_tab, 'price', [['data' => (string) $item['price'], 'currency' => (string) $item['currency']]]);
         return $product;
     }
     // }
 }
Beispiel #2
0
 public function write(array $items)
 {
     foreach ($items as $product) {
         $this->productManager->save($product);
         $this->stepExecution->incrementSummaryInfo('save');
     }
 }
 /**
  * @param ProductManager   $manager    the product manager
  * @param ProductInterface $product    the entity
  * @param array            $attributes the attributes
  */
 protected function addValues(ProductManager $manager, ProductInterface $product, $attributes)
 {
     foreach ($attributes as $attribute) {
         $value = $manager->createProductValue();
         $value->setAttribute($attribute);
         $product->addValue($value);
     }
 }
 /**
  * Displays completeness for a product
  *
  * @param int $id
  *
  * @return Response
  */
 public function completenessAction($id)
 {
     $product = $this->productManager->getProductRepository()->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', array('product' => $product, 'channels' => $channels, 'locales' => $locales, 'completenesses' => $completenesses));
 }
 /**
  * Find a product by its id or return a 404 response
  *
  * @param integer $id the product id
  *
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  *
  * @return \Pim\Bundle\CatalogBundle\Model\ProductInterface
  */
 protected function findProductOr404($id)
 {
     $product = $this->productManager->find($id);
     if (null === $product) {
         throw new NotFoundHttpException(sprintf('Product with id %s could not be found.', (string) $id));
     }
     return $product;
 }
 /**
  * Don't allow creating an identifier attribute if one already exists
  *
  * @param AbstractAttribute $attribute
  * @param Constraint        $constraint
  */
 public function validate($attribute, Constraint $constraint)
 {
     if ($attribute->getAttributeType() === 'pim_catalog_identifier') {
         $identifier = $this->manager->getIdentifierAttribute();
         if ($identifier && $identifier->getId() !== $attribute->getId()) {
             $this->context->addViolationAt('attributeType', $constraint->message);
         }
     }
 }
 /**
  * Constraint is applied on ProductValue data property.
  * That's why we use the current property path to guess the code
  * of the attribute to which the data belongs to.
  * @param object     $rawValue
  * @param Constraint $constraint
  *
  * @see Pim\Bundle\CatalogBundle\Validator\ConstraintGuesser\UniqueValueGuesser
  */
 public function validate($rawValue, Constraint $constraint)
 {
     if (empty($rawValue)) {
         return;
     }
     $value = $this->getProductValue();
     if ($value instanceof ProductValueInterface && $this->productManager->valueExists($value)) {
         $this->context->addViolation($constraint->message);
     }
 }
 /**
  * @param ProductManager   $manager    the product manager
  * @param ProductInterface $product    the entity
  * @param array            $attributes the attributes
  */
 protected function addValues(ProductManager $manager, ProductInterface $product, $attributes)
 {
     foreach ($attributes as $attribute) {
         $value = $manager->createProductValue();
         $value->setAttribute($attribute);
         if ($attribute->getDefaultValue() !== null) {
             $value->setData($attribute->getDefaultValue());
         }
         $product->addValue($value);
     }
 }
 /**
  * Create and configure a family intance
  *
  * @return Family
  */
 public function createFamily()
 {
     $family = new Family();
     $identifier = $this->productManager->getIdentifierAttribute();
     $family->addAttribute($identifier);
     $family->setAttributeAsLabel($identifier);
     foreach ($this->getChannels() as $channel) {
         $family->addAttributeRequirement($this->factory->createAttributeRequirement($identifier, $channel, true));
     }
     return $family;
 }
 /**
  * @return array
  */
 protected function prepareParameters()
 {
     $queryParameters = parent::prepareParameters();
     $variantGroupId = $queryParameters['currentGroup'];
     if (null !== $variantGroupId) {
         $productIds = $this->productManager->getProductRepository()->getEligibleProductIdsForVariantGroup($variantGroupId);
         if (count($productIds) === 0) {
             $productIds = [0];
         }
     } else {
         $productIds = [0];
     }
     $queryParameters['productIds'] = $productIds;
     return $queryParameters;
 }
 function let(ProductManager $productManager, UserContext $userContext, CurrencyManager $currencyManager, Locale $en, Locale $de, AttributeRepository $attributeRepository, AbstractProductValue $productValue, CatalogContext $catalogContext, ProductBuilder $productBuilder, ProductMassActionManager $massActionManager, MetricFactory $metricFactory)
 {
     $en->getCode()->willReturn('en_US');
     $de->getCode()->willReturn('de_DE');
     $userContext->getCurrentLocale()->willReturn($en);
     $userContext->getUserLocales()->willReturn([$en, $de]);
     $catalogContext->setLocaleCode(Argument::any())->willReturn($catalogContext);
     $productManager->createProductValue()->willReturn($productValue);
     $productValue->setAttribute(Argument::any())->willReturn($productValue);
     $productValue->setLocale(Argument::any())->willReturn($productValue);
     $productValue->setScope(Argument::any())->willReturn($productValue);
     $productValue->addPrice(Argument::any())->willReturn($productValue);
     $productManager->getAttributeRepository()->willReturn($attributeRepository);
     $this->beConstructedWith($productManager, $userContext, $currencyManager, $catalogContext, $productBuilder, $massActionManager, $metricFactory, ['product_price' => 'Pim\\Bundle\\CatalogBundle\\Model\\ProductPrice', 'product_media' => 'Pim\\Bundle\\CatalogBundle\\Model\\ProductMedia']);
 }
 /**
  * {@inheritdoc}
  */
 public function write(array $products)
 {
     $this->collection = $this->documentManager->getDocumentCollection($this->productClass);
     $productsToInsert = array();
     $productsToUpdate = array();
     foreach ($products as $product) {
         if (null === $product->getId()) {
             $productsToInsert[] = $product;
             $product->setId($this->mongoFactory->createMongoId());
         } else {
             $productsToUpdate[] = $product;
         }
     }
     $this->productManager->handleAllMedia($products);
     $this->eventDispatcher->dispatch(self::PRE_INSERT, new GenericEvent($productsToInsert));
     $this->eventDispatcher->dispatch(self::PRE_UPDATE, new GenericEvent($productsToUpdate));
     $insertDocs = $this->getDocsFromProducts($productsToInsert);
     $updateDocs = $this->getDocsFromProducts($productsToUpdate);
     if (count($insertDocs) > 0) {
         $this->insertDocuments($insertDocs);
     }
     if (count($updateDocs) > 0) {
         $this->updateDocuments($updateDocs);
     }
     $this->pendingPersister->persistPendingVersions($products);
     $this->eventDispatcher->dispatch(self::POST_INSERT, new GenericEvent($productsToInsert));
     $this->eventDispatcher->dispatch(self::POST_UPDATE, new GenericEvent($productsToUpdate));
     $this->documentManager->clear();
     $this->cacheClearer->clear();
 }
 /**
  * Due to constraint guesser, the constraint is applied on :
  * - ProductValueInterface data when applied through form
  * - ProductValueInterface when applied directly through validator
  *
  * The constraint guesser should be re-worked in a future version to avoid such behavior
  *
  * @param ProductValueInterface|mixed $data
  * @param Constraint                  $constraint
  *
  * @see Pim\Bundle\CatalogBundle\Validator\ConstraintGuesser\UniqueValueGuesser
  */
 public function validate($data, Constraint $constraint)
 {
     if (empty($data)) {
         return;
     }
     if (is_object($data) && $data instanceof ProductValueInterface) {
         $productValue = $data;
     } else {
         $productValue = $this->getProductValueFromForm();
     }
     if ($productValue instanceof ProductValueInterface && $this->productManager->valueExists($productValue)) {
         if ($productValue->getData() !== null && $productValue->getData() !== '') {
             $this->context->addViolation($constraint->message);
         }
     }
 }
 /**
  * Persists an object
  *
  * @param object $object
  */
 protected function persistObject($object)
 {
     if ($object instanceof \Pim\Bundle\CatalogBundle\Model\ProductInterface) {
         $this->productManager->handleMedia($object);
     }
     $this->objectManager->persist($object);
     $this->doctrineCache->setReference($object);
 }
 /**
  * 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->productManager->find($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->manager->find($productId);
     return $product;
 }
 /**
  * {@inheritdoc}
  */
 public function write(array $items)
 {
     $this->versionManager->setRealTimeVersioning($this->realTimeVersioning);
     foreach ($items as $item) {
         $this->incrementCount($item);
     }
     $this->productManager->handleAllMedia($items);
     $this->productManager->saveAllProducts($items, ['recalculate' => false]);
     $this->cacheClearer->clear();
 }
 /**
  * Get attributes configuration for attribute that can be used in grid (as column or filter)
  *
  * @return array
  */
 protected function getAttributesConfig()
 {
     $attributeIds = $this->getAttributeIds();
     if (empty($attributeIds)) {
         return [];
     }
     $currentLocale = $this->getCurrentLocaleCode();
     $repository = $this->productManager->getAttributeRepository();
     $configuration = $repository->getAttributesAsArray(true, $currentLocale, $attributeIds);
     return $configuration;
 }
 /**
  * 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->productManager->find($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 [];
     }
     $repository = $this->manager->getProductRepository();
     $matchingProducts = $repository->findAllForVariantGroup($variantGroup, $criteria);
     if ($entity) {
         $matchingProducts = array_filter($matchingProducts, function ($product) use($entity) {
             return $product->getId() !== $entity->getId();
         });
     }
     return $matchingProducts;
 }
 /**
  * @param ProductValueInterface $productValue
  * @param ProductValueInterface $value
  */
 protected function setProductOption(ProductValueInterface $productValue, ProductValueInterface $value)
 {
     foreach ($productValue->getOptions() as $option) {
         if (!$value->getOptions()->contains($option)) {
             $productValue->removeOption($option);
         }
     }
     // TODO: Clean this code removing flush for ORM
     if (!class_exists(PimCatalogBundle::DOCTRINE_MONGODB)) {
         $this->productManager->getObjectManager()->flush();
     }
     foreach ($value->getOptions() as $option) {
         $productValue->addOption($option);
     }
 }
 /**
  * @param  object                                                $product
  * @param  null                                                  $format
  * @param  array                                                 $context
  * @return array|\Symfony\Component\Serializer\Normalizer\scalar
  */
 public function normalize($product, $format = null, array $context = [])
 {
     $normalizedAssociations = [];
     $identifierAttributeCode = $this->productManager->getIdentifierAttribute()->getCode();
     $sku = $product->getValue($this->productManager->getIdentifierAttribute()->getCode())->getData();
     $normalizedAssociations['sku'] = $sku;
     $normalizedAssociations['family'] = $product->getFamily()->getCode();
     $normalizedAssociations['associations'] = [];
     foreach ($product->getAssociations() as $association) {
         $associationCode = $association->getAssociationType()->getCode();
         if ($association->getGroups()->count() > 0 || $association->getProducts()->count() > 0) {
             /**@var Product $product * */
             $normalizedAssociations['associations'][$associationCode] = ['type' => null, 'groups' => [], 'products' => []];
             $normalizedAssociations['associations'][$associationCode]['type'] = $associationCode;
             foreach ($association->getGroups() as $group) {
                 $normalizedAssociations['associations'][$associationCode]['groups'][] = $group->getCode();
             }
             foreach ($association->getProducts() as $product) {
                 $normalizedAssociations['associations'][$associationCode]['products'][] = $product->getValue($identifierAttributeCode)->getData();
             }
         }
     }
     return $normalizedAssociations;
 }
Beispiel #23
0
    public function process($item)
    {
        $sku       = $item['sku'];
        $attribute = $this->productManager->getIdentifierAttribute();
        $product   = $this->productManager->findByIdentifier($sku);

        if (!$product) {
            $product = $this->productManager->createProduct();
            $value   = $this->productManager->createProductValue();
            $value->setAttribute($attribute);
            $value->setData($sku);
            $product->addValue($value);
            $this->stepExecution->incrementSummaryInfo('create');

            return $product;

        } else {

            $data = current(((array) $item));
            $this->stepExecution->incrementSummaryInfo('skip');

            throw new InvalidItemException(sprintf('Skip the existing %s product', $sku), $data);
        }
    }
 /**
  * @param ProductInterface $product
  * @param array            $drupalProduct
  */
 protected function computeProductAssociation(ProductInterface $product, array &$drupalProduct)
 {
     $identifierAttributeCode = $this->productManager->getIdentifierAttribute()->getCode();
     /** @var Group $group */
     foreach ($product->getAssociations() as $association) {
         $associationCode = $association->getAssociationType()->getCode();
         if ($association->getGroups()->count() > 0 || $association->getProducts()->count() > 0) {
             /**@var Product $product * */
             $drupalProduct['associations'][$associationCode] = ['type' => null, 'groups' => [], 'products' => []];
             $drupalProduct['associations'][$associationCode]['type'] = $associationCode;
             foreach ($association->getGroups() as $group) {
                 $drupalProduct['associations'][$associationCode]['groups'][] = $group->getCode();
             }
             foreach ($association->getProducts() as $product) {
                 $drupalProduct['associations'][$associationCode]['products'][] = $product->getValue($identifierAttributeCode)->getData();
             }
         }
     }
 }
 /**
  * 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->productManager->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] = "";
                     }
                 }
             }
         }
     }
 }
 /**
  * @param string $code
  *
  * @return AbstractAttribute
  */
 public function getAttribute($code)
 {
     $attributeRepo = $this->productManager->getAttributeRepository();
     $attribute = $attributeRepo->findOneByCode($code);
     return $attribute;
 }
 /**
  * Prepare available attribute ids
  *
  * @param array $productIds
  */
 protected function prepareAvailableAttributeIds($productIds)
 {
     $productRepo = $this->productManager->getProductRepository();
     $this->attributeIds = $productRepo->getAvailableAttributeIdsToExport($productIds);
 }
 /**
  * {@inheritdoc}
  */
 public function getTransformedColumnsInfo($class)
 {
     return array_merge(parent::getTransformedColumnsInfo($class), $this->transformedColumns[$this->productManager->getProductValueName()]);
 }
 function it_does_not_validate_with_empty_value(ProductManager $productManager, ProductValueInterface $value, ExecutionContextInterface $context, Constraint $constraint)
 {
     $productManager->valueExists($value)->shouldNotBeCalled();
     $context->addViolation(Argument::any())->shouldNotBeCalled();
     $this->validate("", $constraint)->shouldReturn(null);
 }