Expose default strategy for URL normalization

This commit is contained in:
shalvah
2023-01-08 12:37:10 +01:00
parent 7cdf390364
commit 8fe91d86e6
2 changed files with 27 additions and 3 deletions

View File

@@ -87,10 +87,11 @@ class ExtractedEndpointData extends BaseDTO
parent::__construct($parameters);
$defaultNormalizer = fn() => UrlParamsNormalizer::normalizeParameterNamesInRouteUri($this->route, $this->method);
$this->uri = match (is_callable(Globals::$__normalizeEndpointUrlUsing)) {
true => call_user_func_array(Globals::$__normalizeEndpointUrlUsing,
[$this->route->uri, $this->route, $this->method, $this->controller]),
default => UrlParamsNormalizer::normalizeParameterNamesInRouteUri($this->route, $this->method),
[$this->route->uri, $this->route, $this->method, $this->controller, $defaultNormalizer]),
default => $defaultNormalizer(),
};
}

View File

@@ -32,7 +32,7 @@ class ExtractedEndpointDataTest extends BaseLaravelTest
/** @test */
public function allows_user_specified_normalization()
{
Scribe::normalizeEndpointUrlUsing(function (string $url, LaravelRoute $route, \ReflectionFunctionAbstract $method, ?\ReflectionClass $controller) {
Scribe::normalizeEndpointUrlUsing(function (string $url, LaravelRoute $route) {
if ($url == 'things/{thing}') return 'things/{the_id_of_the_thing}';
if ($route->named('things.otherthings.destroy')) return 'things/{thing-id}/otherthings/{other_thing-id}';
@@ -51,6 +51,29 @@ class ExtractedEndpointDataTest extends BaseLaravelTest
Scribe::normalizeEndpointUrlUsing(null);
}
/** @test */
public function allows_user_specified_normalization_fallback_to_default()
{
Scribe::normalizeEndpointUrlUsing(function (string $url, LaravelRoute $route,
\ReflectionFunctionAbstract $method, ?\ReflectionClass $controller, callable $default) {
if ($route->named('things.otherthings.destroy')) return 'things/{thing-id}/otherthings/{other_thing-id}';
return $default();
});
Route::apiResource('things', TestController::class)->only('show');
$route = $this->getRoute(['prefixes' => '*']);
$this->assertEquals('things/{thing}', $this->originalUri($route));
$this->assertEquals('things/{id}', $this->expectedUri($route));
Route::apiResource('things.otherthings', TestController::class)->only('destroy');
$route = $this->getRoute(['prefixes' => '*/otherthings/*']);
$this->assertEquals('things/{thing}/otherthings/{otherthing}', $this->originalUri($route));
$this->assertEquals('things/{thing-id}/otherthings/{other_thing-id}', $this->expectedUri($route));
Scribe::normalizeEndpointUrlUsing(null);
}
/** @test */
public function normalizes_resource_url_params_from_underscores_to_hyphens()
{