Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
michalananapps opened this issue Nov 6, 2024 · 0 comments · Fixed by #197

Comments

@michalananapps
Copy link
Contributor

michalananapps commented Nov 6, 2024

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);
    }
}
michalananapps added a commit to michalananapps/DeepCopy that referenced this issue Nov 6, 2024
…es DatePeriod objects without modifying their readonly properties.
michalananapps added a commit to michalananapps/DeepCopy that referenced this issue Nov 7, 2024
mnapoli added a commit that referenced this issue Nov 8, 2024
bug: #196 Introduce a custom DatePeriodFilter that safely copies DatePeriod objects without modifying their readonly properties.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant