symfony serializing and deserializing date in object

120 views Asked by At

I have a Symfony2.8 application that works as a RESTful Service to provide customer data that is serialized/deserialized. In Symfony2.8 I used the following code:

  /**
  * @Route("/customer/{id}", name="rest_customer_read")
  * @Method({"GET"})
  */
  public function readCustomer(Customer $customer) {
        $response = new Response();
        if ($customer) {
            $serializer = $this->getSerializer();
            $jsonContent = $serializer->serialize($customer, 'json');
            $response->setContent($jsonContent);
            $response->headers->set("Content-Type", "application/json");
        } else {
            $response->setStatusCode(404, "Customer not found.");
        }
          return $response;
  } 

In order to use the serializer I initiate it as follows:

  private function getSerializer() {
    $encoders = array( new JsonEncoder());
    $normalizer = new GetSetMethodNormalizer();
    $callback = function ($dateTime) {
    return $dateTime instanceof \DateTime
        ? $dateTime->format('Y-m-d H:i:s')
        : '';
    };

    $normalizer->setCircularReferenceLimit(1);
    $normalizer->setIgnoredAttributes(array('customer','visits'));
    // Add Circular reference handler
    $normalizer->setCircularReferenceHandler(function ($object) {
      return $object->getId();
    });

    $normalizer->setCallbacks(array('date'=> $callback, 'birthDate' => $callback,'lastVisit' => $callback,'nextVisit' => $callback,'firstVisit' => $callback,'lastUpdate' => $callback,'gdprDate' => $callback));
    $normalizers = array($normalizer);
    $serializer = new Serializer($normalizers, $encoders);

    return $serializer;
  }

This works as intended. If the object contains a date attribute it is serialized as a String in the format 'Y-m-d H:i:s'.

Now I want to update my application to Symfony 5 / Symfony 6. However my code does not work anymore. Not only that a setCallbacks() method does no longer exist in GetSetMethodNormalizer. There is also no setCircularReferenceLimit().

So how can I can serialize a date object in Symfony5?

0

There are 0 answers