Skip to content

Commit c5be777

Browse files
Fix Carbon::$toStringFormat error when using Carbon 3 (#195)
1 parent 1713855 commit c5be777

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

src/Generator.php

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@
88
use Illuminate\Filesystem\Filesystem;
99
use Illuminate\Routing\Router;
1010
use Illuminate\Support\Arr;
11+
use Illuminate\Support\Facades\Date;
1112
use League\Flysystem\Filesystem as Flysystem;
1213
use League\Flysystem\Local\LocalFilesystemAdapter;
14+
use ReflectionClass;
1315
use Statamic\Contracts\Imaging\UrlBuilder;
1416
use Statamic\Facades\Blink;
1517
use Statamic\Facades\Collection;
@@ -266,8 +268,7 @@ protected function makeContentGenerationClosures($pages, $request)
266268
$errors = [];
267269

268270
foreach ($pages as $page) {
269-
// There is no getter method, so use reflection.
270-
$oldCarbonFormat = (new \ReflectionClass(Carbon::class))->getStaticPropertyValue('toStringFormat');
271+
$oldCarbonFormat = $this->getToStringFormat();
271272

272273
if ($this->shouldSetCarbonFormat($page)) {
273274
Carbon::setToStringFormat(Statamic::dateFormat());
@@ -481,4 +482,29 @@ protected function shouldRejectPage($page, $outputError = false)
481482

482483
return $excluded;
483484
}
485+
486+
/**
487+
* This method is used to get the current toStringFormat for Carbon, in order for us
488+
* to restore it later. There's no getter for it, so we need to use reflection.
489+
*
490+
* @throws \ReflectionException
491+
*/
492+
protected function getToStringFormat(): ?string
493+
{
494+
$reflection = new ReflectionClass($date = Date::now());
495+
496+
// Carbon 2.x
497+
if ($reflection->hasProperty('toStringFormat')) {
498+
$format = $reflection->getProperty('toStringFormat');
499+
$format->setAccessible(true);
500+
501+
return $format->getValue();
502+
}
503+
504+
// Carbon 3.x
505+
$factory = $reflection->getMethod('getFactory');
506+
$factory->setAccessible(true);
507+
508+
return Arr::get($factory->invoke($date)->getSettings(), 'toStringFormat');
509+
}
484510
}

0 commit comments

Comments
 (0)