Skip to content

Denormalize IRI to resource #2123

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

No activity

Activity on this issue will appear here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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