Author: Jordi Boggiano (j.boggiano@seld.be)
    public function testNormalize()
    {
        $obj = new GetSetDummy();
        $object = new \stdClass();
        $obj->setFoo('foo');
        $obj->setBar('bar');
        $obj->setBaz(true);
        $obj->setCamelCase('camelcase');
        $obj->setObject($object);

        $this->serializer
            ->expects($this->once())
            ->method('normalize')
            ->with($object, 'any')
            ->will($this->returnValue('string_object'))
        ;

        $this->assertEquals(
            array(
                'foo' => 'foo',
                'bar' => 'bar',
                'baz' => true,
                'fooBar' => 'foobar',
                'camelCase' => 'camelcase',
                'object' => 'string_object',
            ),
            $this->normalizer->normalize($obj, 'any')
        );
    }
 /**
  * {@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);
 }
Esempio n. 4
0
 /**
  * Create a new item.
  *
  * @param Request    $request
  * @param string|int $id
  *
  * @throws NotFoundHttpException
  * @throws RuntimeException
  * @throws UserProtectedException
  * @throws UserLimitReachedException
  *
  * @return mixed
  */
 public function __invoke(Request $request, $id)
 {
     /**
      * @var $resourceType ResourceInterface
      */
     list($resourceType, $format) = $this->extractAttributes($request);
     /*
      * Workaround to ensure stockLevels are not overwritten in a PUT request.
      * @see https://github.com/partkeepr/PartKeepr/issues/551
      */
     $data = json_decode($request->getContent(), true);
     if (array_key_exists('stockLevels', $data)) {
         unset($data['stockLevels']);
     }
     $requestData = json_encode($data);
     $data = $this->getItem($this->dataProvider, $resourceType, $id);
     $context = $resourceType->getDenormalizationContext();
     $context['object_to_populate'] = $data;
     /**
      * @var $part Part
      */
     $part = $this->serializer->deserialize($requestData, $resourceType->getEntityClass(), $format, $context);
     if (!$this->partService->isInternalPartNumberUnique($part->getInternalPartNumber(), $part)) {
         throw new InternalPartNumberNotUniqueException();
     }
     return $part;
 }
 /**
  * In an API context, converts any data to a XML response.
  *
  * @param GetResponseForControllerResultEvent $event
  *
  * @return Response|mixed
  */
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     $controllerResult = $event->getControllerResult();
     if ($controllerResult instanceof Response) {
         return $controllerResult;
     }
     $request = $event->getRequest();
     $format = $request->attributes->get('_api_format');
     if (self::FORMAT !== $format) {
         return $controllerResult;
     }
     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 Response($this->serializer->serialize($controllerResult, self::FORMAT, $resourceType->getNormalizationContext()), $status, ['Content-Type' => 'application/xml']);
     $event->setResponse($response);
 }
Esempio n. 6
0
 /**
  * Create a new item.
  *
  * @param Request    $request
  * @param string|int $id
  *
  * @throws NotFoundHttpException
  * @throws RuntimeException
  * @throws UserProtectedException
  * @throws UserLimitReachedException
  *
  * @return mixed
  */
 public function __invoke(Request $request, $id)
 {
     /**
      * @var ResourceInterface
      */
     list($resourceType, $format) = $this->extractAttributes($request);
     /**
      * @var User
      */
     $data = $this->getItem($this->dataProvider, $resourceType, $id);
     $context = $resourceType->getDenormalizationContext();
     $context['object_to_populate'] = $data;
     if ($data->isProtected()) {
         throw new UserProtectedException();
     }
     $data = $this->serializer->deserialize($request->getContent(), $resourceType->getEntityClass(), $format, $context);
     if ($data->isActive()) {
         if ($this->userService->checkUserLimit()) {
             throw new UserLimitReachedException();
         }
     }
     $this->userService->syncData($data);
     $data->setNewPassword('');
     $data->setPassword('');
     $data->setLegacy(false);
     return $data;
 }
 /**
  * {@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;
 }
Esempio n. 8
0
 /**
  * @param $url
  * @param array $params
  *
  * @return array
  */
 public function get($url, $params = array())
 {
     $request = $this->provider->request($url, $params);
     $response = $this->client->send($request);
     $data = $response->getBody()->getContents();
     $format = $this->getFormat($params, $response);
     return $this->serializer->deserialize($data, null, $format);
 }
 /**
  * {@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;
 }
 function let(SerializerInterface $serializer, AbstractAttribute $simpleAttribute)
 {
     $serializer->implement('Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface');
     $this->setSerializer($serializer);
     $simpleAttribute->isLocalizable()->willReturn(false);
     $simpleAttribute->isScopable()->willReturn(false);
     $simpleAttribute->getCode()->willReturn('simple');
 }
 /**
  * {@inheritdoc}
  */
 public function current()
 {
     $result = parent::current();
     if ($result !== null && $this->serializer) {
         $result = $this->serializer->deserialize($result, $this->itemType, null, $this->deserializeContext);
     }
     return $result;
 }
 /**
  * @expectedException \Symfony\Component\Serializer\Exception\CircularReferenceException
  */
 public function testCircularNormalize()
 {
     $this->normalizer->setCircularReferenceLimit(1);
     $this->serializer->expects($this->once())->method('normalize')->will($this->returnCallback(function ($data, $format, $context) {
         $this->normalizer->normalize($data['qux'], $format, $context);
         return 'string_object';
     }));
     $this->assertEquals('string_object', $this->normalizer->normalize(new JsonSerializableDummy()));
 }
 /**
  * {@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;
 }
Esempio n. 14
0
 /**
  * Create a new item.
  *
  * @param Request    $request
  * @param string|int $id
  *
  * @return mixed
  *
  * @throws NotFoundHttpException
  * @throws RuntimeException
  */
 public function __invoke(Request $request, $id)
 {
     list($resourceType, $format) = $this->extractAttributes($request);
     $data = $this->getItem($this->dataProvider, $resourceType, $id);
     $context = $resourceType->getDenormalizationContext();
     $context['object_to_populate'] = $data;
     $data = $this->serializer->deserialize($request->getContent(), $resourceType->getEntityClass(), $format, $context);
     return $data;
 }
Esempio n. 15
0
 /**
  * {@inheritdoc}
  */
 public function processRequest(Request $request, RouteMatchInterface $route_match, SerializerInterface $serializer)
 {
     if ($serializer instanceof DecoderInterface) {
         $content = $serializer->decode($request->getContent(), $request->getContentType());
     } else {
         throw new HttpException(500, $this->t("The appropriate DecoderInterface was not found."));
     }
     if (!isset($content)) {
         throw new HttpException(500, $this->t("The content of the request was empty."));
     }
     $flood_config = $this->configFactory->get('user.flood');
     $username = $content['username'];
     $password = $content['password'];
     // Flood protection: this is very similar to the user login form code.
     // @see \Drupal\user\Form\UserLoginForm::validateAuthentication()
     // Do not allow any login from the current user's IP if the limit has been
     // reached. Default is 50 failed attempts allowed in one hour. This is
     // independent of the per-user limit to catch attempts from one IP to log
     // in to many different user accounts.  We have a reasonably high limit
     // since there may be only one apparent IP for all users at an institution.
     if ($this->flood->isAllowed('services.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) {
         $accounts = $this->entityManager->getStorage('user')->loadByProperties(array('name' => $username, 'status' => 1));
         $account = reset($accounts);
         if ($account) {
             if ($flood_config->get('uid_only')) {
                 // Register flood events based on the uid only, so they apply for any
                 // IP address. This is the most secure option.
                 $identifier = $account->id();
             } else {
                 // The default identifier is a combination of uid and IP address. This
                 // is less secure but more resistant to denial-of-service attacks that
                 // could lock out all users with public user names.
                 $identifier = $account->id() . '-' . $request->getClientIP();
             }
             // Don't allow login if the limit for this user has been reached.
             // Default is to allow 5 failed attempts every 6 hours.
             if ($this->flood->isAllowed('services.failed_login_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) {
                 $uid = $this->userAuth->authenticate($username, $password);
                 if ($uid) {
                     $this->flood->clear('services.failed_login_user', $identifier);
                     $this->session->start();
                     user_login_finalize($account);
                     drupal_set_message(t('User succesffully logged in'), 'status', FALSE);
                     return ['id' => $this->session->getId(), 'name' => $this->session->getName()];
                     //return $this->entityManager->getStorage('user')->load($uid);
                 } else {
                     // Register a per-user failed login event.
                     $this->flood->register('services.failed_login_user', $flood_config->get('user_window'), $identifier);
                 }
             }
         }
     }
     // Always register an IP-based failed login event.
     $this->flood->register('services.failed_login_ip', $flood_config->get('ip_window'));
     return [];
 }
 /**
  * {@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);
 }
 /**
  * {@inheritdoc}
  */
 public function process($item)
 {
     if ($this->converter) {
         $item = $this->converter->convertToImportFormat($item);
     }
     $object = $this->serializer->deserialize($item, $this->context->getOption('entityName'), null);
     if ($this->strategy) {
         $object = $this->strategy->process($object);
     }
     return $object ?: null;
 }
Esempio n. 19
0
 /**
  * Injects the specific root node ID if "@local-tree-root" was specified
  *
  * @param Request $request
  *
  * @return mixed
  *
  * @throws RuntimeException
  * @throws PartLimitExceededException
  */
 public function __invoke(Request $request)
 {
     /**
      * @var $resourceType ResourceInterface
      */
     if ($this->partService->checkPartLimit()) {
         throw new PartLimitExceededException();
     }
     list($resourceType, $format) = $this->extractAttributes($request);
     return $this->serializer->deserialize($request->getContent(), $resourceType->getEntityClass(), $format, $resourceType->getDenormalizationContext());
 }
 public function testMakeDto()
 {
     $commentDto = m::mock(CommentDto::class);
     $parameterBag = m::mock(ParameterBagInterface::class);
     $parameterBag->shouldReceive('get')->once()->andReturn(567);
     $request = m::mock(Request::class);
     $request->shouldReceive('getContent')->once();
     $request->attributes = $parameterBag;
     $this->serializer->shouldReceive('deserialize')->once()->andReturn($commentDto);
     $this->commentDtoFactory->makeDto($request);
 }
 /**
  * Processes entity to export format
  *
  * @param mixed $object
  * @return array
  * @throws RuntimeException
  */
 public function process($object)
 {
     if (!$this->serializer) {
         throw new RuntimeException('Serializer must be injected.');
     }
     $data = $this->serializer->serialize($object, null);
     if ($this->dataConverter) {
         $data = $this->dataConverter->convertToExportFormat($data);
     }
     return $data;
 }
 /**
  * {@inheritdoc}
  */
 public function denormalize($data, $class, $format = null, array $context = [])
 {
     if (empty($data)) {
         return null;
     }
     $options = new ArrayCollection();
     foreach ($data as $optionCode) {
         $option = $this->serializer->denormalize($optionCode, 'pim_catalog_simpleselect', $format, $context);
         $options->add($option);
     }
     return $options;
 }
Esempio n. 23
0
 /**
  * {@inheritdoc}
  */
 public function process($item)
 {
     if ($this->dataConverter) {
         $item = $this->dataConverter->convertToImportFormat($item, false);
     }
     $this->context->setValue('itemData', $item);
     $object = $this->serializer->deserialize($item, $this->context->getOption('entityName'), null, $this->context->getConfiguration());
     if ($this->strategy) {
         $object = $this->strategy->process($object);
     }
     return $object ?: null;
 }
 /**
  * {@inheritdoc}
  */
 public function denormalize($data, $class, $format = null, array $context = [])
 {
     if (empty($data)) {
         return null;
     }
     $options = new ArrayCollection();
     foreach ($data as $optionCode) {
         $option = $this->serializer->denormalize($optionCode, AttributeTypes::OPTION_SIMPLE_SELECT, $format, $context);
         $options->add($option);
     }
     return $options;
 }
 /**
  * {@inheritdoc}
  *
  * @return \Drupal\Core\Entity\EntityInterface|array
  */
 public function processRequest(Request $request, RouteMatchInterface $route_match, SerializerInterface $serializer)
 {
     // Unserialize the content of the request if there is any.
     $content = $request->getContent();
     if (!empty($content)) {
         $entity_type_id = $this->getDerivativeId();
         /** @var $entity_type \Drupal\Core\Entity\EntityTypeInterface */
         $entity_type = $this->manager->getDefinition($entity_type_id);
         return $serializer->deserialize($content, $entity_type->getClass(), $request->getContentType(), ['entity_type' => $entity_type_id]);
     }
     return [];
 }
 /**
  * {@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];
 }
Esempio n. 28
0
 /**
  * Return a list of class guessed
  *
  * @param $swaggerSpec
  * @param $name
  * @param $namespace
  * @param $directory
  *
  * @return Context
  */
 public function createContext($swaggerSpec, $name, $namespace, $directory)
 {
     $schema = $this->serializer->deserialize(file_get_contents($swaggerSpec), Swagger::class, 'json');
     $classes = $this->chainGuesser->guessClass($schema, $name);
     foreach ($classes as $class) {
         $properties = $this->chainGuesser->guessProperties($class->getObject(), $name, $classes);
         foreach ($properties as $property) {
             $property->setType($this->chainGuesser->guessType($property->getObject(), $property->getName(), $classes));
         }
         $class->setProperties($properties);
     }
     return new Context($schema, $namespace, $directory, $classes);
 }
 /**
  * {@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;
 }
 public function onManifestPush(ManifestEvent $event)
 {
     $manifest = $event->getManifest();
     $message = new Message($this->serializer->serialize($manifest, 'json', ['groups' => ['manifest_push']]));
     $this->publisher->publish('manifest_push', $message);
     $manifest->setUpdatedAt(new \DateTime());
     $this->om->flush();
 }