/** * {@inheritdoc} */ public function normalize($entity, $format = null, array $context = []) { $data = $entity->getData(); $fieldName = $this->getFieldValue($entity); $result = null; if (is_array($data)) { $data = new ArrayCollection($data); } if (is_null($data)) { $result = [$fieldName => '']; } elseif (is_int($data)) { $result = [$fieldName => (string) $data]; } elseif (is_float($data)) { $result = [$fieldName => sprintf(sprintf('%%.%sF', $this->precision), $data)]; } elseif (is_string($data)) { $result = [$fieldName => $data]; } elseif (is_bool($data)) { $result = [$fieldName => (string) (int) $data]; } elseif (is_object($data)) { $context['field_name'] = $fieldName; $result = $this->serializer->normalize($data, $format, $context); } if (null === $result) { throw new \RuntimeException(sprintf('Cannot normalize product value "%s" which data is a(n) "%s"', $fieldName, is_object($data) ? get_class($data) : gettype($data))); } return $result; }
/** * {@inheritdoc} */ public function collect(RequestObject $requestObject, array $parameters = []) { $parameters = $this->resolveCollectorParameters($parameters); $logFile = sprintf('%s/%s.%s', $this->logFolder, $this->kernelEnvironment, $parameters['logFile']); $this->logger->pushHandler(new StreamHandler($logFile)); $this->logger->info('request_collector.collect', $this->serializer->normalize($requestObject)); }
/** * Normalize a decimal attribute value * * @param mixed $data * @param string $format * @param array $context * * @return mixed|null */ protected function normalizeDecimal($data, $format, $context) { if (false === is_numeric($data)) { return $this->serializer->normalize($data, $format, $context); } return floatval($data); }
/** * {@inheritdoc} */ public function normalize($object, $format = null, array $context = array()) { $normalizedItems = []; foreach ($object as $item) { $normalizedItems[$item->getLocale()] = $this->serializer->normalize($item, $format, $context); } return $normalizedItems; }
/** * {@inheritdoc} */ public function normalize($entity, $format = null, array $context = []) { $data = $entity->getData(); $fieldName = $this->getFieldName($entity); if ($this->filterLocaleSpecific($entity)) { return []; } $result = null; if (is_array($data)) { $data = new ArrayCollection($data); } $type = $entity->getAttribute()->getAttributeType(); $backendType = $entity->getAttribute()->getBackendType(); if (AttributeTypes::BOOLEAN === $type) { $result = [$fieldName => (string) (int) $data]; } elseif (is_null($data)) { $result = [$fieldName => '']; if ('metric' === $backendType) { $result[$fieldName . '-unit'] = ''; } } elseif (is_int($data)) { $result = [$fieldName => (string) $data]; } elseif (is_float($data) || 'decimal' === $entity->getAttribute()->getBackendType()) { $pattern = $entity->getAttribute()->isDecimalsAllowed() ? sprintf('%%.%sF', $this->precision) : '%d'; $result = [$fieldName => sprintf($pattern, $data)]; } elseif (is_string($data)) { $result = [$fieldName => $data]; } elseif (is_object($data)) { // TODO: Find a way to have proper currency-suffixed keys for normalized price data // even when an empty collection is passed if ('prices' === $backendType && $data instanceof Collection && $data->isEmpty()) { $result = []; } elseif ('options' === $backendType && $data instanceof Collection && $data->isEmpty() === false) { $data = $this->sortOptions($data); $context['field_name'] = $fieldName; $result = $this->serializer->normalize($data, $format, $context); } else { $context['field_name'] = $fieldName; if ('metric' === $backendType) { $context['decimals_allowed'] = $entity->getAttribute()->isDecimalsAllowed(); } elseif ('media' === $backendType) { $context['value'] = $entity; } $result = $this->serializer->normalize($data, $format, $context); } } if (null === $result) { throw new \RuntimeException(sprintf('Cannot normalize product value "%s" which data is a(n) "%s"', $fieldName, is_object($data) ? get_class($data) : gettype($data))); } $localizer = $this->localizerRegistry->getLocalizer($type); if (null !== $localizer) { foreach ($result as $field => $data) { $result[$field] = $localizer->localize($data, $context); } } return $result; }
/** * Returned normalized data * * @param Collection $object object to normalize * @param mixed $format * @param array $context * @return array */ public function normalize($object, $format = null, array $context = array()) { $result = array(); foreach ($object as $item) { $serializedItem = $this->serializer->normalize($item, $format, $context); $result[] = $serializedItem; } return $result; }
/** * {@inheritdoc} */ protected function setUp() { $this->normalizer = new EntityReferenceFieldItemNormalizer(); $this->serializer = $this->prophesize(Serializer::class); // Set up the serializer to return an entity property. $this->serializer->normalize(Argument::cetera())->willReturn(['value' => 'test']); $this->normalizer->setSerializer($this->serializer->reveal()); $this->fieldItem = $this->prophesize(EntityReferenceItem::class); $this->fieldItem->getIterator()->willReturn(new \ArrayIterator(['target_id' => []])); }
public function normalize(Kwf_Model_Row_Interface $row, $column, array $settings, $format = null, array $context = array()) { if (!isset($settings['rule'])) { throw new \Exception("rule setting is required"); } $rows = $row->getChildRows($settings['rule']); if (isset($settings['groups'])) { $context['groups'] = $settings['groups']; } return $this->serializer->normalize($rows, $format, $context); }
/** * @param AbstractTypedAddress $object * @param mixed $format * @param array $context * @return array */ public function normalize($object, $format = null, array $context = array()) { $result = $this->addressNormalizer->normalize($object, $format, $context); $types = $object->getTypes(); if (!$types->isEmpty()) { $result['types'] = $this->serializer->normalize($object->getTypes(), $format, $context); } else { $result['types'] = array(); } return $result; }
/** * {@inheritdoc} */ public function normalize($data, $format = null, array $context = []) { $result = []; foreach ($data as $value) { if ($value instanceof ProductValueInterface) { $result[$value->getAttribute()->getCode()][] = $this->serializer->normalize($value, 'json', $context); } else { $result[] = $this->serializer->normalize($value, 'json', $context); } } return $result; }
/** * {@inheritdoc} */ public function normalize($entity, $format = null, array $context = []) { if ($entity->getData() instanceof Collection) { $value = []; foreach ($entity->getData() as $item) { $value[] = $this->serializer->normalize($item, $format, $context); } } else { $value = $this->serializer->normalize($entity->getData(), $format, $context); } return ['locale' => $entity->getLocale(), 'scope' => $entity->getScope(), 'value' => $value]; }
/** * {@inheritdoc} */ public function process($product) { $data['media'] = []; $productMedias = $this->getProductMedias($product); if (count($productMedias) > 0) { try { $data['media'] = $this->serializer->normalize($productMedias, 'flat', ['field_name' => 'media', 'prepare_copy' => true]); } catch (FileNotFoundException $e) { throw new InvalidItemException($e->getMessage(), ['item' => $product->getIdentifier()->getData(), 'uploadDirectory' => $this->uploadDirectory]); } } $data['product'] = $this->serializer->normalize($product, 'flat', $this->getNormalizerContext()); return $data; }
/** * @param ProductValueInterface $productValue * @param null $format * @param array $context * * @return mixed */ protected function getSimpleValue(ProductValueInterface $productValue, $format = null, array $context = []) { $attributeType = $productValue->getAttribute()->getAttributeType(); $context['is_decimals_allowed'] = $productValue->getAttribute()->isDecimalsAllowed(); // if decimals_allowed is false, we return an integer // if true, we return a string to avoid to loose precision (http://floating-point-gui.de) if (AttributeTypes::NUMBER === $attributeType && null !== $productValue->getData() && is_numeric($productValue->getData())) { return $productValue->getAttribute()->isDecimalsAllowed() ? number_format($productValue->getData(), static::DECIMAL_PRECISION, '.', '') : (int) $productValue->getData(); } if (in_array($attributeType, [AttributeTypes::OPTION_SIMPLE_SELECT, AttributeTypes::REFERENCE_DATA_SIMPLE_SELECT])) { return $productValue->getData()->getCode(); } return $this->serializer->normalize($productValue->getData(), $format, $context); }
/** * {@inheritdoc} */ public function normalize($object, $format = null, array $context = []) { if (!$this->serializer instanceof NormalizerInterface) { throw new \LogicException('Serializer must be a normalizer'); } $data = []; if (null !== $object->getFamily()) { $data[self::FAMILY_FIELD] = $this->serializer->normalize($object->getFamily(), $format, $context); } foreach ($object->getGroups() as $group) { $data[self::GROUPS_FIELD][] = $this->serializer->normalize($group, $format, $context); $inGroupField = sprintf('%s_%d', self::IN_GROUP_FIELD, $group->getId()); $data[$inGroupField] = true; } if ($object->getCreated()) { $data[self::CREATED_FIELD] = $this->serializer->normalize($object->getCreated(), $format, $context); } if ($object->getUpdated()) { $data[self::UPDATED_FIELD] = $this->serializer->normalize($object->getUpdated(), $format, $context); } foreach ($object->getValues() as $value) { $normalizedData = $this->serializer->normalize($value, $format, $context); if (null !== $normalizedData) { $data = array_replace($data, $normalizedData); } } $completenesses = []; foreach ($object->getCompletenesses() as $completeness) { $completenesses = array_merge($completenesses, $this->serializer->normalize($completeness, $format, $context)); } $data[self::COMPLETENESSES_FIELD] = $completenesses; $data[self::ENABLED_FIELD] = (bool) $object->isEnabled(); return $data; }
/** * {@inheritdoc} */ public function normalize($entity, $format = null, array $context = []) { $attribute = $entity->getAttribute(); $context['decimals_allowed'] = $attribute->isDecimalsAllowed(); if ($entity->getData() instanceof Collection) { $data = []; foreach ($entity->getData() as $item) { $data[] = $this->serializer->normalize($item, $format, $context); sort($data); } } else { $data = $this->serializer->normalize($entity->getData(), $format, $context); } // fix the number of decimals to be ISO ORM/mongo // we decided to do it in the standard format right now but that it could/should be changed if (AttributeTypes::NUMBER === $attribute->getAttributeType() && null !== $data && is_numeric($data)) { $precision = true === $context['decimals_allowed'] ? static::NUMBER_DECIMAL_PRECISION : 0; $data = number_format($data, $precision, '.', ''); } return ['locale' => $entity->getLocale(), 'scope' => $entity->getScope(), 'data' => $data]; }
/** * {@inheritdoc} */ public function normalize($object, $format = null, array $context = array()) { $targetClass = $this->getTargetClassName(); if (!$object instanceof $targetClass) { return null; } $fieldRules = $this->getProcessedFieldRules(); if (isset($context['mode']) && $context['mode'] == self::SHORT_MODE && $this->primaryField) { return $this->getPropertyAccessor()->getValue($object, $this->primaryField['denormalizeName']); } $result = array(); foreach ($fieldRules as $field) { if (!$field['normalize']) { continue; } $value = $this->getPropertyAccessor()->getValue($object, $field['denormalizeName']); if (isset($field['type']) && $value !== null) { $value = $this->serializer->normalize($value, $format, array_merge($context, $field['context'])); } $result[$field['normalizeName']] = $value; } return $result; }
/** * Show a report * * @param Request $request * @param integer $id * * @return template */ public function showAction(Request $request, $id) { $jobExecution = $this->findOr404('AkeneoBatchBundle:JobExecution', $id); $this->eventDispatcher->dispatch(JobExecutionEvents::PRE_SHOW, new GenericEvent($jobExecution)); if ('json' === $request->getRequestFormat()) { $archives = []; foreach ($this->archivist->getArchives($jobExecution) as $key => $files) { $label = $this->translator->transchoice(sprintf('pim_import_export.download_archive.%s', $key), count($files)); $archives[$key] = ['label' => ucfirst($label), 'files' => $files]; } if (!$this->jobExecutionManager->checkRunningStatus($jobExecution)) { $this->jobExecutionManager->markAsFailed($jobExecution); } return new JsonResponse(['jobExecution' => $this->serializer->normalize($jobExecution, 'json'), 'hasLog' => file_exists($jobExecution->getLogFile()), 'archives' => $archives]); } return $this->render(sprintf('PimImportExportBundle:%sExecution:show.html.twig', ucfirst($this->getJobType())), array('execution' => $jobExecution)); }
/** * Show a job executions report * * @param Request $request * @param int $id * * @return \Symfony\Component\HttpFoundation\Response|JsonResponse */ public function showAction(Request $request, $id) { $jobExecution = $this->findOr404('Akeneo\\Component\\Batch\\Model\\JobExecution', $id); $this->eventDispatcher->dispatch(JobExecutionEvents::PRE_SHOW, new GenericEvent($jobExecution)); if ('json' === $request->getRequestFormat()) { $archives = []; foreach ($this->archivist->getArchives($jobExecution) as $archiveName => $files) { $label = $this->translator->transchoice(sprintf('pim_import_export.download_archive.%s', $archiveName), count($files)); $archives[$archiveName] = ['label' => ucfirst($label), 'files' => $files]; } if (!$this->jobExecutionManager->checkRunningStatus($jobExecution)) { $this->jobExecutionManager->markAsFailed($jobExecution); } // limit the number of step execution returned to avoid memory overflow $context = ['limit_warnings' => 100]; return new JsonResponse(['jobExecution' => $this->serializer->normalize($jobExecution, 'json', $context), 'hasLog' => file_exists($jobExecution->getLogFile()), 'archives' => $archives]); } return $this->render('PimEnrichBundle:JobTracker:show.html.twig', ['execution' => $jobExecution]); }
/** * {@inheritdoc} */ public function normalize($object, $format = null, array $context = array()) { $entityName = ClassUtils::getClass($object); $fields = $this->fieldHelper->getFields($entityName, true); $result = array(); $propertyAccessor = PropertyAccess::createPropertyAccessor(); foreach ($fields as $field) { $fieldName = $field['name']; // Do not normalize excluded fields if ($this->fieldHelper->getConfigValue($entityName, $fieldName, 'excluded')) { continue; } // Do not normalize non identity fields for short mode if ($this->getMode($context) == self::SHORT_MODE && !$this->fieldHelper->getConfigValue($entityName, $fieldName, 'identity')) { continue; } $fieldValue = $propertyAccessor->getValue($object, $fieldName); if (is_object($fieldValue)) { $fieldContext = $context; $fieldContext['fieldName'] = $fieldName; if (method_exists($object, 'getId')) { $fieldContext['entityId'] = $object->getId(); } $isFullMode = $this->fieldHelper->getConfigValue($entityName, $fieldName, 'full'); // Do not export relation in short mode if it does not contain identity fields if (!$isFullMode && isset($field['related_entity_type']) && $this->fieldHelper->hasConfig($field['related_entity_type']) && !$this->hasIdentityFields($field['related_entity_type'])) { continue; } if ($this->fieldHelper->isRelation($field)) { if ($isFullMode) { $fieldContext['mode'] = self::FULL_MODE; } else { $fieldContext['mode'] = self::SHORT_MODE; } } $fieldValue = $this->serializer->normalize($fieldValue, $format, $fieldContext); } $result[$fieldName] = $fieldValue; } return $result; }
/** * Show a report * * @param Request $request * @param int $id * * @return \Symfony\Component\HttpFoundation\Response|JsonResponse */ public function showAction(Request $request, $id) { $jobExecution = $this->jobExecutionRepo->find($id); if (null === $jobExecution) { throw new NotFoundHttpException('Akeneo\\Component\\Batch\\Model\\JobExecution entity not found'); } $this->eventDispatcher->dispatch(JobExecutionEvents::PRE_SHOW, new GenericEvent($jobExecution)); if ('json' === $request->getRequestFormat()) { $archives = []; foreach ($this->archivist->getArchives($jobExecution) as $key => $files) { $label = $this->translator->transChoice(sprintf('pim_import_export.download_archive.%s', $key), count($files)); $archives[$key] = ['label' => ucfirst($label), 'files' => $files]; } if (!$this->jobExecutionManager->checkRunningStatus($jobExecution)) { $this->jobExecutionManager->markAsFailed($jobExecution); } // limit the number of step execution returned to avoid memory overflow $context = ['limit_warnings' => 100]; return new JsonResponse(['jobExecution' => $this->serializer->normalize($jobExecution, 'json', $context), 'hasLog' => file_exists($jobExecution->getLogFile()), 'archives' => $archives]); } return $this->templating->renderResponse(sprintf('PimImportExportBundle:%sExecution:show.html.twig', ucfirst($this->getJobType())), ['execution' => $jobExecution]); }
/** * {@inheritdoc} */ public function normalize($object, $format = null, array $context = []) { $entityName = ClassUtils::getClass($object); $fields = $this->fieldHelper->getFields($entityName, true); $result = []; foreach ($fields as $field) { $fieldName = $field['name']; if ($this->isFieldSkippedForNormalization($entityName, $fieldName, $context)) { continue; } $fieldValue = $this->fieldHelper->getObjectValue($object, $fieldName); if (is_object($fieldValue)) { $fieldContext = $context; $fieldContext['fieldName'] = $fieldName; if (method_exists($object, 'getId')) { $fieldContext['entityId'] = $object->getId(); } $isFullMode = $this->fieldHelper->getConfigValue($entityName, $fieldName, 'full'); // Do not export relation in short mode if it does not contain identity fields if (!$isFullMode && isset($field['related_entity_name']) && $this->fieldHelper->hasConfig($field['related_entity_name']) && !$this->hasIdentityFields($field['related_entity_name'])) { continue; } if ($this->fieldHelper->isRelation($field)) { if ($isFullMode) { $fieldContext['mode'] = self::FULL_MODE; } else { $fieldContext['mode'] = self::SHORT_MODE; } } if ($this->fieldHelper->isDateTimeField($field)) { $fieldContext['type'] = $field['type']; } $fieldValue = $this->serializer->normalize($fieldValue, $format, $fieldContext); } $result[$fieldName] = $fieldValue; } return $result; }
function it_normalizes_a_multi_select(SerializerInterface $serializer, ProductValueInterface $productValue, AttributeInterface $attribute, AttributeOptionInterface $multiSelect, ArrayCollection $values, \ArrayIterator $iterator) { $multiSelect->getCode()->willReturn('optionA'); $serializer->normalize($multiSelect, null, [])->shouldNotBeCalled(); $this->setSerializer($serializer); $values->getIterator()->willReturn($iterator); $iterator->rewind()->willReturn($multiSelect); $valueCount = 1; $iterator->valid()->will(function () use(&$valueCount) { return $valueCount-- > 0; }); $iterator->current()->willReturn($multiSelect); $iterator->next()->willReturn(null); $productValue->getData()->willReturn($values); $productValue->getLocale()->willReturn(null); $productValue->getScope()->willReturn(null); $productValue->getAttribute()->willReturn($attribute); $attribute->getAttributeType()->willReturn(AttributeTypes::OPTION_MULTI_SELECT); $attribute->isDecimalsAllowed()->willReturn(false); $this->normalize($productValue)->shouldReturn(['locale' => null, 'scope' => null, 'data' => ['optionA']]); }
function it_normalizes_product_with_price($filter, ProductInterface $product, AttributeInterface $priceAttribute, ProductValueInterface $price, Collection $prices, Collection $values, ProductPriceInterface $productPrice, FamilyInterface $family, SerializerInterface $serializer) { $family->getCode()->willReturn('shoes'); $priceAttribute->getCode()->willReturn('price'); $priceAttribute->getAttributeType()->willReturn('pim_catalog_price_collection'); $priceAttribute->isLocalizable()->willReturn(false); $priceAttribute->isScopable()->willReturn(false); $price->getAttribute()->willReturn($priceAttribute); $price->getData()->willReturn(null); $productPrice->getData()->willReturn("356.00"); $productPrice->getCurrency()->willReturn("EUR"); $prices->add($productPrice); $price->getPrices()->willReturn($prices); $product->getIdentifier()->willReturn($price); $product->getFamily()->willReturn($family); $product->isEnabled()->willReturn(true); $product->getGroupCodes()->willReturn('group1, group2, variant_group_1'); $product->getCategoryCodes()->willReturn('nice shoes, converse'); $product->getAssociations()->willReturn([]); $values->add($price); $product->getValues()->willReturn($values); $filter->filterCollection($values, 'pim.transform.product_value.flat', Argument::cetera())->willReturn([$price]); $serializer->normalize($price, 'flat', Argument::any())->willReturn(['price-EUR' => '356.00']); $this->normalize($product, 'flat', ['price-EUR' => ''])->shouldReturn(['price-EUR' => '356.00', 'family' => 'shoes', 'groups' => 'group1, group2, variant_group_1', 'categories' => 'nice shoes, converse', 'enabled' => 1]); }
/** * {@inheritdoc} */ public function normalize($object, $format = null, array $context = []) { $optionsValues = $context['onlyActivatedLocales'] ? $this->ensureEmptyOptionValues($object->getOptionValues()) : $object->getOptionValues(); $normalizedValues = $this->serializer->normalize($optionsValues, $format, $context); return ['id' => $object->getId(), 'code' => $object->getCode(), 'optionValues' => $normalizedValues]; }
function it_normalizes_a_value_with_ordered_options_with_a_option_collection_data(ProductValueInterface $value, AttributeInterface $multiColorAttribute, SerializerInterface $serializer, AttributeOptionInterface $redOption, AttributeOptionInterface $blueOption, ArrayCollection $collection) { $collection->toArray()->willReturn([$redOption, $blueOption]); $collection->isEmpty()->willReturn(false); $value->getData()->willReturn($collection); $value->getAttribute()->willReturn($multiColorAttribute); $value->getLocale()->willReturn('en_US'); $multiColorAttribute->getCode()->willReturn('colors'); $multiColorAttribute->isLocaleSpecific()->willReturn(false); $multiColorAttribute->isLocalizable()->willReturn(false); $multiColorAttribute->isScopable()->willReturn(false); $multiColorAttribute->getBackendType()->willReturn('options'); $redOption->getSortOrder()->willReturn(10)->shouldBeCalled(); $blueOption->getSortOrder()->willReturn(11)->shouldBeCalled(); // phpspec raises this php bug https://bugs.php.net/bug.php?id=50688, // warning: usort(): Array was modified by the user comparison function in ProductValueNormalizer.php line 178 $previousReporting = error_reporting(); error_reporting(0); $serializer->normalize(Argument::type('Doctrine\\Common\\Collections\\ArrayCollection'), 'flat', ['field_name' => 'colors'])->shouldBeCalled()->willReturn(['colors' => 'red, blue']); $this->normalize($value, 'flat', [])->shouldReturn(['colors' => 'red, blue']); error_reporting($previousReporting); }