normalize() public method

public normalize ( $data, $format = null )
 public function testCustomNormalizerCanNormalizeCollectionsAndScalar()
 {
     $serializer = new Serializer(array(new TestNormalizer()), array());
     $this->assertNull($serializer->normalize(array('a', 'b')));
     $this->assertNull($serializer->normalize(new \ArrayObject(array('c', 'd'))));
     $this->assertNull($serializer->normalize(array()));
     $this->assertNull($serializer->normalize('test'));
 }
 /**
  * @test
  */
 public function itShouldCollect()
 {
     $this->serializer->normalize(Argument::any())->shouldBeCalled()->willReturn([]);
     $this->logger->pushHandler(Argument::any())->shouldBeCalled()->willReturn(true);
     $this->logger->info(Argument::type('string'), Argument::type('array'))->shouldBeCalled();
     $this->collector->collect($this->requestObject, ['logFile' => 'test.log']);
 }
 public function save(Article $article)
 {
     $metadata = $this->entityManager->getClassMetadata(get_class($article));
     $type = "app." . $metadata->getTableName();
     $this->fluentLogger->post($type, array_filter($this->serializer->normalize($article), function ($idx) {
         return $idx != 'id';
     }, ARRAY_FILTER_USE_KEY));
 }
 /**
  * {@inheritdoc}
  */
 public function normalize($elements, $format = null, array $context = [])
 {
     $normalizedElements = [];
     foreach ($elements as $key => $element) {
         $normalizedElements[$key] = $this->serializer->normalize($element, $format, $context);
     }
     return $normalizedElements;
 }
Ejemplo n.º 5
0
 /**
  * Compares given value object with value object data structure
  *
  * Returns set of value object attribute names. E.g.:
  *
  * [
  *      // Items that are missing in value object
  *      'add'    => ['field1', 'field2', ...]
  *      // Items that shuld not be present in value object
  *      'remove' => ['field3', 'field4', ...]
  * ]
  *
  * @param object $object
  * @param array $comparedData
  * @param string $propertyIdentifier
  * @return array
  */
 public function diff($object, $comparedData, $propertyIdentifier)
 {
     $objectData = $this->serilaizer->normalize($object);
     $comparingColumn = $this->getAttributesOfValueObjects($comparedData, $propertyIdentifier);
     $toAdd = array_diff($comparingColumn, array_column($objectData, $propertyIdentifier));
     $toRemove = array_diff(array_column($objectData, $propertyIdentifier), $comparingColumn);
     // @todo: add items to be updated
     return ['add' => $toAdd, 'remove' => $toRemove];
 }
 /**
  * {@inheritdoc}
  */
 public function process($product)
 {
     $data['media'] = [];
     $mediaValues = $this->getMediaProductValues($product);
     foreach ($mediaValues as $mediaValue) {
         $data['media'][] = $this->serializer->normalize($mediaValue->getMedia(), 'flat', ['field_name' => 'media', 'prepare_copy' => true, 'value' => $mediaValue]);
     }
     $data['product'] = $this->serializer->normalize($product, 'flat', $this->getNormalizerContext());
     return $data;
 }
Ejemplo n.º 7
0
  /**
   * @param $fillpdf_form
   * @return string
   */
  public function getFormExportCode(FillPdfFormInterface $fillpdf_form) {
    $fields = $this->entityHelper->getFormFields($fillpdf_form);

    $form_config = [
      'form' => $this->serializer->normalize($fillpdf_form),
      'fields' => $this->serializer->normalize($fields),
    ];

    $code = $this->serializer->serialize($form_config, 'json');
    return $code;
  }
Ejemplo n.º 8
0
 /**
  * Retrieves a collection of resources.
  *
  * @param Request $request
  *
  * @throws RuntimeException|RootNodeNotFoundException
  *
  * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable
  */
 public function __invoke(Request $request)
 {
     $user = $this->userService->getUser();
     $preferences = $this->userPreferenceService->getPreferences($user);
     list($resourceType) = $this->extractAttributes($request);
     /*
      * @var ResourceInterface $resourceType
      */
     $serializedData = $this->serializer->normalize($preferences, 'json', $resourceType->getNormalizationContext());
     return new JsonResponse($serializedData);
 }
 /**
  * {@inheritdoc}
  */
 public function process($product)
 {
     $contextChannel = $this->channelManager->getChannelByCode($this->channel);
     $this->productBuilder->addMissingProductValues($product, [$contextChannel], $contextChannel->getLocales()->toArray());
     $data['media'] = [];
     $mediaValues = $this->getMediaProductValues($product);
     foreach ($mediaValues as $mediaValue) {
         $data['media'][] = $this->serializer->normalize($mediaValue->getMedia(), 'flat', ['field_name' => 'media', 'prepare_copy' => true, 'value' => $mediaValue]);
     }
     $data['product'] = $this->serializer->normalize($product, 'flat', $this->getNormalizerContext());
     return $data;
 }
 /**
  * {@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;
 }
Ejemplo n.º 11
0
 /**
  * Retrieves a collection of resources.
  *
  * @param Request $request
  *
  * @throws \Exception                                 If the format is invalid
  * @throws RuntimeException|RootNodeNotFoundException
  *
  * @return JsonResponse
  */
 public function __invoke(Request $request)
 {
     $data = json_decode($request->getContent());
     if (property_exists($data, 'preferenceKey') && property_exists($data, 'preferenceValue')) {
         $preference = $this->systemPreferenceService->setSystemPreference($data->preferenceKey, $data->preferenceValue);
     } else {
         throw new \Exception('Invalid format');
     }
     /**
      * @var ResourceInterface $resourceType
      */
     list($resourceType) = $this->extractAttributes($request);
     $serializedData = $this->serializer->normalize($preference, 'json', $resourceType->getNormalizationContext());
     return new JsonResponse($serializedData);
 }
Ejemplo n.º 12
0
 /**
  * @return JsonResponse
  *
  * @Route("/sync")
  */
 public function syncAction()
 {
     $youtube = new Youtube(['key' => $this->getParameter('youtube_api_key')]);
     $videos = $youtube->getPlaylistItemsByPlaylistId($this->getParameter('youtube_playlist_id'));
     $em = $this->getDoctrine()->getManager();
     foreach ($videos as $video) {
         $name = $video->snippet->title;
         $youtubeId = $video->snippet->resourceId->videoId;
         $description = $video->snippet->description;
         if (property_exists($video->snippet->thumbnails, 'maxres')) {
             $thumbnail = $video->snippet->thumbnails->maxres->url;
         } elseif (property_exists($video->snippet->thumbnails, 'high')) {
             $thumbnail = $video->snippet->thumbnails->high->url;
         } elseif (property_exists($video->snippet->thumbnails, 'medium')) {
             $thumbnail = $video->snippet->thumbnails->medium->url;
         } else {
             $thumbnail = $video->snippet->thumbnails->default->url;
         }
         $video = $em->getRepository('TGVideoBundle:Video')->findOneByYoutubeId($youtubeId);
         if ($video === null) {
             $video = new Video();
             $video->setYoutubeId($youtubeId);
             $em->persist($video);
         }
         $video->setName($name);
         $video->setDescription($description);
         $video->setThumbnail($thumbnail);
         $video->setUrl('https://www.youtube.com/embed/' . $youtubeId);
     }
     $em->flush();
     $videos = $this->getDoctrine()->getRepository('TGVideoBundle:Video')->findAll([], ['createdAt' => 'DESC']);
     $serializer = new Serializer([$this->get('tg_video.normalizer')]);
     return new JsonResponse(['videos' => $serializer->normalize($videos)]);
 }
Ejemplo n.º 13
0
 public function testNormalizeWithSupportOnData()
 {
     $normalizer1 = $this->getMock('Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface');
     $normalizer1->method('supportsNormalization')->willReturnCallback(function ($data, $format) {
         return isset($data->test);
     });
     $normalizer1->method('normalize')->willReturn('test1');
     $normalizer2 = $this->getMock('Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface');
     $normalizer2->method('supportsNormalization')->willReturn(true);
     $normalizer2->method('normalize')->willReturn('test2');
     $serializer = new Serializer(array($normalizer1, $normalizer2));
     $data = new \stdClass();
     $data->test = true;
     $this->assertEquals('test1', $serializer->normalize($data));
     $this->assertEquals('test2', $serializer->normalize(new \stdClass()));
 }
Ejemplo n.º 14
0
 /**
  * Retrieves a collection of resources.
  *
  * @param Request $request
  *
  * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable
  * @throws \Exception If the format is invalid
  *
  * @throws RuntimeException|RootNodeNotFoundException
  */
 public function __invoke(Request $request)
 {
     $user = $this->userService->getUser();
     $data = json_decode($request->getContent());
     if (property_exists($data, "preferenceKey") && property_exists($data, "preferenceValue")) {
         $preference = $this->userPreferenceService->setPreference($user, $data->preferenceKey, $data->preferenceValue);
     } else {
         throw new \Exception("Invalid format");
     }
     list($resourceType) = $this->extractAttributes($request);
     /**
      * @var ResourceInterface $resourceType
      */
     $serializedData = $this->serializer->normalize($preference, 'json', $resourceType->getNormalizationContext());
     return new JsonResponse($serializedData);
 }
Ejemplo n.º 15
0
 /**
  * @Route("/player/ajax/get", name="team_player_ajax_get")
  */
 public function ajaxGetAction(Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         try {
             $user = $this->getUser();
             $em = $this->getDoctrine()->getManager();
             $player = $em->getRepository('TeamBundle:Player')->findOneBy(array('id' => $request->get('id')));
             if ($user->getTeam() == $player->getTeam()) {
                 $normalizer = new ObjectNormalizer();
                 $normalizer->setCircularReferenceHandler(function ($object) {
                     return $object->getId();
                 });
                 $serializer = new Serializer(array($normalizer));
                 $player = $serializer->normalize($player);
                 $response = new Response(json_encode(array('status' => 'ok', 'player' => $player)));
             } else {
                 $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Vous n\'avez pas la permission d\'éditer ce joueur', 'debug' => 'Utilisateur connecté != manager de l\'équipe du joueur')));
             }
         } catch (\Exception $e) {
             $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Une erreur inconnue s\'est produite', 'debug' => $e->getMessage())));
         }
         $response->headers->set('Content-Type', 'application/json');
         return $response;
     }
     $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Accès non autorisé', 'debug' => 'Bad request')));
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 public function process($item)
 {
     if (!$item instanceof ProductInterface) {
         throw new InvalidItemException(sprintf('Item should be an instance of %s', ProductInterface::class), $item);
     }
     $normalized = $this->serializer->normalize($item, 'flat');
     return ['sku' => $normalized['sku'], 'image' => $this->getMediaAttribute($this->getImageAttribute(), $normalized), 'thumbnail' => $this->getMediaAttribute($this->getThumbnailAttribute(), $normalized), 'small_image' => $this->getMediaAttribute($this->getSmallImageAttribute(), $normalized), 'gallery' => $this->getGalleryAttribute($this->getGalleryAttributes(), $normalized)];
 }
 function it_returns_flat_data_without_media(ChannelInterface $channel, ChannelManager $channelManager, ProductInterface $product, Serializer $serializer)
 {
     $product->getValues()->willReturn([]);
     $serializer->normalize($product, 'flat', ['scopeCode' => 'foobar', 'localeCodes' => ''])->willReturn(['normalized_product']);
     $channelManager->getChannelByCode('foobar')->willReturn($channel);
     $this->setChannel('foobar');
     $this->process($product)->shouldReturn(['media' => [], 'product' => ['normalized_product']]);
 }
Ejemplo n.º 18
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $serializer = new Serializer([$this->normalizer]);
     $data = $form->getData();
     if ($data instanceof Video) {
         $data = new ArrayCollection([$data]);
     }
     $view->vars['options'] = json_encode(['multiple' => $options['multiple'], 'name' => $view->vars['full_name'], 'selected' => $serializer->normalize($data)]);
 }
Ejemplo n.º 19
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $serializer = new Serializer([$this->normalizer]);
     $data = $form->getData();
     if ($data instanceof File) {
         $data = new ArrayCollection([$data]);
     }
     $view->vars['options'] = json_encode(['multiple' => $options['multiple'], 'name' => $view->vars['full_name'], 'images_only' => $options['images_only'], 'selected' => $serializer->normalize($data), 'allow_upload' => $options['allow_upload'], 'allow_delete' => $options['allow_delete'], 'allow_new_folder' => $options['allow_new_folder']]);
 }
Ejemplo n.º 20
0
 /**
  * {@inheritdoc}
  */
 public function normalize($data, $format = null, array $context = array())
 {
     if ($data instanceof Collection) {
         // Clear cache of normalizer for collections,
         // because of wrong behaviour when selecting normalizer for collections of elements with different types
         unset($this->normalizerCache[get_class($data)][$format]);
     }
     return parent::normalize($data, $format, $context);
 }
 public function testStdClassNormalizer()
 {
     $normalizers = array(new StdClassNormalizer());
     $encoders = array();
     $serializer = new Serializer($normalizers, $encoders);
     $object = (object) array('foo' => 'bar', 'array' => array(1, 'foo' => (object) array('foo' => 'bar')));
     $normalized_object = $serializer->normalize($object);
     $this->assertEquals($object, $normalized_object, 'Normalizer accepted stdClass object.');
 }
Ejemplo n.º 22
0
 /**
  * {@inheritdoc}
  */
 public function normalize($object, $format = null, array $context = array())
 {
     $encoder = new JsonEncoder();
     $normalizer = new ObjectNormalizer();
     $normalizer->setCircularReferenceHandler(function ($object) {
         return $object->getName();
     });
     $serializer = new Serializer(array($normalizer), array($encoder));
     return $serializer->normalize($object);
 }
Ejemplo n.º 23
0
 public function init($type, $data, $instance, $externalCoverageId)
 {
     $this->type = $type;
     $this->data = $data;
     $this->instance = $instance;
     $this->externalCoverageId = $externalCoverageId;
     $serializer = new Serializer(array(new BlockNormalizer()));
     // store data before we give Entity to forms (used by ImgBlock so far)
     $this->oldData = $serializer->normalize($this->instance);
 }
Ejemplo n.º 24
0
 /**
  * @param object $object
  * @param string $format
  * @param array  $context
  *
  * @return array
  */
 public function encode($object, $format, array $context = [])
 {
     if ($object instanceof Request or $object instanceof Request) {
         $context['xml_root_node_name'] = 'methodCall';
     } elseif ($object instanceof Response) {
         $context['xml_root_node_name'] = 'methodResponse';
     }
     $array = $this->serializer->normalize($object, $format);
     $array = $this->encodeValue($array);
     return $this->serializer->encode($array, $context['encoding'], $context);
 }
 /**
  * {@inheritdoc}
  */
 public function process($item)
 {
     if (!$item instanceof GroupInterface || !$item->getType()->isVariant()) {
         throw new InvalidItemException(sprintf('Item should be an instance of %s and be a variant type.', GroupInterface::class), $item);
     }
     if ($item->getProductTemplate() === null) {
         return null;
     }
     $normalized = $this->serializer->normalize($item->getProductTemplate()->getValuesData());
     return $data = ['sku' => $item->getCode(), 'image' => $this->getMediaAttribute($this->getImageAttribute(), $normalized), 'thumbnail' => $this->getMediaAttribute($this->getThumbnailAttribute(), $normalized), 'small_image' => $this->getMediaAttribute($this->getSmallImageAttribute(), $normalized), 'gallery' => $this->getGalleryAttribute($this->getGalleryAttributes(), $normalized)];
 }
 function it_throws_an_exception_if_no_file_is_found(ChannelInterface $channel, ProductInterface $product, ChannelManager $channelManager, Serializer $serializer, ProductValueInterface $productValue, AttributeInterface $attribute)
 {
     $product->getValues()->willReturn([$productValue]);
     $productValue->getAttribute()->willReturn($attribute);
     $attribute->getAttributeType()->willReturn('pim_catalog_image');
     $product->getIdentifier()->willReturn($productValue);
     $productValue->getData()->willReturn('data');
     $this->setChannel('foobar');
     $channelManager->getChannelByCode('foobar')->willReturn($channel);
     $serializer->normalize(['data'], 'flat', ['field_name' => 'media', 'prepare_copy' => true])->willThrow('Symfony\\Component\\HttpFoundation\\File\\Exception\\FileNotFoundException');
     $this->shouldThrow('Akeneo\\Bundle\\BatchBundle\\Item\\InvalidItemException')->during('process', [$product]);
 }
Ejemplo n.º 27
0
 /**
  * @param Folder  $folder
  * @param Request $request
  *
  * @return JsonResponse
  * 
  * @Route("/move/{id}", defaults={"id" = null})
  */
 public function indexAction(Request $request, Folder $folder = null)
 {
     $file_ids = $request->get('files', []);
     $files = $this->getDoctrine()->getRepository('TGFileBundle:File')->findById($file_ids);
     /** @var File $file */
     foreach ($files as $file) {
         $file->setFolder($folder);
     }
     $this->getDoctrine()->getManager()->flush();
     $serializer = new Serializer([$this->get('tg_file.normalizer')]);
     return new JsonResponse(['files' => $serializer->normalize($files)]);
 }
 function it_returns_flat_data_without_media($productBuilder, ChannelInterface $channel, LocaleInterface $locale, ChannelManager $channelManager, ProductInterface $product, Serializer $serializer)
 {
     $localeCodes = ['en_US'];
     $channel->getLocales()->willReturn(new ArrayCollection([$locale]));
     $channel->getLocaleCodes()->willReturn($localeCodes);
     $productBuilder->addMissingProductValues($product, [$channel], [$locale])->shouldBeCalled();
     $product->getValues()->willReturn([]);
     $this->setDecimalSeparator(',');
     $serializer->normalize($product, 'flat', ['scopeCode' => 'foobar', 'localeCodes' => $localeCodes, 'decimal_separator' => ',', 'date_format' => 'yyyy-MM-dd'])->willReturn(['normalized_product']);
     $channelManager->getChannelByCode('foobar')->willReturn($channel);
     $this->setChannel('foobar');
     $this->process($product)->shouldReturn(['media' => [], 'product' => ['normalized_product']]);
 }
Ejemplo n.º 29
0
 /**
  * Tests valid and invalid create requests for 'entity_test' entity type.
  */
 public function testCreateEntityTest()
 {
     $entity_type = 'entity_test';
     // Enables the REST service for 'entity_test' entity type.
     $this->enableService('entity:' . $entity_type, 'POST');
     // Create two accounts with the required permissions to create resources.
     // The second one has administrative permissions.
     $accounts = $this->createAccountPerEntity($entity_type);
     // Verify create requests per user.
     foreach ($accounts as $key => $account) {
         $this->drupalLogin($account);
         // Populate some entity properties before create the entity.
         $entity_values = $this->entityValues($entity_type);
         $entity = EntityTest::create($entity_values);
         // Serialize the entity before the POST request.
         $serialized = $this->serializer->serialize($entity, $this->defaultFormat, ['account' => $account]);
         // Create the entity over the REST API.
         $this->assertCreateEntityOverRestApi($entity_type, $serialized);
         // Get the entity ID from the location header and try to read it from the
         // database.
         $this->assertReadEntityIdFromHeaderAndDb($entity_type, $entity, $entity_values);
         // Try to create an entity with an access protected field.
         // @see entity_test_entity_field_access()
         $normalized = $this->serializer->normalize($entity, $this->defaultFormat, ['account' => $account]);
         $normalized['field_test_text'][0]['value'] = 'no access value';
         $this->httpRequest('entity/' . $entity_type, 'POST', $this->serializer->serialize($normalized, $this->defaultFormat, ['account' => $account]), $this->defaultMimeType);
         $this->assertResponse(403);
         $this->assertFalse(EntityTest::loadMultiple(), 'No entity has been created in the database.');
         // Try to create a field with a text format this user has no access to.
         $entity->field_test_text->value = $entity_values['field_test_text'][0]['value'];
         $entity->field_test_text->format = 'full_html';
         $serialized = $this->serializer->serialize($entity, $this->defaultFormat, ['account' => $account]);
         $this->httpRequest('entity/' . $entity_type, 'POST', $serialized, $this->defaultMimeType);
         // The value selected is not a valid choice because the format must be
         // 'plain_txt'.
         $this->assertResponse(422);
         $this->assertFalse(EntityTest::loadMultiple(), 'No entity has been created in the database.');
         // Restore the valid test value.
         $entity->field_test_text->format = 'plain_text';
         $serialized = $this->serializer->serialize($entity, $this->defaultFormat, ['account' => $account]);
         // Try to send invalid data that cannot be correctly deserialized.
         $this->assertCreateEntityInvalidData($entity_type);
         // Try to send no data at all, which does not make sense on POST requests.
         $this->assertCreateEntityNoData($entity_type);
         // Try to send invalid data to trigger the entity validation constraints.
         // Send a UUID that is too long.
         $this->assertCreateEntityInvalidSerialized($entity, $entity_type);
         // Try to create an entity without proper permissions.
         $this->assertCreateEntityWithoutProperPermissions($entity_type, $serialized, ['account' => $account]);
     }
 }
Ejemplo n.º 30
0
 /**
  * @Route("/upload/{id}", defaults={"id" = null})
  *
  * @param Folder  $folder
  * @param Request $request
  *
  * @return JsonResponse
  */
 public function uploadAction(Request $request, Folder $folder = null)
 {
     $error_list = [];
     $upload_list = [];
     if ($request->isMethod('POST')) {
         $em = $this->getDoctrine()->getManager();
         $validator = $this->get('validator');
         $translator = $this->get('translator');
         $serializer = new Serializer([$this->get('tg_file.normalizer')]);
         /** @var UploadedFile $uploaded_file */
         foreach ($request->files as $uploaded_file) {
             $file = new File();
             $file->setFile($uploaded_file);
             $file->setSize($uploaded_file->getSize());
             // client original filename could be null, assume current base name by default
             $originalName = $uploaded_file->getClientOriginalName();
             if ($originalName === null) {
                 $originalName = $uploaded_file->getBasename();
             }
             $file->setOriginalName($originalName);
             // mime type could be null, assume generic binary file by default
             $mimeType = $uploaded_file->getMimeType();
             if ($mimeType === null) {
                 $mimeType = 'application/octet-stream';
             }
             $file->setMimeType($mimeType);
             if (null !== $folder) {
                 $file->setFolder($folder);
             }
             $errors = $validator->validate($file);
             if (0 === count($errors)) {
                 $em->persist($file);
                 $upload_list[] = $serializer->normalize($file);
             } else {
                 $name = $uploaded_file->getClientOriginalName();
                 $error_list[$name] = [];
                 /** @var ConstraintViolation $error */
                 foreach ($errors as $error) {
                     $error_list[$name][] = $translator->trans($error->getMessage());
                 }
             }
         }
         $em->flush();
     }
     return new JsonResponse(['errors' => $error_list, 'uploads' => $upload_list]);
 }