Re: Add __toString() to DateInterval

From: Date: Wed, 03 Mar 2021 10:53:40 +0000
Subject: Re: Add __toString() to DateInterval
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-113337@lists.php.net to get a copy of this message
Le 03/03/2021 à 11:37, Moritz Friedrich a écrit :
Hi internals, I’ve been active in the PHP ecosystem as @Radiergummi for quite a while now, but not on internals yet, so: nice to meet you all! I would like to propose adding a __toString() method to the DateInterval class that should return a valid ISO8601 interval (https://en.wikipedia.org/wiki/ISO_8601#Time_intervals). As it stands, the class supports creating instances from such interval strings passed to its constructor, but the reverse isn’t true: The only way to build a string representation of the interval is by querying the DateInterval::format method for the individual durations multiple times (see https://stackoverflow.com/questions/33787039/format-dateinterval-as-iso8601#answers for examples). Allowing to cast DateIntervals to strings would make the most sense in my opinion, and probably doesn’t break BC. Use cases include communicating with other APIs that work with ISO8601, or persistence of periods in databases, for example. So instead of the following:
     function formatDateInterval(DateInterval $interval, string $default = 'PT0S'): string {
         return rtrim(str_replace(
             ['M0S', 'H0M', 'DT0H', 'M0D', 'P0Y', 'Y0M', 'P0M'],
             ['M', 'H', 'DT', 'M', 'P', 'Y', 'P'],
             $interval->format('P%yY%mM%dDT%hH%iM%sS')
         ), 'PT') ?: $default;
     }
          formatDateInterval(new DateInterval('P1DT5H')) === 'P1DT5H'
I’d like to be able to do this:
     (string)new DateInterval('P1DT5H') === 'P1DT5H'
Following alternative approaches come to mind: 1. Adding a new, specialized method to the class (eg. DateInterval::toIsoString(): string):
    While being the most BC-safe option, this would be completely different to the rest of the PHP date APIs.
2. Adding a new interval format constant to be passed to DateInterval::format (eg. DATE_INTERVAL_ISO8601):
    Most in line with the DateTime API, but probably requires special case handling in format code.
From those, having __toString seems most desirable to me. While I’m not proficient with C, I’d really like to see this implemented and would gladly help out where I can. Might someone be able to advise? Sincerely Moritz / Radiergummi
Hello, I don't like implicit __toString() methods, they have to be very carefully documented and it's "magic". Wouldn't it be best to have both the toIsoString() and __toString() (as a fallback) methods ? Having the constant is a good idea too, it would make it probably more consistent with the DateTime class, I'm not opposed having three variations to do skin the same cat. Regards, Pierre

« previous php.internals (#113337) next »