/** * Get the list of all locales * * @return JsonResponse all activated locales */ public function indexAction() { $locales = $this->localeRepository->getActivatedLocales(); $filteredLocales = $this->collectionFilter->filterCollection($locales, 'pim.internal_api.locale.view'); $normalizedLocales = $this->normalizer->normalize($filteredLocales, 'internal_api'); return new JsonResponse($normalizedLocales); }
/** * In an API context, converts any data to a JSON-LD response. * * @param GetResponseForControllerResultEvent $event * * @return JsonLdResponse|mixed */ public function onKernelView(GetResponseForControllerResultEvent $event) { $controllerResult = $event->getControllerResult(); if ($controllerResult instanceof Response) { return; } $request = $event->getRequest(); $format = $request->attributes->get('_api_format'); if (self::FORMAT !== $format) { return; } switch ($request->getMethod()) { case Request::METHOD_POST: $status = 201; break; case Request::METHOD_DELETE: $status = 204; break; default: $status = 200; break; } $resourceType = $request->attributes->get('_resource_type'); $response = new JsonLdResponse($resourceType ? $this->normalizer->normalize($controllerResult, self::FORMAT, $resourceType->getNormalizationContext() + ['request_uri' => $request->getRequestUri()]) : $controllerResult, $status); $event->setResponse($response); }
/** * {@inheritdoc} */ public function process($attribute) { $context = ['locales' => $this->localeManager->getActiveCodes()]; $flatAttribute = ['type' => $attribute->getAttributeType(), 'code' => $attribute->getCode()] + $this->transNormalizer->normalize($attribute, null, $context); $flatAttribute = array_merge($flatAttribute, ['group' => $attribute->getGroup() ? $attribute->getGroup()->getCode() : null, 'unique' => (int) $attribute->isUnique(), 'useable_as_grid_filter' => (int) $attribute->isUseableAsGridFilter(), 'allowed_extensions' => implode(self::ITEM_SEPARATOR, $attribute->getAllowedExtensions()), 'metric_family' => $attribute->getMetricFamily(), 'default_metric_unit' => $attribute->getDefaultMetricUnit(), 'localizable' => (int) $attribute->isLocalizable(), 'scopable' => (int) $attribute->isScopable(), 'families' => $this->getAttributeFamilyCodes($attribute)]); return $flatAttribute; }
/** * {@inheritdoc} */ public function normalize($attribute, $format = null, array $context = []) { $dateMin = null === $attribute->getDateMin() ? '' : $attribute->getDateMin()->format(\DateTime::ISO8601); $dateMax = null === $attribute->getDateMax() ? '' : $attribute->getDateMax()->format(\DateTime::ISO8601); $normalizedAttribute = $this->normalizer->normalize($attribute, 'json', $context) + ['id' => $attribute->getId(), 'wysiwyg_enabled' => $attribute->isWysiwygEnabled(), 'empty_value' => $this->emptyValueProvider->getEmptyValue($attribute), 'field_type' => $this->fieldProvider->getField($attribute), 'is_locale_specific' => (int) $attribute->isLocaleSpecific(), 'locale_specific_codes' => $attribute->getLocaleSpecificCodes(), 'max_characters' => $attribute->getMaxCharacters(), 'validation_rule' => $attribute->getValidationRule(), 'validation_regexp' => $attribute->getValidationRegexp(), 'number_min' => $attribute->getNumberMin(), 'number_max' => $attribute->getNumberMax(), 'decimals_allowed' => $attribute->isDecimalsAllowed(), 'negative_allowed' => $attribute->isNegativeAllowed(), 'date_min' => $dateMin, 'date_max' => $dateMax, 'metric_family' => $attribute->getMetricFamily(), 'default_metric_unit' => $attribute->getDefaultMetricUnit(), 'max_file_size' => $attribute->getMaxFileSize(), 'sort_order' => $attribute->getSortOrder()]; return $normalizedAttribute; }
/** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); if (!$request->attributes->has('_resource_type') || self::FORMAT !== $request->attributes->get('_api_format')) { return; } $exception = $event->getException(); $headers = []; if ($exception instanceof HttpException) { $status = $exception->getStatusCode(); $headers = $exception->getHeaders(); $data = $exception; } elseif ($exception instanceof ValidationException) { $status = Response::HTTP_BAD_REQUEST; $data = $exception->getConstraintViolationList(); } elseif ($exception instanceof ExceptionInterface || $exception instanceof InvalidArgumentException) { $status = Response::HTTP_BAD_REQUEST; $data = $exception; } else { $status = Response::HTTP_INTERNAL_SERVER_ERROR; $data = $exception; } $event->setResponse(new Response($this->normalizer->normalize($data, 'hydra-error'), $status, $headers)); }
/** * Returns a list of violations normalized in the Hydra format. * * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof ValidationException) { $event->setResponse(new Response($this->normalizer->normalize($exception->getConstraintViolationList(), 'hydra-error'), Response::HTTP_BAD_REQUEST)); } }
/** * Get the attribute collection * * @return JsonResponse */ public function indexAction() { $attributes = $this->attributeRepository->findAll(); $filteredAttributes = $this->collectionFilter->filterCollection($attributes, 'pim.internal_api.attribute.view'); $normalizedAttributes = $this->normalizer->normalize($filteredAttributes, 'internal_api'); return new JsonResponse($normalizedAttributes); }
/** * {@inheritdoc} */ public function addAttributes(ProductTemplateInterface $template, array $attributes, $locale) { $options = ['entity' => 'product', 'locale' => $locale, 'disable_grouping_separator' => true]; $values = $this->buildProductValuesFromTemplateValuesData($template, $attributes, $locale); $valuesData = $this->normalizer->normalize($values, 'json', $options); $template->setValuesData($valuesData); }
/** * {@inheritdoc} */ public function process($family) { $flatFamily = ['code' => $family->getCode()]; $familyLabels = $this->transNormalizer->normalize($family); $flatFamily['label'] = $familyLabels['label'][$this->labelLocale]; return $flatFamily; }
/** * Normalize a completeness element * * @param array $completeness * @param string $format * @param array $context * * @return array */ protected function normalizeCompleteness($completeness, $format = null, array $context = array()) { $missing = []; foreach ($completeness['missing'] as $attribute) { $missing[] = $attribute->getCode(); } return ['missing' => $missing, 'completeness' => $this->normalizer->normalize($completeness['completeness'], $format, $context)]; }
/** * Converts a {@see \Symfony\Component\Debug\Exception\FlattenException} * to a {@see \Dunglas\ApiBundle\JsonLd\Response}. * * @param FlattenException $exception * * @return Response */ public function __invoke(FlattenException $exception) { $exceptionClass = $exception->getClass(); if (is_a($exceptionClass, ExceptionInterface::class, true) || is_a($exceptionClass, InvalidArgumentException::class, true)) { $exception->setStatusCode(Response::HTTP_BAD_REQUEST); } return new Response($this->normalizer->normalize($exception, 'hydra-error'), $exception->getStatusCode(), $exception->getHeaders()); }
/** * Get a single family * * @param int $identifier * * @return JsonResponse */ public function getAction($identifier) { $family = $this->familyRepository->findOneByIdentifier($identifier); if (null === $family) { throw new NotFoundHttpException(sprintf('Family with code "%s" not found', $identifier)); } return new JsonResponse($this->normalizer->normalize($family, 'json')); }
/** * {@inheritdoc} */ public function normalize($product, $format = null, array $context = []) { $normalizedProduct = $this->productNormalizer->normalize($product, 'json', $context); $oldestLog = $this->versionManager->getOldestLogEntry($product); $newestLog = $this->versionManager->getNewestLogEntry($product); $normalizedProduct['meta'] = ['id' => $product->getId(), 'created' => $oldestLog !== null ? $this->versionNormalizer->normalize($oldestLog, 'internal_api') : null, 'updated' => $newestLog !== null ? $this->versionNormalizer->normalize($newestLog, 'internal_api') : null] + $this->getLabels($product) + $this->getAssociationMeta($product); return $normalizedProduct; }
public function normalize(NormalizerInterface $normalizer, $format = null, array $context = array()) { $result = array('id' => $this->getId(), 'title' => $this->getTitle(), 'projectName' => $this->getProjectName(), 'status' => $this->getStatus(), 'running' => $this->isRunning(), 'properties' => $this->getProperties(), 'count' => array('pending' => $this->countStatus('pending'), 'running' => $this->countStatus('running'), 'succeeded' => $this->countStatus('succeeded'), 'failed' => $this->countStatus('failed')), 'progress' => $this->getProgress()); if (isset($context['run_details']) && $context['run_details']) { $result['units'] = $normalizer->normalize($this->getUnits()); } return $result; }
/** * 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')); }
/** * Get a single variant group * * @param int $identifier * * @return JsonResponse */ public function getAction($identifier) { $variantGroup = $this->variantGroupRepo->findOneByCode($identifier); if (!$variantGroup) { throw new NotFoundHttpException(sprintf('Variant group with code "%s" not found', $identifier)); } return new JsonResponse($this->normalizer->normalize($variantGroup, 'internal_api', ['with_variant_group_values' => true])); }
/** * {@inheritdoc} */ public function normalize($price, $format = null, array $context = []) { $price = $this->priceNormalizer->normalize($price, $format, $context); foreach ($price as $currency => $data) { $price[$currency] = $this->localizer->convertDefaultToLocalized($data, $context); } return $price; }
/** * Normalize and return given $locales * * @param $locales * * @return array|\ArrayAccess */ protected function normalizeLocales($locales) { $normalizedLocales = []; foreach ($this->collectionFilter->filterCollection($locales, 'pim.internal_api.locale.view') as $locale) { $normalizedLocales[] = $this->localeNormalizer->normalize($locale, 'json'); } return $normalizedLocales; }
/** * @Route("/api/v1/authors", name="api_authors") * @param Request $request * * @return JsonResponse */ public function indexAction(Request $request) { $authorName = $request->query->get('fullNameStartsWith'); if (strlen($authorName) < 3) { throw new BadRequestHttpException("At least three letters needed to fetch author list"); } $authors = $this->repository->findWithNameStartingWith($authorName); return new JsonResponse($this->normalizer->normalize($authors, 'json', ['groups' => ['list']])); }
/** * @param FormEvent $event * * @return null */ public function postSubmit(FormEvent $event) { $data = $event->getData(); if (null === $data || !$data instanceof ProductTemplateInterface) { return; } $valuesData = $this->normalizer->normalize($data->getValues(), 'json', ['entity' => 'product']); $data->setValuesData($valuesData); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $this->commandParserChain->execute($input, $output); $filename = sprintf('%s.json', Inflector::camelize(strtolower($this->collectionName))); $filepath = $this->rootDir . '/../' . $filename; file_put_contents($filepath, json_encode($this->normalizer->normalize($this->collectionGenerator->generate(), 'json'))); $text = sprintf('Postman collection has been successfully built in file %s.', $filename); $output->writeln(['', $this->getHelperSet()->get('formatter')->formatBlock($text, 'bg=blue;fg=white', true), '']); }
/** * Get the family collection * * @return JsonResponse */ public function indexAction() { $families = $this->familyRepository->findAll(); $normalizedFamilies = []; foreach ($families as $family) { $normalizedFamilies[$family->getCode()] = $this->normalizer->normalize($family, 'json'); } return new JsonResponse($normalizedFamilies); }
/** * {@inheritdoc} */ public function normalize($metric, $format = null, array $context = []) { $metric = $this->metricNormalizer->normalize($metric, $format, $context); if (!isset($context['field_name']) || !isset($metric[$context['field_name']])) { return $metric; } $metric[$context['field_name']] = $this->localizer->convertDefaultToLocalized($metric[$context['field_name']], $context); return $metric; }
/** * @return JsonResponse */ public function getAction() { $token = $this->securityContext->getToken(); $user = null !== $token ? $token->getUser() : null; if (null === $user) { throw new NotFoundHttpException('No logged in user found'); } return new JsonResponse($this->normalizer->normalize($user, 'internal_api')); }
/** * {@inheritdoc} */ public function normalize($product, $format = null, array $context = []) { $normalizedProduct = $this->productNormalizer->normalize($product, 'json', $context); $oldestLog = $this->versionManager->getOldestLogEntry($product); $newestLog = $this->versionManager->getNewestLogEntry($product); $created = null !== $oldestLog ? $this->versionNormalizer->normalize($oldestLog, 'internal_api') : null; $updated = null !== $newestLog ? $this->versionNormalizer->normalize($newestLog, 'internal_api') : null; $normalizedProduct['meta'] = ['form' => $this->formProvider->getForm($product), 'id' => $product->getId(), 'created' => $created, 'updated' => $updated, 'model_type' => 'product', 'structure_version' => $this->structureVersionProvider->getStructureVersion()] + $this->getLabels($product) + $this->getAssociationMeta($product); return $normalizedProduct; }
/** * 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 normalize($price, $format = null, array $context = []) { $price = $this->priceNormalizer->normalize($price, $format, $context); foreach ($price as $currency => $data) { $formattedPrice = [['currency' => $currency, 'data' => $data]]; $localizedPrice = $this->localizer->convertDefaultToLocalized($formattedPrice, $context); $price[$currency] = $localizedPrice[0]['data']; } return $price; }
/** * Get attribute group collection * * @return JsonResponse */ public function indexAction() { $attributeGroups = $this->attributeGroupRepo->findAll(); $filteredAttrGroups = $this->collectionFilter->filterCollection($attributeGroups, 'pim.internal_api.attribute_group.view'); $normalizedAttrGroups = []; foreach ($filteredAttrGroups as $attributeGroup) { $normalizedAttrGroups[$attributeGroup->getCode()] = $this->normalizer->normalize($attributeGroup, 'json'); } return new JsonResponse($normalizedAttrGroups); }
/** * @param FormEvent $event */ public function postSubmit(FormEvent $event) { $data = $event->getData(); if (null === $data || !$data instanceof ProductTemplateInterface) { return; } $options = ['entity' => 'product', 'locale' => $this->localeResolver->getCurrentLocale(), 'disable_grouping_separator' => true]; $valuesData = $this->normalizer->normalize($data->getValues(), 'json', $options); $data->setValuesData($valuesData); }
/** * {@inheritdoc} */ public function normalize($entity, $format = null, array $context = []) { $result = $this->valuesNormalizer->normalize($entity, $format, $context); $type = $entity->getAttribute()->getAttributeType(); $localizer = $this->localizerRegistry->getProductValueLocalizer($type); if (null !== $localizer) { $result['data'] = $localizer->localize($result['data'], $context); } return $result; }