10000 Denormalize IRI to resource · Issue #2123 · api-platform/core · GitHub
[go: up one dir, main page]

Skip to content
Denormalize IRI to resource #2123
@ghettovoice

Description

@ghettovoice

Hi, I noticed that ItemNormalizer doesn't support denormalizing of IRI string. I have an issue, probably related to #2036, with deserializing entity with type hinted constructor. For example if we have User and Group entities which are exposed as API resources:

/**
 * @ApiResource
 */
class User {
  /**
   * @var string
   */
  private $username;
   /**
    * @var Group
    */
   private $group;

   public function __construct(string $username, Group $group)
   {
      $this->username = $username;
      $this->group = $group;
   }
   ....
}

/**
 * @ApiResource
 */
class Group {
  /**
   * @var string
   */
   private $name;

  public function __construct(string $name) { ...  }
}

Sending POST to /users request with payload:

{
   "username": "test",
   "group": "/groups/123456" // already persisted group
}

This leads to exception when symfony AbstractNormalizer trying to denormalize $group argument to the Group resource from string /groups/123456. Actually ItemNormalizer is used to denormalize IRI string but it doesn't trying to load resource from IRI converter like it does for array with id field here .

As a workaround currently I'm using extended ItemNormalizer

final class ResourceItemNormalizer extends ItemNormalizer
{
    public function denormalize($data, $class, $format = null, array $context = [])
    {
        // fix issue denormalizing of the IRI string into resource object (for example as constructor argument)
        if (is_string($data) && !isset($context[ItemNormalizer::OBJECT_TO_POPULATE])) {
            return $this->iriConverter->getItemFromIri($data, $context + ['fetch_data' => true]);
        }

        return parent::denormalize($data, $class, $format, $context);
    }
}

I'm using the latest api-platform/core:2.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0