Search code examples
phpsymfonyannotationsjmsserializerbundlejms-serializer

JMS Serializer does not apply formatting to newly created objects


When getting an object from an API, I receive a properly serialized Course object.

"startDate": "2018-05-21",

But when I create a new object and try to return it, the formatting is not applied.

"startDate": "2019-02-01T02:37:02+00:00",

Even if I use the repository to get a new Course object, if it is the same object I have just created then it is still not serialized with formatting. Maybe because it is already loaded in memory by that point?

If I use the repository to get a different course from the database then the serialization formatting is applied.

I expected formatting to be applied when I return a Course object regardless of whether it has just been created or not. Any ideas?

Course class

/**
 * @ORM\Entity(repositoryClass="App\Repository\CourseRepository")
 *
 * @HasLifecycleCallbacks
 */
class Course
{
    /**
     * @var string
     *
     * @ORM\Column(type="date")
     *
     * @Assert\Date
     * @Assert\NotNull
     *
     * @JMS\Type("DateTime<'Y-m-d'>")
     * @JMS\Groups({"courses-list", "course-details"})
     */
    private $startDate;

    /**
     * @return string
     */
     public function getStartDate(): string
     {
         return $this->startDate;
     }
}

Course API Controller Class

public function getCourse($id)
{
    $em = $this->getDoctrine()->getManager();
    $repo = $em->getRepository('App:Course');
    $course = $repo->find($id);

    if(!$course) {
        throw new NotFoundHttpException('Course not found', null, 2001);
    }

    return $course;
}

public function addCourse(Request $request) {
    $course = new Course();
    $course->setStartDate($startDate);
    $validator = $this->get('validator');

    $em->persist($course);
    $em->flush();

    return $course;
}

Solution

  • Turns out that you shouldn't use Carbon objects with JMS Serializer.

    As soon as I set DateTime objects on the Course object instead of Carbon objects, it worked fine.

    Strange behaviour considering that they both implement DateTimeInterface.