Skip to content

Commit

Permalink
Merge pull request #2857 from hettiger/feature/var-export-support-on-…
Browse files Browse the repository at this point in the history
…intervals

Add `var_export()` support for `CarbonInterval`
  • Loading branch information
kylekatarnls authored Sep 25, 2023
2 parents 8f4a735 + d23bb33 commit 9827623
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Carbon/CarbonInterval.php
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,23 @@ public static function __callStatic($method, $parameters)
}
}

/**
* Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance.
*
* @param array $dump data as exported by var_export()
*
* @return static
*/
#[ReturnTypeWillChange]
public static function __set_state($dump)
{
/** @noinspection PhpVoidFunctionResultUsedInspection */
/** @var DateInterval $dateInterval */
$dateInterval = parent::__set_state($dump);

return static::instance($dateInterval);
}

/**
* Return the current context from inside a macro callee or a new one if static.
*
Expand Down
38 changes: 38 additions & 0 deletions tests/CarbonInterval/SetStateTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Tests\CarbonInterval;

use Carbon\CarbonInterval;
use Tests\AbstractTestCase;

class SetStateTest extends AbstractTestCase
{
public function testEvaluatingVarExportReturnsCarbonIntervalInstance()
{
$export = var_export(CarbonInterval::minutes(3), true);

$this->assertInstanceOfCarbonInterval(eval("return $export;"));
}

public function testStateIsPreserved()
{
$serializedInterval = CarbonInterval::minutes(3);
$export = var_export($serializedInterval, true);

/** @var CarbonInterval $deserializedInterval */
$deserializedInterval = eval("return $export;");

$this->assertTrue($deserializedInterval->eq($serializedInterval));
}
}

0 comments on commit 9827623

Please sign in to comment.