skip to Main Content

I’m currently developing a Symfony-based REST API application, where I encounter a specific requirement related to the formatting of date values returned from entity fields. Within my entity, I have a field named birthdate, defined as @ORMColumn(type="date"). When this field is included in API responses, it provides both the date and time components, which is not aligned with the project’s specifications. Instead, I need the API response to exclusively provide the date part without any time information.

Below is a condensed version of the relevant section of the entity, including the existing getBirthdate() method:

/**
 * @var DateTime|null
 *
 * @ORMColumn(name="birthdate", type="date", nullable=true)
 */
private $birthdate;

// Existing getBirthdate() method
public function getBirthdate(): ?DateTimeInterface
{
    return $this->birthdate;
}

// Additional properties and methods...

While I’ve considered utilizing DateTimeImmutable objects to ensure immutability, I’m uncertain about the precise implementation within the getBirthdate() method. Therefore, I seek guidance on how to modify this method effectively to exclusively return the date part without any time components, utilizing DateTimeImmutable.

2

Answers


  1. As shown here, you can use a Context attribute to set a specific date format for your field:

    use SymfonyComponentSerializerAnnotationContext;
    use SymfonyComponentSerializerNormalizerDateTimeNormalizer;
    
    #[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
    private $birthdate;
    
    Login or Signup to reply.
  2. You can create custom normalizer for your entity which will be returning output from your specification.

    <?php
    
    namespace AppNormalizers;
    
    use AppEntityTransactions;
    use SymfonyComponentSerializerNormalizerNormalizerInterface;
    
    class TransactionsNormalizer implements NormalizerInterface
    {
    public function normalize(mixed $object, string $format = null, array $context = []): array
    {
        if (!$object instanceof Transactions) {
            return [];
        }
    
        if (isset($context['groups']) && 'transaction_status' === $context['groups']) {
            return [
                'status' => $object->getStatus(),
                'paymentGatewayUrl' => $object->getUrl(),
            ];
        }
    
        if (isset($context['groups']) && 'transactions' === $context['groups']) {
         return [
            'id' => $object->getId(),
            'transactionId' => $object->getTransactionId(),
            'product' => $object->getProduct(),
            'price' => $object->getPrice(),
            'status' => $object->getStatus(),
            'createdAt' => $object->getCreatedAt()->format('Y-m-d H:i:s),
          ];
        }
    
        return $this->normalizer->normalize($object, $format, $context);
    }
    
    public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool
    {
        return $data instanceof Transactions;
    }
    
    public function getSupportedTypes(?string $format): array
    {
        return [
            Transactions::class,
        ];
    }
    

    }

    public function list(#[MapQueryString] GetTransactionsListDTO $dto): JsonResponse
    {
        $result = $this->transactionsService->getFilteredList($dto, true);
    
        return new JsonResponse(
            $this->serializer->serialize($result, 'json', ['groups' => 'transactions']),
            200,
            [],
            true
        );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search