Skip to content

Facades\Cookie is missing use DateTime, passing a DateTime throws a TypeError #14

Description

@nkforeg

Thanks for this library, the API is clean and it has been a pleasure to work with.
I ran into one issue while switching from the instance class to the facade.

Summary

src/Facades/Cookie.php does not import DateTime, so the DateTime in its
signatures resolves to Josantonius\Cookie\Facades\DateTime, which does not exist.
Passing any DateTime instance therefore throws a TypeError.

The non-facade Josantonius\Cookie\Cookie does have use DateTime; and works
correctly, so the two classes behave differently for the same input.

Affected: set() and replace(), the only two facade methods with an $expires
parameter. The other 7 methods use no class types and are unaffected.

Reproduction

use Josantonius\Cookie\Facades\Cookie;
use Josantonius\Cookie\Cookie as CookieInstance;

$expires = (new DateTime())->modify('+3 months');

Cookie::set('mode', 'barcode', $expires);                  // fails
(new CookieInstance())->set('mode', 'barcode', $expires);  // works

Actual

TypeError: Josantonius\Cookie\Facades\Cookie::set(): Argument #3 ($expires)
must be of type Josantonius\Cookie\Facades\DateTime|int|null, DateTime given

Note the expected type in the message: Josantonius\Cookie\Facades\DateTime.

Expected

Same behaviour as the instance class, a DateTime is accepted.

Root cause

src/Facades/Cookie.php imports only:

use Josantonius\Cookie\Cookie as CookieInstance;
use Josantonius\Cookie\Exceptions\CookieException;

Without use DateTime;, the unqualified DateTime in the signatures is resolved
relative to the Josantonius\Cookie\Facades namespace.

Suggested fix

+use DateTime;
 use Josantonius\Cookie\Cookie as CookieInstance;
 use Josantonius\Cookie\Exceptions\CookieException;

Workaround

Pass a Unix timestamp:

Cookie::set('mode', 'barcode', (new DateTime())->modify('+3 months')->getTimestamp());

Environment

  • josantonius/cookie v2.0.7
  • PHP 8.2.9

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions