Skip to content

Bug: deepcopy fails with DatePeriod - Cannot modify readonly property DatePeriod::$start #196

@michalananapps

Description

@michalananapps

Description

The deepcopy library throws an error when attempting to copy instances of PHP's DatePeriod due to the readonly property DatePeriod::$start. This issue arises because deepcopy tries to modify the $start property of DatePeriod, which is read-only as of PHP 8.2.

The error message is:

Cannot modify readonly property DatePeriod::$start

Proposed Solution

Introduce a custom DatePeriodFilter that safely copies DatePeriod objects without modifying their readonly properties.

Code Example for DatePeriodFilter

The following filter can be added to handle DatePeriod objects in deepcopy:

<?php

namespace DeepCopy\TypeFilter\Date;

use DatePeriod;
use DeepCopy\TypeFilter\TypeFilter;

/**
 * @final
 */
class DatePeriodFilter implements TypeFilter
{
    /**
     * {@inheritdoc}
     *
     * @param DatePeriod $element
     *
     * @see http://news.php.net/php.bugs/205076
     */
    public function apply($element)
    {
        $options = 0;
        if (PHP_VERSION_ID >= 80200 && $element->include_end_date) {
            $options |= DatePeriod::INCLUDE_END_DATE;
        }
        if (!$element->include_start_date) {
            $options |= DatePeriod::EXCLUDE_START_DATE;
        }

        if ($element->getEndDate()) {
            return new DatePeriod($element->getStartDate(), $element->getDateInterval(), $element->getEndDate(), $options);
        }

        return new DatePeriod($element->getStartDate(), $element->getDateInterval(), $element->getRecurrences(), $options);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions