coste/now-bundle

Allows you to inject the current date as argument of controllers

Installs: 3

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Forks: 0

Type:symfony-bundle

0.1-RC1 2024-10-22 00:00 UTC

This package is auto-updated.

Last update: 2025-04-21 23:11:01 UTC


README

What is it ?

This is a really tiny simple bundle for Symfony framework. Allowing developers to inject the current date directly into controllers arguments.

If you want to write unit tests for a time-sensitive controller, you may have unpredictable results because time is never the same. Time can be mocked in Symfony, but you need to use one of those built-in functions : time(), microtime(), sleep(), usleep(), gmdate(), and hrtime().

This mean that you cannot write new DateTime() but use this instead (and check that everybody on your project is doing so) :

$now = DateTime::createFromFormat('U', (string) time());

With this bundle, all you have to do is to typehint a DateTime or a DateTimeImmutable variable, and to name it $now.

Installation

composer require coste/now-bundle

Examples

<?php
// src/Controller/TodayController.php
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/now', name: 'app_now')]
class TodayController
{
    public function __invoke(\DateTime $now): Response
    {
        return new Response(
            "<html><body>Current date : {$now->format('Y-m-d')}</body></html>"
        );
    }
}

For now, only the DateTime and DateTimeImmutable classes are available. You can also use DateTimeInterface for type hinting, though the actual class used will be DateTimeImmutable.

Licence

AGPL

Copyright (C) 2024 Charles-Édouard Coste

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/.