Add #[NoDiscard] to CarbonImmutable modify(), next(), previous() and __call()

On PHP 8.5, DateTimeImmutable::modify() warns when its result is
discarded, but CarbonImmutable overrides it and lost the attribute.
Override modify(), next(), previous() and __call() in CarbonImmutable
with #[NoDiscard] so a discarded result warns again. The attribute is
ignored on older PHP versions, and mutable Carbon is unchanged.

Existing immutable tests that discarded results now keep them; in
IsTest::testIsSameMonth this was a real slip, the loop never moved $dt.

Fixes #3377
This commit is contained in:
dualfroz committed 2026-10-03 02:24:35 +02:00
1 parent 8dc8cfa977
commit b3fc145df6
9 files changed
+143 -11

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\CarbonImmutable;
use Carbon\Carbon as MutableCarbon;
use Carbon\CarbonImmutable as Carbon;
use ErrorException;
use Generator;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhp;
use Tests\AbstractTestCase;
#[RequiresPhp('>=8.5.0')]
class NoDiscardTest extends AbstractTestCase
{
public static function dataForDiscardedCalls(): Generator
{
yield ['modify', ['+1 day']];
yield ['next', []];
yield ['previous', []];
yield ['addDays', [2]];
}
#[DataProvider('dataForDiscardedCalls')]
public function testDiscardedResultTriggersWarning(string $method, array $arguments): void
{
$this->expectException(ErrorException::class);
$this->expectExceptionMessage(
"The return value of method Carbon\\CarbonImmutable::$method() should either be used or intentionally ignored by casting it as (void)",
);
$date = Carbon::parse('2026-10-02 12:00');
$this->withErrorAsException(static function () use ($date, $method, $arguments) {
$date->$method(...$arguments);
});
}
public function testMutableResultCanBeDiscarded(): void
{
$date = MutableCarbon::parse('2026-10-02 12:00');
$this->withErrorAsException(static function () use ($date) {
$date->modify('+1 day');
$date->next();
$date->addDays(2);
});
$this->assertSame('2026-10-12 00:00:00', $date->format('Y-m-d H:i:s'));
}
}