repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
roots/sage
https://github.com/roots/sage/blob/7920ac9eae20e7f12e62f496a41561c5c48eca1b/resources/views/partials/comments.blade.php
resources/views/partials/comments.blade.php
@if (! post_password_required()) <section id="comments" class="comments"> @if ($responses()) <h2> {!! $title !!} </h2> <ol class="comment-list"> {!! $responses !!} </ol> @if ($paginated()) <nav aria-label="Comment"> <ul class="pager"> @if ($previous()) <li class="previous"> {!! $previous !!} </li> @endif @if ($next()) <li class="next"> {!! $next !!} </li> @endif </ul> </nav> @endif @endif @if ($closed()) <x-alert type="warning"> {!! __('Comments are closed.', 'sage') !!} </x-alert> @endif @php(comment_form()) </section> @endif
php
MIT
7920ac9eae20e7f12e62f496a41561c5c48eca1b
2026-01-04T15:02:59.095642Z
false
roots/sage
https://github.com/roots/sage/blob/7920ac9eae20e7f12e62f496a41561c5c48eca1b/resources/views/partials/entry-meta.blade.php
resources/views/partials/entry-meta.blade.php
<time class="dt-published" datetime="{{ get_post_time('c', true) }}"> {{ get_the_date() }} </time> <p> <span>{{ __('By', 'sage') }}</span> <a href="{{ get_author_posts_url(get_the_author_meta('ID')) }}" class="p-author h-card"> {{ get_the_author() }} </a> </p>
php
MIT
7920ac9eae20e7f12e62f496a41561c5c48eca1b
2026-01-04T15:02:59.095642Z
false
roots/sage
https://github.com/roots/sage/blob/7920ac9eae20e7f12e62f496a41561c5c48eca1b/resources/views/partials/content-single.blade.php
resources/views/partials/content-single.blade.php
<article @php(post_class('h-entry'))> <header> <h1 class="p-name"> {!! $title !!} </h1> @include('partials.entry-meta') </header> <div class="e-content"> @php(the_content()) </div> @if ($pagination()) <footer> <nav class="page-nav" aria-label="Page"> {!! $pagination !!} </nav> </footer> @endif @php(comments_template()) </article>
php
MIT
7920ac9eae20e7f12e62f496a41561c5c48eca1b
2026-01-04T15:02:59.095642Z
false
roots/sage
https://github.com/roots/sage/blob/7920ac9eae20e7f12e62f496a41561c5c48eca1b/resources/views/partials/content-page.blade.php
resources/views/partials/content-page.blade.php
@php(the_content()) @if ($pagination()) <nav class="page-nav" aria-label="Page"> {!! $pagination !!} </nav> @endif
php
MIT
7920ac9eae20e7f12e62f496a41561c5c48eca1b
2026-01-04T15:02:59.095642Z
false
roots/sage
https://github.com/roots/sage/blob/7920ac9eae20e7f12e62f496a41561c5c48eca1b/resources/views/layouts/app.blade.php
resources/views/layouts/app.blade.php
<!doctype html> <html @php(language_attributes())> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> @php(do_action('get_header')) @php(wp_head()) @vite(['resources/css/app.css', 'resources/js/app.js']) </head> <body @php(body_class())> @php(wp_body_open()) <div id="app"> <a class="sr-only focus:not-sr-only" href="#main"> {{ __('Skip to content', 'sage') }} </a> @include('sections.header') <main id="main" class="main"> @yield('content') </main> @hasSection('sidebar') <aside class="sidebar"> @yield('sidebar') </aside> @endif @include('sections.footer') </div> @php(do_action('get_footer')) @php(wp_footer()) </body> </html>
php
MIT
7920ac9eae20e7f12e62f496a41561c5c48eca1b
2026-01-04T15:02:59.095642Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/ResponseEmitterTest.php
tests/ResponseEmitterTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests; use ReflectionClass; use Slim\ResponseEmitter; use Slim\Tests\Assets\HeaderStack; use Slim\Tests\Mocks\MockStream; use Slim\Tests\Mocks\SlowPokeStream; use Slim\Tests\Mocks\SmallChunksStream; use function base64_decode; use function fopen; use function fwrite; use function in_array; use function popen; use function rewind; use function str_repeat; use function stream_filter_append; use function stream_filter_remove; use function stream_get_filters; use function strlen; use function trim; use const CONNECTION_ABORTED; use const CONNECTION_TIMEOUT; use const STREAM_FILTER_READ; use const STREAM_FILTER_WRITE; class ResponseEmitterTest extends TestCase { public function setUp(): void { HeaderStack::reset(); } public function tearDown(): void { HeaderStack::reset(); } public function testRespond(): void { $response = $this->createResponse(); $response->getBody()->write('Hello'); $responseEmitter = new ResponseEmitter(); $responseEmitter->emit($response); $this->expectOutputString('Hello'); } public function testRespondWithPaddedStreamFilterOutput(): void { $availableFilter = stream_get_filters(); $filterName = 'string.rot13'; $unfilterName = 'string.rot13'; $specificFilterName = 'string.rot13'; $specificUnfilterName = 'string.rot13'; if (in_array($filterName, $availableFilter) && in_array($unfilterName, $availableFilter)) { $key = base64_decode('xxxxxxxxxxxxxxxx'); $iv = base64_decode('Z6wNDk9LogWI4HYlRu0mng=='); $data = 'Hello'; $length = strlen($data); $stream = fopen('php://temp', 'r+'); $filter = stream_filter_append($stream, $specificFilterName, STREAM_FILTER_WRITE, [ 'key' => $key, 'iv' => $iv ]); fwrite($stream, $data); rewind($stream); stream_filter_remove($filter); stream_filter_append($stream, $specificUnfilterName, STREAM_FILTER_READ, [ 'key' => $key, 'iv' => $iv ]); $body = $this->getStreamFactory()->createStreamFromResource($stream); $response = $this ->createResponse() ->withHeader('Content-Length', $length) ->withBody($body); $responseEmitter = new ResponseEmitter(); $responseEmitter->emit($response); $this->expectOutputString('Hello'); } else { $this->assertTrue(true); } } public function testRespondIndeterminateLength(): void { $stream = fopen('php://temp', 'r+'); fwrite($stream, 'Hello'); rewind($stream); $body = $this ->getMockBuilder(MockStream::class) ->setConstructorArgs([$stream]) ->onlyMethods(['getSize']) ->getMock(); $body->method('getSize')->willReturn(null); $response = $this->createResponse()->withBody($body); $responseEmitter = new ResponseEmitter(); $responseEmitter->emit($response); $this->expectOutputString('Hello'); } public function testResponseWithStreamReadYieldingLessBytesThanAsked(): void { $body = new SmallChunksStream(); $response = $this->createResponse()->withBody($body); $responseEmitter = new ResponseEmitter($body::CHUNK_SIZE * 2); $responseEmitter->emit($response); $this->expectOutputString(str_repeat('.', $body->getSize())); } public function testResponseReplacesPreviouslySetHeaders(): void { $response = $this ->createResponse(200, 'OK') ->withHeader('X-Foo', 'baz1') ->withAddedHeader('X-Foo', 'baz2'); $responseEmitter = new ResponseEmitter(); $responseEmitter->emit($response); $expectedStack = [ ['header' => 'X-Foo: baz1', 'replace' => true, 'status_code' => null], ['header' => 'X-Foo: baz2', 'replace' => false, 'status_code' => null], ['header' => 'HTTP/1.1 200 OK', 'replace' => true, 'status_code' => 200], ]; $this->assertSame($expectedStack, HeaderStack::stack()); } public function testResponseDoesNotReplacePreviouslySetSetCookieHeaders(): void { $response = $this ->createResponse(200, 'OK') ->withHeader('set-cOOkie', 'foo=bar') ->withAddedHeader('Set-Cookie', 'bar=baz'); $responseEmitter = new ResponseEmitter(); $responseEmitter->emit($response); $expectedStack = [ ['header' => 'set-cOOkie: foo=bar', 'replace' => false, 'status_code' => null], ['header' => 'set-cOOkie: bar=baz', 'replace' => false, 'status_code' => null], ['header' => 'HTTP/1.1 200 OK', 'replace' => true, 'status_code' => 200], ]; $this->assertSame($expectedStack, HeaderStack::stack()); } public function testIsResponseEmptyWithNonEmptyBodyAndTriggeringStatusCode(): void { $body = $this->createStream('Hello'); $response = $this ->createResponse(204) ->withBody($body); $responseEmitter = new ResponseEmitter(); $this->assertTrue($responseEmitter->isResponseEmpty($response)); } public function testIsResponseEmptyDoesNotReadAllDataFromNonEmptySeekableResponse(): void { $body = $this->createStream('Hello'); $response = $this ->createResponse(200) ->withBody($body); $responseEmitter = new ResponseEmitter(); $responseEmitter->isResponseEmpty($response); $this->assertTrue($body->isSeekable()); $this->assertFalse($body->eof()); } public function testIsResponseEmptyDoesNotDrainNonSeekableResponseWithContent(): void { $resource = popen('echo 12', 'r'); $body = $this->getStreamFactory()->createStreamFromResource($resource); $response = $this->createResponse(200)->withBody($body); $responseEmitter = new ResponseEmitter(); $responseEmitter->isResponseEmpty($response); $this->assertFalse($body->isSeekable()); $this->assertSame('12', trim((string) $body)); } public function testAvoidReadFromSlowStreamAccordingToStatus(): void { $body = new SlowPokeStream(); $response = $this ->createResponse(204, 'No content') ->withBody($body); $responseEmitter = new ResponseEmitter(); $responseEmitter->emit($response); $this->assertFalse($body->eof()); $this->expectOutputString(''); } public function testIsResponseEmptyWithEmptyBody(): void { $response = $this->createResponse(200); $responseEmitter = new ResponseEmitter(); $this->assertTrue($responseEmitter->isResponseEmpty($response)); } public function testIsResponseEmptyWithZeroAsBody(): void { $body = $this->createStream('0'); $response = $this ->createResponse(200) ->withBody($body); $responseEmitter = new ResponseEmitter(); $this->assertFalse($responseEmitter->isResponseEmpty($response)); } public function testWillHandleInvalidConnectionStatusWithADeterminateBody(): void { $body = $this->getStreamFactory()->createStreamFromResource(fopen('php://temp', 'r+')); $body->write('Hello!' . "\n"); $body->write('Hello!' . "\n"); // Tell connection_status() to fail. $GLOBALS['connection_status_return'] = CONNECTION_ABORTED; $response = $this ->createResponse() ->withHeader('Content-Length', $body->getSize()) ->withBody($body); $responseEmitter = new ResponseEmitter(); $responseEmitter->emit($response); $this->expectOutputString("Hello!\nHello!\n"); // Tell connection_status() to pass. unset($GLOBALS['connection_status_return']); } public function testWillHandleInvalidConnectionStatusWithAnIndeterminateBody(): void { $body = $this->getStreamFactory()->createStreamFromResource(fopen('php://input', 'r+')); // Tell connection_status() to fail. $GLOBALS['connection_status_return'] = CONNECTION_TIMEOUT; $response = $this ->createResponse() ->withBody($body); $responseEmitter = new ResponseEmitter(); $mirror = new ReflectionClass(ResponseEmitter::class); $emitBodyMethod = $mirror->getMethod('emitBody'); $this->setAccessible($emitBodyMethod); $emitBodyMethod->invoke($responseEmitter, $response); $this->expectOutputString(""); // Tell connection_status() to pass. unset($GLOBALS['connection_status_return']); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/TestCase.php
tests/TestCase.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests; use PHPUnit\Framework\TestCase as PHPUnitTestCase; use Prophecy\PhpUnit\ProphecyTrait; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestFactoryInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; use Psr\Http\Server\RequestHandlerInterface; use ReflectionMethod; use ReflectionProperty; use Slim\CallableResolver; use Slim\Interfaces\CallableResolverInterface; use Slim\MiddlewareDispatcher; use Slim\Tests\Providers\PSR7ObjectProvider; abstract class TestCase extends PhpUnitTestCase { use ProphecyTrait; /** * @return ServerRequestFactoryInterface */ protected function getServerRequestFactory(): ServerRequestFactoryInterface { $psr7ObjectProvider = new PSR7ObjectProvider(); return $psr7ObjectProvider->getServerRequestFactory(); } /** * @return ResponseFactoryInterface */ protected function getResponseFactory(): ResponseFactoryInterface { $psr7ObjectProvider = new PSR7ObjectProvider(); return $psr7ObjectProvider->getResponseFactory(); } /** * @return StreamFactoryInterface */ protected function getStreamFactory(): StreamFactoryInterface { $psr7ObjectProvider = new PSR7ObjectProvider(); return $psr7ObjectProvider->getStreamFactory(); } /** * @param ContainerInterface|null $container * * @return CallableResolverInterface */ protected function getCallableResolver(?ContainerInterface $container = null): CallableResolverInterface { return new CallableResolver($container); } /** * @param RequestHandlerInterface $requestHandler * @param ContainerInterface|null $container * @param CallableResolverInterface|null $callableResolver * * @return MiddlewareDispatcher */ protected function createMiddlewareDispatcher( RequestHandlerInterface $requestHandler, ?ContainerInterface $container = null, ?CallableResolverInterface $callableResolver = null ): MiddlewareDispatcher { return new MiddlewareDispatcher( $requestHandler, $callableResolver ?? $this->getCallableResolver($container), $container ); } /** * @param string $uri * @param string $method * @param array $data * @return ServerRequestInterface */ protected function createServerRequest( string $uri, string $method = 'GET', array $data = [] ): ServerRequestInterface { $psr7ObjectProvider = new PSR7ObjectProvider(); return $psr7ObjectProvider->createServerRequest($uri, $method, $data); } /** * @param int $statusCode * @param string $reasonPhrase * @return ResponseInterface */ protected function createResponse(int $statusCode = 200, string $reasonPhrase = ''): ResponseInterface { $psr7ObjectProvider = new PSR7ObjectProvider(); return $psr7ObjectProvider->createResponse($statusCode, $reasonPhrase); } /** * @param string $contents * @return StreamInterface */ protected function createStream(string $contents = ''): StreamInterface { $psr7ObjectProvider = new PSR7ObjectProvider(); return $psr7ObjectProvider->createStream($contents); } /** * @param ReflectionProperty|ReflectionMethod $ref * @return void */ protected function setAccessible($ref, bool $accessible = true): void { if (PHP_VERSION_ID < 80100) { $ref->setAccessible($accessible); } } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/AppTest.php
tests/AppTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests; use Prophecy\Argument; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamInterface; use Psr\Http\Message\UriInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Psr\Log\LoggerInterface; use ReflectionClass; use ReflectionProperty; use RuntimeException; use Slim\App; use Slim\CallableResolver; use Slim\Exception\HttpMethodNotAllowedException; use Slim\Exception\HttpNotFoundException; use Slim\Handlers\Strategies\RequestResponseArgs; use Slim\Handlers\Strategies\RequestResponseNamedArgs; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\MiddlewareDispatcherInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteCollectorProxyInterface; use Slim\Interfaces\RouteParserInterface; use Slim\Middleware\BodyParsingMiddleware; use Slim\Middleware\ErrorMiddleware; use Slim\Middleware\RoutingMiddleware; use Slim\MiddlewareDispatcher; use Slim\Routing\RouteCollector; use Slim\Routing\RouteCollectorProxy; use Slim\Routing\RouteContext; use Slim\Tests\Mocks\MockAction; use stdClass; use function array_key_exists; use function array_shift; use function count; use function ini_set; use function json_encode; use function strtolower; use function sys_get_temp_dir; use function tempnam; class AppTest extends TestCase { public static function setupBeforeClass(): void { ini_set('error_log', tempnam(sys_get_temp_dir(), 'slim')); } public function testDoesNotUseContainerAsServiceLocator(): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $app = new App($responseFactoryProphecy->reveal(), $containerProphecy->reveal()); $containerProphecy->has(Argument::type('string'))->shouldNotHaveBeenCalled(); $containerProphecy->get(Argument::type('string'))->shouldNotHaveBeenCalled(); } /******************************************************************************** * Getter methods *******************************************************************************/ public function testGetContainer(): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $app = new App($responseFactoryProphecy->reveal(), $containerProphecy->reveal()); $this->assertSame($containerProphecy->reveal(), $app->getContainer()); } public function testGetCallableResolverReturnsInjectedInstance(): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $app = new App($responseFactoryProphecy->reveal(), null, $callableResolverProphecy->reveal()); $this->assertSame($callableResolverProphecy->reveal(), $app->getCallableResolver()); } public function testCreatesCallableResolverWhenNull(): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $callableResolver = new CallableResolver($containerProphecy->reveal()); $app = new App($responseFactoryProphecy->reveal(), $containerProphecy->reveal(), null); $this->assertEquals($callableResolver, $app->getCallableResolver()); } public function testGetRouteCollectorReturnsInjectedInstance(): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeParserProphecy = $this->prophesize(RouteParserInterface::class); $routeCollectorProphecy->getRouteParser()->willReturn($routeParserProphecy->reveal()); $app = new App($responseFactoryProphecy->reveal(), null, null, $routeCollectorProphecy->reveal()); $this->assertSame($routeCollectorProphecy->reveal(), $app->getRouteCollector()); } public function testCreatesRouteCollectorWhenNullWithInjectedContainer(): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), $containerProphecy->reveal() ); $app = new App( $responseFactoryProphecy->reveal(), $containerProphecy->reveal(), $callableResolverProphecy->reveal() ); $this->assertEquals($routeCollector, $app->getRouteCollector()); } public function testGetMiddlewareDispatcherGetsSeededAndReturnsInjectedInstance(): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $middlewareDispatcherProphecy = $this->prophesize(MiddlewareDispatcherInterface::class); $middlewareDispatcherProphecy ->seedMiddlewareStack(Argument::any()) ->shouldBeCalledOnce(); $app = new App( $responseFactoryProphecy->reveal(), null, null, null, null, $middlewareDispatcherProphecy->reveal() ); $this->assertSame($middlewareDispatcherProphecy->reveal(), $app->getMiddlewareDispatcher()); } public static function lowerCaseRequestMethodsProvider(): array { return [ ['get'], ['post'], ['put'], ['patch'], ['delete'], ['options'], ]; } /** * @param string $method * @dataProvider upperCaseRequestMethodsProvider() */ #[\PHPUnit\Framework\Attributes\DataProvider('upperCaseRequestMethodsProvider')] public function testGetPostPutPatchDeleteOptionsMethods(string $method): void { $streamProphecy = $this->prophesize(StreamInterface::class); $streamProphecy->__toString()->willReturn('Hello World'); $responseProphecy = $this->prophesize(ResponseInterface::class); $responseProphecy->getBody()->willReturn($streamProphecy->reveal()); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy->createResponse()->willReturn($responseProphecy->reveal()); $uriProphecy = $this->prophesize(UriInterface::class); $uriProphecy->getPath()->willReturn('/'); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $requestProphecy->getMethod()->willReturn($method); $requestProphecy->getUri()->willReturn($uriProphecy->reveal()); $requestProphecy->getAttribute(RouteContext::ROUTING_RESULTS)->willReturn(null); $requestProphecy->withAttribute(Argument::type('string'), Argument::any())->will(function ($args) { $this->getAttribute($args[0])->willReturn($args[1]); return $this; }); $methodName = strtolower($method); $app = new App($responseFactoryProphecy->reveal()); $app->$methodName('/', function (ServerRequestInterface $request, ResponseInterface $response) { return $response; }); $response = $app->handle($requestProphecy->reveal()); $this->assertSame('Hello World', (string) $response->getBody()); } public function testAnyRoute(): void { $streamProphecy = $this->prophesize(StreamInterface::class); $streamProphecy->__toString()->willReturn('Hello World'); $responseProphecy = $this->prophesize(ResponseInterface::class); $responseProphecy->getBody()->willReturn($streamProphecy->reveal()); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy->createResponse()->willReturn($responseProphecy->reveal()); $app = new App($responseFactoryProphecy->reveal()); $app->any('/', function (ServerRequestInterface $request, ResponseInterface $response) { return $response; }); foreach ($this->upperCaseRequestMethodsProvider() as $methods) { $method = $methods[0]; $uriProphecy = $this->prophesize(UriInterface::class); $uriProphecy->getPath()->willReturn('/'); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $requestProphecy->getMethod()->willReturn($method); $requestProphecy->getUri()->willReturn($uriProphecy->reveal()); $requestProphecy->getAttribute(RouteContext::ROUTING_RESULTS)->willReturn(null); $requestProphecy->withAttribute(Argument::type('string'), Argument::any())->will(function ($args) { $this->getAttribute($args[0])->willReturn($args[1]); return $this; }); $response = $app->handle($requestProphecy->reveal()); $this->assertSame('Hello World', (string) $response->getBody()); } } /******************************************************************************** * Route collector proxy methods *******************************************************************************/ public static function upperCaseRequestMethodsProvider(): array { return [ ['GET'], ['POST'], ['PUT'], ['PATCH'], ['DELETE'], ['OPTIONS'], ]; } /** * @param string $method * @dataProvider lowerCaseRequestMethodsProvider * @dataProvider upperCaseRequestMethodsProvider */ #[\PHPUnit\Framework\Attributes\DataProvider('lowerCaseRequestMethodsProvider')] #[\PHPUnit\Framework\Attributes\DataProvider('upperCaseRequestMethodsProvider')] public function testMapRoute(string $method): void { $streamProphecy = $this->prophesize(StreamInterface::class); $streamProphecy->__toString()->willReturn('Hello World'); $responseProphecy = $this->prophesize(ResponseInterface::class); $responseProphecy->getBody()->willReturn($streamProphecy->reveal()); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy->createResponse()->willReturn($responseProphecy->reveal()); $uriProphecy = $this->prophesize(UriInterface::class); $uriProphecy->getPath()->willReturn('/'); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $requestProphecy->getMethod()->willReturn($method); $requestProphecy->getUri()->willReturn($uriProphecy->reveal()); $requestProphecy->getAttribute(RouteContext::ROUTING_RESULTS)->willReturn(null); $requestProphecy->withAttribute(Argument::type('string'), Argument::any())->will(function ($args) { $this->getAttribute($args[0])->willReturn($args[1]); return $this; }); $app = new App($responseFactoryProphecy->reveal()); $app->map([$method], '/', function (ServerRequestInterface $request, ResponseInterface $response) { return $response; }); $response = $app->handle($requestProphecy->reveal()); $this->assertSame('Hello World', (string) $response->getBody()); } public function testRedirectRoute(): void { $from = '/from'; $to = '/to'; $routeCreatedResponse = $this->prophesize(ResponseInterface::class); $handlerCreatedResponse = $this->prophesize(ResponseInterface::class); $handlerCreatedResponse->getStatusCode()->willReturn(301); $handlerCreatedResponse->getHeaderLine('Location')->willReturn($to); $handlerCreatedResponse->withHeader( Argument::type('string'), Argument::type('string') )->will(function ($args) { $this->getHeader($args[0])->willReturn($args[1]); return $this; }); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy->createResponse()->willReturn($routeCreatedResponse->reveal()); $responseFactoryProphecy->createResponse(301)->willReturn($handlerCreatedResponse->reveal()); $uriProphecy = $this->prophesize(UriInterface::class); $uriProphecy->getPath()->willReturn($from); $uriProphecy->__toString()->willReturn($to); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $requestProphecy->getMethod()->willReturn('GET'); $requestProphecy->getUri()->willReturn($uriProphecy->reveal()); $requestProphecy->getAttribute(RouteContext::ROUTING_RESULTS)->willReturn(null); $requestProphecy->withAttribute(Argument::type('string'), Argument::any())->will(function ($args) { $this->getAttribute($args[0])->willReturn($args[1]); return $this; }); $app = new App($responseFactoryProphecy->reveal()); $app->redirect($from, $to, 301); $response = $app->handle($requestProphecy->reveal()); $responseFactoryProphecy->createResponse(301)->shouldHaveBeenCalled(); $this->assertSame(301, $response->getStatusCode()); $this->assertSame($to, $response->getHeaderLine('Location')); } public function testRouteWithInternationalCharacters(): void { $path = '/новости'; $streamProphecy = $this->prophesize(StreamInterface::class); $streamProphecy->__toString()->willReturn('Hello World'); $responseProphecy = $this->prophesize(ResponseInterface::class); $responseProphecy->getBody()->willReturn($streamProphecy->reveal()); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy->createResponse()->willReturn($responseProphecy->reveal()); $app = new App($responseFactoryProphecy->reveal()); $app->get($path, function () use ($responseProphecy) { return $responseProphecy->reveal(); }); $uriProphecy = $this->prophesize(UriInterface::class); $uriProphecy->getPath()->willReturn($path); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $requestProphecy->getMethod()->willReturn('GET'); $requestProphecy->getUri()->willReturn($uriProphecy->reveal()); $requestProphecy->getAttribute(RouteContext::ROUTING_RESULTS)->willReturn(null); $requestProphecy->withAttribute(Argument::type('string'), Argument::any())->will(function ($args) { $this->getAttribute($args[0])->willReturn($args[1]); return $this; }); $response = $app->handle($requestProphecy->reveal()); $this->assertInstanceOf(ResponseInterface::class, $response); $this->assertSame('Hello World', (string) $response->getBody()); } /******************************************************************************** * Route Patterns *******************************************************************************/ public static function routePatternsProvider(): array { return [ [''], // Empty Route ['/'], // Single Slash Route ['foo'], // Route That Does Not Start With A Slash ['/foo'], // Route That Does Not End In A Slash ['/foo/'], // Route That Ends In A Slash ]; } /** * @param string $pattern * @dataProvider routePatternsProvider */ #[\PHPUnit\Framework\Attributes\DataProvider('routePatternsProvider')] public function testRoutePatterns(string $pattern): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $app = new App($responseFactoryProphecy->reveal()); $app->get($pattern, function () { }); $routeCollector = $app->getRouteCollector(); $route = $routeCollector->lookupRoute('route0'); $this->assertSame($pattern, $route->getPattern()); } /******************************************************************************** * Route Groups *******************************************************************************/ public static function routeGroupsDataProvider(): array { return [ 'empty group with empty route' => [ ['', ''], '' ], 'empty group with single slash route' => [ ['', '/'], '/' ], 'empty group with segment route that does not end in aSlash' => [ ['', '/foo'], '/foo' ], 'empty group with segment route that ends in aSlash' => [ ['', '/foo/'], '/foo/' ], 'group single slash with empty route' => [ ['/', ''], '/' ], 'group single slash with single slash route' => [ ['/', '/'], '//' ], 'group single slash with segment route that does not end in aSlash' => [ ['/', '/foo'], '//foo' ], 'group single slash with segment route that ends in aSlash' => [ ['/', '/foo/'], '//foo/' ], 'group segment with empty route' => [ ['/foo', ''], '/foo' ], 'group segment with single slash route' => [ ['/foo', '/'], '/foo/' ], 'group segment with segment route that does not end in aSlash' => [ ['/foo', '/bar'], '/foo/bar' ], 'group segment with segment route that ends in aSlash' => [ ['/foo', '/bar/'], '/foo/bar/' ], 'empty group with nested group segment with an empty route' => [ ['', '/foo', ''], '/foo' ], 'empty group with nested group segment with single slash route' => [ ['', '/foo', '/'], '/foo/' ], 'group single slash with empty nested group and segment route without leading slash' => [ ['/', '', 'foo'], '/foo' ], 'group single slash with empty nested group and segment route' => [ ['/', '', '/foo'], '//foo' ], 'group single slash with single slash group and segment route without leading slash' => [ ['/', '/', 'foo'], '//foo' ], 'group single slash with single slash nested group and segment route' => [ ['/', '/', '/foo'], '///foo' ], 'group single slash with nested group segment with an empty route' => [ ['/', '/foo', ''], '//foo' ], 'group single slash with nested group segment with single slash route' => [ ['/', '/foo', '/'], '//foo/' ], 'group single slash with nested group segment with segment route' => [ ['/', '/foo', '/bar'], '//foo/bar' ], 'group single slash with nested group segment with segment route that has aTrailing slash' => [ ['/', '/foo', '/bar/'], '//foo/bar/' ], 'empty group with empty nested group and segment route without leading slash' => [ ['', '', 'foo'], 'foo' ], 'empty group with empty nested group and segment route' => [ ['', '', '/foo'], '/foo' ], 'empty group with single slash group and segment route without leading slash' => [ ['', '/', 'foo'], '/foo' ], 'empty group with single slash nested group and segment route' => [ ['', '/', '/foo'], '//foo' ], 'empty group with nested group segment with segment route' => [ ['', '/foo', '/bar'], '/foo/bar' ], 'empty group with nested group segment with segment route that has aTrailing slash' => [ ['', '/foo', '/bar/'], '/foo/bar/' ], 'group segment with empty nested group and segment route without leading slash' => [ ['/foo', '', 'bar'], '/foobar' ], 'group segment with empty nested group and segment route' => [ ['/foo', '', '/bar'], '/foo/bar' ], 'group segment with single slash nested group and segment route' => [ ['/foo', '/', 'bar'], '/foo/bar' ], 'group segment with single slash nested group and slash segment route' => [ ['/foo', '/', '/bar'], '/foo//bar' ], 'two group segments with empty route' => [ ['/foo', '/bar', ''], '/foo/bar' ], 'two group segments with single slash route' => [ ['/foo', '/bar', '/'], '/foo/bar/' ], 'two group segments with segment route' => [ ['/foo', '/bar', '/baz'], '/foo/bar/baz' ], 'two group segments with segment route that has aTrailing slash' => [ ['/foo', '/bar', '/baz/'], '/foo/bar/baz/' ], ]; } public function testGroupClosureIsBoundToThisClass(): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $app = new App($responseFactoryProphecy->reveal()); $testCase = $this; $app->group('/foo', function () use ($testCase) { $testCase->assertSame($testCase, $this); }); } /** * @dataProvider routeGroupsDataProvider * @param array $sequence * @param string $expectedPath */ #[\PHPUnit\Framework\Attributes\DataProvider('routeGroupsDataProvider')] public function testRouteGroupCombinations(array $sequence, string $expectedPath): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $app = new App($responseFactoryProphecy->reveal()); $processSequence = function (RouteCollectorProxy $app, array $sequence, $processSequence) { $path = array_shift($sequence); /** * If sequence isn't on last element we use $app->group() * The very tail of the sequence uses the $app->get() method */ if (count($sequence)) { $app->group($path, function (RouteCollectorProxy $group) use (&$sequence, $processSequence) { $processSequence($group, $sequence, $processSequence); }); } else { $app->get($path, function () { }); } }; $processSequence($app, $sequence, $processSequence); $routeCollector = $app->getRouteCollector(); $route = $routeCollector->lookupRoute('route0'); $this->assertSame($expectedPath, $route->getPattern()); } public function testRouteGroupPattern(): void { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); /** @var ResponseFactoryInterface $responseFactoryInterface */ $responseFactoryInterface = $responseFactoryProphecy->reveal(); $app = new App($responseFactoryInterface); $group = $app->group('/foo', function () { }); $this->assertSame('/foo', $group->getPattern()); } /******************************************************************************** * Middleware *******************************************************************************/ public function testAddMiddleware(): void { $streamProphecy = $this->prophesize(StreamInterface::class); $streamProphecy->__toString()->willReturn('Hello World'); $responseProphecy = $this->prophesize(ResponseInterface::class); $responseProphecy->getBody()->willReturn($streamProphecy->reveal()); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy->createResponse()->willReturn($responseProphecy->reveal()); $app = new App($responseFactoryProphecy->reveal()); $middlewareProphecy = $this->prophesize(MiddlewareInterface::class); $middlewareProphecy->process(Argument::cetera())->will(function () use ($responseProphecy) { return $responseProphecy->reveal(); }); $middlewareProphecy2 = $this->prophesize(MiddlewareInterface::class); $middlewareProphecy2->process( Argument::type(ServerRequestInterface::class), Argument::type(RequestHandlerInterface::class) )->will(function ($args) { /** @var ServerRequestInterface $request */ $request = $args[0]; /** @var RequestHandlerInterface $handler */ $handler = $args[1]; return $handler->handle($request); }); $app->add($middlewareProphecy->reveal()); $app->addMiddleware($middlewareProphecy2->reveal()); $app->get('/', function (ServerRequestInterface $request, $response) { return $response; }); $uriProphecy = $this->prophesize(UriInterface::class); $uriProphecy->getPath()->willReturn('/'); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $requestProphecy->getMethod()->willReturn('GET'); $requestProphecy->getUri()->willReturn($uriProphecy->reveal()); $requestProphecy->getAttribute(RouteContext::ROUTING_RESULTS)->willReturn(null); $requestProphecy->withAttribute(Argument::type('string'), Argument::any())->will(function ($args) { $this->getAttribute($args[0])->willReturn($args[1]); return $this; }); $response = $app->handle($requestProphecy->reveal()); $middlewareProphecy->process( Argument::type(ServerRequestInterface::class), Argument::type(RequestHandlerInterface::class) )->shouldHaveBeenCalled(); $middlewareProphecy2->process( Argument::type(ServerRequestInterface::class), Argument::type(RequestHandlerInterface::class) )->shouldHaveBeenCalled(); $this->assertSame($responseProphecy->reveal(), $response); } public function testAddMiddlewareUsingDeferredResolution(): void { $streamProphecy = $this->prophesize(StreamInterface::class); $streamProphecy->__toString()->willReturn('Hello World'); $responseProphecy = $this->prophesize(ResponseInterface::class); $responseProphecy->getBody()->willReturn($streamProphecy->reveal()); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy->createResponse()->willReturn($responseProphecy->reveal()); $middlewareProphecy = $this->prophesize(MiddlewareInterface::class); $middlewareProphecy->process(Argument::cetera())->willReturn($responseProphecy->reveal()); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy->has('middleware')->willReturn(true); $containerProphecy->get('middleware')->willReturn($middlewareProphecy); $app = new App($responseFactoryProphecy->reveal(), $containerProphecy->reveal()); $app->add('middleware'); $app->get('/', function (ServerRequestInterface $request, ResponseInterface $response) { return $response; }); $uriProphecy = $this->prophesize(UriInterface::class); $uriProphecy->getPath()->willReturn('/'); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $requestProphecy->getMethod()->willReturn('GET'); $requestProphecy->getUri()->willReturn($uriProphecy->reveal()); $response = $app->handle($requestProphecy->reveal()); $this->assertSame('Hello World', (string) $response->getBody()); } public function testAddRoutingMiddleware(): void { /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $this->prophesize(ResponseFactoryInterface::class)->reveal(); // Create the app. $app = new App($responseFactory); // Add the routing middleware. $routingMiddleware = $app->addRoutingMiddleware(); // Check that the routing middleware really has been added to the tip of the app middleware stack. $middlewareDispatcherProperty = new ReflectionProperty(App::class, 'middlewareDispatcher'); $this->setAccessible($middlewareDispatcherProperty); /** @var MiddlewareDispatcher $middlewareDispatcher */ $middlewareDispatcher = $middlewareDispatcherProperty->getValue($app); $tipProperty = new ReflectionProperty(MiddlewareDispatcher::class, 'tip'); $this->setAccessible($tipProperty); /** @var RequestHandlerInterface $tip */ $tip = $tipProperty->getValue($middlewareDispatcher); $reflection = new ReflectionClass($tip); $middlewareProperty = $reflection->getProperty('middleware'); $this->setAccessible($middlewareProperty); $this->assertSame($routingMiddleware, $middlewareProperty->getValue($tip)); $this->assertInstanceOf(RoutingMiddleware::class, $routingMiddleware); } public function testAddErrorMiddleware(): void { /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $this->prophesize(ResponseFactoryInterface::class)->reveal(); /** @var LoggerInterface $logger */ $logger = $this->prophesize(LoggerInterface::class)->reveal(); // Create the app. $app = new App($responseFactory); // Add the error middleware. $errorMiddleware = $app->addErrorMiddleware(true, true, true, $logger); // Check that the error middleware really has been added to the tip of the app middleware stack. $middlewareDispatcherProperty = new ReflectionProperty(App::class, 'middlewareDispatcher'); $this->setAccessible($middlewareDispatcherProperty); /** @var MiddlewareDispatcher $middlewareDispatcher */ $middlewareDispatcher = $middlewareDispatcherProperty->getValue($app); $tipProperty = new ReflectionProperty(MiddlewareDispatcher::class, 'tip'); $this->setAccessible($tipProperty); /** @var RequestHandlerInterface $tip */ $tip = $tipProperty->getValue($middlewareDispatcher); $reflection = new ReflectionClass($tip); $middlewareProperty = $reflection->getProperty('middleware'); $this->setAccessible($middlewareProperty); $this->assertSame($errorMiddleware, $middlewareProperty->getValue($tip)); $this->assertInstanceOf(ErrorMiddleware::class, $errorMiddleware); } public function testAddBodyParsingMiddleware(): void { /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $this->prophesize(ResponseFactoryInterface::class)->reveal(); // Create the app. $app = new App($responseFactory); // Add the error middleware. $bodyParsingMiddleware = $app->addBodyParsingMiddleware(); // Check that the body parsing middleware really has been added to the tip of the app middleware stack. $middlewareDispatcherProperty = new ReflectionProperty(App::class, 'middlewareDispatcher'); $this->setAccessible($middlewareDispatcherProperty); /** @var MiddlewareDispatcher $middlewareDispatcher */ $middlewareDispatcher = $middlewareDispatcherProperty->getValue($app); $tipProperty = new ReflectionProperty(MiddlewareDispatcher::class, 'tip'); $this->setAccessible($tipProperty); /** @var RequestHandlerInterface $tip */ $tip = $tipProperty->getValue($middlewareDispatcher); $reflection = new ReflectionClass($tip); $middlewareProperty = $reflection->getProperty('middleware'); $this->setAccessible($middlewareProperty);
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
true
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/CallableResolverTest.php
tests/CallableResolverTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use Psr\Container\ContainerInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; use Slim\CallableResolver; use Slim\Tests\Mocks\CallableTest; use Slim\Tests\Mocks\InvokableTest; use Slim\Tests\Mocks\MiddlewareTest; use Slim\Tests\Mocks\RequestHandlerTest; class CallableResolverTest extends TestCase { private ObjectProphecy $containerProphecy; public static function setUpBeforeClass(): void { function testAdvancedCallable() { return true; } } public function setUp(): void { CallableTest::$CalledCount = 0; InvokableTest::$CalledCount = 0; RequestHandlerTest::$CalledCount = 0; $this->containerProphecy = $this->prophesize(ContainerInterface::class); $this->containerProphecy->has(Argument::type('string'))->willReturn(false); } public function testClosure(): void { $test = function () { return true; }; $resolver = new CallableResolver(); // No container injected $callable = $resolver->resolve($test); $callableRoute = $resolver->resolveRoute($test); $callableMiddleware = $resolver->resolveMiddleware($test); $this->assertTrue($callable()); $this->assertTrue($callableRoute()); $this->assertTrue($callableMiddleware()); } public function testClosureContainer(): void { $this->containerProphecy->has('ultimateAnswer')->willReturn(true); $this->containerProphecy->get('ultimateAnswer')->willReturn(42); $that = $this; $test = function () use ($that) { $that->assertInstanceOf(ContainerInterface::class, $this); /** @var ContainerInterface $this */ return $this->get('ultimateAnswer'); }; /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $callable = $resolver->resolve($test); $callableRoute = $resolver->resolveRoute($test); $callableMiddleware = $resolver->resolveMiddleware($test); $this->assertSame(42, $callable()); $this->assertSame(42, $callableRoute()); $this->assertSame(42, $callableMiddleware()); } public function testFunctionName(): void { $resolver = new CallableResolver(); // No container injected $callable = $resolver->resolve(__NAMESPACE__ . '\testAdvancedCallable'); $callableRoute = $resolver->resolveRoute(__NAMESPACE__ . '\testAdvancedCallable'); $callableMiddleware = $resolver->resolveMiddleware(__NAMESPACE__ . '\testAdvancedCallable'); $this->assertTrue($callable()); $this->assertTrue($callableRoute()); $this->assertTrue($callableMiddleware()); } public function testObjMethodArray(): void { $obj = new CallableTest(); $resolver = new CallableResolver(); // No container injected $callable = $resolver->resolve([$obj, 'toCall']); $callableRoute = $resolver->resolveRoute([$obj, 'toCall']); $callableMiddleware = $resolver->resolveMiddleware([$obj, 'toCall']); $callable(); $this->assertSame(1, CallableTest::$CalledCount); $callableRoute(); $this->assertSame(2, CallableTest::$CalledCount); $callableMiddleware(); $this->assertSame(3, CallableTest::$CalledCount); } public function testSlimCallable(): void { $resolver = new CallableResolver(); // No container injected $callable = $resolver->resolve('Slim\Tests\Mocks\CallableTest:toCall'); $callableRoute = $resolver->resolveRoute('Slim\Tests\Mocks\CallableTest:toCall'); $callableMiddleware = $resolver->resolveMiddleware('Slim\Tests\Mocks\CallableTest:toCall'); $callable(); $this->assertSame(1, CallableTest::$CalledCount); $callableRoute(); $this->assertSame(2, CallableTest::$CalledCount); $callableMiddleware(); $this->assertSame(3, CallableTest::$CalledCount); } public function testSlimCallableAsArray(): void { $resolver = new CallableResolver(); // No container injected $callable = $resolver->resolve([CallableTest::class, 'toCall']); $callableRoute = $resolver->resolveRoute([CallableTest::class, 'toCall']); $callableMiddleware = $resolver->resolveMiddleware([CallableTest::class, 'toCall']); $callable(); $this->assertSame(1, CallableTest::$CalledCount); $callableRoute(); $this->assertSame(2, CallableTest::$CalledCount); $callableMiddleware(); $this->assertSame(3, CallableTest::$CalledCount); } public function testSlimCallableContainer(): void { /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolve('Slim\Tests\Mocks\CallableTest:toCall'); $this->assertSame($container, CallableTest::$CalledContainer); CallableTest::$CalledContainer = null; $resolver->resolveRoute('Slim\Tests\Mocks\CallableTest:toCall'); $this->assertSame($container, CallableTest::$CalledContainer); CallableTest::$CalledContainer = null; $resolver->resolveMiddleware('Slim\Tests\Mocks\CallableTest:toCall'); $this->assertSame($container, CallableTest::$CalledContainer); } public function testSlimCallableAsArrayContainer(): void { /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolve([CallableTest::class, 'toCall']); $this->assertSame($container, CallableTest::$CalledContainer); CallableTest::$CalledContainer = null; $resolver->resolveRoute([CallableTest::class, 'toCall']); $this->assertSame($container, CallableTest::$CalledContainer); CallableTest::$CalledContainer = null; $resolver->resolveMiddleware([CallableTest::class ,'toCall']); $this->assertSame($container, CallableTest::$CalledContainer); } public function testContainer(): void { $this->containerProphecy->has('callable_service')->willReturn(true); $this->containerProphecy->get('callable_service')->willReturn(new CallableTest()); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $callable = $resolver->resolve('callable_service:toCall'); $callableRoute = $resolver->resolveRoute('callable_service:toCall'); $callableMiddleware = $resolver->resolveMiddleware('callable_service:toCall'); $callable(); $this->assertSame(1, CallableTest::$CalledCount); $callableRoute(); $this->assertSame(2, CallableTest::$CalledCount); $callableMiddleware(); $this->assertSame(3, CallableTest::$CalledCount); } public function testResolutionToAnInvokableClassInContainer(): void { $this->containerProphecy->has('an_invokable')->willReturn(true); $this->containerProphecy->get('an_invokable')->willReturn(new InvokableTest()); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $callable = $resolver->resolve('an_invokable'); $callableRoute = $resolver->resolveRoute('an_invokable'); $callableMiddleware = $resolver->resolveMiddleware('an_invokable'); $callable(); $this->assertSame(1, InvokableTest::$CalledCount); $callableRoute(); $this->assertSame(2, InvokableTest::$CalledCount); $callableMiddleware(); $this->assertSame(3, InvokableTest::$CalledCount); } public function testResolutionToAnInvokableClass(): void { $resolver = new CallableResolver(); // No container injected $callable = $resolver->resolve('Slim\Tests\Mocks\InvokableTest'); $callableRoute = $resolver->resolveRoute('Slim\Tests\Mocks\InvokableTest'); $callableMiddleware = $resolver->resolveMiddleware('Slim\Tests\Mocks\InvokableTest'); $callable(); $this->assertSame(1, InvokableTest::$CalledCount); $callableRoute(); $this->assertSame(2, InvokableTest::$CalledCount); $callableMiddleware(); $this->assertSame(3, InvokableTest::$CalledCount); } public function testResolutionToAPsrRequestHandlerClass(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Slim\\Tests\\Mocks\\RequestHandlerTest is not resolvable'); $resolver = new CallableResolver(); // No container injected $resolver->resolve(RequestHandlerTest::class); } public function testRouteResolutionToAPsrRequestHandlerClass(): void { $request = $this->createServerRequest('/', 'GET'); $resolver = new CallableResolver(); // No container injected $callableRoute = $resolver->resolveRoute(RequestHandlerTest::class); $callableRoute($request); $this->assertSame(1, RequestHandlerTest::$CalledCount); } public function testMiddlewareResolutionToAPsrRequestHandlerClass(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Slim\\Tests\\Mocks\\RequestHandlerTest is not resolvable'); $resolver = new CallableResolver(); // No container injected $resolver->resolveMiddleware(RequestHandlerTest::class); } public function testObjPsrRequestHandlerClass(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('{} is not resolvable'); $obj = new RequestHandlerTest(); $resolver = new CallableResolver(); // No container injected $resolver->resolve($obj); } public function testRouteObjPsrRequestHandlerClass(): void { $obj = new RequestHandlerTest(); $request = $this->createServerRequest('/', 'GET'); $resolver = new CallableResolver(); // No container injected $callableRoute = $resolver->resolveRoute($obj); $callableRoute($request); $this->assertSame(1, RequestHandlerTest::$CalledCount); } public function testMiddlewareObjPsrRequestHandlerClass(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('{} is not resolvable'); $obj = new RequestHandlerTest(); $resolver = new CallableResolver(); // No container injected $resolver->resolveMiddleware($obj); } public function testObjPsrRequestHandlerClassInContainer(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('a_requesthandler is not resolvable'); $this->containerProphecy->has('a_requesthandler')->willReturn(true); $this->containerProphecy->get('a_requesthandler')->willReturn(new RequestHandlerTest()); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolve('a_requesthandler'); } public function testRouteObjPsrRequestHandlerClassInContainer(): void { $this->containerProphecy->has('a_requesthandler')->willReturn(true); $this->containerProphecy->get('a_requesthandler')->willReturn(new RequestHandlerTest()); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $request = $this->createServerRequest('/', 'GET'); $resolver = new CallableResolver($container); $callable = $resolver->resolveRoute('a_requesthandler'); $callable($request); $this->assertSame(1, RequestHandlerTest::$CalledCount); } public function testMiddlewareObjPsrRequestHandlerClassInContainer(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('a_requesthandler is not resolvable'); $this->containerProphecy->has('a_requesthandler')->willReturn(true); $this->containerProphecy->get('a_requesthandler')->willReturn(new RequestHandlerTest()); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolveMiddleware('a_requesthandler'); } public function testResolutionToAPsrRequestHandlerClassWithCustomMethod(): void { $resolver = new CallableResolver(); // No container injected $callable = $resolver->resolve(RequestHandlerTest::class . ':custom'); $callableRoute = $resolver->resolveRoute(RequestHandlerTest::class . ':custom'); $callableMiddleware = $resolver->resolveMiddleware(RequestHandlerTest::class . ':custom'); $this->assertIsArray($callable); $this->assertInstanceOf(RequestHandlerTest::class, $callable[0]); $this->assertSame('custom', $callable[1]); $this->assertIsArray($callableRoute); $this->assertInstanceOf(RequestHandlerTest::class, $callableRoute[0]); $this->assertSame('custom', $callableRoute[1]); $this->assertIsArray($callableMiddleware); $this->assertInstanceOf(RequestHandlerTest::class, $callableMiddleware[0]); $this->assertSame('custom', $callableMiddleware[1]); } public function testObjMiddlewareClass(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('{} is not resolvable'); $obj = new MiddlewareTest(); $resolver = new CallableResolver(); // No container injected $resolver->resolve($obj); } public function testRouteObjMiddlewareClass(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('{} is not resolvable'); $obj = new MiddlewareTest(); $resolver = new CallableResolver(); // No container injected $resolver->resolveRoute($obj); } public function testMiddlewareObjMiddlewareClass(): void { $obj = new MiddlewareTest(); $request = $this->createServerRequest('/', 'GET'); $resolver = new CallableResolver(); // No container injected $callableRouteMiddleware = $resolver->resolveMiddleware($obj); $callableRouteMiddleware($request, $this->createMock(RequestHandlerInterface::class)); $this->assertSame(1, MiddlewareTest::$CalledCount); } public function testNotObjectInContainerThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('callable_service container entry is not an object'); $this->containerProphecy->has('callable_service')->willReturn(true); $this->containerProphecy->get('callable_service')->willReturn('NOT AN OBJECT'); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolve('callable_service'); } public function testMethodNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('callable_service:notFound is not resolvable'); $this->containerProphecy->has('callable_service')->willReturn(true); $this->containerProphecy->get('callable_service')->willReturn(new CallableTest()); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolve('callable_service:notFound'); } public function testRouteMethodNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('callable_service:notFound is not resolvable'); $this->containerProphecy->has('callable_service')->willReturn(true); $this->containerProphecy->get('callable_service')->willReturn(new CallableTest()); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolveRoute('callable_service:notFound'); } public function testMiddlewareMethodNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('callable_service:notFound is not resolvable'); $this->containerProphecy->has('callable_service')->willReturn(true); $this->containerProphecy->get('callable_service')->willReturn(new CallableTest()); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolveMiddleware('callable_service:notFound'); } public function testFunctionNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Callable notFound does not exist'); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolve('notFound'); } public function testRouteFunctionNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Callable notFound does not exist'); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolveRoute('notFound'); } public function testMiddlewareFunctionNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Callable notFound does not exist'); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolveMiddleware('notFound'); } public function testClassNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Callable Unknown::notFound() does not exist'); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolve('Unknown:notFound'); } public function testRouteClassNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Callable Unknown::notFound() does not exist'); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolveRoute('Unknown:notFound'); } public function testMiddlewareClassNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Callable Unknown::notFound() does not exist'); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolveMiddleware('Unknown:notFound'); } public function testCallableClassNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Callable Unknown::notFound() does not exist'); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolve(['Unknown', 'notFound']); } public function testRouteCallableClassNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Callable Unknown::notFound() does not exist'); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolveRoute(['Unknown', 'notFound']); } public function testMiddlewareCallableClassNotFoundThrowException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Callable Unknown::notFound() does not exist'); /** @var ContainerInterface $container */ $container = $this->containerProphecy->reveal(); $resolver = new CallableResolver($container); $resolver->resolveMiddleware(['Unknown', 'notFound']); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/bootstrap.php
tests/bootstrap.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); use AdrianSuter\Autoload\Override\Override; use Slim\ResponseEmitter; use Slim\Routing\RouteCollector; use Slim\Tests\Assets\HeaderStack; $classLoader = require __DIR__ . '/../vendor/autoload.php'; Override::apply($classLoader, [ ResponseEmitter::class => [ 'connection_status' => function (): int { if (isset($GLOBALS['connection_status_return'])) { return $GLOBALS['connection_status_return']; } return connection_status(); }, 'header' => function (string $string, bool $replace = true, ?int $statusCode = null): void { HeaderStack::push( [ 'header' => $string, 'replace' => $replace, 'status_code' => $statusCode, ] ); }, 'headers_sent' => function (): bool { return false; } ], RouteCollector::class => [ 'is_readable' => function (string $file): bool { return stripos($file, 'non-readable.cache') === false; }, 'is_writable' => function (string $path): bool { return stripos($path, 'non-writable-directory') === false; } ] ]);
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/MiddlewareDispatcherTest.php
tests/MiddlewareDispatcherTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests; use Prophecy\Argument; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; use Slim\Interfaces\CallableResolverInterface; use Slim\Tests\Mocks\MockMiddlewareSlimCallable; use Slim\Tests\Mocks\MockMiddlewareWithConstructor; use Slim\Tests\Mocks\MockMiddlewareWithoutConstructor; use Slim\Tests\Mocks\MockRequestHandler; use Slim\Tests\Mocks\MockSequenceMiddleware; use stdClass; class MiddlewareDispatcherTest extends TestCase { public static function setUpBeforeClass(): void { function testProcessRequest(ServerRequestInterface $request, RequestHandlerInterface $handler) { return $handler->handle($request); } } public function testAddMiddleware(): void { $responseFactory = $this->getResponseFactory(); $callable = function ($request, $handler) use ($responseFactory) { return $responseFactory->createResponse(); }; $requestProphecy = $this->prophesize(ServerRequestInterface::class); $requestHandlerProphecy = $this->prophesize(RequestHandlerInterface::class); $middlewareDispatcher = $this->createMiddlewareDispatcher($requestHandlerProphecy->reveal()); $middlewareDispatcher->add($callable); $response = $middlewareDispatcher->handle($requestProphecy->reveal()); $this->assertInstanceOf(ResponseInterface::class, $response); } public function testNamedFunctionIsResolved(): void { $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, null); $middlewareDispatcher->addDeferred(__NAMESPACE__ . '\testProcessRequest'); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); $this->assertSame(1, $handler->getCalledCount()); } public function testDeferredResolvedCallable(): void { $callable = function (ServerRequestInterface $request, RequestHandlerInterface $handler) { return $handler->handle($request); }; $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy ->has('callable') ->willReturn(true) ->shouldBeCalledOnce(); $containerProphecy ->get('callable') ->willReturn($callable) ->shouldBeCalledOnce(); $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, $containerProphecy->reveal()); $middlewareDispatcher->addDeferred('callable'); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); $this->assertSame(1, $handler->getCalledCount()); } public function testDeferredResolvedCallableWithoutContainerAndNonAdvancedCallableResolver(): void { $callable = function (ServerRequestInterface $request, RequestHandlerInterface $handler) { return $handler->handle($request); }; $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $callableResolverProphecy ->resolve('callable') ->willReturn($callable) ->shouldBeCalledOnce(); $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, null, $callableResolverProphecy->reveal()); $middlewareDispatcher->addDeferred('callable'); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); $this->assertSame(1, $handler->getCalledCount()); } public function testDeferredResolvedCallableWithDirectConstructorCall(): void { $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $callableResolverProphecy ->resolve(MockMiddlewareWithoutConstructor::class) ->willThrow(new RuntimeException('Callable not available from resolver')) ->shouldBeCalledOnce(); $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, null, $callableResolverProphecy->reveal()); $middlewareDispatcher->addDeferred(MockMiddlewareWithoutConstructor::class); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); $this->assertSame(1, $handler->getCalledCount()); } public static function deferredCallableProvider(): array { return [ [MockMiddlewareSlimCallable::class . ':custom', new MockMiddlewareSlimCallable()], ['MiddlewareInstance', new MockMiddlewareWithoutConstructor()], ['NamedFunction', __NAMESPACE__ . '\testProcessRequest'], ['Callable', function (ServerRequestInterface $request, RequestHandlerInterface $handler) { return $handler->handle($request); }], ['MiddlewareInterfaceNotImplemented', 'MiddlewareInterfaceNotImplemented'] ]; } /** * @dataProvider deferredCallableProvider * * @param string $callable * @param callable|MiddlewareInterface */ #[\PHPUnit\Framework\Attributes\DataProvider('deferredCallableProvider')] public function testDeferredResolvedCallableWithContainerAndNonAdvancedCallableResolverUnableToResolveCallable( $callable, $result ): void { if ($callable === 'MiddlewareInterfaceNotImplemented') { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Middleware MiddlewareInterfaceNotImplemented is not resolvable'); } $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $callableResolverProphecy ->resolve($callable) ->willThrow(RuntimeException::class) ->shouldBeCalledOnce(); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy ->has(Argument::any()) ->willReturn(true) ->shouldBeCalledOnce(); $containerProphecy ->get(Argument::any()) ->willReturn($result) ->shouldBeCalledOnce(); $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher( $handler, $containerProphecy->reveal(), $callableResolverProphecy->reveal() ); $middlewareDispatcher->addDeferred($callable); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); $this->assertSame(1, $handler->getCalledCount()); } public function testDeferredResolvedSlimCallable(): void { $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, null); $middlewareDispatcher->addDeferred(MockMiddlewareSlimCallable::class . ':custom'); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); $this->assertSame(1, $handler->getCalledCount()); } public function testDeferredResolvedClosureIsBoundToContainer(): void { $containerProphecy = $this->prophesize(ContainerInterface::class); $self = $this; $callable = function ( ServerRequestInterface $request, RequestHandlerInterface $handler ) use ($self) { $self->assertInstanceOf(ContainerInterface::class, $this); return $handler->handle($request); }; $containerProphecy->has('callable')->willReturn(true); $containerProphecy->get('callable')->willReturn($callable); $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, $containerProphecy->reveal()); $middlewareDispatcher->addDeferred('callable'); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); } public function testAddCallableBindsClosureToContainer(): void { $containerProphecy = $this->prophesize(ContainerInterface::class); $self = $this; $callable = function ( ServerRequestInterface $request, RequestHandlerInterface $handler ) use ( $self, $containerProphecy ) { $self->assertSame($containerProphecy->reveal(), $this); return $handler->handle($request); }; $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, $containerProphecy->reveal()); $middlewareDispatcher->addCallable($callable); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); } public function testResolvableReturnsInstantiatedObject(): void { MockMiddlewareWithoutConstructor::$CalledCount = 0; $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, null); $middlewareDispatcher->addDeferred(MockMiddlewareWithoutConstructor::class); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); $this->assertSame(1, MockMiddlewareWithoutConstructor::$CalledCount); $this->assertSame(1, $handler->getCalledCount()); } public function testResolveThrowsExceptionWhenResolvableDoesNotImplementMiddlewareInterface(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('MiddlewareInterfaceNotImplemented is not resolvable'); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy ->has('MiddlewareInterfaceNotImplemented') ->willReturn(true) ->shouldBeCalledOnce(); $containerProphecy ->get('MiddlewareInterfaceNotImplemented') ->willReturn(new stdClass()) ->shouldBeCalledOnce(); $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, $containerProphecy->reveal()); $middlewareDispatcher->addDeferred('MiddlewareInterfaceNotImplemented'); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); } public function testResolveThrowsExceptionWithoutContainerAndUnresolvableClass(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessageMatches('/(Middleware|Callable) Unresolvable::class does not exist/'); $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, null); $middlewareDispatcher->addDeferred('Unresolvable::class'); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); } public function testResolveThrowsExceptionWithoutContainerNonAdvancedCallableResolverAndUnresolvableClass(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessageMatches('/(Middleware|Callable) Unresolvable::class does not exist/'); $unresolvable = 'Unresolvable::class'; $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $callableResolverProphecy ->resolve($unresolvable) ->willThrow(RuntimeException::class) ->shouldBeCalledOnce(); $handler = new MockRequestHandler(); $middlewareDispatcher = $this->createMiddlewareDispatcher($handler, null, $callableResolverProphecy->reveal()); $middlewareDispatcher->addDeferred($unresolvable); $request = $this->createServerRequest('/'); $middlewareDispatcher->handle($request); } public function testExecutesKernelWithEmptyMiddlewareStack(): void { $requestProphecy = $this->prophesize(ServerRequestInterface::class); $responseProphecy = $this->prophesize(ResponseInterface::class); $kernelProphecy = $this->prophesize(RequestHandlerInterface::class); $kernelProphecy->handle(Argument::type(ServerRequestInterface::class))->willReturn($responseProphecy->reveal()); /** @var RequestHandlerInterface $kernel */ $kernel = $kernelProphecy->reveal(); $dispatcher = $this->createMiddlewareDispatcher($kernel, null); $response = $dispatcher->handle($requestProphecy->reveal()); $kernelProphecy->handle(Argument::type(ServerRequestInterface::class))->shouldHaveBeenCalled(); $this->assertSame($responseProphecy->reveal(), $response); } public function testExecutesMiddlewareLastInFirstOut(): void { $requestProphecy = $this->prophesize(ServerRequestInterface::class); $requestProphecy->getHeader(Argument::type('string'))->willReturn([]); $requestProphecy->withAddedHeader(Argument::type('string'), Argument::type('string'))->will(function ($args) { $headers = $this->reveal()->getHeader($args[0]); $headers[] = $args[1]; $this->getHeader($args[0])->willReturn($headers); $this->hasHeader($args[0])->willReturn(true); return $this; }); $responseProphecy = $this->prophesize(ResponseInterface::class); $responseProphecy->getHeader(Argument::type('string'))->willReturn([]); $responseProphecy->withHeader(Argument::type('string'), Argument::type('array'))->will(function ($args) { $this->getHeader($args[0])->willReturn($args[1]); $this->hasHeader($args[0])->willReturn(true); return $this; }); $responseProphecy->withAddedHeader(Argument::type('string'), Argument::type('string'))->will(function ($args) { $headers = $this->reveal()->getHeader($args[0]); $headers[] = $args[1]; $this->getHeader($args[0])->willReturn($headers); $this->hasHeader($args[0])->willReturn(true); return $this; }); $responseProphecy->withStatus(Argument::type('int'))->will(function ($args) { $this->getStatusCode()->willReturn($args[0]); return $this; }); $kernelProphecy = $this->prophesize(RequestHandlerInterface::class); $kernelProphecy->handle(Argument::type(ServerRequestInterface::class)) ->will(function ($args) use ($responseProphecy): ResponseInterface { $request = $args[0]; return $responseProphecy->reveal() ->withStatus(204) ->withHeader('X-SEQ-PRE-REQ-HANDLER', $request->getHeader('X-SEQ-PRE-REQ-HANDLER')); }); $middleware0Prophecy = $this->prophesize(MiddlewareInterface::class); $middleware0Prophecy ->process( Argument::type(ServerRequestInterface::class), Argument::type(RequestHandlerInterface::class) ) ->will(function ($args): ResponseInterface { return $args[1]->handle($args[0]->withAddedHeader('X-SEQ-PRE-REQ-HANDLER', '0')) ->withAddedHeader('X-SEQ-POST-REQ-HANDLER', '0'); }); $middleware1Prophecy = $this->prophesize(MiddlewareInterface::class); $middleware1Prophecy ->process( Argument::type(ServerRequestInterface::class), Argument::type(RequestHandlerInterface::class) ) ->will(function ($args): ResponseInterface { return $args[1]->handle($args[0]->withAddedHeader('X-SEQ-PRE-REQ-HANDLER', '1')) ->withAddedHeader('X-SEQ-POST-REQ-HANDLER', '1'); }); MockSequenceMiddleware::$id = '2'; $middleware3Prophecy = $this->prophesize(MiddlewareInterface::class); $middleware3Prophecy ->process( Argument::type(ServerRequestInterface::class), Argument::type(RequestHandlerInterface::class) ) ->will(function ($args): ResponseInterface { return $args[1]->handle($args[0]->withAddedHeader('X-SEQ-PRE-REQ-HANDLER', '3')) ->withAddedHeader('X-SEQ-POST-REQ-HANDLER', '3'); }); /** @var RequestHandlerInterface $kernel */ $kernel = $kernelProphecy->reveal(); $dispatcher = $this->createMiddlewareDispatcher($kernel, null); $dispatcher->add($middleware0Prophecy->reveal()); $dispatcher->addMiddleware($middleware1Prophecy->reveal()); $dispatcher->addDeferred(MockSequenceMiddleware::class); $dispatcher->add($middleware3Prophecy->reveal()); $response = $dispatcher->handle($requestProphecy->reveal()); $this->assertSame(['3', '2', '1', '0'], $response->getHeader('X-SEQ-PRE-REQ-HANDLER')); $this->assertSame(['0', '1', '2', '3'], $response->getHeader('X-SEQ-POST-REQ-HANDLER')); $this->assertSame(204, $response->getStatusCode()); } public function testDoesNotInstantiateDeferredMiddlewareInCaseOfAnEarlyReturningOuterMiddleware(): void { $kernelProphecy = $this->prophesize(RequestHandlerInterface::class); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $responseProphecy = $this->prophesize(ResponseInterface::class); $middlewareProphecy = $this->prophesize(MiddlewareInterface::class); $middlewareProphecy->process(Argument::cetera())->willReturn($responseProphecy->reveal()); MockSequenceMiddleware::$hasBeenInstantiated = false; /** @var RequestHandlerInterface $kernel */ $kernel = $kernelProphecy->reveal(); $dispatcher = $this->createMiddlewareDispatcher($kernel, null); $dispatcher->addDeferred(MockSequenceMiddleware::class); $dispatcher->addMiddleware($middlewareProphecy->reveal()); $response = $dispatcher->handle($requestProphecy->reveal()); $this->assertFalse(MockSequenceMiddleware::$hasBeenInstantiated); $this->assertSame($responseProphecy->reveal(), $response); $kernelProphecy->handle(Argument::type(ServerRequestInterface::class))->shouldNotHaveBeenCalled(); } public function testThrowsExceptionForDeferredNonMiddlewareInterfaceClasses(): void { $this->expectException(RuntimeException::class); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $kernelProphecy = $this->prophesize(RequestHandlerInterface::class); /** @var RequestHandlerInterface $kernel */ $kernel = $kernelProphecy->reveal(); $dispatcher = $this->createMiddlewareDispatcher($kernel, null); $dispatcher->addDeferred(stdClass::class); $dispatcher->handle($requestProphecy->reveal()); $kernelProphecy->handle(Argument::type(ServerRequestInterface::class))->shouldNotHaveBeenCalled(); } public function testCanBeExecutedMultipleTimes(): void { $requestProphecy = $this->prophesize(ServerRequestInterface::class); $responseProphecy = $this->prophesize(ResponseInterface::class); $kernelProphecy = $this->prophesize(RequestHandlerInterface::class); $middlewareProphecy = $this->prophesize(MiddlewareInterface::class); $middlewareProphecy->process(Argument::cetera())->willReturn($responseProphecy->reveal()); /** @var RequestHandlerInterface $kernel */ $kernel = $kernelProphecy->reveal(); $dispatcher = $this->createMiddlewareDispatcher($kernel, null); $dispatcher->add($middlewareProphecy->reveal()); $response1 = $dispatcher->handle($requestProphecy->reveal()); $response2 = $dispatcher->handle($requestProphecy->reveal()); $this->assertSame($responseProphecy->reveal(), $response1); $this->assertSame($responseProphecy->reveal(), $response2); $kernelProphecy->handle(Argument::type(ServerRequestInterface::class))->shouldNotHaveBeenCalled(); } public function testCanBeReExecutedRecursivelyDuringDispatch(): void { $requestProphecy = $this->prophesize(ServerRequestInterface::class); $responseProphecy = $this->prophesize(ResponseInterface::class); $kernelProphecy = $this->prophesize(RequestHandlerInterface::class); $requestProphecy->hasHeader('X-NESTED')->willReturn(false); $requestProphecy->withAddedHeader('X-NESTED', '1')->will(function () { $this->hasHeader('X-NESTED')->willReturn(true); return $this; }); $responseProphecy->getHeader(Argument::type('string'))->willReturn([]); $responseProphecy->withAddedHeader(Argument::type('string'), Argument::type('string'))->will(function ($args) { $headers = $this->reveal()->getHeader($args[0]); $headers[] = $args[1]; $this->getHeader($args[0])->willReturn($headers); $this->hasHeader($args[0])->willReturn(true); return $this; }); /** @var RequestHandlerInterface $kernel */ $kernel = $kernelProphecy->reveal(); $dispatcher = $this->createMiddlewareDispatcher($kernel, null); $middlewareProphecy = $this->prophesize(MiddlewareInterface::class); $middlewareProphecy ->process( Argument::type(ServerRequestInterface::class), Argument::type(RequestHandlerInterface::class) ) ->will(function ($args) use ($dispatcher, $responseProphecy): ResponseInterface { $request = $args[0]; if ($request->hasHeader('X-NESTED')) { return $responseProphecy->reveal()->withAddedHeader('X-TRACE', 'nested'); } $response = $dispatcher->handle($request->withAddedHeader('X-NESTED', '1')); return $response->withAddedHeader('X-TRACE', 'outer'); }); $dispatcher->add($middlewareProphecy->reveal()); $response = $dispatcher->handle($requestProphecy->reveal()); $this->assertSame(['nested', 'outer'], $response->getHeader('X-TRACE')); } public function testFetchesMiddlewareFromContainer(): void { $kernelProphecy = $this->prophesize(RequestHandlerInterface::class); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $responseProphecy = $this->prophesize(ResponseInterface::class); $middlewareProphecy = $this->prophesize(MiddlewareInterface::class); $middlewareProphecy->process(Argument::cetera())->willReturn($responseProphecy->reveal()); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy->has('somemiddlewarename')->willReturn(true); $containerProphecy->get('somemiddlewarename')->willReturn($middlewareProphecy->reveal()); /** @var ContainerInterface $container */ $container = $containerProphecy->reveal(); /** @var RequestHandlerInterface $kernel */ $kernel = $kernelProphecy->reveal(); $dispatcher = $this->createMiddlewareDispatcher($kernel, $container); $dispatcher->addDeferred('somemiddlewarename'); $response = $dispatcher->handle($requestProphecy->reveal()); $this->assertSame($responseProphecy->reveal(), $response); $kernelProphecy->handle(Argument::type(ServerRequestInterface::class))->shouldNotHaveBeenCalled(); } public function testMiddlewareGetsInstantiatedWithContainer(): void { $kernelProphecy = $this->prophesize(RequestHandlerInterface::class); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy->has(MockMiddlewareWithConstructor::class)->willReturn(false); /** @var ContainerInterface $container */ $container = $containerProphecy->reveal(); /** @var RequestHandlerInterface $kernel */ $kernel = $kernelProphecy->reveal(); $dispatcher = $this->createMiddlewareDispatcher($kernel, $container); $dispatcher->addDeferred(MockMiddlewareWithConstructor::class); $dispatcher->handle($requestProphecy->reveal()); $this->assertSame($containerProphecy->reveal(), MockMiddlewareWithConstructor::$container); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Routing/RouteRunnerTest.php
tests/Routing/RouteRunnerTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Routing; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Slim\MiddlewareDispatcher; use Slim\Routing\RouteCollector; use Slim\Routing\RouteContext; use Slim\Routing\RouteParser; use Slim\Routing\RouteResolver; use Slim\Routing\RouteRunner; use Slim\Routing\RoutingResults; use Slim\Tests\TestCase; class RouteRunnerTest extends TestCase { public function testRoutingIsPerformedIfRoutingResultsAreUnavailable() { $handler = (function (ServerRequestInterface $request, ResponseInterface $response) { $routeParser = $request->getAttribute(RouteContext::ROUTE_PARSER); $this->assertInstanceOf(RouteParser::class, $routeParser); $routingResults = $request->getAttribute(RouteContext::ROUTING_RESULTS); $this->assertInstanceOf(RoutingResults::class, $routingResults); return $response; })->bindTo($this); $callableResolver = $this->getCallableResolver(); $responseFactory = $this->getResponseFactory(); $routeCollector = new RouteCollector($responseFactory, $callableResolver); $routeCollector->map(['GET'], '/hello/{name}', $handler); $routeParser = new RouteParser($routeCollector); $routeResolver = new RouteResolver($routeCollector); $request = $this->createServerRequest('https://example.com:443/hello/foo', 'GET'); $dispatcher = new RouteRunner($routeResolver, $routeParser); $middlewareDispatcher = new MiddlewareDispatcher($dispatcher, $callableResolver); $middlewareDispatcher->handle($request); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Routing/FastRouteDispatcherTest.php
tests/Routing/FastRouteDispatcherTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Routing; use FastRoute\BadRouteException; use FastRoute\DataGenerator\GroupCountBased; use FastRoute\RouteCollector; use Slim\Routing\FastRouteDispatcher; use Slim\Tests\TestCase; use function FastRoute\simpleDispatcher; class FastRouteDispatcherTest extends TestCase { /** * @dataProvider provideFoundDispatchCases */ #[\PHPUnit\Framework\Attributes\DataProvider('provideFoundDispatchCases')] public function testFoundDispatches($method, $uri, $callback, $handler, $argDict) { /** @var FastRouteDispatcher $dispatcher */ $dispatcher = simpleDispatcher($callback, $this->generateDispatcherOptions()); $results = $dispatcher->dispatch($method, $uri); $this->assertSame($dispatcher::FOUND, $results[0]); $this->assertSame($handler, $results[1]); $this->assertSame($argDict, $results[2]); } /** * Set appropriate options for the specific Dispatcher class we're testing */ private function generateDispatcherOptions() { return [ 'dataGenerator' => $this->getDataGeneratorClass(), 'dispatcher' => $this->getDispatcherClass() ]; } protected function getDataGeneratorClass() { return GroupCountBased::class; } protected function getDispatcherClass() { return FastRouteDispatcher::class; } /** * @dataProvider provideNotFoundDispatchCases */ #[\PHPUnit\Framework\Attributes\DataProvider('provideNotFoundDispatchCases')] public function testNotFoundDispatches($method, $uri, $callback) { /** @var FastRouteDispatcher $dispatcher */ $dispatcher = simpleDispatcher($callback, $this->generateDispatcherOptions()); $results = $dispatcher->dispatch($method, $uri); $this->assertSame($dispatcher::NOT_FOUND, $results[0]); } /** * @dataProvider provideMethodNotAllowedDispatchCases * @param $method * @param $uri * @param $callback * @param $allowedMethods */ #[\PHPUnit\Framework\Attributes\DataProvider('provideMethodNotAllowedDispatchCases')] public function testMethodNotAllowedDispatches($method, $uri, $callback, $allowedMethods) { /** @var FastRouteDispatcher $dispatcher */ $dispatcher = simpleDispatcher($callback, $this->generateDispatcherOptions()); $results = $dispatcher->dispatch($method, $uri); $this->assertSame($dispatcher::METHOD_NOT_ALLOWED, $results[0]); } /** * @dataProvider provideMethodNotAllowedDispatchCases * @param $method * @param $uri * @param $callback * @param $allowedMethods */ #[\PHPUnit\Framework\Attributes\DataProvider('provideMethodNotAllowedDispatchCases')] public function testGetAllowedMethods($method, $uri, $callback, $allowedMethods) { /** @var FastRouteDispatcher $dispatcher */ $dispatcher = simpleDispatcher($callback, $this->generateDispatcherOptions()); $results = $dispatcher->getAllowedMethods($uri); $this->assertSame($results, $allowedMethods); } public function testDuplicateVariableNameError() { $this->expectException(BadRouteException::class); $this->expectExceptionMessage('Cannot use the same placeholder "test" twice'); simpleDispatcher(function (RouteCollector $r) { $r->addRoute('GET', '/foo/{test}/{test:\d+}', 'handler0'); }, $this->generateDispatcherOptions()); } public function testDuplicateVariableRoute() { $this->expectException(BadRouteException::class); $this->expectExceptionMessage('Cannot register two routes matching "/user/([^/]+)" for method "GET"'); simpleDispatcher(function (RouteCollector $r) { $r->addRoute('GET', '/user/{id}', 'handler0'); // oops, forgot \d+ restriction ;) $r->addRoute('GET', '/user/{name}', 'handler1'); }, $this->generateDispatcherOptions()); } public function testDuplicateStaticRoute() { $this->expectException(BadRouteException::class); $this->expectExceptionMessage('Cannot register two routes matching "/user" for method "GET"'); simpleDispatcher(function (RouteCollector $r) { $r->addRoute('GET', '/user', 'handler0'); $r->addRoute('GET', '/user', 'handler1'); }, $this->generateDispatcherOptions()); } /** * @codingStandardsIgnoreStart * @codingStandardsIgnoreEnd */ public function testShadowedStaticRoute() { $this->expectException(BadRouteException::class); $this->expectExceptionMessage('Static route "/user/nikic" is shadowed by previously defined variable route' . ' "/user/([^/]+)" for method "GET"'); simpleDispatcher(function (RouteCollector $r) { $r->addRoute('GET', '/user/{name}', 'handler0'); $r->addRoute('GET', '/user/nikic', 'handler1'); }, $this->generateDispatcherOptions()); } public function testCapturing() { $this->expectException(BadRouteException::class); $this->expectExceptionMessage('Regex "(en|de)" for parameter "lang" contains a capturing group'); simpleDispatcher(function (RouteCollector $r) { $r->addRoute('GET', '/{lang:(en|de)}', 'handler0'); }, $this->generateDispatcherOptions()); } public static function provideFoundDispatchCases() { $cases = []; // 0 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/resource/123/456', 'handler0'); }; $method = 'GET'; $uri = '/resource/123/456'; $handler = 'handler0'; $argDict = []; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 1 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/handler0', 'handler0'); $r->addRoute('GET', '/handler1', 'handler1'); $r->addRoute('GET', '/handler2', 'handler2'); }; $method = 'GET'; $uri = '/handler2'; $handler = 'handler2'; $argDict = []; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 2 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0'); $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1'); $r->addRoute('GET', '/user/{name}', 'handler2'); }; $method = 'GET'; $uri = '/user/rdlowrey'; $handler = 'handler2'; $argDict = ['name' => 'rdlowrey']; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 3 --------------------------------------------------------------------------------------> // reuse $callback from #2 $method = 'GET'; $uri = '/user/12345'; $handler = 'handler1'; $argDict = ['id' => '12345']; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 4 --------------------------------------------------------------------------------------> // reuse $callback from #3 $method = 'GET'; $uri = '/user/NaN'; $handler = 'handler2'; $argDict = ['name' => 'NaN']; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 5 --------------------------------------------------------------------------------------> // reuse $callback from #4 $method = 'GET'; $uri = '/user/rdlowrey/12345'; $handler = 'handler0'; $argDict = ['name' => 'rdlowrey', 'id' => '12345']; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 6 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler0'); $r->addRoute('GET', '/user/12345/extension', 'handler1'); $r->addRoute('GET', '/user/{id:[0-9]+}.{extension}', 'handler2'); }; $method = 'GET'; $uri = '/user/12345.svg'; $handler = 'handler2'; $argDict = ['id' => '12345', 'extension' => 'svg']; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 7 ----- Test GET method fallback on HEAD route miss ------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/user/{name}', 'handler0'); $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler1'); $r->addRoute('GET', '/static0', 'handler2'); $r->addRoute('GET', '/static1', 'handler3'); $r->addRoute('HEAD', '/static1', 'handler4'); }; $method = 'HEAD'; $uri = '/user/rdlowrey'; $handler = 'handler0'; $argDict = ['name' => 'rdlowrey']; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 8 ----- Test GET method fallback on HEAD route miss ------------------------------------> // reuse $callback from #7 $method = 'HEAD'; $uri = '/user/rdlowrey/1234'; $handler = 'handler1'; $argDict = ['name' => 'rdlowrey', 'id' => '1234']; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 9 ----- Test GET method fallback on HEAD route miss ------------------------------------> // reuse $callback from #8 $method = 'HEAD'; $uri = '/static0'; $handler = 'handler2'; $argDict = []; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 10 ---- Test existing HEAD route used if available (no fallback) -----------------------> // reuse $callback from #9 $method = 'HEAD'; $uri = '/static1'; $handler = 'handler4'; $argDict = []; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 11 ---- More specified routes are not shadowed by less specific of another method ------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/user/{name}', 'handler0'); $r->addRoute('POST', '/user/{name:[a-z]+}', 'handler1'); }; $method = 'POST'; $uri = '/user/rdlowrey'; $handler = 'handler1'; $argDict = ['name' => 'rdlowrey']; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 12 ---- Handler of more specific routes is used, if it occurs first --------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/user/{name}', 'handler0'); $r->addRoute('POST', '/user/{name:[a-z]+}', 'handler1'); $r->addRoute('POST', '/user/{name}', 'handler2'); }; $method = 'POST'; $uri = '/user/rdlowrey'; $handler = 'handler1'; $argDict = ['name' => 'rdlowrey']; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 13 ---- Route with constant suffix -----------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/user/{name}', 'handler0'); $r->addRoute('GET', '/user/{name}/edit', 'handler1'); }; $method = 'GET'; $uri = '/user/rdlowrey/edit'; $handler = 'handler1'; $argDict = ['name' => 'rdlowrey']; $cases[] = [$method, $uri, $callback, $handler, $argDict]; // 14 ---- Handle multiple methods with the same handler ----------------------------------> $callback = function (RouteCollector $r) { $r->addRoute(['GET', 'POST'], '/user', 'handlerGetPost'); $r->addRoute(['DELETE'], '/user', 'handlerDelete'); $r->addRoute([], '/user', 'handlerNone'); }; $argDict = []; $cases[] = ['GET', '/user', $callback, 'handlerGetPost', $argDict]; $cases[] = ['POST', '/user', $callback, 'handlerGetPost', $argDict]; $cases[] = ['DELETE', '/user', $callback, 'handlerDelete', $argDict]; // 17 ---- $callback = function (RouteCollector $r) { $r->addRoute('POST', '/user.json', 'handler0'); $r->addRoute('GET', '/{entity}.json', 'handler1'); }; $cases[] = ['GET', '/user.json', $callback, 'handler1', ['entity' => 'user']]; // 18 ---- $callback = function (RouteCollector $r) { $r->addRoute('GET', '', 'handler0'); }; $cases[] = ['GET', '', $callback, 'handler0', []]; // 19 ---- $callback = function (RouteCollector $r) { $r->addRoute('HEAD', '/a/{foo}', 'handler0'); $r->addRoute('GET', '/b/{foo}', 'handler1'); }; $cases[] = ['HEAD', '/b/bar', $callback, 'handler1', ['foo' => 'bar']]; // 20 ---- $callback = function (RouteCollector $r) { $r->addRoute('HEAD', '/a', 'handler0'); $r->addRoute('GET', '/b', 'handler1'); }; $cases[] = ['HEAD', '/b', $callback, 'handler1', []]; // 21 ---- $callback = function (RouteCollector $r) { $r->addRoute('GET', '/foo', 'handler0'); $r->addRoute('HEAD', '/{bar}', 'handler1'); }; $cases[] = ['HEAD', '/foo', $callback, 'handler1', ['bar' => 'foo']]; // 22 ---- $callback = function (RouteCollector $r) { $r->addRoute('*', '/user', 'handler0'); $r->addRoute('*', '/{user}', 'handler1'); $r->addRoute('GET', '/user', 'handler2'); }; $cases[] = ['GET', '/user', $callback, 'handler2', []]; // 23 ---- $callback = function (RouteCollector $r) { $r->addRoute('*', '/user', 'handler0'); $r->addRoute('GET', '/user', 'handler1'); }; $cases[] = ['POST', '/user', $callback, 'handler0', []]; // 24 ---- $cases[] = ['HEAD', '/user', $callback, 'handler1', []]; // 25 ---- $callback = function (RouteCollector $r) { $r->addRoute('GET', '/{bar}', 'handler0'); $r->addRoute('*', '/foo', 'handler1'); }; $cases[] = ['GET', '/foo', $callback, 'handler0', ['bar' => 'foo']]; // 26 ---- $callback = function (RouteCollector $r) { $r->addRoute('GET', '/user', 'handler0'); $r->addRoute('*', '/{foo:.*}', 'handler1'); }; $cases[] = ['POST', '/bar', $callback, 'handler1', ['foo' => 'bar']]; // 27 --- International characters $callback = function (RouteCollector $r) { $r->addRoute('GET', '/новости/{name}', 'handler0'); }; $cases[] = ['GET', '/новости/rdlowrey', $callback, 'handler0', ['name' => 'rdlowrey']]; // x --------------------------------------------------------------------------------------> return $cases; } public static function provideNotFoundDispatchCases() { $cases = []; // 0 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/resource/123/456', 'handler0'); }; $method = 'GET'; $uri = '/not-found'; $cases[] = [$method, $uri, $callback]; // 1 --------------------------------------------------------------------------------------> // reuse callback from #0 $method = 'POST'; $uri = '/not-found'; $cases[] = [$method, $uri, $callback]; // 2 --------------------------------------------------------------------------------------> // reuse callback from #1 $method = 'PUT'; $uri = '/not-found'; $cases[] = [$method, $uri, $callback]; // 3 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/handler0', 'handler0'); $r->addRoute('GET', '/handler1', 'handler1'); $r->addRoute('GET', '/handler2', 'handler2'); }; $method = 'GET'; $uri = '/not-found'; $cases[] = [$method, $uri, $callback]; // 4 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0'); $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1'); $r->addRoute('GET', '/user/{name}', 'handler2'); }; $method = 'GET'; $uri = '/not-found'; $cases[] = [$method, $uri, $callback]; // 5 --------------------------------------------------------------------------------------> // reuse callback from #4 $method = 'GET'; $uri = '/user/rdlowrey/12345/not-found'; $cases[] = [$method, $uri, $callback]; // 6 --------------------------------------------------------------------------------------> // reuse callback from #5 $method = 'HEAD'; $cases[] = [$method, $uri, $callback]; // x --------------------------------------------------------------------------------------> return $cases; } public static function provideMethodNotAllowedDispatchCases() { $cases = []; // 0 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/resource/123/456', 'handler0'); }; $method = 'POST'; $uri = '/resource/123/456'; $allowedMethods = ['GET']; $cases[] = [$method, $uri, $callback, $allowedMethods]; // 1 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/resource/123/456', 'handler0'); $r->addRoute('POST', '/resource/123/456', 'handler1'); $r->addRoute('PUT', '/resource/123/456', 'handler2'); $r->addRoute('*', '/', 'handler3'); }; $method = 'DELETE'; $uri = '/resource/123/456'; $allowedMethods = ['GET', 'POST', 'PUT']; $cases[] = [$method, $uri, $callback, $allowedMethods]; // 2 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0'); $r->addRoute('POST', '/user/{name}/{id:[0-9]+}', 'handler1'); $r->addRoute('PUT', '/user/{name}/{id:[0-9]+}', 'handler2'); $r->addRoute('PATCH', '/user/{name}/{id:[0-9]+}', 'handler3'); }; $method = 'DELETE'; $uri = '/user/rdlowrey/42'; $allowedMethods = ['GET', 'POST', 'PUT', 'PATCH']; $cases[] = [$method, $uri, $callback, $allowedMethods]; // 3 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute('POST', '/user/{name}', 'handler1'); $r->addRoute('PUT', '/user/{name:[a-z]+}', 'handler2'); $r->addRoute('PATCH', '/user/{name:[a-z]+}', 'handler3'); }; $method = 'GET'; $uri = '/user/rdlowrey'; $allowedMethods = ['POST', 'PUT', 'PATCH']; $cases[] = [$method, $uri, $callback, $allowedMethods]; // 4 --------------------------------------------------------------------------------------> $callback = function (RouteCollector $r) { $r->addRoute(['GET', 'POST'], '/user', 'handlerGetPost'); $r->addRoute(['DELETE'], '/user', 'handlerDelete'); $r->addRoute([], '/user', 'handlerNone'); }; $cases[] = ['PUT', '/user', $callback, ['GET', 'POST', 'DELETE']]; // 5 $callback = function (RouteCollector $r) { $r->addRoute('POST', '/user.json', 'handler0'); $r->addRoute('GET', '/{entity}.json', 'handler1'); }; $cases[] = ['PUT', '/user.json', $callback, ['POST', 'GET']]; // x --------------------------------------------------------------------------------------> return $cases; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Routing/RouteResolverTest.php
tests/Routing/RouteResolverTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Routing; use Error; use Prophecy\Argument; use Slim\Interfaces\DispatcherInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteInterface; use Slim\Routing\RouteResolver; use Slim\Routing\RoutingResults; use Slim\Tests\TestCase; use function sprintf; class RouteResolverTest extends TestCase { public static function computeRoutingResultsDataProvider(): array { return [ ['GET', '', '/'], ['GET', '/', '/'], ['GET', '//foo', '//foo'], ['GET', 'hello%20world', '/hello world'], ]; } /** * @dataProvider computeRoutingResultsDataProvider * * @param string $method The request method * @param string $uri The request uri * @param string $expectedUri The expected uri after transformation in the computeRoutingResults() */ #[\PHPUnit\Framework\Attributes\DataProvider('computeRoutingResultsDataProvider')] public function testComputeRoutingResults(string $method, string $uri, string $expectedUri) { $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routingResultsProphecy = $this->prophesize(RoutingResults::class); $dispatcherProphecy = $this->prophesize(DispatcherInterface::class); $dispatcherProphecy ->dispatch(Argument::type('string'), Argument::type('string')) ->will(function ($args) use ($routingResultsProphecy, $expectedUri) { if ($args[1] !== $expectedUri) { throw new Error(sprintf( "URI transformation failed.\n Received: '%s'\n Expected: '%s'", $args[1], $expectedUri )); } return $routingResultsProphecy->reveal(); }) ->shouldBeCalledOnce(); $routeResolver = new RouteResolver( $routeCollectorProphecy->reveal(), $dispatcherProphecy->reveal() ); $routeResolver->computeRoutingResults($uri, $method); } public function testResolveRoute() { $identifier = 'test'; $routeProphecy = $this->prophesize(RouteInterface::class); $dispatcherProphecy = $this->prophesize(DispatcherInterface::class); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->lookupRoute($identifier) ->willReturn($routeProphecy->reveal()) ->shouldBeCalledOnce(); $routeResolver = new RouteResolver( $routeCollectorProphecy->reveal(), $dispatcherProphecy->reveal() ); $routeResolver->resolveRoute($identifier); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Routing/RouteCollectorTest.php
tests/Routing/RouteCollectorTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Routing; use Prophecy\Argument; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use RuntimeException; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\InvocationStrategyInterface; use Slim\Routing\RouteCollector; use Slim\Routing\RouteCollectorProxy; use Slim\Tests\TestCase; use function dirname; use function file_exists; use function file_put_contents; use function sprintf; use function unlink; class RouteCollectorTest extends TestCase { /** * @var null|string */ protected $cacheFile; public function tearDown(): void { if ($this->cacheFile && file_exists($this->cacheFile)) { unlink($this->cacheFile); } } public function testGetSetBasePath() { $basePath = '/app'; $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeCollector->setBasePath($basePath); $this->assertSame($basePath, $routeCollector->getBasePath()); } public function testMap() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $route = $routeCollector->map(['GET'], '/', function () { }); $routes = $routeCollector->getRoutes(); $this->assertSame($route, $routes[$route->getIdentifier()]); } public function testMapPrependsGroupPattern() { $self = $this; $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callable = function (RouteCollectorProxy $proxy) use ($self) { $route = $proxy->get('/test', function () { }); $self->assertSame('/prefix/test', $route->getPattern()); }; $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $callableResolverProphecy ->resolve(Argument::is($callable)) ->willReturn($callable) ->shouldBeCalledOnce(); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeCollector->group('/prefix', $callable); } public function testGetRouteInvocationStrategy() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $invocationStrategyProphecy = $this->prophesize(InvocationStrategyInterface::class); $routeCollector = new RouteCollector( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), $containerProphecy->reveal(), $invocationStrategyProphecy->reveal() ); $this->assertSame($invocationStrategyProphecy->reveal(), $routeCollector->getDefaultInvocationStrategy()); } public function testRemoveNamedRoute() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeCollector->setBasePath('/base/path'); $route = $routeCollector->map(['GET'], '/test', function () { }); $route->setName('test'); $routes = $routeCollector->getRoutes(); $this->assertCount(1, $routes); $routeCollector->removeNamedRoute('test'); $routes = $routeCollector->getRoutes(); $this->assertCount(0, $routes); } public function testRemoveNamedRouteWithARouteThatDoesNotExist() { $this->expectException(RuntimeException::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeCollector->removeNamedRoute('missing'); } public function testLookupRouteThrowsExceptionIfRouteNotFound() { $this->expectException(RuntimeException::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeCollector->lookupRoute('missing'); } /** * Test cache file exists but is not writable */ public function testCacheFileExistsAndIsNotReadable() { $this->cacheFile = __DIR__ . '/non-readable.cache'; file_put_contents($this->cacheFile, '<?php return []; ?>'); $this->expectException(RuntimeException::class); $this->expectExceptionMessage(sprintf('Route collector cache file `%s` is not readable', $this->cacheFile)); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeCollector->setCacheFile($this->cacheFile); } /** * Test cache file does not exist and directory is not writable */ public function testCacheFileDoesNotExistsAndDirectoryIsNotWritable() { $cacheFile = __DIR__ . '/non-writable-directory/router.cache'; $this->expectException(RuntimeException::class); $this->expectExceptionMessage(sprintf( 'Route collector cache file directory `%s` is not writable', dirname($cacheFile) )); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeCollector->setCacheFile($cacheFile); } public function testSetCacheFileViaConstructor() { $cacheFile = __DIR__ . '/router.cache'; $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, null, null, $cacheFile ); $this->assertSame($cacheFile, $routeCollector->getCacheFile()); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Routing/RouteParserTest.php
tests/Routing/RouteParserTest.php
<?php declare(strict_types=1); namespace Slim\Tests\Routing; use InvalidArgumentException; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\UriInterface; use RuntimeException; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteInterface; use Slim\Routing\RouteCollector; use Slim\Routing\RouteParser; use Slim\Tests\TestCase; class RouteParserTest extends TestCase { public static function urlForCases() { return [ 'with base path' => [ true, '/{first}/{second}', ['first' => 'hello', 'second' => 'world'], [], '/app/hello/world', ], 'without base path' => [ false, '/{first}/{second}', ['first' => 'hello', 'second' => 'world'], [], '/hello/world', ], 'with query parameters' => [ false, '/{first}/{second}', ['first' => 'hello', 'second' => 'world'], ['a' => 'b', 'c' => 'd'], '/hello/world?a=b&c=d', ], 'with query parameters containing array with string keys' => [ false, '/{first}/{second}', ['first' => 'hello', 'second' => 'world'], ['a' => ['k' => '1', 'f' => 'x'], 'b', 'c' => 'd'], '/hello/world?a%5Bk%5D=1&a%5Bf%5D=x&0=b&c=d', ], 'with query parameters containing array with numeric keys' => [ false, '/{first}/{second}', ['first' => 'hello', 'second' => 'world'], ['a' => ['b', 'x', 'y'], 'c' => 'd'], '/hello/world?a%5B0%5D=b&a%5B1%5D=x&a%5B2%5D=y&c=d', ], 'with argument without optional parameter' => [ false, '/archive/{year}[/{month:[\d:{2}]}[/d/{day}]]', ['year' => '2015'], [], '/archive/2015', ], 'with argument and optional parameter' => [ false, '/archive/{year}[/{month:[\d:{2}]}[/d/{day}]]', ['year' => '2015', 'month' => '07'], [], '/archive/2015/07', ], 'with argument and optional parameters' => [ false, '/archive/{year}[/{month:[\d:{2}]}[/d/{day}]]', ['year' => '2015', 'month' => '07', 'day' => '19'], [], '/archive/2015/07/d/19', ], ]; } public function testRelativePathForWithNoBasePath() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $route = $routeCollector->map(['GET'], '/{first}/{second}', function () { }); $route->setName('test'); $routeParser = $routeCollector->getRouteParser(); $results = $routeParser->relativeUrlFor('test', ['first' => 'hello', 'second' => 'world']); $this->assertSame('/hello/world', $results); } public function testBasePathIsIgnoreInRelativePathFor() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeCollector->setBasePath('/app'); $route = $routeCollector->map(['GET'], '/{first}/{second}', function () { }); $route->setName('test'); $routeParser = $routeCollector->getRouteParser(); $results = $routeParser->relativeUrlFor('test', ['first' => 'hello', 'second' => 'world']); $this->assertSame('/hello/world', $results); } /** * @dataProvider urlForCases * @param $withBasePath * @param $pattern * @param $arguments * @param $queryParams * @param $expectedResult */ #[\PHPUnit\Framework\Attributes\DataProvider('urlForCases')] public function testUrlForWithBasePath($withBasePath, $pattern, $arguments, $queryParams, $expectedResult) { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); if ($withBasePath) { $routeCollector->setBasePath('/app'); } $route = $routeCollector->map(['GET'], $pattern, function () { }); $route->setName('test'); $routeParser = $routeCollector->getRouteParser(); $results = $routeParser->urlFor('test', $arguments, $queryParams); $this->assertSame($expectedResult, $results); } public function testUrlForWithMissingSegmentData() { $this->expectException(InvalidArgumentException::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $route = $routeCollector->map(['GET'], '/{first}/{last}', function () { }); $route->setName('test'); $routeParser = $routeCollector->getRouteParser(); $routeParser->urlFor('test', ['last' => 'world']); } public function testUrlForRouteThatDoesNotExist() { $this->expectException(RuntimeException::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeParser = $routeCollector->getRouteParser(); $routeParser->urlFor('test'); } public function testFullUrlFor() { $uriProphecy = $this->prophesize(UriInterface::class); $uriProphecy ->getScheme() ->willReturn('http') ->shouldBeCalledOnce(); $uriProphecy ->getAuthority() ->willReturn('example.com:8080') ->shouldBeCalledOnce(); $routeProphecy = $this->prophesize(RouteInterface::class); $routeProphecy ->getPattern() ->willReturn('/{token}') ->shouldBeCalledOnce(); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->getBasePath() ->willReturn('/app') ->shouldBeCalledOnce(); $routeCollectorProphecy ->getNamedRoute('test') ->willReturn($routeProphecy->reveal()) ->shouldBeCalledOnce(); $routeParser = new RouteParser($routeCollectorProphecy->reveal()); $result = $routeParser->fullUrlFor($uriProphecy->reveal(), 'test', ['token' => '123']); $expectedResult = 'http://example.com:8080/app/123'; $this->assertSame($expectedResult, $result); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Routing/RouteContextTest.php
tests/Routing/RouteContextTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Routing; use Psr\Http\Message\ServerRequestInterface; use RuntimeException; use Slim\Interfaces\RouteInterface; use Slim\Interfaces\RouteParserInterface; use Slim\Routing\RouteContext; use Slim\Routing\RoutingResults; use Slim\Tests\TestCase; class RouteContextTest extends TestCase { public function testCanCreateInstanceFromServerRequest(): void { $route = $this->createMock(RouteInterface::class); $routeParser = $this->createMock(RouteParserInterface::class); $routingResults = $this->createMock(RoutingResults::class); $serverRequest = $this->createServerRequest('/') ->withAttribute(RouteContext::BASE_PATH, '') ->withAttribute(RouteContext::ROUTE, $route) ->withAttribute(RouteContext::ROUTE_PARSER, $routeParser) ->withAttribute(RouteContext::ROUTING_RESULTS, $routingResults); $routeContext = RouteContext::fromRequest($serverRequest); $this->assertSame($route, $routeContext->getRoute()); $this->assertSame($routeParser, $routeContext->getRouteParser()); $this->assertSame($routingResults, $routeContext->getRoutingResults()); $this->assertSame('', $routeContext->getBasePath()); } public function testCanCreateInstanceWithoutRoute(): void { $serverRequest = $this->createServerRequestWithRouteAttributes(); // Route attribute is not required $serverRequest = $serverRequest->withoutAttribute(RouteContext::ROUTE); $routeContext = RouteContext::fromRequest($serverRequest); $this->assertNull($routeContext->getRoute()); $this->assertNotNull($routeContext->getRouteParser()); $this->assertNotNull($routeContext->getRoutingResults()); $this->assertNotNull($routeContext->getBasePath()); } public function testCanCreateInstanceWithoutBasePathAndThrowExceptionIfGetBasePathIsCalled(): void { $serverRequest = $this->createServerRequestWithRouteAttributes(); // Route attribute is not required $serverRequest = $serverRequest->withoutAttribute(RouteContext::BASE_PATH); $routeContext = RouteContext::fromRequest($serverRequest); $this->assertNotNull($routeContext->getRoute()); $this->assertNotNull($routeContext->getRouteParser()); $this->assertNotNull($routeContext->getRoutingResults()); $this->expectException(RuntimeException::class); $routeContext->getBasePath(); } public static function requiredRouteContextRequestAttributes(): array { return [ [RouteContext::ROUTE_PARSER], [RouteContext::ROUTING_RESULTS], ]; } /** * @dataProvider requiredRouteContextRequestAttributes * @param string $attribute */ #[\PHPUnit\Framework\Attributes\DataProvider('requiredRouteContextRequestAttributes')] public function testCannotCreateInstanceIfRequestIsMissingAttributes(string $attribute): void { $this->expectException(RuntimeException::class); $serverRequest = $this->createServerRequestWithRouteAttributes()->withoutAttribute($attribute); RouteContext::fromRequest($serverRequest); } private function createServerRequestWithRouteAttributes(): ServerRequestInterface { $route = $this->createMock(RouteInterface::class); $routeParser = $this->createMock(RouteParserInterface::class); $routingResults = $this->createMock(RoutingResults::class); return $this->createServerRequest('/') ->withAttribute(RouteContext::BASE_PATH, '') ->withAttribute(RouteContext::ROUTE, $route) ->withAttribute(RouteContext::ROUTE_PARSER, $routeParser) ->withAttribute(RouteContext::ROUTING_RESULTS, $routingResults); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Routing/RouteTest.php
tests/Routing/RouteTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests; use Closure; use Exception; use Prophecy\Argument; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; use Slim\CallableResolver; use Slim\Handlers\Strategies\RequestHandler; use Slim\Handlers\Strategies\RequestResponse; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\InvocationStrategyInterface; use Slim\Interfaces\RouteCollectorProxyInterface; use Slim\Routing\Route; use Slim\Routing\RouteGroup; use Slim\Tests\Mocks\CallableTest; use Slim\Tests\Mocks\InvocationStrategyTest; use Slim\Tests\Mocks\MockCustomRequestHandlerInvocationStrategy; use Slim\Tests\Mocks\MockMiddlewareWithoutConstructor; use Slim\Tests\Mocks\MockMiddlewareWithoutInterface; use Slim\Tests\Mocks\RequestHandlerTest; use function is_callable; use function is_string; use function ob_end_clean; use function ob_start; class RouteTest extends TestCase { /** * @param string|array $methods * @param string $pattern * @param Closure|string|null $callable * @return Route */ public function createRoute($methods = 'GET', string $pattern = '/', $callable = null): Route { $callable ??= function (ServerRequestInterface $request, ResponseInterface $response) { return $response; }; $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $callableResolverProphecy ->resolve(Argument::is($callable)) ->willReturn($callable); $callableResolverProphecy ->resolve(MockMiddlewareWithoutConstructor::class) ->will(function ($args) { return [new MockMiddlewareWithoutConstructor(), 'process']; }); $streamProphecy = $this->prophesize(StreamInterface::class); $value = ''; $streamProphecy ->write(Argument::type('string')) ->will(function ($args) use ($value) { $value .= $args[0]; $this->__toString()->willReturn($value); return strlen($value); }); $streamProphecy ->__toString() ->willReturn($value); $responseProphecy = $this->prophesize(ResponseInterface::class); $responseProphecy ->getBody() ->willReturn($streamProphecy->reveal()); $responseProphecy ->withStatus(Argument::type('integer')) ->will(function ($args) { $this->getStatusCode()->willReturn($args[0]); return $this->reveal(); }); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()); $methods = is_string($methods) ? [$methods] : $methods; return new Route( $methods, $pattern, $callable, $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal() ); } public function testConstructor() { $methods = ['GET', 'POST']; $pattern = '/hello/{name}'; $callable = function ($request, $response, $args) { return $response; }; $route = $this->createRoute($methods, $pattern, $callable); $this->assertSame($methods, $route->getMethods()); $this->assertSame($pattern, $route->getPattern()); $this->assertSame($callable, $route->getCallable()); } public function testGetMethodsReturnsArrayWhenConstructedWithString() { $route = $this->createRoute(); $this->assertSame(['GET'], $route->getMethods()); } public function testGetMethods() { $methods = ['GET', 'POST']; $route = $this->createRoute($methods); $this->assertSame($methods, $route->getMethods()); } public function testGetPattern() { $route = $this->createRoute(); $this->assertSame('/', $route->getPattern()); } public function testGetCallable() { $route = $this->createRoute(); $this->assertTrue(is_callable($route->getCallable())); } public function testGetCallableResolver() { $callable = function (ServerRequestInterface $request, ResponseInterface $response) { return $response; }; $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $route = new Route( ['GET'], '/', $callable, $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal() ); $this->assertSame($callableResolverProphecy->reveal(), $route->getCallableResolver()); } public function testGetInvocationStrategy() { $callable = function (ServerRequestInterface $request, ResponseInterface $response) { return $response; }; $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $strategyProphecy = $this->prophesize(InvocationStrategyInterface::class); $route = new Route( ['GET'], '/', $callable, $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), $containerProphecy->reveal(), $strategyProphecy->reveal() ); $this->assertSame($strategyProphecy->reveal(), $route->getInvocationStrategy()); } public function testSetInvocationStrategy() { $callable = function (ServerRequestInterface $request, ResponseInterface $response) { return $response; }; $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $strategyProphecy = $this->prophesize(InvocationStrategyInterface::class); $route = new Route( ['GET'], '/', $callable, $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal() ); $route->setInvocationStrategy($strategyProphecy->reveal()); $this->assertSame($strategyProphecy->reveal(), $route->getInvocationStrategy()); } public function testGetGroups() { $callable = function (ServerRequestInterface $request, ResponseInterface $response) { return $response; }; $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $strategyProphecy = $this->prophesize(InvocationStrategyInterface::class); $routeCollectorProxyProphecy = $this->prophesize(RouteCollectorProxyInterface::class); $routeGroup = new RouteGroup( '/group', $callable, $callableResolverProphecy->reveal(), $routeCollectorProxyProphecy->reveal() ); $groups = [$routeGroup]; $route = new Route( ['GET'], '/', $callable, $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $strategyProphecy->reveal(), $groups ); $this->assertSame($groups, $route->getGroups()); } public function testArgumentSetting() { $route = $this->createRoute(); $route->setArguments(['foo' => 'FOO', 'bar' => 'BAR']); $this->assertSame($route->getArguments(), ['foo' => 'FOO', 'bar' => 'BAR']); $route->setArgument('bar', 'bar'); $this->assertSame($route->getArguments(), ['foo' => 'FOO', 'bar' => 'bar']); $route->setArgument('baz', 'BAZ'); $this->assertSame($route->getArguments(), ['foo' => 'FOO', 'bar' => 'bar', 'baz' => 'BAZ']); $route->setArguments(['a' => 'b']); $this->assertSame($route->getArguments(), ['a' => 'b']); $this->assertSame($route->getArgument('a', 'default'), 'b'); $this->assertSame($route->getArgument('b', 'default'), 'default'); } public function testAddMiddleware() { $route = $this->createRoute(); $called = 0; $mw = function (ServerRequestInterface $request, RequestHandlerInterface $handler) use (&$called) { $called++; return $handler->handle($request); }; $route->add($mw); $request = $this->createServerRequest('/'); $route->run($request); $this->assertSame($called, 1); } public function testAddMiddlewareOnGroup() { $callable = function (ServerRequestInterface $request, ResponseInterface $response) { return $response; }; $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $callableResolverProphecy ->resolve(Argument::is($callable)) ->willReturn($callable) ->shouldBeCalledOnce(); $responseProphecy = $this->prophesize(ResponseInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $routeCollectorProxyProphecy = $this->prophesize(RouteCollectorProxyInterface::class); $strategy = new RequestResponse(); $called = 0; $mw = function (ServerRequestInterface $request, RequestHandlerInterface $handler) use (&$called) { $called++; return $handler->handle($request); }; $routeGroup = new RouteGroup( '/group', $callable, $callableResolverProphecy->reveal(), $routeCollectorProxyProphecy->reveal() ); $routeGroup->add($mw); $groups = [$routeGroup]; $route = new Route( ['GET'], '/', $callable, $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $strategy, $groups ); $request = $this->createServerRequest('/'); $route->run($request); $this->assertSame($called, 1); } public function testAddClosureMiddleware() { $route = $this->createRoute(); $called = 0; $route->add(function (ServerRequestInterface $request, RequestHandlerInterface $handler) use (&$called) { $called++; return $handler->handle($request); }); $request = $this->createServerRequest('/'); $route->run($request); $this->assertSame($called, 1); } public function testAddMiddlewareUsingDeferredResolution() { $route = $this->createRoute(); $route->add(MockMiddlewareWithoutConstructor::class); $output = ''; $appendToOutput = function (string $value) use (&$output) { $output .= $value; }; $request = $this->createServerRequest('/')->withAttribute('appendToOutput', $appendToOutput); $route->run($request); $this->assertSame('Hello World', $output); } public function testAddMiddlewareAsStringNotImplementingInterfaceThrowsException() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage( 'A middleware must be an object/class name referencing an implementation of ' . 'MiddlewareInterface or a callable with a matching signature.' ); $route = $this->createRoute(); $route->add(new MockMiddlewareWithoutInterface()); } public function testIdentifier() { $route = $this->createRoute(); $this->assertSame('route0', $route->getIdentifier()); } public function testSetName() { $route = $this->createRoute(); $this->assertSame($route, $route->setName('foo')); $this->assertSame('foo', $route->getName()); } public function testControllerMethodAsStringResolvesWithoutContainer() { $callableResolver = new CallableResolver(); $responseFactory = $this->getResponseFactory(); $deferred = $callableResolver->resolve('\Slim\Tests\Mocks\CallableTest:toCall'); $route = new Route(['GET'], '/', $deferred, $responseFactory, $callableResolver); CallableTest::$CalledCount = 0; $request = $this->createServerRequest('/'); $response = $route->run($request); $this->assertInstanceOf(ResponseInterface::class, $response); $this->assertSame(1, CallableTest::$CalledCount); } public function testControllerMethodAsStringResolvesWithContainer() { $self = $this; $responseProphecy = $this->prophesize(ResponseInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $callable = 'callable'; $callableResolverProphecy ->resolve(Argument::is($callable)) ->willReturn(function ( ServerRequestInterface $request, ResponseInterface $response ) use ( $self, $responseProphecy ) { $self->assertSame($responseProphecy->reveal(), $response); return $response; }) ->shouldBeCalledOnce(); $deferred = $callableResolverProphecy->reveal()->resolve($callable); $callableResolverProphecy ->resolve(Argument::is($deferred)) ->willReturn($deferred) ->shouldBeCalledOnce(); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()); $route = new Route( ['GET'], '/', $deferred, $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal() ); $request = $this->createServerRequest('/'); $response = $route->run($request); $this->assertInstanceOf(ResponseInterface::class, $response); } /** * Ensure that the response returned by a route callable is the response * object that is returned by __invoke(). */ public function testProcessWhenReturningAResponse() { $callable = function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write('foo'); return $response; }; $route = $this->createRoute(['GET'], '/', $callable); $request = $this->createServerRequest('/'); $response = $route->run($request); $this->assertSame('foo', (string) $response->getBody()); } /** * Ensure that anything echo'd in a route callable is, by default, NOT * added to the response object body. */ public function testRouteCallableDoesNotAppendEchoedOutput() { $callable = function (ServerRequestInterface $request, ResponseInterface $response) { echo "foo"; return $response->withStatus(201); }; $route = $this->createRoute(['GET'], '/', $callable); $request = $this->createServerRequest('/'); // We capture output buffer here only to clean test CLI output ob_start(); $response = $route->run($request); ob_end_clean(); // Output buffer is ignored without optional middleware $this->assertSame('', (string) $response->getBody()); $this->assertSame(201, $response->getStatusCode()); } /** * Ensure that if a string is returned by a route callable, then it is * added to the response object that is returned by __invoke(). */ public function testRouteCallableAppendsCorrectOutputToResponse() { $callable = function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write('foo'); return $response; }; $route = $this->createRoute(['GET'], '/', $callable); $request = $this->createServerRequest('/'); $response = $route->run($request); $this->assertSame('foo', (string) $response->getBody()); } public function testInvokeWithException() { $this->expectException(Exception::class); $callable = function (ServerRequestInterface $request, ResponseInterface $response) { throw new Exception(); }; $route = $this->createRoute(['GET'], '/', $callable); $request = $this->createServerRequest('/'); $route->run($request); } /** * Ensure that `foundHandler` is called on actual callable */ public function testInvokeDeferredCallableWithNoContainer() { $responseProphecy = $this->prophesize(ResponseInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $callableResolver = new CallableResolver(); $invocationStrategy = new InvocationStrategyTest(); $deferred = '\Slim\Tests\Mocks\CallableTest:toCall'; $route = new Route( ['GET'], '/', $deferred, $responseFactoryProphecy->reveal(), $callableResolver, null, $invocationStrategy ); $request = $this->createServerRequest('/'); $response = $route->run($request); $this->assertInstanceOf(ResponseInterface::class, $response); $this->assertEquals([new CallableTest(), 'toCall'], InvocationStrategyTest::$LastCalledFor); } /** * Ensure that `foundHandler` is called on actual callable */ public function testInvokeDeferredCallableWithContainer() { $responseProphecy = $this->prophesize(ResponseInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy->has('\Slim\Tests\Mocks\CallableTest')->willReturn(true); $containerProphecy->get('\Slim\Tests\Mocks\CallableTest')->willReturn(new CallableTest()); $callableResolver = new CallableResolver($containerProphecy->reveal()); $strategy = new InvocationStrategyTest(); $deferred = '\Slim\Tests\Mocks\CallableTest:toCall'; $route = new Route( ['GET'], '/', $deferred, $responseFactoryProphecy->reveal(), $callableResolver, $containerProphecy->reveal(), $strategy ); $request = $this->createServerRequest('/'); $response = $route->run($request); $this->assertInstanceOf(ResponseInterface::class, $response); $this->assertEquals([new CallableTest(), 'toCall'], InvocationStrategyTest::$LastCalledFor); } public function testInvokeUsesRequestHandlerStrategyForRequestHandlers() { $responseProphecy = $this->prophesize(ResponseInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy->has(RequestHandlerTest::class)->willReturn(true); $containerProphecy->get(RequestHandlerTest::class)->willReturn(new RequestHandlerTest()); $callableResolver = new CallableResolver($containerProphecy->reveal()); $deferred = RequestHandlerTest::class; $route = new Route( ['GET'], '/', $deferred, $responseFactoryProphecy->reveal(), $callableResolver, $containerProphecy->reveal() ); $request = $this->createServerRequest('/', 'GET'); $route->run($request); /** @var InvocationStrategyInterface $strategy */ $strategy = $containerProphecy ->reveal() ->get(RequestHandlerTest::class)::$strategy; $this->assertSame(RequestHandler::class, $strategy); } public function testInvokeUsesUserSetStrategyForRequestHandlers() { $responseProphecy = $this->prophesize(ResponseInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy->has(RequestHandlerTest::class)->willReturn(true); $containerProphecy->get(RequestHandlerTest::class)->willReturn(new RequestHandlerTest()); $callableResolver = new CallableResolver($containerProphecy->reveal()); $deferred = RequestHandlerTest::class; $route = new Route( ['GET'], '/', $deferred, $responseFactoryProphecy->reveal(), $callableResolver, $containerProphecy->reveal() ); $strategy = new MockCustomRequestHandlerInvocationStrategy(); $route->setInvocationStrategy($strategy); $request = $this->createServerRequest('/', 'GET'); $route->run($request); $this->assertSame(1, $strategy::$CalledCount); } public function testRequestHandlerStrategyAppendsRouteArgumentsAsAttributesToRequest() { $self = $this; $responseProphecy = $this->prophesize(ResponseInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy->has(RequestHandlerTest::class)->willReturn(true); $containerProphecy->get(RequestHandlerTest::class)->willReturn(new RequestHandlerTest()); $callableResolver = new CallableResolver($containerProphecy->reveal()); $deferred = RequestHandlerTest::class; $route = new Route( ['GET'], '/', $deferred, $responseFactoryProphecy->reveal(), $callableResolver, $containerProphecy->reveal() ); $strategy = new RequestHandler(true); $route->setInvocationStrategy($strategy); $route->setArguments(['id' => 1]); $requestProphecy = $this->prophesize(ServerRequestInterface::class); $requestProphecy->withAttribute(Argument::type('string'), Argument::any())->will(function ($args) use ($self) { $name = $args[0]; $value = $args[1]; $self->assertSame('id', $name); $self->assertSame(1, $value); return $this; })->shouldBeCalledOnce(); $route->run($requestProphecy->reveal()); } /** * Ensure that the pattern can be dynamically changed */ public function testPatternCanBeChanged() { $route = $this->createRoute(); $route->setPattern('/hola/{nombre}'); $this->assertSame('/hola/{nombre}', $route->getPattern()); } /** * Ensure that the callable can be changed */ public function testChangingCallableWithNoContainer() { $responseProphecy = $this->prophesize(ResponseInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $callableResolver = new CallableResolver(); $strategy = new InvocationStrategyTest(); $deferred = 'NonExistent:toCall'; $route = new Route( ['GET'], '/', $deferred, $responseFactoryProphecy->reveal(), $callableResolver, null, $strategy ); $route->setCallable('\Slim\Tests\Mocks\CallableTest:toCall'); //Then we fix it here. $request = $this->createServerRequest('/'); $response = $route->run($request); $this->assertInstanceOf(ResponseInterface::class, $response); $this->assertEquals([new CallableTest(), 'toCall'], InvocationStrategyTest::$LastCalledFor); } /** * Ensure that the callable can be changed */ public function testChangingCallableWithContainer() { $responseProphecy = $this->prophesize(ResponseInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy->has('CallableTest2')->willReturn(true); $containerProphecy->get('CallableTest2')->willReturn(new CallableTest()); $callableResolver = new CallableResolver($containerProphecy->reveal()); $strategy = new InvocationStrategyTest(); $deferred = 'NonExistent:toCall'; $route = new Route( ['GET'], '/', $deferred, $responseFactoryProphecy->reveal(), $callableResolver, $containerProphecy->reveal(), $strategy ); $route->setCallable('CallableTest2:toCall'); //Then we fix it here. $request = $this->createServerRequest('/'); $response = $route->run($request); $this->assertInstanceOf(ResponseInterface::class, $response); $this->assertSame( [$containerProphecy->reveal()->get('CallableTest2'), 'toCall'], InvocationStrategyTest::$LastCalledFor ); } public function testRouteCallableIsResolvedUsingContainerWhenCallableResolverIsPresent() { $streamProphecy = $this->prophesize(StreamInterface::class); $value = ''; $streamProphecy ->write(Argument::type('string')) ->will(function ($args) use ($value) { $value .= $args[0]; $this->__toString()->willReturn($value); return strlen($value); }); $streamProphecy ->__toString() ->willReturn($value); $responseProphecy = $this->prophesize(ResponseInterface::class); $responseProphecy ->getBody() ->willReturn($streamProphecy->reveal()) ->shouldBeCalledTimes(2); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy->has('CallableTest3')->willReturn(true); $containerProphecy->get('CallableTest3')->willReturn(new CallableTest()); $containerProphecy->has('ClosureMiddleware')->willReturn(true); $containerProphecy->get('ClosureMiddleware')->willReturn(function () use ($responseFactoryProphecy) { $response = $responseFactoryProphecy->reveal()->createResponse(); $response->getBody()->write('Hello'); return $response; }); $callableResolver = new CallableResolver($containerProphecy->reveal()); $strategy = new InvocationStrategyTest(); $deferred = 'CallableTest3'; $route = new Route( ['GET'], '/', $deferred, $responseFactoryProphecy->reveal(), $callableResolver, $containerProphecy->reveal(), $strategy ); $route->add('ClosureMiddleware'); $request = $this->createServerRequest('/'); $response = $route->run($request); $this->assertSame('Hello', (string) $response->getBody()); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Routing/DispatcherTest.php
tests/Routing/DispatcherTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Routing; use Psr\Http\Message\ResponseFactoryInterface; use ReflectionMethod; use Slim\Interfaces\CallableResolverInterface; use Slim\Routing\Dispatcher; use Slim\Routing\FastRouteDispatcher; use Slim\Routing\RouteCollector; use Slim\Routing\RoutingResults; use Slim\Tests\TestCase; use function dirname; use function microtime; use function uniqid; use function unlink; class DispatcherTest extends TestCase { public function testCreateDispatcher() { $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $dispatcher = new Dispatcher($routeCollector); $method = new ReflectionMethod(Dispatcher::class, 'createDispatcher'); $this->setAccessible($method); $this->assertInstanceOf(FastRouteDispatcher::class, $method->invoke($dispatcher)); } /** * Test cached routes file is created & that it holds our routes. */ public function testRouteCacheFileCanBeDispatched() { $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $dispatcher = new Dispatcher($routeCollector); $route = $routeCollector->map(['GET'], '/', function () { }); $route->setName('foo'); $cacheFile = __DIR__ . '/' . uniqid((string) microtime(true)); $routeCollector->setCacheFile($cacheFile); $method = new ReflectionMethod(Dispatcher::class, 'createDispatcher'); $this->setAccessible($method); $method->invoke($dispatcher); $this->assertFileExists($cacheFile, 'cache file was not created'); $routeCollector2 = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeCollector2->setCacheFile($cacheFile); $dispatcher2 = new Dispatcher($routeCollector2); $method = new ReflectionMethod(Dispatcher::class, 'createDispatcher'); $this->setAccessible($method); $method->invoke($dispatcher2); /** @var RoutingResults $result */ $result = $dispatcher2->dispatch('GET', '/'); $this->assertSame(FastRouteDispatcher::FOUND, $result->getRouteStatus()); unlink($cacheFile); } /** * Calling createDispatcher as second time should give you back the same * dispatcher as when you called it the first time. */ public function testCreateDispatcherReturnsSameDispatcherASecondTime() { $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $dispatcher = new Dispatcher($routeCollector); $method = new ReflectionMethod(Dispatcher::class, 'createDispatcher'); $this->setAccessible($method); $fastRouteDispatcher = $method->invoke($dispatcher); $fastRouteDispatcher2 = $method->invoke($dispatcher); $this->assertSame($fastRouteDispatcher, $fastRouteDispatcher2); } public function testGetAllowedMethods() { $methods = ['GET', 'POST', 'PUT']; $uri = '/'; $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $routeCollector->map($methods, $uri, function () { }); $dispatcher = new Dispatcher($routeCollector); $results = $dispatcher->getAllowedMethods('/'); $this->assertSame($methods, $results); } public function testDispatch() { $methods = ['GET', 'POST']; $uri = '/hello/{name}'; $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callable = function () { }; $routeCollector = new RouteCollector($responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal()); $route = $routeCollector->map($methods, $uri, $callable); $dispatcher = new Dispatcher($routeCollector); $results = $dispatcher->dispatch('GET', '/hello/Foo%20Bar'); $this->assertSame(RoutingResults::FOUND, $results->getRouteStatus()); $this->assertSame('GET', $results->getMethod()); $this->assertSame('/hello/Foo%20Bar', $results->getUri()); $this->assertSame($route->getIdentifier(), $results->getRouteIdentifier()); $this->assertSame(['name' => 'Foo Bar'], $results->getRouteArguments()); $this->assertSame(['name' => 'Foo%20Bar'], $results->getRouteArguments(false)); $this->assertSame($methods, $results->getAllowedMethods()); $this->assertSame($dispatcher, $results->getDispatcher()); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Routing/RouteCollectorProxyTest.php
tests/Routing/RouteCollectorProxyTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Routing; use Prophecy\Argument; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Slim\CallableResolver; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteGroupInterface; use Slim\Interfaces\RouteInterface; use Slim\Routing\RouteCollector; use Slim\Routing\RouteCollectorProxy; use Slim\Tests\TestCase; class RouteCollectorProxyTest extends TestCase { public function testGetResponseFactory() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal() ); $this->assertSame( $responseFactoryProphecy->reveal(), $routeCollectorProxy->getResponseFactory() ); } public function testGetCallableResolver() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal() ); $this->assertSame( $callableResolverProphecy->reveal(), $routeCollectorProxy->getCallableResolver() ); } public function testGetContainerReturnsInjectedInstance() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), $containerProphecy->reveal() ); $this->assertSame( $containerProphecy->reveal(), $routeCollectorProxy->getContainer() ); } public function testGetRouteCollectorReturnsInjectedInstance() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), $containerProphecy->reveal(), $routeCollectorProphecy->reveal() ); $this->assertSame( $routeCollectorProphecy->reveal(), $routeCollectorProxy->getRouteCollector() ); } public function testGetSetBasePath() { $basePath = '/base/path'; $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), $containerProphecy->reveal() ); $routeCollectorProxy->setBasePath($basePath); $this->assertSame($basePath, $routeCollectorProxy->getBasePath()); $newBasePath = '/new/base/path'; $routeCollectorProxy->setBasePath('/new/base/path'); $this->assertSame($newBasePath, $routeCollectorProxy->getBasePath()); } public function testGet() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $pattern = '/'; $callable = function () { }; $routeProphecy = $this->prophesize(RouteInterface::class); $routeProphecy ->getPattern() ->willReturn($pattern) ->shouldBeCalledOnce(); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->map(['GET'], $pattern, Argument::is($callable)) ->willReturn($routeProphecy->reveal()) ->shouldBeCalledOnce(); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $routeCollectorProphecy->reveal() ); $route = $routeCollectorProxy->get($pattern, $callable); $this->assertSame($pattern, $route->getPattern()); } public function testPost() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $pattern = '/'; $callable = function () { }; $routeProphecy = $this->prophesize(RouteInterface::class); $routeProphecy ->getPattern() ->willReturn($pattern) ->shouldBeCalledOnce(); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->map(['POST'], $pattern, Argument::is($callable)) ->willReturn($routeProphecy->reveal()) ->shouldBeCalledOnce(); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $routeCollectorProphecy->reveal() ); $route = $routeCollectorProxy->post($pattern, $callable); $this->assertSame($pattern, $route->getPattern()); } public function testPut() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $pattern = '/'; $callable = function () { }; $routeProphecy = $this->prophesize(RouteInterface::class); $routeProphecy ->getPattern() ->willReturn($pattern) ->shouldBeCalledOnce(); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->map(['PUT'], $pattern, Argument::is($callable)) ->willReturn($routeProphecy->reveal()) ->shouldBeCalledOnce(); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $routeCollectorProphecy->reveal() ); $route = $routeCollectorProxy->put($pattern, $callable); $this->assertSame($pattern, $route->getPattern()); } public function testPatch() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $pattern = '/'; $callable = function () { }; $routeProphecy = $this->prophesize(RouteInterface::class); $routeProphecy ->getPattern() ->willReturn($pattern) ->shouldBeCalledOnce(); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->map(['PATCH'], $pattern, Argument::is($callable)) ->willReturn($routeProphecy->reveal()) ->shouldBeCalledOnce(); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $routeCollectorProphecy->reveal() ); $route = $routeCollectorProxy->patch($pattern, $callable); $this->assertSame($pattern, $route->getPattern()); } public function testDelete() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $pattern = '/'; $callable = function () { }; $routeProphecy = $this->prophesize(RouteInterface::class); $routeProphecy ->getPattern() ->willReturn($pattern) ->shouldBeCalledOnce(); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->map(['DELETE'], $pattern, Argument::is($callable)) ->willReturn($routeProphecy->reveal()) ->shouldBeCalledOnce(); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $routeCollectorProphecy->reveal() ); $route = $routeCollectorProxy->delete($pattern, $callable); $this->assertSame($pattern, $route->getPattern()); } public function testOptions() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $pattern = '/'; $callable = function () { }; $routeProphecy = $this->prophesize(RouteInterface::class); $routeProphecy ->getPattern() ->willReturn($pattern) ->shouldBeCalledOnce(); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->map(['OPTIONS'], $pattern, Argument::is($callable)) ->willReturn($routeProphecy->reveal()) ->shouldBeCalledOnce(); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $routeCollectorProphecy->reveal() ); $route = $routeCollectorProxy->options($pattern, $callable); $this->assertSame($pattern, $route->getPattern()); } public function testAny() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $pattern = '/'; $callable = function () { }; $routeProphecy = $this->prophesize(RouteInterface::class); $routeProphecy ->getPattern() ->willReturn($pattern) ->shouldBeCalledOnce(); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->map(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], $pattern, Argument::is($callable)) ->willReturn($routeProphecy->reveal()) ->shouldBeCalledOnce(); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $routeCollectorProphecy->reveal() ); $route = $routeCollectorProxy->any($pattern, $callable); $this->assertSame($pattern, $route->getPattern()); } public function testMap() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $pattern = '/'; $methods = ['GET', 'POST']; $callable = function () { }; $routeProphecy = $this->prophesize(RouteInterface::class); $routeProphecy ->getPattern() ->willReturn($pattern) ->shouldBeCalledOnce(); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->map($methods, $pattern, Argument::is($callable)) ->willReturn($routeProphecy->reveal()) ->shouldBeCalledOnce(); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $routeCollectorProphecy->reveal() ); $route = $routeCollectorProxy->map($methods, $pattern, $callable); $this->assertSame($pattern, $route->getPattern()); } public function testRedirect() { $containerProphecy = $this->prophesize(ContainerInterface::class); $callableResolver = new CallableResolver($containerProphecy->reveal()); $from = '/from'; $to = '/to'; $responseProphecy = $this->prophesize(ResponseInterface::class); $responseProphecy ->withHeader('Location', $to) ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse() ->will(function () use ($responseProphecy) { $this ->createResponse(302) ->willReturn($responseProphecy) ->shouldBeCalledOnce(); return $responseProphecy->reveal(); }) ->shouldBeCalledOnce(); $routeCollector = new RouteCollector( $responseFactoryProphecy->reveal(), $callableResolver ); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolver, $containerProphecy->reveal(), $routeCollector ); $route = $routeCollectorProxy->redirect($from, $to); $request = $this->createServerRequest('/'); $response = $route->run($request); $this->assertSame($responseProphecy->reveal(), $response); } public function testGroup() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $pattern = '/group'; $callable = function () { }; $routeGroupProphecy = $this->prophesize(RouteGroupInterface::class); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->group($pattern, Argument::is($callable)) ->willReturn($routeGroupProphecy->reveal()) ->shouldBeCalledOnce(); $routeCollectorProxy = new RouteCollectorProxy( $responseFactoryProphecy->reveal(), $callableResolverProphecy->reveal(), null, $routeCollectorProphecy->reveal() ); $routeCollectorProxy->group($pattern, $callable); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Assets/HeaderStack.php
tests/Assets/HeaderStack.php
<?php /** * This is a direct copy of zend-diactoros/test/TestAsset/Functions.php and is used to override * header() and headers_sent() so we can test that they do the right thing. * * We put these into the Slim namespace, so that Slim\App will use these versions of header() and * headers_sent() when we test its output. */ declare(strict_types=1); namespace Slim\Tests\Assets; use function explode; use function trim; /** * Zend Framework (http://framework.zend.com/) * * This file exists to allow overriding the various output-related functions * in order to test what happens during the `Server::listen()` cycle. * * These functions include: * * - headers_sent(): we want to always return false so that headers will be * emitted, and we can test to see their values. * - header(): we want to aggregate calls to this function. * * The HeaderStack class then aggregates that information for us, and the test * harness resets the values pre and post test. * * @see http://github.com/zendframework/zend-diactoros for the canonical source repository * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License */ /** * Store output artifacts */ class HeaderStack { /** * @var string[][] */ private static $data = []; /** * Reset state */ public static function reset() { self::$data = []; } /** * Push a header on the stack * * @param array $header */ public static function push(array $header) { self::$data[] = $header; } /** * Return the current header stack * * @return string[][] */ public static function stack() { return self::$data; } /** * Verify if there's a header line on the stack * * @param string $header * * @return bool */ public static function has($header) { foreach (self::$data as $item) { $components = explode(':', $item['header']); if (trim($components[0]) === $header) { return true; } } return false; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockCustomException.php
tests/Mocks/MockCustomException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Exception; class MockCustomException extends Exception { }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockAction.php
tests/Mocks/MockAction.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use InvalidArgumentException; use function compact; use function count; use function json_encode; class MockAction { public function __call($name, array $arguments) { if (count($arguments) !== 3) { throw new InvalidArgumentException("Not a Slim call"); } $response = $arguments[1]; $contents = json_encode(compact('name') + ['arguments' => $arguments[2]]); $arguments[1]->getBody()->write($contents); return $response; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/RequestHandlerTest.php
tests/Mocks/RequestHandlerTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Slim\Tests\Providers\PSR7ObjectProvider; use function debug_backtrace; class RequestHandlerTest implements RequestHandlerInterface { public static $CalledCount = 0; public static $strategy = ''; public function handle(ServerRequestInterface $request): ResponseInterface { static::$CalledCount++; // store the strategy that was used to call this handler - it's in the back trace $trace = debug_backtrace(); if (isset($trace[1])) { static::$strategy = $trace[1]['class']; } $psr7ObjectProvider = new PSR7ObjectProvider(); $responseFactory = $psr7ObjectProvider->getResponseFactory(); $response = $responseFactory ->createResponse() ->withHeader('Content-Type', 'text/plain'); $calledCount = static::$CalledCount; $response->getBody()->write("{$calledCount}"); return $response; } public function custom(ServerRequestInterface $request): ResponseInterface { $psr7ObjectProvider = new PSR7ObjectProvider(); $responseFactory = $psr7ObjectProvider->getResponseFactory(); return $responseFactory->createResponse(); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockCustomRequestHandlerInvocationStrategy.php
tests/Mocks/MockCustomRequestHandlerInvocationStrategy.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Slim\Interfaces\RequestHandlerInvocationStrategyInterface; class MockCustomRequestHandlerInvocationStrategy implements RequestHandlerInvocationStrategyInterface { public static $CalledCount = 0; public function __invoke( callable $callable, ServerRequestInterface $request, ResponseInterface $response, array $routeArguments ): ResponseInterface { self::$CalledCount += 1; return $callable($request); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/CallableTest.php
tests/Mocks/CallableTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Slim\Tests\Providers\PSR7ObjectProvider; class CallableTest { public static $CalledCount = 0; public static $CalledContainer = null; public function __construct($container = null) { static::$CalledContainer = $container; } public function toCall() { static::$CalledCount++; $psr7ObjectProvider = new PSR7ObjectProvider(); return $psr7ObjectProvider->createResponse(); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockMiddlewareSlimCallable.php
tests/Mocks/MockMiddlewareSlimCallable.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; class MockMiddlewareSlimCallable { /** * @param ServerRequestInterface $request * @param RequestHandlerInterface $handler * @return ResponseInterface */ public function custom(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { return $handler->handle($request); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockRequestHandler.php
tests/Mocks/MockRequestHandler.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Slim\Tests\Providers\PSR7ObjectProvider; class MockRequestHandler implements RequestHandlerInterface { /** * @var int */ private $calledCount = 0; /** * @param ServerRequestInterface $request * @return ResponseInterface */ public function handle(ServerRequestInterface $request): ResponseInterface { $psr7ObjectProvider = new PSR7ObjectProvider(); $responseFactory = $psr7ObjectProvider->getResponseFactory(); $this->calledCount += 1; return $responseFactory->createResponse(); } /** * @return int */ public function getCalledCount(): int { return $this->calledCount; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockStream.php
tests/Mocks/MockStream.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Exception; use InvalidArgumentException; use Psr\Http\Message\StreamInterface; use RuntimeException; use function clearstatcache; use function fclose; use function feof; use function fopen; use function fread; use function fseek; use function fstat; use function ftell; use function fwrite; use function gettype; use function is_resource; use function is_string; use function stream_get_contents; use function stream_get_meta_data; use function var_export; use const SEEK_SET; class MockStream implements StreamInterface { /** @var resource A resource reference */ private $stream; /** @var bool */ private $seekable; /** @var bool */ private $readable; /** @var bool */ private $writable; /** @var array|mixed|null|void */ private $uri; /** @var int|null */ private $size; /** @var array Hash of readable and writable stream types */ private static $readWriteHash = [ 'read' => [ 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true, 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true, 'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true, 'x+t' => true, 'c+t' => true, 'a+' => true, ], 'write' => [ 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true, 'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true, 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true, ], ]; /** * MockStream constructor. * @param string|resource $body */ public function __construct($body = '') { if (is_string($body)) { $resource = fopen('php://temp', 'rw+'); fwrite($resource, $body); $body = $resource; } if ('resource' === gettype($body)) { $this->stream = $body; $meta = stream_get_meta_data($this->stream); $this->seekable = $meta['seekable']; $this->readable = isset(self::$readWriteHash['read'][$meta['mode']]); $this->writable = isset(self::$readWriteHash['write'][$meta['mode']]); $this->uri = $this->getMetadata('uri'); } else { throw new InvalidArgumentException( 'First argument to Stream::create() must be a string, resource or StreamInterface.' ); } } /** * Closes the stream when the destructed. */ public function __destruct() { $this->close(); } public function __toString(): string { try { if ($this->isSeekable()) { $this->seek(0); } return $this->getContents(); } catch (Exception $e) { return ''; } } public function close(): void { if (isset($this->stream)) { if (is_resource($this->stream)) { fclose($this->stream); } $this->detach(); } } public function detach() { if (!isset($this->stream)) { return null; } $result = $this->stream; unset($this->stream); $this->size = $this->uri = null; $this->readable = $this->writable = $this->seekable = false; return $result; } public function getSize(): ?int { if (null !== $this->size) { return $this->size; } if (!isset($this->stream)) { return null; } // Clear the stat cache if the stream has a URI if ($this->uri) { clearstatcache(true, $this->uri); } $stats = fstat($this->stream); if (isset($stats['size'])) { $this->size = $stats['size']; return $this->size; } return null; } public function tell(): int { if (false === $result = ftell($this->stream)) { throw new RuntimeException('Unable to determine stream position'); } return $result; } public function eof(): bool { return !$this->stream || feof($this->stream); } public function isSeekable(): bool { return $this->seekable; } public function seek($offset, $whence = SEEK_SET): void { if (!$this->seekable) { throw new RuntimeException('Stream is not seekable'); } if (fseek($this->stream, $offset, $whence) === -1) { throw new RuntimeException( 'Unable to seek to stream position ' . $offset . ' with whence ' . var_export($whence, true) ); } } public function rewind(): void { $this->seek(0); } public function isWritable(): bool { return $this->writable; } public function write($string): int { if (!$this->writable) { throw new RuntimeException('Cannot write to a non-writable stream'); } // We can't know the size after writing anything $this->size = null; if (false === $result = fwrite($this->stream, $string)) { throw new RuntimeException('Unable to write to stream'); } return $result; } public function isReadable(): bool { return $this->readable; } public function read($length): string { if (!$this->readable) { throw new RuntimeException('Cannot read from non-readable stream'); } return fread($this->stream, $length); } public function getContents(): string { if (!isset($this->stream)) { throw new RuntimeException('Unable to read stream contents'); } if (false === $contents = stream_get_contents($this->stream)) { throw new RuntimeException('Unable to read stream contents'); } return $contents; } public function getMetadata($key = null) { if (!isset($this->stream)) { return $key ? null : []; } if (null === $key) { return stream_get_meta_data($this->stream); } $meta = stream_get_meta_data($this->stream); return $meta[$key] ?? null; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockPsr17Factory.php
tests/Mocks/MockPsr17Factory.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Slim\Factory\Psr17\Psr17Factory; class MockPsr17Factory extends Psr17Factory { protected static string $responseFactoryClass = ''; protected static string $streamFactoryClass = ''; protected static string $serverRequestCreatorClass = ''; protected static string $serverRequestCreatorMethod = ''; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockPsr17FactoryWithoutStreamFactory.php
tests/Mocks/MockPsr17FactoryWithoutStreamFactory.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Slim\Factory\Psr17\Psr17Factory; class MockPsr17FactoryWithoutStreamFactory extends Psr17Factory { protected static string $responseFactoryClass = 'Slim\Psr7\Factory\ResponseFactory'; protected static string $streamFactoryClass = ''; protected static string $serverRequestCreatorClass = ''; protected static string $serverRequestCreatorMethod = ''; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockSequenceMiddleware.php
tests/Mocks/MockSequenceMiddleware.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; class MockSequenceMiddleware implements MiddlewareInterface { /** * @var string */ public static $id = '0'; /** * @var bool */ public static $hasBeenInstantiated = false; public function __construct() { static::$hasBeenInstantiated = true; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $request = $request->withAddedHeader('X-SEQ-PRE-REQ-HANDLER', static::$id); $response = $handler->handle($request); return $response->withAddedHeader('X-SEQ-POST-REQ-HANDLER', static::$id); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/InvocationStrategyTest.php
tests/Mocks/InvocationStrategyTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Slim\Interfaces\InvocationStrategyInterface; class InvocationStrategyTest implements InvocationStrategyInterface { public static $LastCalledFor = null; /** * Invoke a route callable. * * @param callable $callable The callable to invoke using the strategy. * @param ServerRequestInterface $request The request object. * @param ResponseInterface $response The response object. * @param array $routeArguments The route's placeholder arguments * * @return ResponseInterface The response from the callable. */ public function __invoke( callable $callable, ServerRequestInterface $request, ResponseInterface $response, array $routeArguments ): ResponseInterface { static::$LastCalledFor = $callable; return $response; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/SmallChunksStream.php
tests/Mocks/SmallChunksStream.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Exception; use Psr\Http\Message\StreamInterface; use function min; use function str_repeat; use const SEEK_SET; class SmallChunksStream implements StreamInterface { public const CHUNK_SIZE = 10; public const SIZE = 40; /** * @var int */ private $amountToRead; public function __construct() { $this->amountToRead = self::SIZE; } public function __toString(): string { return str_repeat('.', self::SIZE); } public function close(): void { } public function detach() { throw new Exception('not implemented'); } public function eof(): bool { return $this->amountToRead === 0; } public function getContents(): string { throw new Exception('not implemented'); } public function getMetadata($key = null) { throw new Exception('not implemented'); } public function getSize(): ?int { return self::SIZE; } public function isReadable(): bool { return true; } public function isSeekable(): bool { return false; } public function isWritable(): bool { return false; } public function read($length): string { $size = min($this->amountToRead, self::CHUNK_SIZE, $length); $this->amountToRead -= $size; return str_repeat('.', min($length, $size)); } public function rewind(): void { throw new Exception('not implemented'); } public function seek($offset, $whence = SEEK_SET): void { throw new Exception('not implemented'); } public function tell(): int { throw new Exception('not implemented'); } public function write($string): int { return strlen($string); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockMiddlewareWithConstructor.php
tests/Mocks/MockMiddlewareWithConstructor.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Prophecy\Prophet; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; class MockMiddlewareWithConstructor implements MiddlewareInterface { /** * @var ContainerInterface|null */ public static $container; /** * @param ContainerInterface|null $container */ public function __construct(?ContainerInterface $container = null) { self::$container = $container; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $prophet = new Prophet(); $responseProphecy = $prophet->prophesize(ResponseInterface::class); return $responseProphecy->reveal(); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/SlowPokeStream.php
tests/Mocks/SlowPokeStream.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Exception; use Psr\Http\Message\StreamInterface; use function min; use function str_repeat; use function usleep; use const SEEK_SET; class SlowPokeStream implements StreamInterface { public const CHUNK_SIZE = 1; public const SIZE = 500; /** * @var int */ private $amountToRead; public function __construct() { $this->amountToRead = self::SIZE; } public function __toString(): string { $content = ''; while (!$this->eof()) { $content .= $this->read(self::CHUNK_SIZE); } return $content; } public function close(): void { } public function detach() { throw new Exception('not implemented'); } public function eof(): bool { return $this->amountToRead === 0; } public function getContents(): string { throw new Exception('not implemented'); } public function getMetadata($key = null) { throw new Exception('not implemented'); } public function getSize(): ?int { return null; } public function isReadable(): bool { return true; } public function isSeekable(): bool { return false; } public function isWritable(): bool { return false; } public function read($length): string { usleep(1); $size = min($this->amountToRead, self::CHUNK_SIZE, $length); $this->amountToRead -= $size; return str_repeat('.', $size); } public function rewind(): void { throw new Exception('not implemented'); } public function seek($offset, $whence = SEEK_SET): void { throw new Exception('not implemented'); } public function tell(): int { throw new Exception('not implemented'); } public function write($string): int { return strlen($string); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/InvokableTest.php
tests/Mocks/InvokableTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; class InvokableTest { public static $CalledCount = 0; public function __invoke() { return static::$CalledCount++; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockMiddlewareWithoutConstructor.php
tests/Mocks/MockMiddlewareWithoutConstructor.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; class MockMiddlewareWithoutConstructor implements MiddlewareInterface { public static $CalledCount = 0; /** * @param ServerRequestInterface $request * @param RequestHandlerInterface $handler * @return ResponseInterface */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $appendToOutput = $request->getAttribute('appendToOutput'); if ($appendToOutput !== null) { $appendToOutput('Hello World'); } static::$CalledCount++; return $handler->handle($request); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MockMiddlewareWithoutInterface.php
tests/Mocks/MockMiddlewareWithoutInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; class MockMiddlewareWithoutInterface { }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Mocks/MiddlewareTest.php
tests/Mocks/MiddlewareTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Mocks; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Slim\Tests\Providers\PSR7ObjectProvider; class MiddlewareTest implements MiddlewareInterface { public static $CalledCount = 0; /** * {@inheritdoc} */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { static::$CalledCount++; $psr7ObjectProvider = new PSR7ObjectProvider(); $responseFactory = $psr7ObjectProvider->getResponseFactory(); $response = $responseFactory ->createResponse() ->withHeader('Content-Type', 'text/plain'); $calledCount = static::$CalledCount; $response->getBody()->write("{$calledCount}"); return $response; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Exception/HttpUnauthorizedExceptionTest.php
tests/Exception/HttpUnauthorizedExceptionTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Exception; use Slim\Exception\HttpUnauthorizedException; use Slim\Tests\TestCase; class HttpUnauthorizedExceptionTest extends TestCase { public function testHttpUnauthorizedException() { $request = $this->createServerRequest('/'); $exception = new HttpUnauthorizedException($request); $this->assertInstanceOf(HttpUnauthorizedException::class, $exception); } public function testHttpUnauthorizedExceptionWithMessage() { $request = $this->createServerRequest('/'); $exception = new HttpUnauthorizedException($request, 'Hello World'); $this->assertSame('Hello World', $exception->getMessage()); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Exception/HttpExceptionTest.php
tests/Exception/HttpExceptionTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Exception; use Psr\Http\Message\ServerRequestInterface; use Slim\Exception\HttpMethodNotAllowedException; use Slim\Exception\HttpNotFoundException; use Slim\Tests\TestCase; class HttpExceptionTest extends TestCase { public function testHttpExceptionRequestReponseGetterSetters() { $request = $this->createServerRequest('/'); $exception = new HttpNotFoundException($request); $this->assertInstanceOf(ServerRequestInterface::class, $exception->getRequest()); } public function testHttpExceptionAttributeGettersSetters() { $request = $this->createServerRequest('/'); $exception = new HttpNotFoundException($request); $exception->setTitle('Title'); $exception->setDescription('Description'); $this->assertSame('Title', $exception->getTitle()); $this->assertSame('Description', $exception->getDescription()); } public function testHttpNotAllowedExceptionGetAllowedMethods() { $request = $this->createServerRequest('/'); $exception = new HttpMethodNotAllowedException($request); $exception->setAllowedMethods(['GET']); $this->assertSame(['GET'], $exception->getAllowedMethods()); $this->assertSame('Method not allowed. Must be one of: GET', $exception->getMessage()); $exception = new HttpMethodNotAllowedException($request); $this->assertSame([], $exception->getAllowedMethods()); $this->assertSame('Method not allowed.', $exception->getMessage()); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Middleware/MethodOverrideMiddlewareTest.php
tests/Middleware/MethodOverrideMiddlewareTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Middleware; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\StreamInterface; use Psr\Http\Server\RequestHandlerInterface as RequestHandler; use Slim\Middleware\MethodOverrideMiddleware; use Slim\Tests\TestCase; class MethodOverrideMiddlewareTest extends TestCase { public function testHeader() { $responseFactory = $this->getResponseFactory(); $middleware = (function (Request $request, RequestHandler $handler) use ($responseFactory) { $this->assertSame('PUT', $request->getMethod()); return $responseFactory->createResponse(); })->bindTo($this); $methodOverrideMiddleware = new MethodOverrideMiddleware(); $request = $this ->createServerRequest('/', 'POST') ->withHeader('X-Http-Method-Override', 'PUT'); $middlewareDispatcher = $this->createMiddlewareDispatcher( $this->createMock(RequestHandler::class), null ); $middlewareDispatcher->addCallable($middleware); $middlewareDispatcher->addMiddleware($methodOverrideMiddleware); $middlewareDispatcher->handle($request); } public function testBodyParam() { $responseFactory = $this->getResponseFactory(); $middleware = (function (Request $request, RequestHandler $handler) use ($responseFactory) { $this->assertSame('PUT', $request->getMethod()); return $responseFactory->createResponse(); })->bindTo($this); $methodOverrideMiddleware = new MethodOverrideMiddleware(); $request = $this ->createServerRequest('/', 'POST') ->withParsedBody(['_METHOD' => 'PUT']); $middlewareDispatcher = $this->createMiddlewareDispatcher( $this->createMock(RequestHandler::class), null ); $middlewareDispatcher->addCallable($middleware); $middlewareDispatcher->addMiddleware($methodOverrideMiddleware); $middlewareDispatcher->handle($request); } public function testHeaderPreferred() { $responseFactory = $this->getResponseFactory(); $middleware = (function (Request $request, RequestHandler $handler) use ($responseFactory) { $this->assertSame('DELETE', $request->getMethod()); return $responseFactory->createResponse(); })->bindTo($this); $methodOverrideMiddleware = new MethodOverrideMiddleware(); $request = $this ->createServerRequest('/', 'POST') ->withHeader('X-Http-Method-Override', 'DELETE') ->withParsedBody((object) ['_METHOD' => 'PUT']); $middlewareDispatcher = $this->createMiddlewareDispatcher( $this->createMock(RequestHandler::class), null ); $middlewareDispatcher->addCallable($middleware); $middlewareDispatcher->addMiddleware($methodOverrideMiddleware); $middlewareDispatcher->handle($request); } public function testNoOverride() { $responseFactory = $this->getResponseFactory(); $middleware = (function (Request $request, RequestHandler $handler) use ($responseFactory) { $this->assertSame('POST', $request->getMethod()); return $responseFactory->createResponse(); })->bindTo($this); $methodOverrideMiddleware = new MethodOverrideMiddleware(); $request = $this->createServerRequest('/', 'POST'); $middlewareDispatcher = $this->createMiddlewareDispatcher( $this->createMock(RequestHandler::class), null ); $middlewareDispatcher->addCallable($middleware); $middlewareDispatcher->addMiddleware($methodOverrideMiddleware); $middlewareDispatcher->handle($request); } public function testNoOverrideRewindEofBodyStream() { $responseFactory = $this->getResponseFactory(); $middleware = (function (Request $request, RequestHandler $handler) use ($responseFactory) { $this->assertSame('POST', $request->getMethod()); return $responseFactory->createResponse(); })->bindTo($this); $methodOverrideMiddleware = new MethodOverrideMiddleware(); $request = $this->createServerRequest('/', 'POST'); // Prophesize the body stream for which `eof()` returns `true` and the // `rewind()` has to be called. $bodyProphecy = $this->prophesize(StreamInterface::class); /** @noinspection PhpUndefinedMethodInspection */ $bodyProphecy->eof() ->willReturn(true) ->shouldBeCalled(); /** @noinspection PhpUndefinedMethodInspection */ $bodyProphecy->rewind() ->shouldBeCalled(); /** @var StreamInterface $body */ $body = $bodyProphecy->reveal(); $request = $request->withBody($body); $middlewareDispatcher = $this->createMiddlewareDispatcher( $this->createMock(RequestHandler::class), null ); $middlewareDispatcher->addCallable($middleware); $middlewareDispatcher->addMiddleware($methodOverrideMiddleware); $middlewareDispatcher->handle($request); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Middleware/BodyParsingMiddlewareTest.php
tests/Middleware/BodyParsingMiddlewareTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; use Slim\Middleware\BodyParsingMiddleware; use Slim\Tests\TestCase; use function is_string; use function simplexml_load_string; class BodyParsingMiddlewareTest extends TestCase { /** * Create a request handler that simply assigns the $request that it receives to a public property * of the returned response, so that we can then inspect that request. */ protected function createRequestHandler(): RequestHandlerInterface { $response = $this->createResponse(); return new class ($response) implements RequestHandlerInterface { private $response; public $request; public function __construct(ResponseInterface $response) { $this->response = $response; } public function handle(ServerRequestInterface $request): ResponseInterface { $this->request = $request; return $this->response; } }; } /** * @param string $contentType * @param string $body * @return ServerRequestInterface */ protected function createRequestWithBody($contentType, $body) { $request = $this->createServerRequest('/', 'POST'); if (is_string($contentType)) { $request = $request->withHeader('Content-Type', $contentType); } if (is_string($body)) { $request = $request->withBody($this->createStream($body)); } return $request; } public static function parsingProvider() { return [ 'form' => [ 'application/x-www-form-urlencoded;charset=utf8', 'foo=bar', ['foo' => 'bar'], ], 'json' => [ "application/json", '{"foo":"bar"}', ['foo' => 'bar'], ], 'json-with-charset' => [ "application/json\t ; charset=utf8", '{"foo":"bar"}', ['foo' => 'bar'], ], 'json-suffix' => [ 'application/vnd.api+json;charset=utf8', '{"foo":"bar"}', ['foo' => 'bar'], ], 'xml' => [ 'application/xml', '<person><name>John</name></person>', simplexml_load_string('<person><name>John</name></person>'), ], 'xml-suffix' => [ 'application/hal+xml;charset=utf8', '<person><name>John</name></person>', simplexml_load_string('<person><name>John</name></person>'), ], 'text-xml' => [ 'text/xml', '<person><name>John</name></person>', simplexml_load_string('<person><name>John</name></person>'), ], 'invalid-json' => [ 'application/json;charset=utf8', '{"foo"}/bar', null, ], 'valid-json-but-not-an-array' => [ 'application/json;charset=utf8', '"foo bar"', null, ], 'unknown-contenttype' => [ 'text/foo+bar', '"foo bar"', null, ], 'empty-contenttype' => [ '', '"foo bar"', null, ], 'no-contenttype' => [ null, '"foo bar"', null, ], 'invalid-contenttype' => [ 'foo', '"foo bar"', null, ], 'invalid-xml' => [ 'application/xml', '<person><name>John</name></invalid>', null, ], 'invalid-textxml' => [ 'text/xml', '<person><name>John</name></invalid>', null, ], ]; } /** * @dataProvider parsingProvider */ #[\PHPUnit\Framework\Attributes\DataProvider('parsingProvider')] public function testParsing($contentType, $body, $expected) { $request = $this->createRequestWithBody($contentType, $body); $middleware = new BodyParsingMiddleware(); $requestHandler = $this->createRequestHandler(); $middleware->process($request, $requestHandler); $this->assertEquals($expected, $requestHandler->request->getParsedBody()); } public function testParsingWithARegisteredParser() { $request = $this->createRequestWithBody('application/vnd.api+json', '{"foo":"bar"}'); $parsers = [ 'application/vnd.api+json' => function ($input) { return ['data' => $input]; }, ]; $middleware = new BodyParsingMiddleware($parsers); $requestHandler = $this->createRequestHandler(); $middleware->process($request, $requestHandler); $this->assertSame(['data' => '{"foo":"bar"}'], $requestHandler->request->getParsedBody()); } public function testParsingFailsWhenAnInvalidTypeIsReturned() { $request = $this->createRequestWithBody('application/json;charset=utf8', '{"foo":"bar"}'); $parsers = [ 'application/json' => function ($input) { return 10; // invalid - should return null, array or object }, ]; $middleware = new BodyParsingMiddleware($parsers); $this->expectException(RuntimeException::class); $middleware->process($request, $this->createRequestHandler()); } public function testSettingAndGettingAParser() { $middleware = new BodyParsingMiddleware(); $parser = function ($input) { return ['data' => $input]; }; $this->assertFalse($middleware->hasBodyParser('text/foo')); $middleware->registerBodyParser('text/foo', $parser); $this->assertTrue($middleware->hasBodyParser('text/foo')); $this->assertSame($parser, $middleware->getBodyParser('text/foo')); } public function testGettingUnknownParser() { $middleware = new BodyParsingMiddleware(); $this->expectException(RuntimeException::class); $middleware->getBodyParser('text/foo'); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Middleware/ErrorMiddlewareTest.php
tests/Middleware/ErrorMiddlewareTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Middleware; use Error; use InvalidArgumentException; use LogicException; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LoggerInterface; use RuntimeException; use Slim\App; use Slim\Exception\HttpNotFoundException; use Slim\Handlers\ErrorHandler; use Slim\Middleware\ErrorMiddleware; use Slim\Middleware\RoutingMiddleware; use Slim\Tests\Mocks\MockCustomException; use Slim\Tests\TestCase; class ErrorMiddlewareTest extends TestCase { private function getMockLogger(): LoggerInterface { return $this->createMock(LoggerInterface::class); } public function testSetErrorHandler() { $responseFactory = $this->getResponseFactory(); $app = new App($responseFactory); $callableResolver = $app->getCallableResolver(); $logger = $this->getMockLogger(); $routingMiddleware = new RoutingMiddleware( $app->getRouteResolver(), $app->getRouteCollector()->getRouteParser() ); $app->add($routingMiddleware); $exception = HttpNotFoundException::class; $handler = (function () { $response = $this->createResponse(500); $response->getBody()->write('Oops..'); return $response; })->bindTo($this); $errorMiddleware = new ErrorMiddleware( $callableResolver, $this->getResponseFactory(), false, false, false, $logger ); $errorMiddleware->setErrorHandler($exception, $handler); $app->add($errorMiddleware); $request = $this->createServerRequest('/foo/baz/'); $app->run($request); $this->expectOutputString('Oops..'); } public function testSetDefaultErrorHandler() { $responseFactory = $this->getResponseFactory(); $app = new App($responseFactory); $callableResolver = $app->getCallableResolver(); $logger = $this->getMockLogger(); $routingMiddleware = new RoutingMiddleware( $app->getRouteResolver(), $app->getRouteCollector()->getRouteParser() ); $app->add($routingMiddleware); $handler = (function () { $response = $this->createResponse(); $response->getBody()->write('Oops..'); return $response; })->bindTo($this); $errorMiddleware = new ErrorMiddleware( $callableResolver, $this->getResponseFactory(), false, false, false, $logger ); $errorMiddleware->setDefaultErrorHandler($handler); $app->add($errorMiddleware); $request = $this->createServerRequest('/foo/baz/'); $app->run($request); $this->expectOutputString('Oops..'); } public function testSetDefaultErrorHandlerThrowsException() { $this->expectException(RuntimeException::class); $responseFactory = $this->getResponseFactory(); $app = new App($responseFactory); $callableResolver = $app->getCallableResolver(); $logger = $this->getMockLogger(); $errorMiddleware = new ErrorMiddleware( $callableResolver, $this->getResponseFactory(), false, false, false, $logger ); $errorMiddleware->setDefaultErrorHandler('Uncallable'); $errorMiddleware->getDefaultErrorHandler(); } public function testGetErrorHandlerWillReturnDefaultErrorHandlerForUnhandledExceptions() { $responseFactory = $this->getResponseFactory(); $app = new App($responseFactory); $callableResolver = $app->getCallableResolver(); $logger = $this->getMockLogger(); $middleware = new ErrorMiddleware($callableResolver, $this->getResponseFactory(), false, false, false, $logger); $exception = MockCustomException::class; $handler = $middleware->getErrorHandler($exception); $this->assertInstanceOf(ErrorHandler::class, $handler); } public function testSuperclassExceptionHandlerHandlesExceptionWithSubclassExactMatch() { $responseFactory = $this->getResponseFactory(); $app = new App($responseFactory); $callableResolver = $app->getCallableResolver(); $logger = $this->getMockLogger(); $middleware = new ErrorMiddleware($callableResolver, $this->getResponseFactory(), false, false, false, $logger); $app->add(function ($request, $handler) { throw new LogicException('This is a LogicException...'); }); $middleware->setErrorHandler(LogicException::class, (function (ServerRequestInterface $request, $exception) { $response = $this->createResponse(); $response->getBody()->write($exception->getMessage()); return $response; })->bindTo($this), true); // - true; handle subclass but also LogicException explicitly $middleware->setDefaultErrorHandler((function () { $response = $this->createResponse(); $response->getBody()->write('Oops..'); return $response; })->bindTo($this)); $app->add($middleware); $app->get('/foo', function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write('...'); return $response; }); $request = $this->createServerRequest('/foo'); $app->run($request); $this->expectOutputString('This is a LogicException...'); } public function testSuperclassExceptionHandlerHandlesSubclassException() { $responseFactory = $this->getResponseFactory(); $app = new App($responseFactory); $callableResolver = $app->getCallableResolver(); $logger = $this->getMockLogger(); $middleware = new ErrorMiddleware($callableResolver, $this->getResponseFactory(), false, false, false, $logger); $app->add(function ($request, $handler) { throw new InvalidArgumentException('This is a subclass of LogicException...'); }); $middleware->setErrorHandler(LogicException::class, (function (ServerRequestInterface $request, $exception) { $response = $this->createResponse(); $response->getBody()->write($exception->getMessage()); return $response; })->bindTo($this), true); // - true; handle subclass $middleware->setDefaultErrorHandler((function () { $response = $this->createResponse(); $response->getBody()->write('Oops..'); return $response; })->bindTo($this)); $app->add($middleware); $app->get('/foo', function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write('...'); return $response; }); $request = $this->createServerRequest('/foo'); $app->run($request); $this->expectOutputString('This is a subclass of LogicException...'); } public function testSuperclassExceptionHandlerDoesNotHandleSubclassException() { $responseFactory = $this->getResponseFactory(); $app = new App($responseFactory); $callableResolver = $app->getCallableResolver(); $logger = $this->getMockLogger(); $middleware = new ErrorMiddleware($callableResolver, $this->getResponseFactory(), false, false, false, $logger); $app->add(function ($request, $handler) { throw new InvalidArgumentException('This is a subclass of LogicException...'); }); $middleware->setErrorHandler(LogicException::class, (function (ServerRequestInterface $request, $exception) { $response = $this->createResponse(); $response->getBody()->write($exception->getMessage()); return $response; })->bindTo($this), false); // - false; don't handle subclass $middleware->setDefaultErrorHandler((function () { $response = $this->createResponse(); $response->getBody()->write('Oops..'); return $response; })->bindTo($this)); $app->add($middleware); $app->get('/foo', function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write('...'); return $response; }); $request = $this->createServerRequest('/foo'); $app->run($request); $this->expectOutputString('Oops..'); } public function testHandleMultipleExceptionsAddedAsArray() { $responseFactory = $this->getResponseFactory(); $app = new App($responseFactory); $callableResolver = $app->getCallableResolver(); $logger = $this->getMockLogger(); $middleware = new ErrorMiddleware($callableResolver, $this->getResponseFactory(), false, false, false, $logger); $app->add(function ($request, $handler) { throw new InvalidArgumentException('This is an invalid argument exception...'); }); $handler = (function (ServerRequestInterface $request, $exception) { $response = $this->createResponse(); $response->getBody()->write($exception->getMessage()); return $response; }); $middleware->setErrorHandler([LogicException::class, InvalidArgumentException::class], $handler->bindTo($this)); $middleware->setDefaultErrorHandler((function () { $response = $this->createResponse(); $response->getBody()->write('Oops..'); return $response; })->bindTo($this)); $app->add($middleware); $app->get('/foo', function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write('...'); return $response; }); $request = $this->createServerRequest('/foo'); $app->run($request); $this->expectOutputString('This is an invalid argument exception...'); } public function testErrorHandlerHandlesThrowables() { $responseFactory = $this->getResponseFactory(); $app = new App($responseFactory); $callableResolver = $app->getCallableResolver(); $logger = $this->getMockLogger(); $middleware = new ErrorMiddleware($callableResolver, $this->getResponseFactory(), false, false, false, $logger); $app->add(function ($request, $handler) { throw new Error('Oops..'); }); $middleware->setDefaultErrorHandler((function (ServerRequestInterface $request, $exception) { $response = $this->createResponse(); $response->getBody()->write($exception->getMessage()); return $response; })->bindTo($this)); $app->add($middleware); $app->get('/foo', function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write('...'); return $response; }); $request = $this->createServerRequest('/foo'); $app->run($request); $this->expectOutputString('Oops..'); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Middleware/OutputBufferingMiddlewareTest.php
tests/Middleware/OutputBufferingMiddlewareTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Middleware; use Exception; use InvalidArgumentException; use Psr\Http\Server\RequestHandlerInterface; use ReflectionProperty; use Slim\Middleware\OutputBufferingMiddleware; use Slim\Tests\TestCase; use function ob_get_contents; class OutputBufferingMiddlewareTest extends TestCase { public function testStyleDefaultValid() { $middleware = new OutputBufferingMiddleware($this->getStreamFactory()); $reflectionProperty = new ReflectionProperty($middleware, 'style'); $this->setAccessible($reflectionProperty); $value = $reflectionProperty->getValue($middleware); $this->assertSame('append', $value); } public function testStyleCustomValid() { $middleware = new OutputBufferingMiddleware($this->getStreamFactory(), 'prepend'); $reflectionProperty = new ReflectionProperty($middleware, 'style'); $this->setAccessible($reflectionProperty); $value = $reflectionProperty->getValue($middleware); $this->assertSame('prepend', $value); } public function testStyleCustomInvalid() { $this->expectException(InvalidArgumentException::class); new OutputBufferingMiddleware($this->getStreamFactory(), 'foo'); } public function testAppend() { $responseFactory = $this->getResponseFactory(); $middleware = function ($request, $handler) use ($responseFactory) { $response = $responseFactory->createResponse(); $response->getBody()->write('Body'); echo 'Test'; return $response; }; $outputBufferingMiddleware = new OutputBufferingMiddleware($this->getStreamFactory(), 'append'); $request = $this->createServerRequest('/', 'GET'); $middlewareDispatcher = $this->createMiddlewareDispatcher( $this->createMock(RequestHandlerInterface::class), null ); $middlewareDispatcher->addCallable($middleware); $middlewareDispatcher->addMiddleware($outputBufferingMiddleware); $response = $middlewareDispatcher->handle($request); $this->assertSame('BodyTest', (string) $response->getBody()); } public function testPrepend() { $responseFactory = $this->getResponseFactory(); $middleware = function ($request, $handler) use ($responseFactory) { $response = $responseFactory->createResponse(); $response->getBody()->write('Body'); echo 'Test'; return $response; }; $outputBufferingMiddleware = new OutputBufferingMiddleware($this->getStreamFactory(), 'prepend'); $request = $this->createServerRequest('/', 'GET'); $middlewareDispatcher = $this->createMiddlewareDispatcher( $this->createMock(RequestHandlerInterface::class), null ); $middlewareDispatcher->addCallable($middleware); $middlewareDispatcher->addMiddleware($outputBufferingMiddleware); $response = $middlewareDispatcher->handle($request); $this->assertSame('TestBody', (string) $response->getBody()); } public function testOutputBufferIsCleanedWhenThrowableIsCaught() { $this->getResponseFactory(); $middleware = (function ($request, $handler) { echo "Test"; $this->assertSame('Test', ob_get_contents()); throw new Exception('Oops...'); })->bindTo($this); $outputBufferingMiddleware = new OutputBufferingMiddleware($this->getStreamFactory(), 'prepend'); $request = $this->createServerRequest('/', 'GET'); $middlewareDispatcher = $this->createMiddlewareDispatcher( $this->createMock(RequestHandlerInterface::class), null ); $middlewareDispatcher->addCallable($middleware); $middlewareDispatcher->addMiddleware($outputBufferingMiddleware); try { $middlewareDispatcher->handle($request); } catch (Exception $e) { $this->assertSame('', ob_get_contents()); } } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Middleware/ContentLengthMiddlewareTest.php
tests/Middleware/ContentLengthMiddlewareTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Middleware; use Psr\Http\Server\RequestHandlerInterface; use Slim\Middleware\ContentLengthMiddleware; use Slim\Tests\TestCase; class ContentLengthMiddlewareTest extends TestCase { public function testAddsContentLength() { $request = $this->createServerRequest('/'); $responseFactory = $this->getResponseFactory(); $mw = function ($request, $handler) use ($responseFactory) { $response = $responseFactory->createResponse(); $response->getBody()->write('Body'); return $response; }; $mw2 = new ContentLengthMiddleware(); $middlewareDispatcher = $this->createMiddlewareDispatcher( $this->createMock(RequestHandlerInterface::class), null ); $middlewareDispatcher->addCallable($mw); $middlewareDispatcher->addMiddleware($mw2); $response = $middlewareDispatcher->handle($request); $this->assertSame('4', $response->getHeaderLine('Content-Length')); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Middleware/RoutingMiddlewareTest.php
tests/Middleware/RoutingMiddlewareTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Middleware; use FastRoute\Dispatcher; use Prophecy\Argument; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; use Slim\CallableResolver; use Slim\Exception\HttpMethodNotAllowedException; use Slim\Exception\HttpNotFoundException; use Slim\Interfaces\RouteParserInterface; use Slim\Interfaces\RouteResolverInterface; use Slim\Middleware\RoutingMiddleware; use Slim\Routing\RouteCollector; use Slim\Routing\RouteContext; use Slim\Routing\RouteParser; use Slim\Routing\RouteResolver; use Slim\Routing\RoutingResults; use Slim\Tests\TestCase; class RoutingMiddlewareTest extends TestCase { protected function getRouteCollector() { $callableResolver = new CallableResolver(); $responseFactory = $this->getResponseFactory(); $routeCollector = new RouteCollector($responseFactory, $callableResolver); $routeCollector->map(['GET'], '/hello/{name}', null); return $routeCollector; } public function testRouteIsStoredOnSuccessfulMatch() { $responseFactory = $this->getResponseFactory(); $middleware = (function (ServerRequestInterface $request) use ($responseFactory) { // route is available $route = $request->getAttribute(RouteContext::ROUTE); $this->assertNotNull($route); $this->assertSame('foo', $route->getArgument('name')); // routeParser is available $routeParser = $request->getAttribute(RouteContext::ROUTE_PARSER); $this->assertNotNull($routeParser); $this->assertInstanceOf(RouteParserInterface::class, $routeParser); // routingResults is available $routingResults = $request->getAttribute(RouteContext::ROUTING_RESULTS); $this->assertInstanceOf(RoutingResults::class, $routingResults); return $responseFactory->createResponse(); })->bindTo($this); $routeCollector = $this->getRouteCollector(); $routeParser = new RouteParser($routeCollector); $routeResolver = new RouteResolver($routeCollector); $routingMiddleware = new RoutingMiddleware($routeResolver, $routeParser); $request = $this->createServerRequest('https://example.com:443/hello/foo', 'GET'); $middlewareDispatcher = $this->createMiddlewareDispatcher( $this->createMock(RequestHandlerInterface::class), null ); $middlewareDispatcher->addCallable($middleware); $middlewareDispatcher->addMiddleware($routingMiddleware); $middlewareDispatcher->handle($request); } public function testRouteIsNotStoredOnMethodNotAllowed() { $routeCollector = $this->getRouteCollector(); $routeParser = new RouteParser($routeCollector); $routeResolver = new RouteResolver($routeCollector); $routingMiddleware = new RoutingMiddleware($routeResolver, $routeParser); $request = $this->createServerRequest('https://example.com:443/hello/foo', 'POST'); $requestHandlerProphecy = $this->prophesize(RequestHandlerInterface::class); /** @var RequestHandlerInterface $requestHandler */ $requestHandler = $requestHandlerProphecy->reveal(); $middlewareDispatcher = $this->createMiddlewareDispatcher($requestHandler, null); $middlewareDispatcher->addMiddleware($routingMiddleware); try { $middlewareDispatcher->handle($request); $this->fail('HTTP method should not have been allowed'); } catch (HttpMethodNotAllowedException $exception) { $request = $exception->getRequest(); // route is not available $route = $request->getAttribute(RouteContext::ROUTE); $this->assertNull($route); // routeParser is available $routeParser = $request->getAttribute(RouteContext::ROUTE_PARSER); $this->assertNotNull($routeParser); $this->assertInstanceOf(RouteParserInterface::class, $routeParser); // routingResults is available $routingResults = $request->getAttribute(RouteContext::ROUTING_RESULTS); $this->assertInstanceOf(RoutingResults::class, $routingResults); $this->assertSame(Dispatcher::METHOD_NOT_ALLOWED, $routingResults->getRouteStatus()); } } public function testRouteIsNotStoredOnNotFound() { $routeCollector = $this->getRouteCollector(); $routeParser = new RouteParser($routeCollector); $routeResolver = new RouteResolver($routeCollector); $routingMiddleware = new RoutingMiddleware($routeResolver, $routeParser); $request = $this->createServerRequest('https://example.com:443/goodbye', 'GET'); $requestHandlerProphecy = $this->prophesize(RequestHandlerInterface::class); /** @var RequestHandlerInterface $requestHandler */ $requestHandler = $requestHandlerProphecy->reveal(); $middlewareDispatcher = $this->createMiddlewareDispatcher($requestHandler, null); $middlewareDispatcher->addMiddleware($routingMiddleware); try { $middlewareDispatcher->handle($request); $this->fail('HTTP route should not have been found'); } catch (HttpNotFoundException $exception) { $request = $exception->getRequest(); // route is not available $route = $request->getAttribute(RouteContext::ROUTE); $this->assertNull($route); // routeParser is available $routeParser = $request->getAttribute(RouteContext::ROUTE_PARSER); $this->assertNotNull($routeParser); $this->assertInstanceOf(RouteParserInterface::class, $routeParser); // routingResults is available $routingResults = $request->getAttribute(RouteContext::ROUTING_RESULTS); $this->assertInstanceOf(RoutingResults::class, $routingResults); $this->assertSame(Dispatcher::NOT_FOUND, $routingResults->getRouteStatus()); } } public function testPerformRoutingThrowsExceptionOnInvalidRoutingResultsRouteStatus() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('An unexpected error occurred while performing routing.'); // Prophesize the `RoutingResults` instance that would return an invalid route // status when the method `getRouteStatus()` gets called. $routingResultsProphecy = $this->prophesize(RoutingResults::class); /** @noinspection PhpUndefinedMethodInspection */ $routingResultsProphecy->getRouteStatus() ->willReturn(-1) ->shouldBeCalledOnce(); /** @var RoutingResults $routingResults */ $routingResults = $routingResultsProphecy->reveal(); // Prophesize the `RouteParserInterface` instance will be created. $routeParserProphecy = $this->prophesize(RouteParser::class); /** @var RouteParserInterface $routeParser */ $routeParser = $routeParserProphecy->reveal(); // Prophesize the `RouteResolverInterface` that would return the `RoutingResults` // defined above, when the method `computeRoutingResults()` gets called. $routeResolverProphecy = $this->prophesize(RouteResolverInterface::class); /** @noinspection PhpUndefinedMethodInspection */ $routeResolverProphecy->computeRoutingResults(Argument::any(), Argument::any()) ->willReturn($routingResults) ->shouldBeCalled(); /** @var RouteResolverInterface $routeResolver */ $routeResolver = $routeResolverProphecy->reveal(); // Create the server request. $request = $this->createServerRequest('https://example.com:443/hello/foo', 'GET'); // Create the routing middleware with the `RouteResolverInterface` defined // above. Perform the routing, which should throw the RuntimeException. $middleware = new RoutingMiddleware($routeResolver, $routeParser); /** @noinspection PhpUnhandledExceptionInspection */ $middleware->performRouting($request); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Error/AbstractErrorRendererTest.php
tests/Error/AbstractErrorRendererTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Error; use Exception; use ReflectionClass; use RuntimeException; use Slim\Error\Renderers\HtmlErrorRenderer; use Slim\Error\Renderers\JsonErrorRenderer; use Slim\Error\Renderers\PlainTextErrorRenderer; use Slim\Error\Renderers\XmlErrorRenderer; use Slim\Exception\HttpException; use Slim\Tests\TestCase; use stdClass; use function json_decode; use function json_encode; use function simplexml_load_string; class AbstractErrorRendererTest extends TestCase { public function testHTMLErrorRendererDisplaysErrorDetails() { $exception = new RuntimeException('Oops..'); $renderer = new HtmlErrorRenderer(); $output = $renderer->__invoke($exception, true); $this->assertMatchesRegularExpression( '/.*The application could not run because of the following error:.*/', $output ); $this->assertStringContainsString('Oops..', $output); } public function testHTMLErrorRendererNoErrorDetails() { $exception = new RuntimeException('Oops..'); $renderer = new HtmlErrorRenderer(); $output = $renderer->__invoke($exception, false); $this->assertMatchesRegularExpression( '/.*A website error has occurred. Sorry for the temporary inconvenience.*/', $output ); $this->assertStringNotContainsString('Oops..', $output); } public function testHTMLErrorRendererRenderFragmentMethod() { $exception = new Exception('Oops..', 500); $renderer = new HtmlErrorRenderer(); $reflectionRenderer = new ReflectionClass(HtmlErrorRenderer::class); $method = $reflectionRenderer->getMethod('renderExceptionFragment'); $this->setAccessible($method); $output = $method->invoke($renderer, $exception); $this->assertMatchesRegularExpression('/.*Type:*/', $output); $this->assertMatchesRegularExpression('/.*Code:*/', $output); $this->assertMatchesRegularExpression('/.*Message*/', $output); $this->assertMatchesRegularExpression('/.*File*/', $output); $this->assertMatchesRegularExpression('/.*Line*/', $output); } public function testHTMLErrorRendererRenderHttpException() { $exceptionTitle = 'title'; $exceptionDescription = 'description'; $httpExceptionProphecy = $this->prophesize(HttpException::class); $httpExceptionProphecy ->getTitle() ->willReturn($exceptionTitle) ->shouldBeCalledOnce(); $httpExceptionProphecy ->getDescription() ->willReturn($exceptionDescription) ->shouldBeCalledOnce(); $renderer = new HtmlErrorRenderer(); $output = $renderer->__invoke($httpExceptionProphecy->reveal(), false); $this->assertStringContainsString($exceptionTitle, $output, 'Should contain http exception title'); $this->assertStringContainsString($exceptionDescription, $output, 'Should contain http exception description'); } public function testJSONErrorRendererDisplaysErrorDetails() { $exception = new Exception('Oops..'); $renderer = new JsonErrorRenderer(); $reflectionRenderer = new ReflectionClass(JsonErrorRenderer::class); $method = $reflectionRenderer->getMethod('formatExceptionFragment'); $this->setAccessible($method); $fragment = $method->invoke($renderer, $exception); $output = json_encode(json_decode($renderer->__invoke($exception, true))); $expectedString = json_encode(['message' => 'Slim Application Error', 'exception' => [$fragment]]); $this->assertSame($output, $expectedString); } public function testJSONErrorRendererDoesNotDisplayErrorDetails() { $exception = new Exception('Oops..'); $renderer = new JsonErrorRenderer(); $output = json_encode(json_decode($renderer->__invoke($exception, false))); $this->assertSame($output, json_encode(['message' => 'Slim Application Error'])); } public function testJSONErrorRendererDisplaysPreviousError() { $previousException = new Exception('Oh no!'); $exception = new Exception('Oops..', 0, $previousException); $renderer = new JsonErrorRenderer(); $reflectionRenderer = new ReflectionClass(JsonErrorRenderer::class); $method = $reflectionRenderer->getMethod('formatExceptionFragment'); $this->setAccessible($method); $output = json_encode(json_decode($renderer->__invoke($exception, true))); $fragments = [ $method->invoke($renderer, $exception), $method->invoke($renderer, $previousException), ]; $expectedString = json_encode(['message' => 'Slim Application Error', 'exception' => $fragments]); $this->assertSame($output, $expectedString); } public function testJSONErrorRendererRenderHttpException() { $exceptionTitle = 'title'; $httpExceptionProphecy = $this->prophesize(HttpException::class); $httpExceptionProphecy ->getTitle() ->willReturn($exceptionTitle) ->shouldBeCalledOnce(); $renderer = new JsonErrorRenderer(); $output = json_encode(json_decode($renderer->__invoke($httpExceptionProphecy->reveal(), false))); $this->assertSame( $output, json_encode(['message' => $exceptionTitle]), 'Should contain http exception title' ); } public function testXMLErrorRendererDisplaysErrorDetails() { $previousException = new RuntimeException('Oops..'); $exception = new Exception('Ooops...', 0, $previousException); $renderer = new XmlErrorRenderer(); /** @var stdClass $output */ $output = simplexml_load_string($renderer->__invoke($exception, true)); $this->assertSame((string) $output->message[0], 'Slim Application Error'); $this->assertSame((string) $output->exception[0]->type, 'Exception'); $this->assertSame((string) $output->exception[0]->message, 'Ooops...'); $this->assertSame((string) $output->exception[1]->type, 'RuntimeException'); $this->assertSame((string) $output->exception[1]->message, 'Oops..'); } public function testXMLErrorRendererRenderHttpException() { $exceptionTitle = 'title'; $httpExceptionProphecy = $this->prophesize(HttpException::class); $httpExceptionProphecy ->getTitle() ->willReturn($exceptionTitle) ->shouldBeCalledOnce(); $renderer = new XmlErrorRenderer(); /** @var stdClass $output */ $output = simplexml_load_string($renderer->__invoke($httpExceptionProphecy->reveal(), true)); $this->assertSame((string) $output->message[0], $exceptionTitle, 'Should contain http exception title'); } public function testPlainTextErrorRendererFormatFragmentMethod() { $message = 'Oops.. <br>'; $exception = new Exception($message, 500); $renderer = new PlainTextErrorRenderer(); $reflectionRenderer = new ReflectionClass(PlainTextErrorRenderer::class); $method = $reflectionRenderer->getMethod('formatExceptionFragment'); $this->setAccessible($method); $output = $method->invoke($renderer, $exception); $this->assertIsString($output); $this->assertMatchesRegularExpression('/.*Type:*/', $output); $this->assertMatchesRegularExpression('/.*Code:*/', $output); $this->assertMatchesRegularExpression('/.*Message*/', $output); $this->assertMatchesRegularExpression('/.*File*/', $output); $this->assertMatchesRegularExpression('/.*Line*/', $output); // ensure the renderer doesn't reformat the message $this->assertMatchesRegularExpression("/.*$message/", $output); } public function testPlainTextErrorRendererDisplaysErrorDetails() { $previousException = new RuntimeException('Oops..'); $exception = new Exception('Ooops...', 0, $previousException); $renderer = new PlainTextErrorRenderer(); $output = $renderer->__invoke($exception, true); $this->assertMatchesRegularExpression('/Ooops.../', $output); } public function testPlainTextErrorRendererNotDisplaysErrorDetails() { $previousException = new RuntimeException('Oops..'); $exception = new Exception('Ooops...', 0, $previousException); $renderer = new PlainTextErrorRenderer(); $output = $renderer->__invoke($exception, false); $this->assertSame("Slim Application Error\n", $output, 'Should show only one string'); } public function testPlainTextErrorRendererRenderHttpException() { $exceptionTitle = 'title'; $httpExceptionProphecy = $this->prophesize(HttpException::class); $httpExceptionProphecy ->getTitle() ->willReturn($exceptionTitle) ->shouldBeCalledOnce(); $renderer = new PlainTextErrorRenderer(); $output = $renderer->__invoke($httpExceptionProphecy->reveal(), true); $this->assertStringContainsString($exceptionTitle, $output, 'Should contain http exception title'); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Providers/PSR7ObjectProviderInterface.php
tests/Providers/PSR7ObjectProviderInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Providers; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestFactoryInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; /** * Interface PSR7ObjectProviderInterface * * @package Slim\Tests\Providers */ interface PSR7ObjectProviderInterface { /** * @return ServerRequestFactoryInterface */ public function getServerRequestFactory(): ServerRequestFactoryInterface; /** * @return ResponseFactoryInterface */ public function getResponseFactory(): ResponseFactoryInterface; /** * @return StreamFactoryInterface */ public function getStreamFactory(): StreamFactoryInterface; /** * @param string $uri * @param string $method * @param array $data * @return ServerRequestInterface */ public function createServerRequest(string $uri, string $method = 'GET', array $data = []): ServerRequestInterface; /** * @param int $statusCode * @param string $reasonPhrase * @return ResponseInterface */ public function createResponse(int $statusCode = 200, string $reasonPhrase = ''): ResponseInterface; /** * @param string $contents * @return StreamInterface */ public function createStream(string $contents = ''): StreamInterface; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Providers/PSR7ObjectProvider.php
tests/Providers/PSR7ObjectProvider.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Providers; use Nyholm\Psr7\Factory\Psr17Factory; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestFactoryInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; use function array_merge; use function microtime; use function time; /** * Class PSR7ObjectProvider * * @package Slim\Tests\Providers */ class PSR7ObjectProvider implements PSR7ObjectProviderInterface { /** * @param string $uri * @param string $method * @param array $data * @return ServerRequestInterface */ public function createServerRequest( string $uri, string $method = 'GET', array $data = [] ): ServerRequestInterface { $headers = array_merge([ 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8', 'HTTP_HOST' => 'localhost', 'HTTP_USER_AGENT' => 'Slim Framework', 'QUERY_STRING' => '', 'REMOTE_ADDR' => '127.0.0.1', 'REQUEST_METHOD' => $method, 'REQUEST_TIME' => time(), 'REQUEST_TIME_FLOAT' => microtime(true), 'REQUEST_URI' => '', 'SCRIPT_NAME' => '/index.php', 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => 80, 'SERVER_PROTOCOL' => 'HTTP/1.1', ], $data); return $this ->getServerRequestFactory() ->createServerRequest($method, $uri, $headers); } /** * @return ServerRequestFactoryInterface */ public function getServerRequestFactory(): ServerRequestFactoryInterface { return new Psr17Factory(); } /** * @param int $statusCode * @param string $reasonPhrase * @return ResponseInterface */ public function createResponse(int $statusCode = 200, string $reasonPhrase = ''): ResponseInterface { return $this ->getResponseFactory() ->createResponse($statusCode, $reasonPhrase); } /** * @return ResponseFactoryInterface */ public function getResponseFactory(): ResponseFactoryInterface { return new Psr17Factory(); } /** * @param string $contents * @return StreamInterface */ public function createStream(string $contents = ''): StreamInterface { return $this ->getStreamFactory() ->createStream($contents); } /** * @return StreamFactoryInterface */ public function getStreamFactory(): StreamFactoryInterface { return new Psr17Factory(); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Handlers/ErrorHandlerTest.php
tests/Handlers/ErrorHandlerTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Handlers; use Prophecy\Argument; use Psr\Http\Message\ResponseInterface; use Psr\Log\LoggerInterface; use ReflectionClass; use ReflectionMethod; use ReflectionProperty; use RuntimeException; use Slim\Error\Renderers\HtmlErrorRenderer; use Slim\Error\Renderers\JsonErrorRenderer; use Slim\Error\Renderers\PlainTextErrorRenderer; use Slim\Error\Renderers\XmlErrorRenderer; use Slim\Exception\HttpMethodNotAllowedException; use Slim\Exception\HttpNotFoundException; use Slim\Handlers\ErrorHandler; use Slim\Interfaces\CallableResolverInterface; use Slim\Tests\Mocks\MockCustomException; use Slim\Tests\TestCase; class ErrorHandlerTest extends TestCase { private function getMockLogger(): LoggerInterface { return $this->createMock(LoggerInterface::class); } public function testDetermineRenderer() { $handler = $this->createMock(ErrorHandler::class); $class = new ReflectionClass(ErrorHandler::class); $callableResolverProperty = $class->getProperty('callableResolver'); $this->setAccessible($callableResolverProperty); $callableResolverProperty->setValue($handler, $this->getCallableResolver()); $reflectionProperty = $class->getProperty('contentType'); $this->setAccessible($reflectionProperty); $reflectionProperty->setValue($handler, 'application/json'); $method = $class->getMethod('determineRenderer'); $this->setAccessible($method); $renderer = $method->invoke($handler); $this->assertIsCallable($renderer); $this->assertInstanceOf(JsonErrorRenderer::class, $renderer[0]); $reflectionProperty->setValue($handler, 'application/xml'); $renderer = $method->invoke($handler); $this->assertIsCallable($renderer); $this->assertInstanceOf(XmlErrorRenderer::class, $renderer[0]); $reflectionProperty->setValue($handler, 'text/plain'); $renderer = $method->invoke($handler); $this->assertIsCallable($renderer); $this->assertInstanceOf(PlainTextErrorRenderer::class, $renderer[0]); // Test the default error renderer $reflectionProperty->setValue($handler, 'text/unknown'); $renderer = $method->invoke($handler); $this->assertIsCallable($renderer); $this->assertInstanceOf(HtmlErrorRenderer::class, $renderer[0]); } public function testDetermineStatusCode() { $request = $this->createServerRequest('/'); $handler = $this->createMock(ErrorHandler::class); $class = new ReflectionClass(ErrorHandler::class); $reflectionProperty = $class->getProperty('responseFactory'); $this->setAccessible($reflectionProperty); $reflectionProperty->setValue($handler, $this->getResponseFactory()); $reflectionProperty = $class->getProperty('exception'); $this->setAccessible($reflectionProperty); $reflectionProperty->setValue($handler, new HttpNotFoundException($request)); $method = $class->getMethod('determineStatusCode'); $this->setAccessible($method); $statusCode = $method->invoke($handler); $this->assertSame($statusCode, 404); $reflectionProperty->setValue($handler, new MockCustomException()); $statusCode = $method->invoke($handler); $this->assertSame($statusCode, 500); } /** * Test if we can force the content type of all error handler responses. */ public function testForceContentType() { $request = $this ->createServerRequest('/not-defined', 'GET') ->withHeader('Accept', 'text/plain,text/xml'); $handler = new ErrorHandler($this->getCallableResolver(), $this->getResponseFactory()); $handler->forceContentType('application/json'); $exception = new HttpNotFoundException($request); /** @var ResponseInterface $response */ $response = $handler->__invoke($request, $exception, false, false, false); $this->assertSame(['application/json'], $response->getHeader('Content-Type')); } public function testHalfValidContentType() { $request = $this ->createServerRequest('/', 'GET') ->withHeader('Content-Type', 'unknown/json+'); $handler = $this->createMock(ErrorHandler::class); $newErrorRenderers = [ 'application/xml' => XmlErrorRenderer::class, 'text/xml' => XmlErrorRenderer::class, 'text/html' => HtmlErrorRenderer::class, ]; $class = new ReflectionClass(ErrorHandler::class); $reflectionProperty = $class->getProperty('responseFactory'); $this->setAccessible($reflectionProperty); $reflectionProperty->setValue($handler, $this->getResponseFactory()); $reflectionProperty = $class->getProperty('errorRenderers'); $this->setAccessible($reflectionProperty); $reflectionProperty->setValue($handler, $newErrorRenderers); $method = $class->getMethod('determineContentType'); $this->setAccessible($method); $contentType = $method->invoke($handler, $request); $this->assertNull($contentType); } public function testDetermineContentTypeTextPlainMultiAcceptHeader() { $request = $this ->createServerRequest('/', 'GET') ->withHeader('Content-Type', 'text/plain') ->withHeader('Accept', 'text/plain,text/xml'); $handler = $this->createMock(ErrorHandler::class); $errorRenderers = [ 'text/plain' => PlainTextErrorRenderer::class, 'text/xml' => XmlErrorRenderer::class, ]; $class = new ReflectionClass(ErrorHandler::class); $reflectionProperty = $class->getProperty('responseFactory'); $this->setAccessible($reflectionProperty); $reflectionProperty->setValue($handler, $this->getResponseFactory()); $reflectionProperty = $class->getProperty('errorRenderers'); $this->setAccessible($reflectionProperty); $reflectionProperty->setValue($handler, $errorRenderers); $method = $class->getMethod('determineContentType'); $this->setAccessible($method); $contentType = $method->invoke($handler, $request); $this->assertSame('text/xml', $contentType); } public function testDetermineContentTypeApplicationJsonOrXml() { $request = $this ->createServerRequest('/', 'GET') ->withHeader('Content-Type', 'text/json') ->withHeader('Accept', 'application/xhtml+xml'); $handler = $this->createMock(ErrorHandler::class); $errorRenderers = [ 'application/xml' => XmlErrorRenderer::class ]; $class = new ReflectionClass(ErrorHandler::class); $reflectionProperty = $class->getProperty('responseFactory'); $this->setAccessible($reflectionProperty); $reflectionProperty->setValue($handler, $this->getResponseFactory()); $reflectionProperty = $class->getProperty('errorRenderers'); $this->setAccessible($reflectionProperty); $reflectionProperty->setValue($handler, $errorRenderers); $method = $class->getMethod('determineContentType'); $this->setAccessible($method); $contentType = $method->invoke($handler, $request); $this->assertSame('application/xml', $contentType); } /** * Ensure that an acceptable media-type is found in the Accept header even * if it's not the first in the list. */ public function testAcceptableMediaTypeIsNotFirstInList() { $request = $this ->createServerRequest('/', 'GET') ->withHeader('Accept', 'text/plain,text/html'); // provide access to the determineContentType() as it's a protected method $class = new ReflectionClass(ErrorHandler::class); $method = $class->getMethod('determineContentType'); $this->setAccessible($method); // use a mock object here as ErrorHandler cannot be directly instantiated $handler = $this->createMock(ErrorHandler::class); // call determineContentType() $return = $method->invoke($handler, $request); $this->assertSame('text/html', $return); } public function testRegisterErrorRenderer() { $handler = new ErrorHandler($this->getCallableResolver(), $this->getResponseFactory()); $handler->registerErrorRenderer('application/slim', PlainTextErrorRenderer::class); $reflectionClass = new ReflectionClass(ErrorHandler::class); $reflectionProperty = $reflectionClass->getProperty('errorRenderers'); $this->setAccessible($reflectionProperty); $errorRenderers = $reflectionProperty->getValue($handler); $this->assertArrayHasKey('application/slim', $errorRenderers); } public function testSetDefaultErrorRenderer() { $handler = new ErrorHandler($this->getCallableResolver(), $this->getResponseFactory()); $handler->setDefaultErrorRenderer('text/plain', PlainTextErrorRenderer::class); $reflectionClass = new ReflectionClass(ErrorHandler::class); $reflectionProperty = $reflectionClass->getProperty('defaultErrorRenderer'); $this->setAccessible($reflectionProperty); $defaultErrorRenderer = $reflectionProperty->getValue($handler); $defaultErrorRendererContentTypeProperty = $reflectionClass->getProperty('defaultErrorRendererContentType'); $this->setAccessible($defaultErrorRendererContentTypeProperty); $defaultErrorRendererContentType = $defaultErrorRendererContentTypeProperty->getValue($handler); $this->assertSame(PlainTextErrorRenderer::class, $defaultErrorRenderer); $this->assertSame('text/plain', $defaultErrorRendererContentType); } public function testOptions() { $request = $this->createServerRequest('/', 'OPTIONS'); $handler = new ErrorHandler($this->getCallableResolver(), $this->getResponseFactory()); $exception = new HttpMethodNotAllowedException($request); $exception->setAllowedMethods(['POST', 'PUT']); /** @var ResponseInterface $res */ $res = $handler->__invoke($request, $exception, true, false, true); $this->assertSame(200, $res->getStatusCode()); $this->assertTrue($res->hasHeader('Allow')); $this->assertSame('POST, PUT', $res->getHeaderLine('Allow')); } public function testWriteToErrorLog() { $request = $this ->createServerRequest('/', 'GET') ->withHeader('Accept', 'application/json'); $logger = $this->getMockLogger(); $handler = new ErrorHandler( $this->getCallableResolver(), $this->getResponseFactory(), $logger ); $logger->expects(self::once()) ->method('error') ->willReturnCallback(static function (string $error) { self::assertStringNotContainsString( 'set "displayErrorDetails" to true in the ErrorHandler constructor', $error ); }); $exception = new HttpNotFoundException($request); $handler->__invoke($request, $exception, true, true, true); } public function testWriteToErrorLogShowTip() { $request = $this ->createServerRequest('/', 'GET') ->withHeader('Accept', 'application/json'); $logger = $this->getMockLogger(); $handler = new ErrorHandler( $this->getCallableResolver(), $this->getResponseFactory(), $logger ); $logger->expects(self::once()) ->method('error') ->willReturnCallback(static function (string $error) { self::assertStringContainsString( 'set "displayErrorDetails" to true in the ErrorHandler constructor', $error ); }); $exception = new HttpNotFoundException($request); $handler->__invoke($request, $exception, false, true, true); } public function testWriteToErrorLogDoesNotShowTipIfErrorLogRendererIsNotPlainText() { $request = $this ->createServerRequest('/', 'GET') ->withHeader('Accept', 'application/json'); $logger = $this->getMockLogger(); $handler = new ErrorHandler( $this->getCallableResolver(), $this->getResponseFactory(), $logger ); $handler->setLogErrorRenderer(HtmlErrorRenderer::class); $logger->expects(self::once()) ->method('error') ->willReturnCallback(static function (string $error) { self::assertStringNotContainsString( 'set "displayErrorDetails" to true in the ErrorHandler constructor', $error ); }); $exception = new HttpNotFoundException($request); $handler->__invoke($request, $exception, false, true, true); } public function testDefaultErrorRenderer() { $request = $this ->createServerRequest('/', 'GET') ->withHeader('Accept', 'application/unknown'); $handler = new ErrorHandler($this->getCallableResolver(), $this->getResponseFactory()); $exception = new RuntimeException(); /** @var ResponseInterface $res */ $res = $handler->__invoke($request, $exception, true, false, true); $this->assertTrue($res->hasHeader('Content-Type')); $this->assertSame('text/html', $res->getHeaderLine('Content-Type')); } public function testLogErrorRenderer() { $renderer = function () { return ''; }; $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $callableResolverProphecy ->resolve('logErrorRenderer') ->willReturn($renderer) ->shouldBeCalledOnce(); $loggerProphecy = $this->prophesize(LoggerInterface::class); $loggerProphecy ->error(Argument::type('string')) ->shouldBeCalled(); $handler = new ErrorHandler( $callableResolverProphecy->reveal(), $this->getResponseFactory(), $loggerProphecy->reveal() ); $handler->setLogErrorRenderer('logErrorRenderer'); $displayErrorDetailsProperty = new ReflectionProperty($handler, 'displayErrorDetails'); $this->setAccessible($displayErrorDetailsProperty); $displayErrorDetailsProperty->setValue($handler, true); $exception = new RuntimeException(); $exceptionProperty = new ReflectionProperty($handler, 'exception'); $this->setAccessible($exceptionProperty); $exceptionProperty->setValue($handler, $exception); $writeToErrorLogMethod = new ReflectionMethod($handler, 'writeToErrorLog'); $this->setAccessible($writeToErrorLogMethod); $writeToErrorLogMethod->invoke($handler); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Handlers/Strategies/RequestResponseNamedArgsTest.php
tests/Handlers/Strategies/RequestResponseNamedArgsTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Handlers\Strategies; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Slim\Handlers\Strategies\RequestResponseNamedArgs; use Slim\Tests\TestCase; class RequestResponseNamedArgsTest extends TestCase { private ServerRequestInterface $request; private ResponseInterface $response; private const PHP_8_0_VERSION_ID = 80000; public function setUp(): void { $this->request = $this->createMock(ServerRequestInterface::class); $this->response = $this->createMock(ResponseInterface::class); } public function testCallingWithEmptyArguments() { if (PHP_VERSION_ID < self::PHP_8_0_VERSION_ID) { $this->markTestSkipped('Named arguments are not supported in PHP versions prior to 8.0'); } $args = []; $invocationStrategy = new RequestResponseNamedArgs(); $callback = function ($request, $response) { $this->assertSame($this->request, $request); $this->assertSame($this->response, $response); return $response; }; $this->assertSame($this->response, $invocationStrategy($callback, $this->request, $this->response, $args)); } public function testCallingWithKnownArguments() { if (PHP_VERSION_ID < self::PHP_8_0_VERSION_ID) { $this->markTestSkipped('Named arguments are not supported in PHP versions prior to 8.0'); } $args = [ 'name' => 'world', 'greeting' => 'hello', ]; $invocationStrategy = new RequestResponseNamedArgs(); $callback = function ($request, $response, $greeting, $name) use ($args) { $this->assertSame($this->request, $request); $this->assertSame($this->response, $response); $this->assertSame($greeting, $args['greeting']); $this->assertSame($name, $args['name']); return $response; }; $this->assertSame($this->response, $invocationStrategy($callback, $this->request, $this->response, $args)); } public function testCallingWithOptionalArguments() { if (PHP_VERSION_ID < 80000) { $this->markTestSkipped('Named arguments are not supported in PHP versions prior to 8.0'); } $args = [ 'name' => 'world', ]; $invocationStrategy = new RequestResponseNamedArgs(); $callback = function ($request, $response, $greeting = 'Hello', $name = 'Rob') use ($args) { $this->assertSame($this->request, $request); $this->assertSame($this->response, $response); $this->assertSame($greeting, 'Hello'); $this->assertSame($name, $args['name']); return $response; }; $this->assertSame($this->response, $invocationStrategy($callback, $this->request, $this->response, $args)); } public function testCallingWithUnknownAndVariadic() { if (PHP_VERSION_ID < self::PHP_8_0_VERSION_ID) { $this->markTestSkipped('Named arguments are not supported in PHP versions prior to 8.0'); } $args = [ 'name' => 'world', 'greeting' => 'hello', ]; $invocationStrategy = new RequestResponseNamedArgs(); $callback = function ($request, $response, ...$arguments) use ($args) { $this->assertSame($this->request, $request); $this->assertSame($this->response, $response); $this->assertSame($args, $arguments); return $response; }; $this->assertSame($this->response, $invocationStrategy($callback, $this->request, $this->response, $args)); } public function testCallingWithMixedKnownAndUnknownParametersAndVariadic() { if (PHP_VERSION_ID < self::PHP_8_0_VERSION_ID) { $this->markTestSkipped('Named arguments are not supported in PHP versions prior to 8.0'); } $known = [ 'name' => 'world', 'greeting' => 'hello', ]; $unknown = [ 'foo' => 'foo', 'bar' => 'bar', ]; $args = array_merge($known, $unknown); $invocationStrategy = new RequestResponseNamedArgs(); $callback = function ($request, $response, $name, $greeting, ...$arguments) use ($known, $unknown) { $this->assertSame($this->request, $request); $this->assertSame($this->response, $response); $this->assertSame($name, $known['name']); $this->assertSame($greeting, $known['greeting']); $this->assertSame($unknown, $arguments); return $response; }; $this->assertSame($this->response, $invocationStrategy($callback, $this->request, $this->response, $args)); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Factory/ServerRequestCreatorFactoryTest.php
tests/Factory/ServerRequestCreatorFactoryTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Factory; use GuzzleHttp\Psr7\ServerRequest as GuzzleServerRequest; use Laminas\Diactoros\ServerRequest as LaminasDiactorosServerRequest; use Nyholm\Psr7\ServerRequest as NyholmServerRequest; use HttpSoft\Message\ServerRequest as HttpSoftServerRequest; use Psr\Http\Message\ServerRequestInterface; use RuntimeException; use Slim\Factory\Psr17\GuzzlePsr17Factory; use Slim\Factory\Psr17\HttpSoftPsr17Factory; use Slim\Factory\Psr17\LaminasDiactorosPsr17Factory; use Slim\Factory\Psr17\NyholmPsr17Factory; use Slim\Factory\Psr17\Psr17FactoryProvider; use Slim\Factory\Psr17\SlimHttpServerRequestCreator; use Slim\Factory\Psr17\SlimPsr17Factory; use Slim\Factory\ServerRequestCreatorFactory; use Slim\Http\ServerRequest; use Slim\Interfaces\ServerRequestCreatorInterface; use Slim\Psr7\Request as SlimServerRequest; use Slim\Tests\TestCase; class ServerRequestCreatorFactoryTest extends TestCase { public static function provideImplementations() { return [ [SlimPsr17Factory::class, SlimServerRequest::class], [HttpSoftPsr17Factory::class, HttpSoftServerRequest::class], [NyholmPsr17Factory::class, NyholmServerRequest::class], [GuzzlePsr17Factory::class, GuzzleServerRequest::class], [LaminasDiactorosPsr17Factory::class, LaminasDiactorosServerRequest::class], ]; } /** * @dataProvider provideImplementations * @param string $psr17factory * @param string $expectedServerRequestClass */ #[\PHPUnit\Framework\Attributes\DataProvider('provideImplementations')] public function testCreateAppWithAllImplementations(string $psr17factory, string $expectedServerRequestClass) { Psr17FactoryProvider::setFactories([$psr17factory]); ServerRequestCreatorFactory::setSlimHttpDecoratorsAutomaticDetection(false); $serverRequestCreator = ServerRequestCreatorFactory::create(); $serverRequest = $serverRequestCreator->createServerRequestFromGlobals(); $this->assertInstanceOf($expectedServerRequestClass, $serverRequest); } public function testDetermineServerRequestCreatorReturnsDecoratedServerRequestCreator() { Psr17FactoryProvider::setFactories([SlimPsr17Factory::class]); ServerRequestCreatorFactory::setSlimHttpDecoratorsAutomaticDetection(true); $serverRequestCreator = ServerRequestCreatorFactory::create(); $this->assertInstanceOf(SlimHttpServerRequestCreator::class, $serverRequestCreator); $this->assertInstanceOf(ServerRequest::class, $serverRequestCreator->createServerRequestFromGlobals()); } /** * @runInSeparateProcess - Psr17FactoryProvider::setFactories breaks other tests */ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess] public function testDetermineServerRequestCreatorThrowsRuntimeException() { $this->expectException(RuntimeException::class); Psr17FactoryProvider::setFactories([]); ServerRequestCreatorFactory::create(); } public function testSetPsr17FactoryProvider() { $psr17FactoryProvider = new Psr17FactoryProvider(); $psr17FactoryProvider::setFactories([SlimPsr17Factory::class]); ServerRequestCreatorFactory::setPsr17FactoryProvider($psr17FactoryProvider); ServerRequestCreatorFactory::setSlimHttpDecoratorsAutomaticDetection(false); $serverRequestCreator = ServerRequestCreatorFactory::create(); $this->assertInstanceOf(SlimServerRequest::class, $serverRequestCreator->createServerRequestFromGlobals()); } /** * @runInSeparateProcess - ServerRequestCreatorFactory::setServerRequestCreator breaks other tests */ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess] public function testSetServerRequestCreatorWithoutDecorators() { ServerRequestCreatorFactory::setSlimHttpDecoratorsAutomaticDetection(false); $serverRequestProphecy = $this->prophesize(ServerRequestInterface::class); $serverRequestCreatorProphecy = $this->prophesize(ServerRequestCreatorInterface::class); $serverRequestCreatorProphecy ->createServerRequestFromGlobals() ->willReturn($serverRequestProphecy->reveal()) ->shouldBeCalledOnce(); ServerRequestCreatorFactory::setServerRequestCreator($serverRequestCreatorProphecy->reveal()); $serverRequestCreator = ServerRequestCreatorFactory::create(); $this->assertSame($serverRequestProphecy->reveal(), $serverRequestCreator->createServerRequestFromGlobals()); } /** * @runInSeparateProcess - ServerRequestCreatorFactory::setServerRequestCreator breaks other tests */ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess] public function testSetServerRequestCreatorWithDecorators() { ServerRequestCreatorFactory::setSlimHttpDecoratorsAutomaticDetection(true); $serverRequestProphecy = $this->prophesize(ServerRequestInterface::class); $serverRequestCreatorProphecy = $this->prophesize(ServerRequestCreatorInterface::class); $serverRequestCreatorProphecy ->createServerRequestFromGlobals() ->willReturn($serverRequestProphecy->reveal()) ->shouldBeCalledOnce(); ServerRequestCreatorFactory::setServerRequestCreator($serverRequestCreatorProphecy->reveal()); $serverRequestCreator = ServerRequestCreatorFactory::create(); $this->assertInstanceOf(ServerRequest::class, $serverRequestCreator->createServerRequestFromGlobals()); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Factory/AppFactoryTest.php
tests/Factory/AppFactoryTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Factory; use GuzzleHttp\Psr7\HttpFactory; use Laminas\Diactoros\ResponseFactory as LaminasDiactorosResponseFactory; use HttpSoft\Message\ResponseFactory as HttpSoftResponseFactory; use Nyholm\Psr7\Factory\Psr17Factory; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamFactoryInterface; use ReflectionClass; use ReflectionProperty; use RuntimeException; use Slim\Factory\AppFactory; use Slim\Factory\Psr17\GuzzlePsr17Factory; use Slim\Factory\Psr17\HttpSoftPsr17Factory; use Slim\Factory\Psr17\LaminasDiactorosPsr17Factory; use Slim\Factory\Psr17\NyholmPsr17Factory; use Slim\Factory\Psr17\Psr17FactoryProvider; use Slim\Factory\Psr17\SlimHttpPsr17Factory; use Slim\Factory\Psr17\SlimPsr17Factory; use Slim\Http\Factory\DecoratedResponseFactory; use Slim\Http\Response as DecoratedResponse; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\MiddlewareDispatcherInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteParserInterface; use Slim\Interfaces\RouteResolverInterface; use Slim\Psr7\Factory\ResponseFactory as SlimResponseFactory; use Slim\Routing\RouteCollector; use Slim\Tests\Mocks\MockPsr17FactoryWithoutStreamFactory; use Slim\Tests\TestCase; use stdClass; class AppFactoryTest extends TestCase { protected function tearDown(): void { $reflectionClass = new ReflectionClass(SlimHttpPsr17Factory::class); $reflectionClass->setStaticPropertyValue('responseFactoryClass', DecoratedResponseFactory::class); } public static function provideImplementations() { return [ [SlimPsr17Factory::class, SlimResponseFactory::class], [HttpSoftPsr17Factory::class, HttpSoftResponseFactory::class], [NyholmPsr17Factory::class, Psr17Factory::class], [GuzzlePsr17Factory::class, HttpFactory::class], [LaminasDiactorosPsr17Factory::class, LaminasDiactorosResponseFactory::class], ]; } /** * @dataProvider provideImplementations * @param string $psr17factory * @param string $expectedResponseFactoryClass */ #[\PHPUnit\Framework\Attributes\DataProvider('provideImplementations')] public function testCreateAppWithAllImplementations(string $psr17factory, string $expectedResponseFactoryClass) { Psr17FactoryProvider::setFactories([$psr17factory]); AppFactory::setSlimHttpDecoratorsAutomaticDetection(false); $app = AppFactory::create(); $routeCollector = $app->getRouteCollector(); $responseFactoryProperty = new ReflectionProperty(RouteCollector::class, 'responseFactory'); $this->setAccessible($responseFactoryProperty); $responseFactory = $responseFactoryProperty->getValue($routeCollector); $this->assertInstanceOf($expectedResponseFactoryClass, $responseFactory); } public function testDetermineResponseFactoryReturnsDecoratedFactory() { Psr17FactoryProvider::setFactories([SlimPsr17Factory::class]); AppFactory::setSlimHttpDecoratorsAutomaticDetection(true); $app = AppFactory::create(); $this->assertInstanceOf(DecoratedResponseFactory::class, $app->getResponseFactory()); } public function testDetermineResponseFactoryThrowsRuntimeExceptionIfDecoratedNotInstanceOfResponseInterface() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage( 'Slim\\Factory\\Psr17\\SlimHttpPsr17Factory could not instantiate a decorated response factory.' ); $reflectionClass = new ReflectionClass(SlimHttpPsr17Factory::class); $reflectionClass->setStaticPropertyValue('responseFactoryClass', SlimHttpPsr17Factory::class); Psr17FactoryProvider::setFactories([SlimPsr17Factory::class]); AppFactory::setSlimHttpDecoratorsAutomaticDetection(true); AppFactory::create(); } /** * @runInSeparateProcess - Psr17FactoryProvider::setFactories breaks other tests */ public function testDetermineResponseFactoryThrowsRuntimeException() { $this->expectException(RuntimeException::class); Psr17FactoryProvider::setFactories([]); AppFactory::create(); } public function testSetPsr17FactoryProvider() { $psr17FactoryProvider = new Psr17FactoryProvider(); $psr17FactoryProvider::setFactories([SlimPsr17Factory::class]); AppFactory::setPsr17FactoryProvider($psr17FactoryProvider); AppFactory::setSlimHttpDecoratorsAutomaticDetection(false); $this->assertInstanceOf(SlimResponseFactory::class, AppFactory::determineResponseFactory()); } /** * @runInSeparateProcess - Psr17FactoryProvider::setFactories breaks other tests */ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess] public function testResponseFactoryIsStillReturnedIfStreamFactoryIsNotAvailable() { Psr17FactoryProvider::setFactories([MockPsr17FactoryWithoutStreamFactory::class]); AppFactory::setSlimHttpDecoratorsAutomaticDetection(true); $app = AppFactory::create(); $this->assertInstanceOf(SlimResponseFactory::class, $app->getResponseFactory()); } /** * @runInSeparateProcess - AppFactory::setResponseFactory breaks other tests */ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess] public function testAppIsCreatedWithInstancesFromSetters() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeParserProphecy = $this->prophesize(RouteParserInterface::class); $routeResolverProphecy = $this->prophesize(RouteResolverInterface::class); $middlewareDispatcherProphecy = $this->prophesize(MiddlewareDispatcherInterface::class); $routeCollectorProphecy->getRouteParser()->willReturn($routeParserProphecy); AppFactory::setSlimHttpDecoratorsAutomaticDetection(false); AppFactory::setResponseFactory($responseFactoryProphecy->reveal()); AppFactory::setContainer($containerProphecy->reveal()); AppFactory::setCallableResolver($callableResolverProphecy->reveal()); AppFactory::setRouteCollector($routeCollectorProphecy->reveal()); AppFactory::setRouteResolver($routeResolverProphecy->reveal()); AppFactory::setMiddlewareDispatcher($middlewareDispatcherProphecy->reveal()); $app = AppFactory::create(); $this->assertSame( $responseFactoryProphecy->reveal(), $app->getResponseFactory() ); $this->assertSame( $containerProphecy->reveal(), $app->getContainer() ); $this->assertSame( $callableResolverProphecy->reveal(), $app->getCallableResolver() ); $this->assertSame( $routeCollectorProphecy->reveal(), $app->getRouteCollector() ); $this->assertSame( $routeResolverProphecy->reveal(), $app->getRouteResolver() ); $this->assertSame( $middlewareDispatcherProphecy->reveal(), $app->getMiddlewareDispatcher() ); } /** * @runInSeparateProcess - AppFactory::create saves $responseFactory into static::$responseFactory, * this breaks other tests */ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess] public function testAppIsCreatedWithInjectedInstancesFromFunctionArguments() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeParserProphecy = $this->prophesize(RouteParserInterface::class); $routeResolverProphecy = $this->prophesize(RouteResolverInterface::class); $routeCollectorProphecy->getRouteParser()->willReturn($routeParserProphecy->reveal()); AppFactory::setSlimHttpDecoratorsAutomaticDetection(false); $app = AppFactory::create( $responseFactoryProphecy->reveal(), $containerProphecy->reveal(), $callableResolverProphecy->reveal(), $routeCollectorProphecy->reveal(), $routeResolverProphecy->reveal() ); $this->assertSame( $responseFactoryProphecy->reveal(), $app->getResponseFactory() ); $this->assertSame( $containerProphecy->reveal(), $app->getContainer() ); $this->assertSame( $callableResolverProphecy->reveal(), $app->getCallableResolver() ); $this->assertSame( $routeCollectorProphecy->reveal(), $app->getRouteCollector() ); $this->assertSame( $routeResolverProphecy->reveal(), $app->getRouteResolver() ); } /** * @runInSeparateProcess - AppFactory::setResponseFactory breaks other tests */ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess] public function testResponseAndStreamFactoryIsBeingInjectedInDecoratedResponseFactory() { $responseProphecy = $this->prophesize(ResponseInterface::class); $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $responseFactoryProphecy ->createResponse(200, '') ->willReturn($responseProphecy->reveal()) ->shouldBeCalledOnce(); $streamFactoryProphecy = $this->prophesize(StreamFactoryInterface::class); AppFactory::setResponseFactory($responseFactoryProphecy->reveal()); AppFactory::setStreamFactory($streamFactoryProphecy->reveal()); AppFactory::setSlimHttpDecoratorsAutomaticDetection(true); $app = AppFactory::create(); $responseFactory = $app->getResponseFactory(); $response = $responseFactory->createResponse(); $streamFactoryProperty = new ReflectionProperty(DecoratedResponse::class, 'streamFactory'); $this->setAccessible($streamFactoryProperty); $this->assertSame($streamFactoryProphecy->reveal(), $streamFactoryProperty->getValue($response)); } public function testCreateAppWithContainerUsesContainerDependenciesWhenPresent() { $responseFactoryProphecy = $this->prophesize(ResponseFactoryInterface::class); $callableResolverProphecy = $this->prophesize(CallableResolverInterface::class); $routeResolverProphecy = $this->prophesize(RouteResolverInterface::class); $routeParserProphecy = $this->prophesize(RouteParserInterface::class); $routeCollectorProphecy = $this->prophesize(RouteCollectorInterface::class); $routeCollectorProphecy ->getRouteParser() ->willReturn($routeParserProphecy->reveal()) ->shouldBeCalledOnce(); $middlewareDispatcherProphecy = $this->prophesize(MiddlewareDispatcherInterface::class); $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy ->has(ResponseFactoryInterface::class) ->willReturn(true) ->shouldBeCalledOnce(); $containerProphecy ->get(ResponseFactoryInterface::class) ->willReturn($responseFactoryProphecy->reveal()) ->shouldBeCalledOnce(); $containerProphecy ->has(CallableResolverInterface::class) ->willReturn(true) ->shouldBeCalledOnce(); $containerProphecy ->get(CallableResolverInterface::class) ->willReturn($callableResolverProphecy->reveal()) ->shouldBeCalledOnce(); $containerProphecy ->has(RouteCollectorInterface::class) ->willReturn(true) ->shouldBeCalledOnce(); $containerProphecy ->get(RouteCollectorInterface::class) ->willReturn($routeCollectorProphecy->reveal()) ->shouldBeCalledOnce(); $containerProphecy ->has(RouteResolverInterface::class) ->willReturn(true) ->shouldBeCalledOnce(); $containerProphecy ->get(RouteResolverInterface::class) ->willReturn($routeResolverProphecy->reveal()) ->shouldBeCalledOnce(); $containerProphecy ->has(MiddlewareDispatcherInterface::class) ->willReturn(true) ->shouldBeCalledOnce(); $containerProphecy ->get(MiddlewareDispatcherInterface::class) ->willReturn($middlewareDispatcherProphecy->reveal()) ->shouldBeCalledOnce(); AppFactory::setSlimHttpDecoratorsAutomaticDetection(false); $app = AppFactory::createFromContainer($containerProphecy->reveal()); $this->assertSame($app->getResponseFactory(), $responseFactoryProphecy->reveal()); $this->assertSame($app->getContainer(), $containerProphecy->reveal()); $this->assertSame($app->getCallableResolver(), $callableResolverProphecy->reveal()); $this->assertSame($app->getRouteCollector(), $routeCollectorProphecy->reveal()); $this->assertSame($app->getRouteResolver(), $routeResolverProphecy->reveal()); $this->assertSame($app->getMiddlewareDispatcher(), $middlewareDispatcherProphecy->reveal()); } public function testCreateAppWithEmptyContainer() { $containerProphecy = $this->prophesize(ContainerInterface::class); $containerProphecy ->has(ResponseFactoryInterface::class) ->willReturn(false) ->shouldBeCalledOnce(); $containerProphecy ->has(CallableResolverInterface::class) ->willReturn(false) ->shouldBeCalledOnce(); $containerProphecy ->has(RouteCollectorInterface::class) ->willReturn(false) ->shouldBeCalledOnce(); $containerProphecy ->has(RouteResolverInterface::class) ->willReturn(false) ->shouldBeCalledOnce(); $containerProphecy ->has(MiddlewareDispatcherInterface::class) ->willReturn(false) ->shouldBeCalledOnce(); AppFactory::setSlimHttpDecoratorsAutomaticDetection(false); AppFactory::createFromContainer($containerProphecy->reveal()); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Factory/Psr17/Psr17FactoryProviderTest.php
tests/Factory/Psr17/Psr17FactoryProviderTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Factory\Psr17; use Slim\Factory\Psr17\Psr17FactoryProvider; use Slim\Tests\TestCase; class Psr17FactoryProviderTest extends TestCase { /** * @runInSeparateProcess - Psr17FactoryProvider::setFactories breaks other tests */ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess] public function testGetSetFactories() { Psr17FactoryProvider::setFactories([]); $this->assertSame([], Psr17FactoryProvider::getFactories()); } /** * @runInSeparateProcess - Psr17FactoryProvider::setFactories breaks other tests */ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess] public function testAddFactory() { Psr17FactoryProvider::setFactories(['Factory 1']); Psr17FactoryProvider::addFactory('Factory 2'); $this->assertSame(['Factory 2', 'Factory 1'], Psr17FactoryProvider::getFactories()); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Factory/Psr17/Psr17FactoryTest.php
tests/Factory/Psr17/Psr17FactoryTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Factory\Psr17; use RuntimeException; use Slim\Tests\Mocks\MockPsr17Factory; use Slim\Tests\TestCase; class Psr17FactoryTest extends TestCase { public function testGetResponseFactoryThrowsRuntimeException() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Slim\\Tests\\Mocks\\MockPsr17Factory could not instantiate a response factory.'); MockPsr17Factory::getResponseFactory(); } public function testGetStreamFactoryThrowsRuntimeException() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Slim\\Tests\\Mocks\\MockPsr17Factory could not instantiate a stream factory.'); MockPsr17Factory::getStreamFactory(); } public function testGetServerRequestCreatorThrowsRuntimeException() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Slim\\Tests\\Mocks\\MockPsr17Factory' . ' could not instantiate a server request creator.'); MockPsr17Factory::getServerRequestCreator(); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/tests/Factory/Psr17/SlimHttpServerRequestCreatorTest.php
tests/Factory/Psr17/SlimHttpServerRequestCreatorTest.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Tests\Factory\Psr17; use Psr\Http\Message\ServerRequestInterface; use ReflectionClass; use ReflectionProperty; use RuntimeException; use Slim\Factory\Psr17\SlimHttpServerRequestCreator; use Slim\Http\ServerRequest; use Slim\Interfaces\ServerRequestCreatorInterface; use Slim\Tests\TestCase; use stdClass; class SlimHttpServerRequestCreatorTest extends TestCase { /** * We need to reset the static property of SlimHttpServerRequestCreator back to its original value * Otherwise other tests will fail */ public function tearDown(): void { $serverRequestCreatorProphecy = $this->prophesize(ServerRequestCreatorInterface::class); $slimHttpServerRequestCreator = new SlimHttpServerRequestCreator($serverRequestCreatorProphecy->reveal()); $serverRequestDecoratorClassProperty = new ReflectionProperty( SlimHttpServerRequestCreator::class, 'serverRequestDecoratorClass' ); $this->setAccessible($serverRequestDecoratorClassProperty); $serverRequestDecoratorClassProperty->setValue($slimHttpServerRequestCreator, ServerRequest::class); } public function testCreateServerRequestFromGlobals() { $serverRequestProphecy = $this->prophesize(ServerRequestInterface::class); $serverRequestCreatorProphecy = $this->prophesize(ServerRequestCreatorInterface::class); $serverRequestCreatorProphecy ->createServerRequestFromGlobals() ->willReturn($serverRequestProphecy->reveal()) ->shouldBeCalledOnce(); $slimHttpServerRequestCreator = new SlimHttpServerRequestCreator($serverRequestCreatorProphecy->reveal()); $this->assertInstanceOf(ServerRequest::class, $slimHttpServerRequestCreator->createServerRequestFromGlobals()); } public function testCreateServerRequestFromGlobalsThrowsRuntimeException() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The Slim-Http ServerRequest decorator is not available.'); $serverRequestCreatorProphecy = $this->prophesize(ServerRequestCreatorInterface::class); $slimHttpServerRequestCreator = new SlimHttpServerRequestCreator($serverRequestCreatorProphecy->reveal()); $serverRequestDecoratorClassProperty = new ReflectionProperty( SlimHttpServerRequestCreator::class, 'serverRequestDecoratorClass' ); $this->setAccessible($serverRequestDecoratorClassProperty); $serverRequestDecoratorClassProperty->setValue($slimHttpServerRequestCreator, ''); $slimHttpServerRequestCreator->createServerRequestFromGlobals(); } public function testCreateServerRequestFromGlobalsThrowsRuntimeExceptionIfNotInstanceOfServerRequestInterface() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage( 'Slim\\Factory\\Psr17\\SlimHttpServerRequestCreator could not instantiate a decorated server request.' ); $serverRequestProphecy = $this->prophesize(ServerRequestInterface::class); $serverRequestCreatorProphecy = $this->prophesize(ServerRequestCreatorInterface::class); $serverRequestCreatorProphecy ->createServerRequestFromGlobals() ->willReturn($serverRequestProphecy->reveal()) ->shouldBeCalledOnce(); $slimHttpServerRequestCreator = new SlimHttpServerRequestCreator($serverRequestCreatorProphecy->reveal()); $reflectionClass = new ReflectionClass(SlimHttpServerRequestCreator::class); $reflectionClass->setStaticPropertyValue('serverRequestDecoratorClass', stdClass::class); $slimHttpServerRequestCreator->createServerRequestFromGlobals(); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/App.php
Slim/App.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Psr\Log\LoggerInterface; use Slim\Factory\ServerRequestCreatorFactory; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\MiddlewareDispatcherInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteResolverInterface; use Slim\Middleware\BodyParsingMiddleware; use Slim\Middleware\ErrorMiddleware; use Slim\Middleware\RoutingMiddleware; use Slim\Routing\RouteCollectorProxy; use Slim\Routing\RouteResolver; use Slim\Routing\RouteRunner; use function strtoupper; /** * @api * @template TContainerInterface of (ContainerInterface|null) * @template-extends RouteCollectorProxy<TContainerInterface> */ class App extends RouteCollectorProxy implements RequestHandlerInterface { /** * Current version * * @var string */ public const VERSION = '4.15.1'; protected RouteResolverInterface $routeResolver; protected MiddlewareDispatcherInterface $middlewareDispatcher; /** * @param TContainerInterface $container */ public function __construct( ResponseFactoryInterface $responseFactory, ?ContainerInterface $container = null, ?CallableResolverInterface $callableResolver = null, ?RouteCollectorInterface $routeCollector = null, ?RouteResolverInterface $routeResolver = null, ?MiddlewareDispatcherInterface $middlewareDispatcher = null ) { parent::__construct( $responseFactory, $callableResolver ?? new CallableResolver($container), $container, $routeCollector ); $this->routeResolver = $routeResolver ?? new RouteResolver($this->routeCollector); $routeRunner = new RouteRunner($this->routeResolver, $this->routeCollector->getRouteParser(), $this); if (!$middlewareDispatcher) { $middlewareDispatcher = new MiddlewareDispatcher($routeRunner, $this->callableResolver, $container); } else { $middlewareDispatcher->seedMiddlewareStack($routeRunner); } $this->middlewareDispatcher = $middlewareDispatcher; } /** * @return RouteResolverInterface */ public function getRouteResolver(): RouteResolverInterface { return $this->routeResolver; } /** * @return MiddlewareDispatcherInterface */ public function getMiddlewareDispatcher(): MiddlewareDispatcherInterface { return $this->middlewareDispatcher; } /** * @param MiddlewareInterface|string|callable $middleware * @return App<TContainerInterface> */ public function add($middleware): self { $this->middlewareDispatcher->add($middleware); return $this; } /** * @param MiddlewareInterface $middleware * @return App<TContainerInterface> */ public function addMiddleware(MiddlewareInterface $middleware): self { $this->middlewareDispatcher->addMiddleware($middleware); return $this; } /** * Add the Slim built-in routing middleware to the app middleware stack * * This method can be used to control middleware order and is not required for default routing operation. * * @return RoutingMiddleware */ public function addRoutingMiddleware(): RoutingMiddleware { $routingMiddleware = new RoutingMiddleware( $this->getRouteResolver(), $this->getRouteCollector()->getRouteParser() ); $this->add($routingMiddleware); return $routingMiddleware; } /** * Add the Slim built-in error middleware to the app middleware stack * * @param bool $displayErrorDetails * @param bool $logErrors * @param bool $logErrorDetails * @param LoggerInterface|null $logger * * @return ErrorMiddleware */ public function addErrorMiddleware( bool $displayErrorDetails, bool $logErrors, bool $logErrorDetails, ?LoggerInterface $logger = null ): ErrorMiddleware { $errorMiddleware = new ErrorMiddleware( $this->getCallableResolver(), $this->getResponseFactory(), $displayErrorDetails, $logErrors, $logErrorDetails, $logger ); $this->add($errorMiddleware); return $errorMiddleware; } /** * Add the Slim body parsing middleware to the app middleware stack * * @param callable[] $bodyParsers * * @return BodyParsingMiddleware */ public function addBodyParsingMiddleware(array $bodyParsers = []): BodyParsingMiddleware { $bodyParsingMiddleware = new BodyParsingMiddleware($bodyParsers); $this->add($bodyParsingMiddleware); return $bodyParsingMiddleware; } /** * Run application * * This method traverses the application middleware stack and then sends the * resultant Response object to the HTTP client. * * @param ServerRequestInterface|null $request * @return void */ public function run(?ServerRequestInterface $request = null): void { if (!$request) { $serverRequestCreator = ServerRequestCreatorFactory::create(); $request = $serverRequestCreator->createServerRequestFromGlobals(); } $response = $this->handle($request); $responseEmitter = new ResponseEmitter(); $responseEmitter->emit($response); } /** * Handle a request * * This method traverses the application middleware stack and then returns the * resultant Response object. * * @param ServerRequestInterface $request * @return ResponseInterface */ public function handle(ServerRequestInterface $request): ResponseInterface { $response = $this->middlewareDispatcher->handle($request); /** * This is to be in compliance with RFC 2616, Section 9. * If the incoming request method is HEAD, we need to ensure that the response body * is empty as the request may fall back on a GET route handler due to FastRoute's * routing logic which could potentially append content to the response body * https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4 */ $method = strtoupper($request->getMethod()); if ($method === 'HEAD') { $emptyBody = $this->responseFactory->createResponse()->getBody(); return $response->withBody($emptyBody); } return $response; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/CallableResolver.php
Slim/CallableResolver.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim; use Closure; use Psr\Container\ContainerInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; use Slim\Interfaces\AdvancedCallableResolverInterface; use function class_exists; use function is_array; use function is_callable; use function is_object; use function is_string; use function json_encode; use function preg_match; use function sprintf; /** * @template TContainerInterface of (ContainerInterface|null) */ final class CallableResolver implements AdvancedCallableResolverInterface { public static string $callablePattern = '!^([^\:]+)\:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$!'; /** @var TContainerInterface $container */ private ?ContainerInterface $container; /** * @param TContainerInterface $container */ public function __construct(?ContainerInterface $container = null) { $this->container = $container; } /** * {@inheritdoc} */ public function resolve($toResolve): callable { $toResolve = $this->prepareToResolve($toResolve); if (is_callable($toResolve)) { return $this->bindToContainer($toResolve); } $resolved = $toResolve; if (is_string($toResolve)) { $resolved = $this->resolveSlimNotation($toResolve); $resolved[1] ??= '__invoke'; } $callable = $this->assertCallable($resolved, $toResolve); return $this->bindToContainer($callable); } /** * {@inheritdoc} */ public function resolveRoute($toResolve): callable { return $this->resolveByPredicate($toResolve, [$this, 'isRoute'], 'handle'); } /** * {@inheritdoc} */ public function resolveMiddleware($toResolve): callable { return $this->resolveByPredicate($toResolve, [$this, 'isMiddleware'], 'process'); } /** * @param callable|array{class-string, string}|string $toResolve * * @throws RuntimeException */ private function resolveByPredicate($toResolve, callable $predicate, string $defaultMethod): callable { $toResolve = $this->prepareToResolve($toResolve); if (is_callable($toResolve)) { return $this->bindToContainer($toResolve); } $resolved = $toResolve; if ($predicate($toResolve)) { $resolved = [$toResolve, $defaultMethod]; } if (is_string($toResolve)) { [$instance, $method] = $this->resolveSlimNotation($toResolve); if ($method === null && $predicate($instance)) { $method = $defaultMethod; } $resolved = [$instance, $method ?? '__invoke']; } $callable = $this->assertCallable($resolved, $toResolve); return $this->bindToContainer($callable); } /** * @param mixed $toResolve */ private function isRoute($toResolve): bool { return $toResolve instanceof RequestHandlerInterface; } /** * @param mixed $toResolve */ private function isMiddleware($toResolve): bool { return $toResolve instanceof MiddlewareInterface; } /** * @throws RuntimeException * * @return array{object, string|null} [Instance, Method Name] */ private function resolveSlimNotation(string $toResolve): array { /** @psalm-suppress ArgumentTypeCoercion */ preg_match(CallableResolver::$callablePattern, $toResolve, $matches); [$class, $method] = $matches ? [$matches[1], $matches[2]] : [$toResolve, null]; if ($this->container && $this->container->has($class)) { $instance = $this->container->get($class); if (!is_object($instance)) { throw new RuntimeException(sprintf('%s container entry is not an object', $class)); } } else { if (!class_exists($class)) { if ($method) { $class .= '::' . $method . '()'; } throw new RuntimeException(sprintf('Callable %s does not exist', $class)); } $instance = new $class($this->container); } return [$instance, $method]; } /** * @param mixed $resolved * @param mixed $toResolve * * @throws RuntimeException */ private function assertCallable($resolved, $toResolve): callable { if (!is_callable($resolved)) { if (is_callable($toResolve) || is_object($toResolve) || is_array($toResolve)) { $formatedToResolve = ($toResolveJson = json_encode($toResolve)) !== false ? $toResolveJson : ''; } else { $formatedToResolve = is_string($toResolve) ? $toResolve : ''; } throw new RuntimeException(sprintf('%s is not resolvable', $formatedToResolve)); } return $resolved; } private function bindToContainer(callable $callable): callable { if (is_array($callable) && $callable[0] instanceof Closure) { $callable = $callable[0]; } if ($this->container && $callable instanceof Closure) { /** @var Closure $callable */ $callable = $callable->bindTo($this->container); } return $callable; } /** * @param callable|string|array{class-string, string}|mixed $toResolve * * @return callable|string|array{class-string, string}|mixed */ private function prepareToResolve($toResolve) { if (!is_array($toResolve)) { return $toResolve; } $candidate = $toResolve; $class = array_shift($candidate); $method = array_shift($candidate); if (is_string($class) && is_string($method)) { return $class . ':' . $method; } return $toResolve; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/ResponseEmitter.php
Slim/ResponseEmitter.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim; use Psr\Http\Message\ResponseInterface; use function connection_status; use function header; use function headers_sent; use function in_array; use function min; use function sprintf; use function strlen; use function strtolower; use const CONNECTION_NORMAL; class ResponseEmitter { private int $responseChunkSize; public function __construct(int $responseChunkSize = 4096) { $this->responseChunkSize = $responseChunkSize; } /** * Send the response the client */ public function emit(ResponseInterface $response): void { $isEmpty = $this->isResponseEmpty($response); if (headers_sent() === false) { $this->emitHeaders($response); // Set the status _after_ the headers, because of PHP's "helpful" behavior with location headers. // See https://github.com/slimphp/Slim/issues/1730 $this->emitStatusLine($response); } if (!$isEmpty) { $this->emitBody($response); } } /** * Emit Response Headers */ private function emitHeaders(ResponseInterface $response): void { foreach ($response->getHeaders() as $name => $values) { $first = strtolower($name) !== 'set-cookie'; foreach ($values as $value) { $header = sprintf('%s: %s', $name, $value); header($header, $first); $first = false; } } } /** * Emit Status Line */ private function emitStatusLine(ResponseInterface $response): void { $statusLine = sprintf( 'HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase() ); header($statusLine, true, $response->getStatusCode()); } /** * Emit Body */ private function emitBody(ResponseInterface $response): void { $body = $response->getBody(); if ($body->isSeekable()) { $body->rewind(); } $amountToRead = (int) $response->getHeaderLine('Content-Length'); if (!$amountToRead) { $amountToRead = $body->getSize(); } if ($amountToRead) { while ($amountToRead > 0 && !$body->eof()) { $length = min($this->responseChunkSize, $amountToRead); $data = $body->read($length); echo $data; $amountToRead -= strlen($data); if (connection_status() !== CONNECTION_NORMAL) { break; } } } else { while (!$body->eof()) { echo $body->read($this->responseChunkSize); if (connection_status() !== CONNECTION_NORMAL) { break; } } } } /** * Asserts response body is empty or status code is 204, 205 or 304 */ public function isResponseEmpty(ResponseInterface $response): bool { if (in_array($response->getStatusCode(), [204, 205, 304], true)) { return true; } $stream = $response->getBody(); $seekable = $stream->isSeekable(); if ($seekable) { $stream->rewind(); } return $seekable ? $stream->read(1) === '' : $stream->eof(); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/MiddlewareDispatcher.php
Slim/MiddlewareDispatcher.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim; use Closure; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; use Slim\Interfaces\AdvancedCallableResolverInterface; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\MiddlewareDispatcherInterface; use function class_exists; use function function_exists; use function is_callable; use function is_string; use function preg_match; use function sprintf; /** * @api * @template TContainerInterface of (ContainerInterface|null) */ class MiddlewareDispatcher implements MiddlewareDispatcherInterface { /** * Tip of the middleware call stack */ protected RequestHandlerInterface $tip; protected ?CallableResolverInterface $callableResolver; /** @var TContainerInterface $container */ protected ?ContainerInterface $container; /** * @param TContainerInterface $container */ public function __construct( RequestHandlerInterface $kernel, ?CallableResolverInterface $callableResolver = null, ?ContainerInterface $container = null ) { $this->seedMiddlewareStack($kernel); $this->callableResolver = $callableResolver; $this->container = $container; } /** * {@inheritdoc} */ public function seedMiddlewareStack(RequestHandlerInterface $kernel): void { $this->tip = $kernel; } /** * Invoke the middleware stack */ public function handle(ServerRequestInterface $request): ResponseInterface { return $this->tip->handle($request); } /** * Add a new middleware to the stack * * Middleware are organized as a stack. That means middleware * that have been added before will be executed after the newly * added one (last in, first out). * * @param MiddlewareInterface|string|callable $middleware */ public function add($middleware): MiddlewareDispatcherInterface { if ($middleware instanceof MiddlewareInterface) { return $this->addMiddleware($middleware); } if (is_string($middleware)) { return $this->addDeferred($middleware); } if (is_callable($middleware)) { return $this->addCallable($middleware); } /** @phpstan-ignore-next-line */ throw new RuntimeException( 'A middleware must be an object/class name referencing an implementation of ' . 'MiddlewareInterface or a callable with a matching signature.' ); } /** * Add a new middleware to the stack * * Middleware are organized as a stack. That means middleware * that have been added before will be executed after the newly * added one (last in, first out). */ public function addMiddleware(MiddlewareInterface $middleware): MiddlewareDispatcherInterface { $next = $this->tip; $this->tip = new class ($middleware, $next) implements RequestHandlerInterface { private MiddlewareInterface $middleware; private RequestHandlerInterface $next; public function __construct(MiddlewareInterface $middleware, RequestHandlerInterface $next) { $this->middleware = $middleware; $this->next = $next; } public function handle(ServerRequestInterface $request): ResponseInterface { return $this->middleware->process($request, $this->next); } }; return $this; } /** * Add a new middleware by class name * * Middleware are organized as a stack. That means middleware * that have been added before will be executed after the newly * added one (last in, first out). * @return MiddlewareDispatcher<TContainerInterface> */ public function addDeferred(string $middleware): self { $next = $this->tip; $this->tip = new class ( $middleware, $next, $this->container, $this->callableResolver ) implements RequestHandlerInterface { private string $middleware; private RequestHandlerInterface $next; private ?ContainerInterface $container; private ?CallableResolverInterface $callableResolver; public function __construct( string $middleware, RequestHandlerInterface $next, ?ContainerInterface $container = null, ?CallableResolverInterface $callableResolver = null ) { $this->middleware = $middleware; $this->next = $next; $this->container = $container; $this->callableResolver = $callableResolver; } public function handle(ServerRequestInterface $request): ResponseInterface { if ($this->callableResolver instanceof AdvancedCallableResolverInterface) { $callable = $this->callableResolver->resolveMiddleware($this->middleware); /** @var ResponseInterface */ return $callable($request, $this->next); } $callable = null; if ($this->callableResolver instanceof CallableResolverInterface) { try { $callable = $this->callableResolver->resolve($this->middleware); } catch (RuntimeException $e) { // Do Nothing } } if (!$callable) { $resolved = $this->middleware; $instance = null; $method = null; /** @psalm-suppress ArgumentTypeCoercion */ // Check for Slim callable as `class:method` if (preg_match(CallableResolver::$callablePattern, $resolved, $matches)) { $resolved = $matches[1]; $method = $matches[2]; } if ($this->container && $this->container->has($resolved)) { $instance = $this->container->get($resolved); if ($instance instanceof MiddlewareInterface) { return $instance->process($request, $this->next); } } elseif (!function_exists($resolved)) { if (!class_exists($resolved)) { throw new RuntimeException(sprintf('Middleware %s does not exist', $resolved)); } $instance = new $resolved($this->container); } if ($instance && $instance instanceof MiddlewareInterface) { return $instance->process($request, $this->next); } $callable = $instance ?? $resolved; if ($instance && $method) { $callable = [$instance, $method]; } if ($this->container && $callable instanceof Closure) { $callable = $callable->bindTo($this->container); } } if (!is_callable($callable)) { throw new RuntimeException( sprintf( 'Middleware %s is not resolvable', $this->middleware ) ); } /** @var ResponseInterface */ return $callable($request, $this->next); } }; return $this; } /** * Add a (non-standard) callable middleware to the stack * * Middleware are organized as a stack. That means middleware * that have been added before will be executed after the newly * added one (last in, first out). * @return MiddlewareDispatcher<TContainerInterface> */ public function addCallable(callable $middleware): self { $next = $this->tip; if ($this->container && $middleware instanceof Closure) { /** @var Closure $middleware */ $middleware = $middleware->bindTo($this->container); } $this->tip = new class ($middleware, $next) implements RequestHandlerInterface { /** * @var callable */ private $middleware; /** * @var RequestHandlerInterface */ private $next; public function __construct(callable $middleware, RequestHandlerInterface $next) { $this->middleware = $middleware; $this->next = $next; } public function handle(ServerRequestInterface $request): ResponseInterface { /** @var ResponseInterface */ return ($this->middleware)($request, $this->next); } }; return $this; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Logger.php
Slim/Logger.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim; use Psr\Log\AbstractLogger; use Psr\Log\InvalidArgumentException; use Stringable; use function error_log; class Logger extends AbstractLogger { /** * @param mixed $level * @param string|Stringable $message * @param array<mixed> $context * * @throws InvalidArgumentException */ public function log($level, $message, array $context = []): void { error_log((string) $message); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/Route.php
Slim/Routing/Route.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Routing; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Slim\Handlers\Strategies\RequestHandler; use Slim\Handlers\Strategies\RequestResponse; use Slim\Interfaces\AdvancedCallableResolverInterface; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\InvocationStrategyInterface; use Slim\Interfaces\RequestHandlerInvocationStrategyInterface; use Slim\Interfaces\RouteGroupInterface; use Slim\Interfaces\RouteInterface; use Slim\MiddlewareDispatcher; use function array_key_exists; use function array_replace; use function array_reverse; use function class_implements; use function in_array; use function is_array; /** * @api * @template TContainerInterface of (ContainerInterface|null) */ class Route implements RouteInterface, RequestHandlerInterface { /** * HTTP methods supported by this route * * @var string[] */ protected array $methods = []; /** * Route identifier */ protected string $identifier; /** * Route name */ protected ?string $name = null; /** * Parent route groups * * @var RouteGroupInterface[] */ protected array $groups; protected InvocationStrategyInterface $invocationStrategy; /** * Route parameters * * @var array<string, string> */ protected array $arguments = []; /** * Route arguments parameters * * @var array<string, string> */ protected array $savedArguments = []; /** * Container * @var TContainerInterface $container */ protected ?ContainerInterface $container = null; /** @var MiddlewareDispatcher<TContainerInterface> $middlewareDispatcher */ protected MiddlewareDispatcher $middlewareDispatcher; /** * Route callable * * @var callable|array{class-string, string}|string */ protected $callable; protected CallableResolverInterface $callableResolver; protected ResponseFactoryInterface $responseFactory; /** * Route pattern */ protected string $pattern; protected bool $groupMiddlewareAppended = false; /** * @param string[] $methods The route HTTP methods * @param string $pattern The route pattern * @param callable|array{class-string, string}|string $callable The route callable * @param ResponseFactoryInterface $responseFactory * @param CallableResolverInterface $callableResolver * @param TContainerInterface $container * @param InvocationStrategyInterface|null $invocationStrategy * @param RouteGroupInterface[] $groups The parent route groups * @param int $identifier The route identifier */ public function __construct( array $methods, string $pattern, $callable, ResponseFactoryInterface $responseFactory, CallableResolverInterface $callableResolver, ?ContainerInterface $container = null, ?InvocationStrategyInterface $invocationStrategy = null, array $groups = [], int $identifier = 0 ) { $this->methods = $methods; $this->pattern = $pattern; $this->callable = $callable; $this->responseFactory = $responseFactory; $this->callableResolver = $callableResolver; $this->container = $container; $this->invocationStrategy = $invocationStrategy ?? new RequestResponse(); $this->groups = $groups; $this->identifier = 'route' . $identifier; $this->middlewareDispatcher = new MiddlewareDispatcher($this, $callableResolver, $container); } public function getCallableResolver(): CallableResolverInterface { return $this->callableResolver; } /** * {@inheritdoc} */ public function getInvocationStrategy(): InvocationStrategyInterface { return $this->invocationStrategy; } /** * {@inheritdoc} */ public function setInvocationStrategy(InvocationStrategyInterface $invocationStrategy): RouteInterface { $this->invocationStrategy = $invocationStrategy; return $this; } /** * {@inheritdoc} */ public function getMethods(): array { return $this->methods; } /** * {@inheritdoc} */ public function getPattern(): string { return $this->pattern; } /** * {@inheritdoc} */ public function setPattern(string $pattern): RouteInterface { $this->pattern = $pattern; return $this; } /** * {@inheritdoc} */ public function getCallable() { return $this->callable; } /** * {@inheritdoc} */ public function setCallable($callable): RouteInterface { $this->callable = $callable; return $this; } /** * {@inheritdoc} */ public function getName(): ?string { return $this->name; } /** * {@inheritdoc} */ public function setName(string $name): RouteInterface { $this->name = $name; return $this; } /** * {@inheritdoc} */ public function getIdentifier(): string { return $this->identifier; } /** * {@inheritdoc} */ public function getArgument(string $name, ?string $default = null): ?string { if (array_key_exists($name, $this->arguments)) { return $this->arguments[$name]; } return $default; } /** * {@inheritdoc} */ public function getArguments(): array { return $this->arguments; } /** * {@inheritdoc} */ public function setArguments(array $arguments, bool $includeInSavedArguments = true): RouteInterface { if ($includeInSavedArguments) { $this->savedArguments = $arguments; } $this->arguments = $arguments; return $this; } /** * @return RouteGroupInterface[] */ public function getGroups(): array { return $this->groups; } /** * {@inheritdoc} */ public function add($middleware): RouteInterface { $this->middlewareDispatcher->add($middleware); return $this; } /** * {@inheritdoc} */ public function addMiddleware(MiddlewareInterface $middleware): RouteInterface { $this->middlewareDispatcher->addMiddleware($middleware); return $this; } /** * {@inheritdoc} */ public function prepare(array $arguments): RouteInterface { $this->arguments = array_replace($this->savedArguments, $arguments); return $this; } /** * {@inheritdoc} */ public function setArgument(string $name, string $value, bool $includeInSavedArguments = true): RouteInterface { if ($includeInSavedArguments) { $this->savedArguments[$name] = $value; } $this->arguments[$name] = $value; return $this; } /** * {@inheritdoc} */ public function run(ServerRequestInterface $request): ResponseInterface { if (!$this->groupMiddlewareAppended) { $this->appendGroupMiddlewareToRoute(); } return $this->middlewareDispatcher->handle($request); } /** * @return void */ protected function appendGroupMiddlewareToRoute(): void { $inner = $this->middlewareDispatcher; $this->middlewareDispatcher = new MiddlewareDispatcher($inner, $this->callableResolver, $this->container); foreach (array_reverse($this->groups) as $group) { $group->appendMiddlewareToDispatcher($this->middlewareDispatcher); } $this->groupMiddlewareAppended = true; } /** * {@inheritdoc} */ public function handle(ServerRequestInterface $request): ResponseInterface { if ($this->callableResolver instanceof AdvancedCallableResolverInterface) { $callable = $this->callableResolver->resolveRoute($this->callable); } else { $callable = $this->callableResolver->resolve($this->callable); } $strategy = $this->invocationStrategy; $strategyImplements = class_implements($strategy); if ( is_array($callable) && $callable[0] instanceof RequestHandlerInterface && !in_array(RequestHandlerInvocationStrategyInterface::class, $strategyImplements) ) { $strategy = new RequestHandler(); } $response = $this->responseFactory->createResponse(); return $strategy($callable, $request, $response, $this->arguments); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/FastRouteDispatcher.php
Slim/Routing/FastRouteDispatcher.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Routing; use FastRoute\Dispatcher\GroupCountBased; class FastRouteDispatcher extends GroupCountBased { /** * @var string[][] */ private array $allowedMethods = []; /** * @param string $httpMethod * @param string $uri * * @return array{int, string|null, array<string, string>} */ public function dispatch($httpMethod, $uri): array { $routingResults = $this->routingResults($httpMethod, $uri); if ($routingResults[0] === self::FOUND) { return $routingResults; } // For HEAD requests, attempt fallback to GET if ($httpMethod === 'HEAD') { $routingResults = $this->routingResults('GET', $uri); if ($routingResults[0] === self::FOUND) { return $routingResults; } } // If nothing else matches, try fallback routes $routingResults = $this->routingResults('*', $uri); if ($routingResults[0] === self::FOUND) { return $routingResults; } if (!empty($this->getAllowedMethods($uri))) { return [self::METHOD_NOT_ALLOWED, null, []]; } return [self::NOT_FOUND, null, []]; } /** * @param string $httpMethod * @param string $uri * * @return array{int, string|null, array<string, string>} */ private function routingResults(string $httpMethod, string $uri): array { if (isset($this->staticRouteMap[$httpMethod][$uri])) { /** @var string $routeIdentifier */ $routeIdentifier = $this->staticRouteMap[$httpMethod][$uri]; return [self::FOUND, $routeIdentifier, []]; } if (isset($this->variableRouteData[$httpMethod])) { /** @var array{0: int, 1?: string, 2?: array<string, string>} $result */ $result = $this->dispatchVariableRoute($this->variableRouteData[$httpMethod], $uri); if ($result[0] === self::FOUND) { /** @var array{int, string, array<string, string>} $result */ return [self::FOUND, $result[1], $result[2]]; } } return [self::NOT_FOUND, null, []]; } /** * @param string $uri * * @return string[] */ public function getAllowedMethods(string $uri): array { if (isset($this->allowedMethods[$uri])) { return $this->allowedMethods[$uri]; } $allowedMethods = []; foreach ($this->staticRouteMap as $method => $uriMap) { if (isset($uriMap[$uri])) { $allowedMethods[$method] = true; } } foreach ($this->variableRouteData as $method => $routeData) { $result = $this->dispatchVariableRoute($routeData, $uri); if ($result[0] === self::FOUND) { $allowedMethods[$method] = true; } } return $this->allowedMethods[$uri] = array_keys($allowedMethods); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/RoutingResults.php
Slim/Routing/RoutingResults.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Routing; use Slim\Interfaces\DispatcherInterface; use function rawurldecode; /** @api */ class RoutingResults { public const NOT_FOUND = 0; public const FOUND = 1; public const METHOD_NOT_ALLOWED = 2; protected DispatcherInterface $dispatcher; protected string $method; protected string $uri; /** * The status is one of the constants shown above * NOT_FOUND = 0 * FOUND = 1 * METHOD_NOT_ALLOWED = 2 */ protected int $routeStatus; protected ?string $routeIdentifier = null; /** * @var array<string, string> */ protected array $routeArguments; /** * @param array<string, string> $routeArguments */ public function __construct( DispatcherInterface $dispatcher, string $method, string $uri, int $routeStatus, ?string $routeIdentifier = null, array $routeArguments = [] ) { $this->dispatcher = $dispatcher; $this->method = $method; $this->uri = $uri; $this->routeStatus = $routeStatus; $this->routeIdentifier = $routeIdentifier; $this->routeArguments = $routeArguments; } public function getDispatcher(): DispatcherInterface { return $this->dispatcher; } public function getMethod(): string { return $this->method; } public function getUri(): string { return $this->uri; } public function getRouteStatus(): int { return $this->routeStatus; } public function getRouteIdentifier(): ?string { return $this->routeIdentifier; } /** * @return array<string, string> */ public function getRouteArguments(bool $urlDecode = true): array { if (!$urlDecode) { return $this->routeArguments; } $routeArguments = []; foreach ($this->routeArguments as $key => $value) { $routeArguments[$key] = rawurldecode($value); } return $routeArguments; } /** * @return string[] */ public function getAllowedMethods(): array { return $this->dispatcher->getAllowedMethods($this->uri); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/RouteResolver.php
Slim/Routing/RouteResolver.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Routing; use RuntimeException; use Slim\Interfaces\DispatcherInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteInterface; use Slim\Interfaces\RouteResolverInterface; use function rawurldecode; /** * RouteResolver instantiates the FastRoute dispatcher * and computes the routing results of a given URI and request method */ class RouteResolver implements RouteResolverInterface { protected RouteCollectorInterface $routeCollector; private DispatcherInterface $dispatcher; public function __construct(RouteCollectorInterface $routeCollector, ?DispatcherInterface $dispatcher = null) { $this->routeCollector = $routeCollector; $this->dispatcher = $dispatcher ?? new Dispatcher($routeCollector); } /** * @param string $uri Should be $request->getUri()->getPath() */ public function computeRoutingResults(string $uri, string $method): RoutingResults { $uri = rawurldecode($uri); if ($uri === '' || $uri[0] !== '/') { $uri = '/' . $uri; } return $this->dispatcher->dispatch($method, $uri); } /** * @throws RuntimeException */ public function resolveRoute(string $identifier): RouteInterface { return $this->routeCollector->lookupRoute($identifier); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/RouteRunner.php
Slim/Routing/RouteRunner.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Routing; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Slim\Exception\HttpMethodNotAllowedException; use Slim\Exception\HttpNotFoundException; use Slim\Interfaces\RouteCollectorProxyInterface; use Slim\Interfaces\RouteParserInterface; use Slim\Interfaces\RouteResolverInterface; use Slim\Middleware\RoutingMiddleware; class RouteRunner implements RequestHandlerInterface { private RouteResolverInterface $routeResolver; private RouteParserInterface $routeParser; /** * @var RouteCollectorProxyInterface<\Psr\Container\ContainerInterface|null> */ private ?RouteCollectorProxyInterface $routeCollectorProxy; /** * @param RouteCollectorProxyInterface<\Psr\Container\ContainerInterface|null> $routeCollectorProxy */ public function __construct( RouteResolverInterface $routeResolver, RouteParserInterface $routeParser, ?RouteCollectorProxyInterface $routeCollectorProxy = null ) { $this->routeResolver = $routeResolver; $this->routeParser = $routeParser; $this->routeCollectorProxy = $routeCollectorProxy; } /** * This request handler is instantiated automatically in App::__construct() * It is at the very tip of the middleware queue meaning it will be executed * last and it detects whether or not routing has been performed in the user * defined middleware stack. In the event that the user did not perform routing * it is done here * * @throws HttpNotFoundException * @throws HttpMethodNotAllowedException */ public function handle(ServerRequestInterface $request): ResponseInterface { // If routing hasn't been done, then do it now so we can dispatch if ($request->getAttribute(RouteContext::ROUTING_RESULTS) === null) { $routingMiddleware = new RoutingMiddleware($this->routeResolver, $this->routeParser); $request = $routingMiddleware->performRouting($request); } if ($this->routeCollectorProxy !== null) { $request = $request->withAttribute( RouteContext::BASE_PATH, $this->routeCollectorProxy->getBasePath() ); } /** @var Route<\Psr\Container\ContainerInterface|null> $route */ $route = $request->getAttribute(RouteContext::ROUTE); return $route->run($request); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/RouteGroup.php
Slim/Routing/RouteGroup.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Routing; use Psr\Http\Server\MiddlewareInterface; use Slim\Interfaces\AdvancedCallableResolverInterface; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\RouteCollectorProxyInterface; use Slim\Interfaces\RouteGroupInterface; use Slim\MiddlewareDispatcher; class RouteGroup implements RouteGroupInterface { /** * @var callable|string */ protected $callable; protected CallableResolverInterface $callableResolver; /** * @var RouteCollectorProxyInterface<\Psr\Container\ContainerInterface|null> */ protected RouteCollectorProxyInterface $routeCollectorProxy; /** * @var MiddlewareInterface[]|string[]|callable[] */ protected array $middleware = []; protected string $pattern; /** * @param callable|string $callable * @param RouteCollectorProxyInterface<\Psr\Container\ContainerInterface|null> $routeCollectorProxy */ public function __construct( string $pattern, $callable, CallableResolverInterface $callableResolver, RouteCollectorProxyInterface $routeCollectorProxy ) { $this->pattern = $pattern; $this->callable = $callable; $this->callableResolver = $callableResolver; $this->routeCollectorProxy = $routeCollectorProxy; } /** * {@inheritdoc} */ public function collectRoutes(): RouteGroupInterface { if ($this->callableResolver instanceof AdvancedCallableResolverInterface) { $callable = $this->callableResolver->resolveRoute($this->callable); } else { $callable = $this->callableResolver->resolve($this->callable); } $callable($this->routeCollectorProxy); return $this; } /** * {@inheritdoc} */ public function add($middleware): RouteGroupInterface { $this->middleware[] = $middleware; return $this; } /** * {@inheritdoc} */ public function addMiddleware(MiddlewareInterface $middleware): RouteGroupInterface { $this->middleware[] = $middleware; return $this; } /** * {@inheritdoc} * @param MiddlewareDispatcher<\Psr\Container\ContainerInterface|null> $dispatcher */ public function appendMiddlewareToDispatcher(MiddlewareDispatcher $dispatcher): RouteGroupInterface { foreach ($this->middleware as $middleware) { $dispatcher->add($middleware); } return $this; } /** * {@inheritdoc} */ public function getPattern(): string { return $this->pattern; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/Dispatcher.php
Slim/Routing/Dispatcher.php
<?php declare(strict_types=1); namespace Slim\Routing; use FastRoute\DataGenerator\GroupCountBased; use FastRoute\RouteCollector as FastRouteCollector; use FastRoute\RouteParser\Std; use Slim\Interfaces\DispatcherInterface; use Slim\Interfaces\RouteCollectorInterface; class Dispatcher implements DispatcherInterface { private RouteCollectorInterface $routeCollector; private ?FastRouteDispatcher $dispatcher = null; public function __construct(RouteCollectorInterface $routeCollector) { $this->routeCollector = $routeCollector; } protected function createDispatcher(): FastRouteDispatcher { if ($this->dispatcher) { return $this->dispatcher; } $routeDefinitionCallback = function (FastRouteCollector $r): void { $basePath = $this->routeCollector->getBasePath(); foreach ($this->routeCollector->getRoutes() as $route) { $r->addRoute($route->getMethods(), $basePath . $route->getPattern(), $route->getIdentifier()); } }; $cacheFile = $this->routeCollector->getCacheFile(); if ($cacheFile) { /** @var FastRouteDispatcher $dispatcher */ $dispatcher = \FastRoute\cachedDispatcher($routeDefinitionCallback, [ 'dataGenerator' => GroupCountBased::class, 'dispatcher' => FastRouteDispatcher::class, 'routeParser' => new Std(), 'cacheFile' => $cacheFile, ]); } else { /** @var FastRouteDispatcher $dispatcher */ $dispatcher = \FastRoute\simpleDispatcher($routeDefinitionCallback, [ 'dataGenerator' => GroupCountBased::class, 'dispatcher' => FastRouteDispatcher::class, 'routeParser' => new Std(), ]); } $this->dispatcher = $dispatcher; return $this->dispatcher; } /** * {@inheritdoc} */ public function dispatch(string $method, string $uri): RoutingResults { $dispatcher = $this->createDispatcher(); $results = $dispatcher->dispatch($method, $uri); return new RoutingResults($this, $method, $uri, $results[0], $results[1], $results[2]); } /** * {@inheritdoc} */ public function getAllowedMethods(string $uri): array { $dispatcher = $this->createDispatcher(); return $dispatcher->getAllowedMethods($uri); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/RouteCollector.php
Slim/Routing/RouteCollector.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Routing; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use RuntimeException; use Slim\Handlers\Strategies\RequestResponse; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\InvocationStrategyInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteCollectorProxyInterface; use Slim\Interfaces\RouteGroupInterface; use Slim\Interfaces\RouteInterface; use Slim\Interfaces\RouteParserInterface; use function array_pop; use function dirname; use function file_exists; use function is_readable; use function is_writable; use function sprintf; /** * RouteCollector is used to collect routes and route groups * as well as generate paths and URLs relative to its environment * @template TContainerInterface of (ContainerInterface|null) */ class RouteCollector implements RouteCollectorInterface { protected RouteParserInterface $routeParser; protected CallableResolverInterface $callableResolver; protected ?ContainerInterface $container = null; protected InvocationStrategyInterface $defaultInvocationStrategy; /** * Base path used in pathFor() */ protected string $basePath = ''; /** * Path to fast route cache file. Set to null to disable route caching */ protected ?string $cacheFile = null; /** * Routes * * @var RouteInterface[] */ protected array $routes = []; /** * Routes indexed by name * * @var RouteInterface[] */ protected array $routesByName = []; /** * Route groups * * @var RouteGroupInterface[] */ protected array $routeGroups = []; /** * Route counter incrementer */ protected int $routeCounter = 0; protected ResponseFactoryInterface $responseFactory; /** * @param TContainerInterface $container */ public function __construct( ResponseFactoryInterface $responseFactory, CallableResolverInterface $callableResolver, ?ContainerInterface $container = null, ?InvocationStrategyInterface $defaultInvocationStrategy = null, ?RouteParserInterface $routeParser = null, ?string $cacheFile = null ) { $this->responseFactory = $responseFactory; $this->callableResolver = $callableResolver; $this->container = $container; $this->defaultInvocationStrategy = $defaultInvocationStrategy ?? new RequestResponse(); $this->routeParser = $routeParser ?? new RouteParser($this); if ($cacheFile) { $this->setCacheFile($cacheFile); } } public function getRouteParser(): RouteParserInterface { return $this->routeParser; } /** * Get default route invocation strategy */ public function getDefaultInvocationStrategy(): InvocationStrategyInterface { return $this->defaultInvocationStrategy; } public function setDefaultInvocationStrategy(InvocationStrategyInterface $strategy): RouteCollectorInterface { $this->defaultInvocationStrategy = $strategy; return $this; } /** * {@inheritdoc} */ public function getCacheFile(): ?string { return $this->cacheFile; } /** * {@inheritdoc} */ public function setCacheFile(string $cacheFile): RouteCollectorInterface { if (file_exists($cacheFile) && !is_readable($cacheFile)) { throw new RuntimeException( sprintf('Route collector cache file `%s` is not readable', $cacheFile) ); } if (!file_exists($cacheFile) && !is_writable(dirname($cacheFile))) { throw new RuntimeException( sprintf('Route collector cache file directory `%s` is not writable', dirname($cacheFile)) ); } $this->cacheFile = $cacheFile; return $this; } /** * {@inheritdoc} */ public function getBasePath(): string { return $this->basePath; } /** * Set the base path used in urlFor() */ public function setBasePath(string $basePath): RouteCollectorInterface { $this->basePath = $basePath; return $this; } /** * {@inheritdoc} */ public function getRoutes(): array { return $this->routes; } /** * {@inheritdoc} */ public function removeNamedRoute(string $name): RouteCollectorInterface { $route = $this->getNamedRoute($name); /** @psalm-suppress PossiblyNullArrayOffset */ unset($this->routesByName[$route->getName()], $this->routes[$route->getIdentifier()]); return $this; } /** * {@inheritdoc} */ public function getNamedRoute(string $name): RouteInterface { if (isset($this->routesByName[$name])) { $route = $this->routesByName[$name]; if ($route->getName() === $name) { return $route; } unset($this->routesByName[$name]); } foreach ($this->routes as $route) { if ($name === $route->getName()) { $this->routesByName[$name] = $route; return $route; } } throw new RuntimeException('Named route does not exist for name: ' . $name); } /** * {@inheritdoc} */ public function lookupRoute(string $identifier): RouteInterface { if (!isset($this->routes[$identifier])) { throw new RuntimeException('Route not found, looks like your route cache is stale.'); } return $this->routes[$identifier]; } /** * {@inheritdoc} */ public function group(string $pattern, $callable): RouteGroupInterface { $routeGroup = $this->createGroup($pattern, $callable); $this->routeGroups[] = $routeGroup; $routeGroup->collectRoutes(); array_pop($this->routeGroups); return $routeGroup; } /** * @param string|callable $callable */ protected function createGroup(string $pattern, $callable): RouteGroupInterface { $routeCollectorProxy = $this->createProxy($pattern); return new RouteGroup($pattern, $callable, $this->callableResolver, $routeCollectorProxy); } /** * @return RouteCollectorProxyInterface<TContainerInterface> */ protected function createProxy(string $pattern): RouteCollectorProxyInterface { /** @var RouteCollectorProxy<TContainerInterface> */ return new RouteCollectorProxy( $this->responseFactory, $this->callableResolver, $this->container, $this, $pattern ); } /** * {@inheritdoc} */ public function map(array $methods, string $pattern, $handler): RouteInterface { $route = $this->createRoute($methods, $pattern, $handler); $this->routes[$route->getIdentifier()] = $route; $routeName = $route->getName(); if ($routeName !== null && !isset($this->routesByName[$routeName])) { $this->routesByName[$routeName] = $route; } $this->routeCounter++; return $route; } /** * @param string[] $methods * @param callable|array{class-string, string}|string $callable */ protected function createRoute(array $methods, string $pattern, $callable): RouteInterface { return new Route( $methods, $pattern, $callable, $this->responseFactory, $this->callableResolver, $this->container, $this->defaultInvocationStrategy, $this->routeGroups, $this->routeCounter ); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/RouteParser.php
Slim/Routing/RouteParser.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Routing; use FastRoute\RouteParser\Std; use InvalidArgumentException; use Psr\Http\Message\UriInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteParserInterface; use function array_key_exists; use function array_reverse; use function http_build_query; use function implode; use function is_string; class RouteParser implements RouteParserInterface { private RouteCollectorInterface $routeCollector; private Std $routeParser; public function __construct(RouteCollectorInterface $routeCollector) { $this->routeCollector = $routeCollector; $this->routeParser = new Std(); } /** * {@inheritdoc} */ public function relativeUrlFor(string $routeName, array $data = [], array $queryParams = []): string { $route = $this->routeCollector->getNamedRoute($routeName); $pattern = $route->getPattern(); $segments = []; $segmentName = ''; /* * $routes is an associative array of expressions representing a route as multiple segments * There is an expression for each optional parameter plus one without the optional parameters * The most specific is last, hence why we reverse the array before iterating over it */ $expressions = array_reverse($this->routeParser->parse($pattern)); foreach ($expressions as $expression) { foreach ($expression as $segment) { /* * Each $segment is either a string or an array of strings * containing optional parameters of an expression */ if (is_string($segment)) { $segments[] = $segment; continue; } /** @var string[] $segment */ /* * If we don't have a data element for this segment in the provided $data * we cancel testing to move onto the next expression with a less specific item */ if (!array_key_exists($segment[0], $data)) { $segments = []; $segmentName = $segment[0]; break; } $segments[] = $data[$segment[0]]; } /* * If we get to this logic block we have found all the parameters * for the provided $data which means we don't need to continue testing * less specific expressions */ if (!empty($segments)) { break; } } if (empty($segments)) { throw new InvalidArgumentException('Missing data for URL segment: ' . $segmentName); } $url = implode('', $segments); if ($queryParams) { $url .= '?' . http_build_query($queryParams); } return $url; } /** * {@inheritdoc} */ public function urlFor(string $routeName, array $data = [], array $queryParams = []): string { $basePath = $this->routeCollector->getBasePath(); $url = $this->relativeUrlFor($routeName, $data, $queryParams); if ($basePath) { $url = $basePath . $url; } return $url; } /** * {@inheritdoc} */ public function fullUrlFor(UriInterface $uri, string $routeName, array $data = [], array $queryParams = []): string { $path = $this->urlFor($routeName, $data, $queryParams); $scheme = $uri->getScheme(); $authority = $uri->getAuthority(); $protocol = ($scheme ? $scheme . ':' : '') . ($authority ? '//' . $authority : ''); return $protocol . $path; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/RouteCollectorProxy.php
Slim/Routing/RouteCollectorProxy.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Routing; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Slim\Interfaces\CallableResolverInterface; use Slim\Interfaces\RouteCollectorInterface; use Slim\Interfaces\RouteCollectorProxyInterface; use Slim\Interfaces\RouteGroupInterface; use Slim\Interfaces\RouteInterface; /** * @template TContainerInterface of (ContainerInterface|null) * @template-implements RouteCollectorProxyInterface<TContainerInterface> */ class RouteCollectorProxy implements RouteCollectorProxyInterface { protected ResponseFactoryInterface $responseFactory; protected CallableResolverInterface $callableResolver; /** @var TContainerInterface */ protected ?ContainerInterface $container = null; protected RouteCollectorInterface $routeCollector; protected string $groupPattern; /** * @param TContainerInterface $container */ public function __construct( ResponseFactoryInterface $responseFactory, CallableResolverInterface $callableResolver, ?ContainerInterface $container = null, ?RouteCollectorInterface $routeCollector = null, string $groupPattern = '' ) { $this->responseFactory = $responseFactory; $this->callableResolver = $callableResolver; $this->container = $container; $this->routeCollector = $routeCollector ?? new RouteCollector($responseFactory, $callableResolver, $container); $this->groupPattern = $groupPattern; } /** * {@inheritdoc} */ public function getResponseFactory(): ResponseFactoryInterface { return $this->responseFactory; } /** * {@inheritdoc} */ public function getCallableResolver(): CallableResolverInterface { return $this->callableResolver; } /** * {@inheritdoc} * @return TContainerInterface */ public function getContainer(): ?ContainerInterface { return $this->container; } /** * {@inheritdoc} */ public function getRouteCollector(): RouteCollectorInterface { return $this->routeCollector; } /** * {@inheritdoc} */ public function getBasePath(): string { return $this->routeCollector->getBasePath(); } /** * {@inheritdoc} */ public function setBasePath(string $basePath): RouteCollectorProxyInterface { $this->routeCollector->setBasePath($basePath); return $this; } /** * {@inheritdoc} */ public function get(string $pattern, $callable): RouteInterface { return $this->map(['GET'], $pattern, $callable); } /** * {@inheritdoc} */ public function post(string $pattern, $callable): RouteInterface { return $this->map(['POST'], $pattern, $callable); } /** * {@inheritdoc} */ public function put(string $pattern, $callable): RouteInterface { return $this->map(['PUT'], $pattern, $callable); } /** * {@inheritdoc} */ public function patch(string $pattern, $callable): RouteInterface { return $this->map(['PATCH'], $pattern, $callable); } /** * {@inheritdoc} */ public function delete(string $pattern, $callable): RouteInterface { return $this->map(['DELETE'], $pattern, $callable); } /** * {@inheritdoc} */ public function options(string $pattern, $callable): RouteInterface { return $this->map(['OPTIONS'], $pattern, $callable); } /** * {@inheritdoc} */ public function any(string $pattern, $callable): RouteInterface { return $this->map(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], $pattern, $callable); } /** * {@inheritdoc} */ public function map(array $methods, string $pattern, $callable): RouteInterface { $pattern = $this->groupPattern . $pattern; return $this->routeCollector->map($methods, $pattern, $callable); } /** * {@inheritdoc} */ public function group(string $pattern, $callable): RouteGroupInterface { $pattern = $this->groupPattern . $pattern; return $this->routeCollector->group($pattern, $callable); } /** * {@inheritdoc} */ public function redirect(string $from, $to, int $status = 302): RouteInterface { $responseFactory = $this->responseFactory; $handler = function () use ($to, $status, $responseFactory) { $response = $responseFactory->createResponse($status); return $response->withHeader('Location', (string) $to); }; return $this->get($from, $handler); } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Routing/RouteContext.php
Slim/Routing/RouteContext.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Routing; use Psr\Http\Message\ServerRequestInterface; use RuntimeException; use Slim\Interfaces\RouteInterface; use Slim\Interfaces\RouteParserInterface; /** @api */ final class RouteContext { public const ROUTE = '__route__'; public const ROUTE_PARSER = '__routeParser__'; public const ROUTING_RESULTS = '__routingResults__'; public const BASE_PATH = '__basePath__'; public static function fromRequest(ServerRequestInterface $serverRequest): self { $route = $serverRequest->getAttribute(self::ROUTE); $routeParser = $serverRequest->getAttribute(self::ROUTE_PARSER); $routingResults = $serverRequest->getAttribute(self::ROUTING_RESULTS); $basePath = $serverRequest->getAttribute(self::BASE_PATH); if ($routeParser === null || $routingResults === null) { throw new RuntimeException('Cannot create RouteContext before routing has been completed'); } /** @var RouteInterface|null $route */ /** @var RouteParserInterface $routeParser */ /** @var RoutingResults $routingResults */ /** @var string|null $basePath */ return new self($route, $routeParser, $routingResults, $basePath); } private ?RouteInterface $route; private RouteParserInterface $routeParser; private RoutingResults $routingResults; private ?string $basePath; private function __construct( ?RouteInterface $route, RouteParserInterface $routeParser, RoutingResults $routingResults, ?string $basePath = null ) { $this->route = $route; $this->routeParser = $routeParser; $this->routingResults = $routingResults; $this->basePath = $basePath; } public function getRoute(): ?RouteInterface { return $this->route; } public function getRouteParser(): RouteParserInterface { return $this->routeParser; } public function getRoutingResults(): RoutingResults { return $this->routingResults; } public function getBasePath(): string { if ($this->basePath === null) { throw new RuntimeException('No base path defined.'); } return $this->basePath; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/RouteParserInterface.php
Slim/Interfaces/RouteParserInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use InvalidArgumentException; use Psr\Http\Message\UriInterface; use RuntimeException; /** @api */ interface RouteParserInterface { /** * Build the path for a named route excluding the base path * * @param string $routeName Route name * @param array<string, string> $data Named argument replacement data * @param array<string, string | array<array-key, string>> $queryParams Optional query string parameters * * @throws RuntimeException If named route does not exist * @throws InvalidArgumentException If required data not provided */ public function relativeUrlFor(string $routeName, array $data = [], array $queryParams = []): string; /** * Build the path for a named route including the base path * * @param string $routeName Route name * @param array<string, string> $data Named argument replacement data * @param array<string, string | array<array-key, string>> $queryParams Optional query string parameters * * @throws RuntimeException If named route does not exist * @throws InvalidArgumentException If required data not provided */ public function urlFor(string $routeName, array $data = [], array $queryParams = []): string; /** * Get fully qualified URL for named route * * @param UriInterface $uri * @param string $routeName Route name * @param array<string, string> $data Named argument replacement data * @param array<string, string | array<array-key, string>> $queryParams Optional query string parameters */ public function fullUrlFor(UriInterface $uri, string $routeName, array $data = [], array $queryParams = []): string; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/ErrorHandlerInterface.php
Slim/Interfaces/ErrorHandlerInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Throwable; interface ErrorHandlerInterface { public function __invoke( ServerRequestInterface $request, Throwable $exception, bool $displayErrorDetails, bool $logErrors, bool $logErrorDetails ): ResponseInterface; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/RouteCollectorProxyInterface.php
Slim/Interfaces/RouteCollectorProxyInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\UriInterface; /** * @api * @template TContainerInterface of (ContainerInterface|null) */ interface RouteCollectorProxyInterface { public function getResponseFactory(): ResponseFactoryInterface; public function getCallableResolver(): CallableResolverInterface; /** * @return TContainerInterface */ public function getContainer(): ?ContainerInterface; public function getRouteCollector(): RouteCollectorInterface; /** * Get the RouteCollectorProxy's base path */ public function getBasePath(): string; /** * Set the RouteCollectorProxy's base path * @return RouteCollectorProxyInterface<TContainerInterface> */ public function setBasePath(string $basePath): RouteCollectorProxyInterface; /** * Add GET route * * @param string $pattern The route URI pattern * @param callable|array{class-string, string}|string $callable The route callback routine */ public function get(string $pattern, $callable): RouteInterface; /** * Add POST route * * @param string $pattern The route URI pattern * @param callable|array{class-string, string}|string $callable The route callback routine */ public function post(string $pattern, $callable): RouteInterface; /** * Add PUT route * * @param string $pattern The route URI pattern * @param callable|array{class-string, string}|string $callable The route callback routine */ public function put(string $pattern, $callable): RouteInterface; /** * Add PATCH route * * @param string $pattern The route URI pattern * @param callable|array{class-string, string}|string $callable The route callback routine */ public function patch(string $pattern, $callable): RouteInterface; /** * Add DELETE route * * @param string $pattern The route URI pattern * @param callable|array{class-string, string}|string $callable The route callback routine */ public function delete(string $pattern, $callable): RouteInterface; /** * Add OPTIONS route * * @param string $pattern The route URI pattern * @param callable|array{class-string, string}|string $callable The route callback routine */ public function options(string $pattern, $callable): RouteInterface; /** * Add route for any HTTP method * * @param string $pattern The route URI pattern * @param callable|array{class-string, string}|string $callable The route callback routine */ public function any(string $pattern, $callable): RouteInterface; /** * Add route with multiple methods * * @param string[] $methods Numeric array of HTTP method names * @param string $pattern The route URI pattern * @param callable|array{class-string, string}|string $callable The route callback routine */ public function map(array $methods, string $pattern, $callable): RouteInterface; /** * Route Groups * * This method accepts a route pattern and a callback. All route * declarations in the callback will be prepended by the group(s) * that it is in. * @param string|callable $callable */ public function group(string $pattern, $callable): RouteGroupInterface; /** * Add a route that sends an HTTP redirect * * @param string|UriInterface $to */ public function redirect(string $from, $to, int $status = 302): RouteInterface; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/RouteInterface.php
Slim/Interfaces/RouteInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; /** @api */ interface RouteInterface { /** * Get route invocation strategy */ public function getInvocationStrategy(): InvocationStrategyInterface; /** * Set route invocation strategy */ public function setInvocationStrategy(InvocationStrategyInterface $invocationStrategy): RouteInterface; /** * Get route methods * * @return string[] */ public function getMethods(): array; /** * Get route pattern */ public function getPattern(): string; /** * Set route pattern */ public function setPattern(string $pattern): RouteInterface; /** * Get route callable * * @return callable|array{class-string, string}|string */ public function getCallable(); /** * Set route callable * * @param callable|array{class-string, string}|string $callable */ public function setCallable($callable): RouteInterface; /** * Get route name */ public function getName(): ?string; /** * Set route name * * @return static */ public function setName(string $name): RouteInterface; /** * Get the route's unique identifier */ public function getIdentifier(): string; /** * Retrieve a specific route argument */ public function getArgument(string $name, ?string $default = null): ?string; /** * Get route arguments * * @return array<string, string> */ public function getArguments(): array; /** * Set a route argument * * @deprecated 4.14.1 Use a middleware for custom route arguments now. */ public function setArgument(string $name, string $value): RouteInterface; /** * Replace route arguments * * @param array<string, string> $arguments * * @deprecated 4.14.1 Use a middleware for custom route arguments now. */ public function setArguments(array $arguments): self; /** * @param MiddlewareInterface|string|callable $middleware */ public function add($middleware): self; public function addMiddleware(MiddlewareInterface $middleware): self; /** * Prepare the route for use * * @param array<string, string> $arguments */ public function prepare(array $arguments): self; /** * Run route * * This method traverses the middleware stack, including the route's callable * and captures the resultant HTTP response object. It then sends the response * back to the Application. */ public function run(ServerRequestInterface $request): ResponseInterface; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/ServerRequestCreatorInterface.php
Slim/Interfaces/ServerRequestCreatorInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use Psr\Http\Message\ServerRequestInterface; interface ServerRequestCreatorInterface { public function createServerRequestFromGlobals(): ServerRequestInterface; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/RequestHandlerInvocationStrategyInterface.php
Slim/Interfaces/RequestHandlerInvocationStrategyInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; interface RequestHandlerInvocationStrategyInterface extends InvocationStrategyInterface { }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/RouteGroupInterface.php
Slim/Interfaces/RouteGroupInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use Psr\Http\Server\MiddlewareInterface; use Slim\MiddlewareDispatcher; /** @api */ interface RouteGroupInterface { public function collectRoutes(): RouteGroupInterface; /** * Add middleware to the route group * * @param MiddlewareInterface|string|callable $middleware */ public function add($middleware): RouteGroupInterface; /** * Add middleware to the route group */ public function addMiddleware(MiddlewareInterface $middleware): RouteGroupInterface; /** * Append the group's middleware to the MiddlewareDispatcher * @param MiddlewareDispatcher<\Psr\Container\ContainerInterface|null> $dispatcher */ public function appendMiddlewareToDispatcher(MiddlewareDispatcher $dispatcher): RouteGroupInterface; /** * Get the RouteGroup's pattern */ public function getPattern(): string; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/RouteCollectorInterface.php
Slim/Interfaces/RouteCollectorInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use InvalidArgumentException; use RuntimeException; /** @api */ interface RouteCollectorInterface { /** * Get the route parser */ public function getRouteParser(): RouteParserInterface; /** * Get default route invocation strategy */ public function getDefaultInvocationStrategy(): InvocationStrategyInterface; /** * Set default route invocation strategy */ public function setDefaultInvocationStrategy(InvocationStrategyInterface $strategy): RouteCollectorInterface; /** * Get path to FastRoute cache file */ public function getCacheFile(): ?string; /** * Set path to FastRoute cache file * * @throws InvalidArgumentException * @throws RuntimeException */ public function setCacheFile(string $cacheFile): RouteCollectorInterface; /** * Get the base path used in pathFor() */ public function getBasePath(): string; /** * Set the base path used in pathFor() */ public function setBasePath(string $basePath): RouteCollectorInterface; /** * Get route objects * * @return RouteInterface[] */ public function getRoutes(): array; /** * Get named route object * * @param string $name Route name * * @throws RuntimeException If named route does not exist */ public function getNamedRoute(string $name): RouteInterface; /** * Remove named route * * @param string $name Route name * * @throws RuntimeException If named route does not exist */ public function removeNamedRoute(string $name): RouteCollectorInterface; /** * Lookup a route via the route's unique identifier * * @throws RuntimeException If route of identifier does not exist */ public function lookupRoute(string $identifier): RouteInterface; /** * Add route group * @param string|callable $callable */ public function group(string $pattern, $callable): RouteGroupInterface; /** * Add route * * @param string[] $methods Array of HTTP methods * @param string $pattern The route pattern * @param callable|array{class-string, string}|string $handler The route callable */ public function map(array $methods, string $pattern, $handler): RouteInterface; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/MiddlewareDispatcherInterface.php
Slim/Interfaces/MiddlewareDispatcherInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; /** @api */ interface MiddlewareDispatcherInterface extends RequestHandlerInterface { /** * Add a new middleware to the stack * * Middleware are organized as a stack. That means middleware * that have been added before will be executed after the newly * added one (last in, first out). * * @param MiddlewareInterface|string|callable $middleware */ public function add($middleware): self; /** * Add a new middleware to the stack * * Middleware are organized as a stack. That means middleware * that have been added before will be executed after the newly * added one (last in, first out). */ public function addMiddleware(MiddlewareInterface $middleware): self; /** * Seed the middleware stack with the inner request handler */ public function seedMiddlewareStack(RequestHandlerInterface $kernel): void; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/Psr17FactoryProviderInterface.php
Slim/Interfaces/Psr17FactoryProviderInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; /** @api */ interface Psr17FactoryProviderInterface { /** * @return string[] */ public static function getFactories(): array; /** * @param string[] $factories */ public static function setFactories(array $factories): void; public static function addFactory(string $factory): void; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/AdvancedCallableResolverInterface.php
Slim/Interfaces/AdvancedCallableResolverInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; interface AdvancedCallableResolverInterface extends CallableResolverInterface { /** * Resolve $toResolve into a callable * * @param callable|array{class-string, string}|string $toResolve */ public function resolveRoute($toResolve): callable; /** * Resolve $toResolve into a callable * * @param callable|array{class-string, string}|string $toResolve */ public function resolveMiddleware($toResolve): callable; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/CallableResolverInterface.php
Slim/Interfaces/CallableResolverInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; interface CallableResolverInterface { /** * Resolve $toResolve into a callable * * @param callable|array{class-string, string}|string $toResolve */ public function resolve($toResolve): callable; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/Psr17FactoryInterface.php
Slim/Interfaces/Psr17FactoryInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; use RuntimeException; interface Psr17FactoryInterface { /** * @throws RuntimeException when the factory could not be instantiated */ public static function getResponseFactory(): ResponseFactoryInterface; /** * @throws RuntimeException when the factory could not be instantiated */ public static function getStreamFactory(): StreamFactoryInterface; /** * @throws RuntimeException when the factory could not be instantiated */ public static function getServerRequestCreator(): ServerRequestCreatorInterface; /** * Is the PSR-17 ResponseFactory available */ public static function isResponseFactoryAvailable(): bool; /** * Is the PSR-17 StreamFactory available */ public static function isStreamFactoryAvailable(): bool; /** * Is the ServerRequest creator available */ public static function isServerRequestCreatorAvailable(): bool; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/InvocationStrategyInterface.php
Slim/Interfaces/InvocationStrategyInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; /** * Defines a contract for invoking a route callable. */ interface InvocationStrategyInterface { /** * Invoke a route callable. * * @param callable $callable The callable to invoke using the strategy. * @param ServerRequestInterface $request The request object. * @param ResponseInterface $response The response object. * @param array<string, string> $routeArguments The route's placeholder arguments * * @return ResponseInterface The response from the callable. */ public function __invoke( callable $callable, ServerRequestInterface $request, ResponseInterface $response, array $routeArguments ): ResponseInterface; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/ErrorRendererInterface.php
Slim/Interfaces/ErrorRendererInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use Throwable; interface ErrorRendererInterface { public function __invoke(Throwable $exception, bool $displayErrorDetails): string; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/RouteResolverInterface.php
Slim/Interfaces/RouteResolverInterface.php
<?php declare(strict_types=1); namespace Slim\Interfaces; use Slim\Routing\RoutingResults; interface RouteResolverInterface { /** * @param string $uri Should be ServerRequestInterface::getUri()->getPath() */ public function computeRoutingResults(string $uri, string $method): RoutingResults; public function resolveRoute(string $identifier): RouteInterface; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Interfaces/DispatcherInterface.php
Slim/Interfaces/DispatcherInterface.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Interfaces; use Slim\Routing\RoutingResults; interface DispatcherInterface { /** * Get routing results for a given request method and uri */ public function dispatch(string $method, string $uri): RoutingResults; /** * Get allowed methods for a given uri * * @return string[] */ public function getAllowedMethods(string $uri): array; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpTooManyRequestsException.php
Slim/Exception/HttpTooManyRequestsException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; /** @api */ class HttpTooManyRequestsException extends HttpSpecializedException { /** * @var int */ protected $code = 429; /** * @var string */ protected $message = 'Too many requests.'; protected string $title = '429 Too Many Requests'; protected string $description = 'The client application has surpassed its rate limit, ' . 'or number of requests they can send in a given period of time.'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpNotFoundException.php
Slim/Exception/HttpNotFoundException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; class HttpNotFoundException extends HttpSpecializedException { /** * @var int */ protected $code = 404; /** * @var string */ protected $message = 'Not found.'; protected string $title = '404 Not Found'; protected string $description = 'The requested resource could not be found. Please verify the URI and try again.'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpBadRequestException.php
Slim/Exception/HttpBadRequestException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; /** @api */ class HttpBadRequestException extends HttpSpecializedException { /** * @var int */ protected $code = 400; /** * @var string */ protected $message = 'Bad request.'; protected string $title = '400 Bad Request'; protected string $description = 'The server cannot or will not process ' . 'the request due to an apparent client error.'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpNotImplementedException.php
Slim/Exception/HttpNotImplementedException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; /** @api */ class HttpNotImplementedException extends HttpSpecializedException { /** * @var int */ protected $code = 501; /** * @var string */ protected $message = 'Not implemented.'; protected string $title = '501 Not Implemented'; protected string $description = 'The server does not support the functionality required to fulfill the request.'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpInternalServerErrorException.php
Slim/Exception/HttpInternalServerErrorException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; /** @api */ class HttpInternalServerErrorException extends HttpSpecializedException { /** * @var int */ protected $code = 500; /** * @var string */ protected $message = 'Internal server error.'; protected string $title = '500 Internal Server Error'; protected string $description = 'Unexpected condition encountered preventing server from fulfilling request.'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpForbiddenException.php
Slim/Exception/HttpForbiddenException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; /** @api */ class HttpForbiddenException extends HttpSpecializedException { /** * @var int */ protected $code = 403; /** * @var string */ protected $message = 'Forbidden.'; protected string $title = '403 Forbidden'; protected string $description = 'You are not permitted to perform the requested operation.'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpGoneException.php
Slim/Exception/HttpGoneException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; /** @api */ class HttpGoneException extends HttpSpecializedException { /** * @var int */ protected $code = 410; /** * @var string */ protected $message = 'Gone.'; protected string $title = '410 Gone'; protected string $description = 'The target resource is no longer available at the origin server.'; }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpMethodNotAllowedException.php
Slim/Exception/HttpMethodNotAllowedException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; use function implode; class HttpMethodNotAllowedException extends HttpSpecializedException { /** * @var string[] */ protected array $allowedMethods = []; /** * @var int */ protected $code = 405; /** * @var string */ protected $message = 'Method not allowed.'; protected string $title = '405 Method Not Allowed'; protected string $description = 'The request method is not supported for the requested resource.'; /** * @return string[] */ public function getAllowedMethods(): array { return $this->allowedMethods; } /** * @param string[] $methods */ public function setAllowedMethods(array $methods): self { $this->allowedMethods = $methods; $this->message = 'Method not allowed. Must be one of: ' . implode(', ', $methods); return $this; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false
slimphp/Slim
https://github.com/slimphp/Slim/blob/025043ec303c652408ae85900c98653798d91778/Slim/Exception/HttpException.php
Slim/Exception/HttpException.php
<?php /** * Slim Framework (https://slimframework.com) * * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License) */ declare(strict_types=1); namespace Slim\Exception; use Psr\Http\Message\ServerRequestInterface; use RuntimeException; use Throwable; /** * @api * @method int getCode() */ class HttpException extends RuntimeException { protected ServerRequestInterface $request; protected string $title = ''; protected string $description = ''; public function __construct( ServerRequestInterface $request, string $message = '', int $code = 0, ?Throwable $previous = null ) { parent::__construct($message, $code, $previous); $this->request = $request; } public function getRequest(): ServerRequestInterface { return $this->request; } public function getTitle(): string { return $this->title; } public function setTitle(string $title): self { $this->title = $title; return $this; } public function getDescription(): string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } }
php
MIT
025043ec303c652408ae85900c98653798d91778
2026-01-04T15:03:29.198296Z
false