Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding afterRouteMiddlewares configuration option #63

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ parameters:
- App\UsuallyRequestDataValidationMiddleware # second in row
- App\SomeAuthMiddleware # this one is called first

afterRouteMiddlewares:
# this is called for each route, after the route middlewares
- App\SomeAfterRequestMiddleware

beforeRouteMiddlewares:
# this is called for each route, before route middlewares
- App\SomeBeforeRequestMiddleware
Expand Down
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@
"prefer-stable": true,
"config": {
"sort-packages": true,
"process-timeout": 600
"process-timeout": 600,
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
}
}
33 changes: 33 additions & 0 deletions src/SlimApplicationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ final class SlimApplicationFactory
*/
private $beforeRoutesMiddlewares;

/**
* @var array<Middleware>
*/
private $afterRoutesMiddlewares;


/**
* @param mixed[] $configuration
Expand All @@ -40,6 +45,7 @@ public function __construct(array $configuration, Container $container)
$this->configuration = $configuration;
$this->container = $container;
$this->beforeRoutesMiddlewares = [];
$this->afterRoutesMiddlewares = [];
}


Expand All @@ -49,6 +55,7 @@ public function create(): SlimApp

$configuration = $this->getConfiguration($this->configuration['apiDefinitionKey']);

$this->registerAfterRouteMiddlewares($app, $configuration);
$this->registerBeforeRouteMiddlewares($app, $configuration);

foreach ($configuration['routes'] as $apiName => $api) {
Expand Down Expand Up @@ -123,6 +130,8 @@ private function validateConfiguration(


/**
* @param class-string $serviceName
*
* @return Closure
*/
private function getServiceProvider(string $serviceName): callable
Expand Down Expand Up @@ -161,6 +170,9 @@ private function registerHandlers(SlimApp $app, array $handlers): void
}


/**
* @param class-string $serviceName
*/
private function registerServiceIntoContainer(SlimApp $app, string $serviceName): void
{
if (!$app->getContainer()->has($serviceName)) {
Expand Down Expand Up @@ -224,6 +236,10 @@ private function registerInvokableActionRoutes(SlimApp $app, array $routeData, s
$this->registerServiceIntoContainer($app, $service);
$routeToAdd = $app->map([$method], $urlPattern, $service);

foreach ($this->afterRoutesMiddlewares as $middleware) {
$routeToAdd->add($middleware);
}

if (isset($config['middleware'])) {
foreach ($config['middleware'] as $middleware) {
$this->registerServiceIntoContainer($app, $middleware);
Expand Down Expand Up @@ -261,6 +277,9 @@ private function createUrlPattern(string $apiName, string $version, string $rout
}


/**
* @param class-string $middleware
*/
private function registerBeforeRequestMiddleware(SlimApp $app, string $middleware): void
{
$this->registerServiceIntoContainer($app, $middleware);
Expand All @@ -280,4 +299,18 @@ private function registerBeforeRouteMiddlewares(SlimApp $app, array $configurati
}
}
}


/**
* @param mixed[] $configuration
*/
private function registerAfterRouteMiddlewares(SlimApp $app, array $configuration): void
{
if (isset($configuration['afterRouteMiddlewares'])) {
foreach ($configuration['afterRouteMiddlewares'] as $globalMiddleware) {
$this->registerServiceIntoContainer($app, $globalMiddleware);
$this->afterRoutesMiddlewares[] = $app->getContainer()->get($globalMiddleware);
}
}
}
}
10 changes: 5 additions & 5 deletions tests/Request/RequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ public function testShouldDistinguishBetweenNullAndEmptyOption(): void
{
$request = $this->createSampleRequest();

self::assertTrue($request->hasField('thisIsNull'));
self::assertFalse($request->hasField('nonExistingField'));
self::assertTrue($request->hasField('thisIsGandalf'));
Assert::assertTrue($request->hasField('thisIsNull'));
Assert::assertFalse($request->hasField('nonExistingField'));
Assert::assertTrue($request->hasField('thisIsGandalf'));
}


Expand All @@ -53,7 +53,7 @@ public function testShouldRaiseExceptionForMissingRequiredField(): void
{
$request = $this->createSampleRequest();

self::assertEquals('gandalf', $request->getField('thisIsGandalf'));
Assert::assertEquals('gandalf', $request->getField('thisIsGandalf'));
$this->expectException(MissingApiArgumentException::class);
$request->getField('nonExistingField');
}
Expand All @@ -67,7 +67,7 @@ public function testGettingDateTimeQueryParam(): void
$request = new Request($slimRequest);
$dateTime = $request->getDateTimeQueryParam(self::PARAM_NAME);

self::assertSame(self::DATE_TIME_STRING, $dateTime->format(DateTime::ATOM));
Assert::assertSame(self::DATE_TIME_STRING, $dateTime->format(DateTime::ATOM));
}


Expand Down
20 changes: 20 additions & 0 deletions tests/Sample/AfterRouteMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php declare(strict_types = 1);

namespace BrandEmbassyTest\Slim\Sample;

use BrandEmbassy\Slim\Middleware;
use BrandEmbassy\Slim\Request\RequestInterface;
use BrandEmbassy\Slim\Response\ResponseInterface;

class AfterRouteMiddleware implements Middleware
{
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface
{
$response = $response->withHeader(
'header-to-be-changed-by-after-route-middleware',
'changed-value'
);

return $next($request, $response);
}
}
4 changes: 4 additions & 0 deletions tests/Sample/BeforeRouteMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ class BeforeRouteMiddleware implements Middleware
{
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface
{
$response = $response->withAddedHeader(
'header-to-be-changed-by-after-route-middleware',
'initial-value'
);
$response = $response->withAddedHeader(
'processed-by-before-route-middlewares',
'proof-for-before-route'
Expand Down
11 changes: 10 additions & 1 deletion tests/SlimApplicationFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,11 @@ public function routeResponseDataProvider(): array

public function testShouldProcessBothGlobalMiddlewares(): void
{
$request = $this->createRequest('POST', '/new-api/2.0/channels');
$request = $this->createRequest(
'POST',
'/new-api/2.0/channels',
['goldenKey' => GoldenKeyAuthMiddleware::ACCESS_TOKEN]
);

/** @var ResponseInterface $response */
$response = $this->createSlimApp()->process($request, new Response(new \Slim\Http\Response()));
Expand All @@ -118,6 +122,11 @@ public function testShouldProcessBothGlobalMiddlewares(): void
['proof-for-before-route'],
$response->getHeader('processed-by-before-route-middlewares')
);

Assert::assertSame(
['changed-value'],
$response->getHeader('header-to-be-changed-by-after-route-middleware')
);
}


Expand Down
4 changes: 4 additions & 0 deletions tests/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ services:
- BrandEmbassyTest\Slim\Sample\ErroringAction
- BrandEmbassyTest\Slim\Sample\BeforeRequestMiddleware
- BrandEmbassyTest\Slim\Sample\BeforeRouteMiddleware
- BrandEmbassyTest\Slim\Sample\AfterRouteMiddleware

parameters:
api:
Expand Down Expand Up @@ -40,6 +41,9 @@ parameters:
post:
service: BrandEmbassyTest\Slim\Sample\ErroringAction

afterRouteMiddlewares:
- BrandEmbassyTest\Slim\Sample\AfterRouteMiddleware

beforeRouteMiddlewares:
- BrandEmbassyTest\Slim\Sample\BeforeRouteMiddleware

Expand Down
Loading