Skip to content

Commit

Permalink
Revert "Drop support for Carbon 2"
Browse files Browse the repository at this point in the history
This reverts commit afd141c.
  • Loading branch information
duncanmcclean committed Feb 7, 2025
1 parent afd141c commit 11dad31
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"league/glide": "^2.3",
"maennchen/zipstream-php": "^3.1",
"michelf/php-smartypants": "^1.8.1",
"nesbot/carbon": "^3.0",
"nesbot/carbon": "^2.62.1 || ^3.0",
"pixelfear/composer-dist-plugin": "^0.1.4",
"rebing/graphql-laravel": "^9.7",
"rhukster/dom-sanitizer": "^1.0.6",
Expand Down
30 changes: 26 additions & 4 deletions src/Http/Middleware/Localize.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@ public function handle($request, Closure $next)
app()->setLocale($site->lang());

// Get original Carbon format so it can be restored later.
$reflection = new ReflectionClass($date = Date::now());
$factory = $reflection->getMethod('getFactory');
$factory->setAccessible(true);
$originalToStringFormat = Arr::get($factory->invoke($date)->getSettings(), 'toStringFormat');
$originalToStringFormat = $this->getToStringFormat();
Date::setToStringFormat(Statamic::dateFormat());

$response = $next($request);
Expand All @@ -47,4 +44,29 @@ public function handle($request, Closure $next)

return $response;
}

/**
* This method is used to get the current toStringFormat for Carbon, in order for us
* to restore it later. There's no getter for it, so we need to use reflection.
*
* @throws \ReflectionException
*/
private function getToStringFormat(): ?string
{
$reflection = new ReflectionClass($date = Date::now());

// Carbon 2.x
if ($reflection->hasProperty('toStringFormat')) {
$format = $reflection->getProperty('toStringFormat');
$format->setAccessible(true);

return $format->getValue();
}

// Carbon 3.x
$factory = $reflection->getMethod('getFactory');
$factory->setAccessible(true);

return Arr::get($factory->invoke($date)->getSettings(), 'toStringFormat');
}
}
6 changes: 6 additions & 0 deletions tests/Feature/GraphQL/Fieldtypes/DateFieldtypeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ public function setUp(): void
parent::setUp();

Carbon::macro('getToStringFormat', function () {
// Carbon 2.x
if (property_exists(static::this(), 'toStringFormat')) {
return static::$toStringFormat;
}

// Carbon 3.x
$reflection = new ReflectionClass(self::this());
$factory = $reflection->getMethod('getFactory');
$factory->setAccessible(true);
Expand Down

0 comments on commit 11dad31

Please sign in to comment.