denormalize example

$normalized = $this->normalizer->normalize($this->data->reveal());
    $this->assertSame($random_rfc_3339_string$normalized);
  }

  /** * Tests the denormalize function with good data. * * @covers ::denormalize * @dataProvider providerTestDenormalizeValidFormats */
  public function testDenormalizeValidFormats($normalized$expected) {
    $denormalized = $this->normalizer->denormalize($normalized, Timestamp::class, NULL, []);
    $this->assertSame($expected$denormalized);
  }

  /** * Data provider for testDenormalizeValidFormats. * * @return array */
  public function providerTestDenormalizeValidFormats() {
    $expected_stamp = 1478422920;

    
if (!is_array($data)) {
      throw new UnexpectedValueException(sprintf('Field values for "%s" must use an array structure', $items->getName()));
    }

    foreach ($data as $item_data) {
      // Create a new item and pass it as the target for the unserialization of       // $item_data. All items in field should have removed before this method       // was called.       // @see \Drupal\serialization\Normalizer\ContentEntityNormalizer::denormalize().       $context['target_instance'] = $items->appendItem();
      $this->serializer->denormalize($item_data$item_class$format$context);
    }
    return $items;
  }

  /** * {@inheritdoc} */
  public function getSupportedTypes(?string $format): array {
    return [
      FieldItemListInterface::class => TRUE,
    ];
  }
if (!$this->propertyAccessor->isReadable($data$propertyPath)) {
                return null;
            }

            $data = $this->propertyAccessor->getValue($data$propertyPath);
        }

        if (!$this->serializer instanceof DenormalizerInterface) {
            throw new LogicException('Cannot unwrap path because the injected serializer is not a denormalizer.');
        }

        return $this->serializer->denormalize($data$type$format$context);
    }

    public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
    {
        return \array_key_exists(self::UNWRAP_PATH, $context) && !isset($context['unwrapped']);
    }

    /** * @deprecated since Symfony 6.3, use "getSupportedTypes()" instead */
    public function hasCacheableSupportsMethod(): bool
    {
return [
            KernelEvents::CONTROLLER_ARGUMENTS => 'onKernelControllerArguments',
        ];
    }

    private function mapQueryString(Request $request, string $type, MapQueryString $attribute): ?object
    {
        if (!$data = $request->query->all()) {
            return null;
        }

        return $this->serializer->denormalize($data$type, null, self::CONTEXT_DENORMALIZE + $attribute->serializationContext);
    }

    private function mapRequestPayload(Request $request, string $type, MapRequestPayload $attribute): ?object
    {
        if (null === $format = $request->getContentTypeFormat()) {
            throw new HttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE, 'Unsupported format.');
        }

        if ($attribute->acceptFormat && !\in_array($format(array) $attribute->acceptFormat, true)) {
            throw new HttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE, sprintf('Unsupported format, expects "%s", but "%s" given.', implode('", "', (array) $attribute->acceptFormat)$format));
        }

        
$field_definition = $context['field_definition'];
    }
    else {
      throw new InvalidArgumentException('$context[\'target_instance\'] or $context[\'field_definition\'] must be set to denormalize with the DateTimeIso8601Normalizer');
    }

    $datetime_type = $field_definition->getSetting('datetime_type');
    $is_date_only = $datetime_type === DateTimeItem::DATETIME_TYPE_DATE;

    if ($is_date_only) {
      $context['datetime_allowed_formats'] = array_intersect_key($this->allowedFormats, ['date-only' => TRUE]);
      $datetime = parent::denormalize($data$class$format$context);
      if (!$datetime instanceof \DateTime) {
        return $datetime;
      }
      return $datetime->format(DateTimeItemInterface::DATE_STORAGE_FORMAT);
    }

    $context['datetime_allowed_formats'] = array_diff_key($this->allowedFormats, ['date-only' => TRUE]);
    $datetime = parent::denormalize($data$class$format$context);
    if (!$datetime instanceof \DateTime) {
      return $datetime;
    }
    
$object->setMessage($data['message']);
        $object->setCode($data['code']);
        $object->setStatusCode($data['status'] ?? 500);
        $object->setClass($data['class']);
        $object->setFile($data['file']);
        $object->setLine($data['line']);
        $object->setStatusText($data['status_text']);
        $object->setHeaders((array) $data['headers']);

        if (isset($data['previous'])) {
            $object->setPrevious($this->denormalize($data['previous']$type$format$context));
        }

        $property = new \ReflectionProperty(FlattenException::class, 'trace');
        $property->setValue($object(array) $data['trace']);

        $property = new \ReflectionProperty(FlattenException::class, 'traceAsString');
        $property->setValue($object$data['trace_as_string']);

        return $object;
    }

    
$normalizedData = $this->removeNestedValue($serializedPath->getElements()$normalizedData);
        }

        $normalizedData = array_merge($normalizedData$nestedData);

        $object = $this->instantiateObject($normalizedData$mappedClass$contextnew \ReflectionClass($mappedClass)$allowedAttributes$format);
        $resolvedClass = ($this->objectClassResolver)($object);

        foreach ($normalizedData as $attribute => $value) {
            if ($this->nameConverter) {
                $notConverted = $attribute;
                $attribute = $this->nameConverter->denormalize($attribute$resolvedClass$format$context);
                if (isset($nestedData[$notConverted]) && !isset($originalNestedData[$attribute])) {
                    throw new LogicException(sprintf('Duplicate values for key "%s" found. One value is set via the SerializedPath annotation: "%s", the other one is set via the SerializedName annotation: "%s".', $notConvertedimplode('->', $nestedAttributes[$notConverted]->getElements())$attribute));
                }
            }

            $attributeContext = $this->getAttributeDenormalizationContext($resolvedClass$attribute$context);

            if ((false !== $allowedAttributes && !\in_array($attribute$allowedAttributes)) || !$this->isAllowedAttribute($resolvedClass$attribute$format$context)) {
                if (!($context[self::ALLOW_EXTRA_ATTRIBUTES] ?? $this->defaultContext[self::ALLOW_EXTRA_ATTRIBUTES])) {
                    $extraAttributes[] = $attribute;
                }

                
public function testSupportCustomAbstractUid()
    {
        $this->assertTrue($this->normalizer->supportsDenormalization('ccc', TestAbstractCustomUid::class));
    }

    /** * @dataProvider dataProvider */
    public function testDenormalize($uuidString$class)
    {
        $this->assertEquals($class::fromString($uuidString)$this->normalizer->denormalize($uuidString$class));
    }

    /** * @group legacy */
    public function testDenormalizeOurAbstractUid()
    {
        $this->expectDeprecation('Since symfony/serializer 6.1: Denormalizing to an abstract class in "Symfony\Component\Serializer\Normalizer\UidNormalizer" is deprecated.');

        $this->assertEquals(Uuid::fromString($uuidString = '1ea6ecef-eb9a-66fe-b62b-957b45f17e43')$this->normalizer->denormalize($uuidString, AbstractUid::class));
    }

    
$this->dataCollector->collectNormalize($traceId$object$format$context$time$caller);

        return $result;
    }

    public function denormalize(mixed $data, string $type, string $format = null, array $context = []): mixed
    {
        $context[self::DEBUG_TRACE_ID] = $traceId = uniqid();

        $startTime = microtime(true);
        $result = $this->serializer->denormalize($data$type$format$context);
        $time = microtime(true) - $startTime;

        $caller = $this->getCaller(__FUNCTION__, DenormalizerInterface::class);

        $this->dataCollector->collectDenormalize($traceId$data$type$format$context$time$caller);

        return $result;
    }

    public function encode(mixed $data, string $format, array $context = []): string
    {
        
$translation = DynamicTranslationEntityDefinition::create($entityName$translated$container);
        $container->set($translation->getEntityName()$translation);
        $container->set($translation->getEntityName() . '.repository', self::createRepository($container$translation));

        $registry->register($translation$translation->getEntityName());

        return $collection;
    }

    private static function kebabCaseToCamelCase(string $string): string
    {
        return (new CamelCaseToSnakeCaseNameConverter())->denormalize(str_replace('-', '_', $string));
    }

    private static function createRepository(ContainerInterface $container, EntityDefinition $definition): EntityRepository
    {
        return new EntityRepository(
            $definition,
            $container->get(EntityReaderInterface::class),
            $container->get(VersionManager::class),
            $container->get(EntitySearcherInterface::class),
            $container->get(EntityAggregatorInterface::class),
            $container->get('event_dispatcher'),
            
'baz' => true,
                'fooBar' => 'foobar',
                'camelCase' => 'camelcase',
                'object' => 'string_object',
            ],
            $this->normalizer->normalize($obj, 'any')
        );
    }

    public function testDenormalize()
    {
        $obj = $this->normalizer->denormalize(
            ['foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'],
            GetSetDummy::class,
            'any'
        );
        $this->assertEquals('foo', $obj->getFoo());
        $this->assertEquals('bar', $obj->getBar());
        $this->assertTrue($obj->isBaz());
    }

    public function testIgnoredAttributesInContext()
    {
        
$obj->foo = 'foo';
        $obj->setBar('bar');
        $obj->setCamelCase('camelcase');
        $this->assertEquals(
            ['foo' => 'foo', 'camelCase' => 'camelcase'],
            $this->normalizer->normalize($obj, 'any', ['normalize_visibility' => PropertyNormalizer::NORMALIZE_PUBLIC | PropertyNormalizer::NORMALIZE_PROTECTED])
        );
    }

    public function testDenormalize()
    {
        $obj = $this->normalizer->denormalize(
            ['foo' => 'foo', 'bar' => 'bar'],
            PropertyDummy::class,
            'any'
        );
        $this->assertEquals('foo', $obj->foo);
        $this->assertEquals('bar', $obj->getBar());
    }

    public function testNormalizeWithParentClass()
    {
        $group = new GroupDummyChild();
        

        $expected = new ObjectDummy();
        $expected->setBaz(true);
        $expected->bar = 'bar';
        $expected->setFoo('foo');

        $this->serializer->expects($this->exactly(1))
            ->method('denormalize')
            ->with(['foo' => 'foo', 'bar' => 'bar', 'baz' => true])
            ->willReturn($expected);

        $result = $this->denormalizer->denormalize(
            ['data' => ['foo' => 'foo', 'bar' => 'bar', 'baz' => true]],
            ObjectDummy::class,
            'any',
            [UnwrappingDenormalizer::UNWRAP_PATH => '[data]']
        );

        $this->assertEquals('foo', $result->getFoo());
        $this->assertEquals('bar', $result->bar);
        $this->assertTrue($result->isBaz());
    }

    
return array_filter($canonical_ids);
      }$relationships);

      // Add the relationship ids.       $normalized = array_merge($normalized$relationships);
    }
    // Override deserialization target class with the one in the ResourceType.     $class = $context['resource_type']->getDeserializationTargetClass();

    return $this
      ->serializer
      ->denormalize($normalized$class$format$context);
  }

  /** * {@inheritdoc} */
  public function normalize($object$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    assert($object instanceof JsonApiDocumentTopLevel);
    $data = $object->getData();
    $document['jsonapi'] = CacheableNormalization::permanent([
      'version' => JsonApiSpec::SUPPORTED_SPECIFICATION_VERSION,
      'meta' => [
        
public function denormalize(mixed $data, ?string $type = null, ?string $format = null, array $context = [])
    {
        if (\is_string($data) && $date = $this->createDate($data)) {
            return $date;
        }

        if (!\is_array($data)) {
            return $data;
        }

        if (!$this->isObject($data)) {
            return array_map($this->denormalize(...)$data);
        }

        /** @var class-string<object> $class */
        $class = $data['_class'];
        unset($data['_class']);

        // iterate arguments to resolve other serialized objects         $arguments = array_map(fn ($argument) => $this->denormalize($argument)$data);

        // create object instance         return $this->createInstance($class$arguments);
    }
Home | Imprint | This part of the site doesn't use cookies.