skip to Main Content

Here’s a sample entity

use ApiPlatformMetadataApiResource;
use DoctrineORMMapping as ORM;
use SymfonyComponentSerializerAnnotationGroups;

#[ORMTable(name: 'user')]
#[ApiResource(
    operations: [new GetCollection()],
    normalizationContext: [
        'groups' => [
            'user:id',
            'user:score',
            'user:user_score',
        ],
    ]
)]
class User
{
    #[ORMId]
    #[ORMGeneratedValue]
    #[ORMColumn(name: 'ID_USER', type: 'integer')]
    #[Groups(groups: ['user:id'])]
    private int $id;

    #[ORMColumn(name: 'SCORE', type: 'integer')]
    #[Groups(groups: ['user:score'])]
    private int $score;

    #[ORMColumn(name: 'SCORE', type: 'integer')]
    #[Groups(groups: ['user:user_score'])]
    private int $userScore;

    // getters / setters
}

I want to depreciate $score / user:score and remove it from the api endpoint
But can’t do this in 1 step, i need to do first 2 field with the same value in it
and second remove the unwanted field

How to do that ?

2

Answers


  1. Chosen as BEST ANSWER

    Solved code

    use ApiPlatformMetadataApiResource;
    use DoctrineORMMapping as ORM;
    use SymfonyComponentSerializerAnnotationGroups;
    
    #[ORMTable(name: 'user')]
    #[ApiResource(
        operations: [new GetCollection()],
        normalizationContext: [
            'groups' => [
                'user:id',
                'user:score',
                'user:user_score',
            ],
        ]
    )]
    class User
    {
        #[ORMId]
        #[ORMGeneratedValue]
        #[ORMColumn(name: 'ID_USER', type: 'integer')]
        #[Groups(groups: ['user:id'])]
        private int $id;
    
        #[ORMColumn(name: 'SCORE', type: 'integer')]
        #[Groups(groups: ['user:user_score'])]
        private int $userScore;
    
        #[Groups(groups: ['user:score'])]
        #[SerializedName('score')]
        public function getScore()
        {
            return $this->userScore;
        }
    
        // getters / setters
    }
    

  2. Idealy your API exposed the getters and setters,
    probably the serializer uses them anyway

    so to deprecate you could modify your getter and setter like:

    /**
     * @deprecated in 2.x and removed in 3.x.
     *   Use FooBar::getUserScore() instead.
     */
    public function getScore(){
      return $this->getUserScore();
    }
    

    so any calls to getScore will return the userScore property anyway. You can then remove it in some version.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search