Files
Tim Düsterhus 5f9eb6db8a date: Add comparison handler to Time\Duration (#23695)
As stated in the RFC:

> The Time\Duration class will also implement internal “comparison handlers”,
> which means that direct comparisons with operators such as < will work.
> Other operators (such as + for addition) will not be overloaded.
2026-09-16 09:26:50 +02:00

74 lines
2.8 KiB
C

/*
+----------------------------------------------------------------------+
| Copyright © The PHP Group and Contributors. |
+----------------------------------------------------------------------+
| This source file is subject to the Modified BSD License that is |
| bundled with this package in the file LICENSE, and is available |
| through the World Wide Web at <https://www.php.net/license/>. |
| |
| SPDX-License-Identifier: BSD-3-Clause |
+----------------------------------------------------------------------+
| Authors: Derick Rethans <derick@derickrethans.nl> |
| Tim Düsterhus <timwolla@php.net> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "Zend/zend_exceptions.h"
#include "php_time.h"
#include "time_arginfo.h"
zend_class_entry *php_date_ce_time_duration;
zend_class_entry *php_date_ce_time_timeexception;
static zend_object_handlers time_duration_object_handlers;
static zend_object *time_duration_object_create(zend_class_entry *ce)
{
php_date_time_duration *obj = zend_object_alloc(sizeof(*obj), ce);
zend_object_std_init(&obj->std, ce);
object_properties_init(&obj->std, ce);
timelib_duration_ctor_static(&obj->duration, /* seconds */ 0, /* nanoseconds */ 0, /* negative */ false);
return &obj->std;
}
static zend_object *time_duration_object_clone(zend_object *object)
{
const php_date_time_duration *obj = php_date_time_duration_from_obj(object);
php_date_time_duration *new_obj = php_date_time_duration_from_obj(object->ce->create_object(object->ce));
new_obj->duration = obj->duration;
zend_objects_clone_members(&new_obj->std, &obj->std);
return &new_obj->std;
}
static int time_duration_object_compare(zval *a, zval *b)
{
ZEND_COMPARE_OBJECTS_FALLBACK(a, b);
return timelib_duration_compare(&Z_DATE_TIME_DURATION_P(a)->duration, &Z_DATE_TIME_DURATION_P(b)->duration);
}
PHP_MINIT_FUNCTION(date_time)
{
/* Time\TimeException */
php_date_ce_time_timeexception = register_class_Time_TimeException(zend_ce_exception);
/* Time\Duration */
memcpy(&time_duration_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
time_duration_object_handlers.offset = offsetof(php_date_time_duration, std);
time_duration_object_handlers.clone_obj = time_duration_object_clone;
time_duration_object_handlers.compare = time_duration_object_compare;
php_date_ce_time_duration = register_class_Time_Duration();
php_date_ce_time_duration->create_object = time_duration_object_create;
php_date_ce_time_duration->default_object_handlers = &time_duration_object_handlers;
return SUCCESS;
}