cakephp / chronos

A standalone DateTime library originally based off of Carbon

Home Page:http://book.cakephp.org/chronos

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] Is there a way to have chronos properly validate the input against request format?

andrei-dascalu opened this issue · comments

When using createFromFormat the behaviour seems to mimic the built-in PHP DateTime class which has some inconsistencies. Eg:

createFromFormat('Y-m-d', '20-11-11');

will produce 0020-11-11, padding digits instead of validating against the requested 4-digit year. Opposite that, Y-m-d H used against the same value will result in an error (false returned) as opposed to filling in the missing hour with zeroes.

Would it be possible for Chronos to provide some consistent alternatives that would enforce formats rather than randomly padding in various situations?

The only real alternative we have is ICU format parsing. That is supported in cakephp's I18n classes but not Chronos directly. I'm not sure if their 4-digit year formatter accepts 2 digits or not.

@othercorey In Chronos v2, the method getLastErrors would return warnings for improperly formatted dates in the sense that for example you would have 2021-11-11 10:90:30 there would be a warning that minutes are not valid (even if the minutes would be processed in an overflow way, result in the time 11:30:30) so that the user would be able to decide what to do.

However now that this method has been removed, I'm not sure how validation standards could be maintained on client side.
I thought Chronos v3 would be throwing errors in those cases where getLastErrors would return stuff, but it doesn't seem to be the case (completely).

We can re-introduce the getErrors() helper since Chronos still uses DateTimeImmutable for parsing. It's less obvious tha's happening in Chronos 3 since it doesn't extend DateTimeImmutable, but should be easy to document in the docblock.

Sounds good, that would be helpful to be able to retrieve the warnings.

I guess it's difficult to have a balance - personally I see logic in throwing an exception for invalid minutes / seconds rather than silently overflowing into unexpected values as PHP does by default but perhaps that's too much of a breaking behaviour?

In terms of other validation it would be great to have a sort of optional strict parsing mode that would throw exception if the string doesn't fit the pattern perfectly. I'm not sure how others feel about it.