On Wed, Mar 3, 2021, at 4:37 AM, Moritz Friedrich wrote: > 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 `DateInterval`s 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?
I agree that easier round-tripping of interval data is a good thing. As for which approach to take, I think we should defer to Derick, or at least see what his input is. :-) I don't have a super strong preference between these 3 options, other than not liking the idea of tossing that off to user space. For better or worse DateTime is a core functionality and API, so it should be implemented in one place. Beyond that, whatever Derick feels is most consistent with the rest of the API is OK by me. Let's not bikeshed this into a larger overhaul of the whole DateTime API. :-) --Larry Garfield -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php