Skip to content

Commit

Permalink
Merge pull request #9 from BrandEmbassy/revert-8-revert-5-global-midd…
Browse files Browse the repository at this point in the history
…lewares-and-multiple-methods

Revert "Revert "Global app middlewares and multiple action methods""
  • Loading branch information
Petr Hejna authored Oct 1, 2018
2 parents 3f961ed + 03fd245 commit 1053e17
Show file tree
Hide file tree
Showing 6 changed files with 149 additions and 10 deletions.
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ slimApi: # Configure it
```
### First API enpoint
### First API endpoint
Now let's say you want to make a REST endpoint creating channels, `[POST] /new-api/2.0/channels`

You need to define in `parameters.api` section in `config.neon`.
Expand Down Expand Up @@ -71,7 +71,14 @@ parameters:
- App\SomeOtherMiddleware # last in row
- App\UsuallyRequestDataValidationMiddleware # second in row
- App\SomeAuthMiddleware # this one is called first
beforeRouteMiddlewares:
# this is called for each route, before route middlewares
- App\SomeBeforeRequestMiddleware
beforeRequestMiddlewares:
# this is called for each request, even when route does NOT exist (404 requests)
- App\SomeBeforeRouteMiddleware tests/Dummy/BeforeRequestMiddleware.php
```

You can also reference the named service by it's name.
Expand Down
53 changes: 46 additions & 7 deletions src/SlimApplicationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ final class SlimApplicationFactory
*/
private $container;

/**
* @var Middleware[]
*/
private $beforeRoutesMiddlewares;

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

/**
Expand All @@ -41,6 +47,8 @@ public function create()

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

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

foreach ($configuration['routes'] as $apiName => $api) {
$this->registerApis($app, $api, $apiName);
}
Expand All @@ -55,6 +63,12 @@ public function create()
$this->registerHandlers($app, $configuration['handlers']);
}

if (isset($configuration['beforeRequestMiddlewares'])) {
foreach ($configuration['beforeRequestMiddlewares'] as $middleware) {
$this->registerBeforeRequestMiddleware($app, $middleware);
}
}

return $app;

}
Expand Down Expand Up @@ -146,7 +160,9 @@ private function registerHandlers(SlimApp $app, array $handlers)
*/
private function registerServiceIntoContainer(SlimApp $app, $serviceName)
{
$app->getContainer()[$serviceName] = $this->getServiceProvider($serviceName);
if (!$app->getContainer()->has($serviceName)) {
$app->getContainer()[$serviceName] = $this->getServiceProvider($serviceName);
}
}

/**
Expand Down Expand Up @@ -210,17 +226,17 @@ private function registerInvokableActionRoutes(SlimApp $app, array $routeData, $
$this->registerServiceIntoContainer($app, $service);
$routeToAdd = $app->map([$method], $urlPattern, $service);

if (isset($config['middleware']) && count($config['middleware']) > 0) {
if (isset($config['middleware'])) {
foreach ($config['middleware'] as $middleware) {
$container = $app->getContainer();

if (!$container->has($middleware)) {
$this->registerServiceIntoContainer($app, $middleware);
}
$this->registerServiceIntoContainer($app, $middleware);

$routeToAdd->add($middleware);
}
}

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

Expand All @@ -235,4 +251,27 @@ private function createUrlPattern($apiName, $version, $routeName)
return sprintf('/%s/%s%s', $apiName, $version, $routeName);
}

/**
* @param SlimApp $app
* @param string $middleware
*/
private function registerBeforeRequestMiddleware(SlimApp $app, $middleware)
{
$this->registerServiceIntoContainer($app, $middleware);
$app->add($middleware);
}

/**
* @param SlimApp $app
* @param array $configuration
*/
private function registerBeforeRouteMiddlewares(SlimApp $app, $configuration)
{
if (isset($configuration['beforeRouteMiddlewares'])) {
foreach ($configuration['beforeRouteMiddlewares'] as $globalMiddleware) {
$this->registerServiceIntoContainer($app, $globalMiddleware);
$this->beforeRoutesMiddlewares[] = $app->getContainer()->get($globalMiddleware);
}
}
}
}
27 changes: 27 additions & 0 deletions tests/Dummy/BeforeRequestMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace BrandEmbassyTest\Slim\Dummy;

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

class BeforeRequestMiddleware implements Middleware
{

/**
* @param RequestInterface $request
* @param ResponseInterface $response
* @param callable $next
* @return ResponseInterface
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
$response = $response->withAddedHeader(
'processed-by-before-request-middleware',
'proof-for-before-request'
);

return $next($request, $response);
}
}
27 changes: 27 additions & 0 deletions tests/Dummy/BeforeRouteMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace BrandEmbassyTest\Slim\Dummy;

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

class BeforeRouteMiddleware implements Middleware
{

/**
* @param RequestInterface $request
* @param ResponseInterface $response
* @param callable $next
* @return ResponseInterface
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
$response = $response->withAddedHeader(
'processed-by-before-route-middlewares',
'proof-for-before-route'
);

return $next($request, $response);
}
}
32 changes: 31 additions & 1 deletion tests/SlimApplicationFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use BrandEmbassy\Slim\SlimApplicationFactory;
use BrandEmbassy\Slim\Request\Request;
use BrandEmbassy\Slim\Response\Response;
use LogicException;
use Nette\DI\Compiler;
use Nette\DI\Container;
use Nette\DI\ContainerLoader;
Expand Down Expand Up @@ -87,6 +86,37 @@ public function testShouldAllowRequestByAccessMiddleware()
$this->assertEquals('{"channelId":"fb_1234"}', $this->getContents($response));
}

public function testShouldProcessBothGlobalMiddlewares()
{
$request = $this->createRequest('POST', '/new-api/2.0/channels');

/** @var ResponseInterface $response */
$response = $this->createSlimApp()->process($request, new Response(new \Slim\Http\Response()));

$this->assertEquals(
['proof-for-before-request'],
$response->getHeader('processed-by-before-request-middleware')
);

$this->assertEquals(
['proof-for-before-route'],
$response->getHeader('processed-by-before-route-middlewares')
);
}

public function testShouldProcessBeforeRequestMiddleware()
{
$request = $this->createRequest('POST', '/non-existing/path');

/** @var ResponseInterface $response */
$response = $this->createSlimApp()->process($request, new Response(new \Slim\Http\Response()));

$this->assertEquals(
['proof-for-before-request'],
$response->getHeader('processed-by-before-request-middleware')
);
}

/**
* @param string $configPath
* @return Container
Expand Down
9 changes: 9 additions & 0 deletions tests/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ services:
- BrandEmbassyTest\Slim\Dummy\GoldenKeyAuthMiddleware
- BrandEmbassyTest\Slim\Dummy\CreateChannelAction
- BrandEmbassyTest\Slim\Dummy\ErroringAction
- BrandEmbassyTest\Slim\Dummy\BeforeRequestMiddleware
- BrandEmbassyTest\Slim\Dummy\BeforeRouteMiddleware

parameters:
api:
Expand All @@ -30,6 +32,13 @@ parameters:
post:
service: BrandEmbassyTest\Slim\Dummy\ErroringAction

beforeRouteMiddlewares:
- BrandEmbassyTest\Slim\Dummy\BeforeRouteMiddleware

beforeRequestMiddlewares:
- BrandEmbassyTest\Slim\Dummy\BeforeRequestMiddleware


slimApi:
slimConfiguration:
settings:
Expand Down

0 comments on commit 1053e17

Please sign in to comment.