Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating an Assert:datetime method #211

Open
JasonBenett opened this issue Jul 17, 2020 · 6 comments
Open

Creating an Assert:datetime method #211

JasonBenett opened this issue Jul 17, 2020 · 6 comments

Comments

@JasonBenett
Copy link

The goal is to create a fast way to assert that a string match a given date pattern. Something like:

Assert::datetime($myStringDate, 'Y-m-d H:i:s', 'My message');

What do you think about it ?

@zerkms
Copy link
Contributor

zerkms commented Jul 17, 2020

What is the suggested workflow?

Assert::datetime($myStringDate, 'Y-m-d H:i:s', 'My message');

$dt = \DateTime::createFromFormat('Y-m-d H:i:s', $myStringDate);
Assert::notNull($dt);

If something like ^ then the first assert looks redundant. Or you have something else in mind?

@JasonBenett
Copy link
Author

As a pure assertion, for me, the goal is not to create the datetime object but just controlling that the given string is a well formatted datetime. If, for instance, I extends this library to build assertions via PHP annotations, my goal will not be to create instances but just checking things such as Symfony Constraints do it for example.

It's useful when you receive some data from an API or when you are working with DTO for instance.

@JasonBenett
Copy link
Author

JasonBenett commented Nov 20, 2020

@zerkms What do you think about this idea? I saw there is a PR in that way too. We are currently asserting emails and uuids. Why should it be different for a date or a datetime given as a string?
I can create the PR without any problem :-)

@zerkms
Copy link
Contributor

zerkms commented Nov 20, 2020

I'm just another contributor not a core developer here :-)

If I led the project I wouldn't let emails and uuids as well, as I think those encapsulate too much of domain-specific knowledge.

@jokaorgua
Copy link

I would like to use such an assertion too.

@King2500
Copy link

King2500 commented Nov 11, 2022

What is the suggested workflow?

Assert::datetime($myStringDate, 'Y-m-d H:i:s', 'My message');

$dt = \DateTime::createFromFormat('Y-m-d H:i:s', $myStringDate);
Assert::notNull($dt);

If something like ^ then the first assert looks redundant. Or you have something else in mind?

I would rather call the above kind of check dateTimeFormat.

Under dateTime I would suggest this check:

try
{
    new \DateTime($dateTimeString);
    return true;
}
catch (\Exception $ex)
{
    return false;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants