0

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;
}
RonnyKnoxville
  • 6,166
  • 10
  • 46
  • 75
  • With JMS serializer you can't just return an item that will be converted to right output format. This means that you have somewhere in your code a listener on `kernel.view` that uses JMS Serializer. The problem is probably in this listener and not inside JMS. Maybe different serializers are used on each of your methods. In any cases with the code you give it's impossible to understand what's wrong here but it does not look related to JMS Serializer. – Nek May 23 '18 at 09:21
  • Both POST and GET are using listeners which must have come set up when installing the bundles. Neither have been modified. – RonnyKnoxville May 23 '18 at 09:48

1 Answers1

0

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.

RonnyKnoxville
  • 6,166
  • 10
  • 46
  • 75