Skip to content

Commit

Permalink
feat: support middlewares testing
Browse files Browse the repository at this point in the history
  • Loading branch information
martenb committed Feb 26, 2023
1 parent f772ac2 commit b32f2ae
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
6 changes: 5 additions & 1 deletion .phpstan.neon
Expand Up @@ -4,7 +4,11 @@ parameters:
- src
- tests
excludePaths:
- tests/tmp/*
- tests/tmp/*
fileExtensions:
- php
- phpt
ignoreErrors:
-
message: "#^Call to function method_exists\\(\\) with Contributte\\\\Middlewares\\\\Application\\\\IApplication and 'runWith' will always evaluate to true\\.$#"
path: src/ControllerTester.php
2 changes: 1 addition & 1 deletion composer.json
Expand Up @@ -10,7 +10,7 @@
"license": "MIT",
"require": {
"php": ">=7.4",
"contributte/apitte": "^0.9 | ^0.10",
"contributte/apitte": "^0.9 | ^0.10 | ^0.11",
"nette/tester": "^2.0"
},
"require-dev": {
Expand Down
20 changes: 19 additions & 1 deletion src/ControllerTester.php
Expand Up @@ -7,8 +7,11 @@
use Apitte\Core\ErrorHandler\IErrorHandler;
use Apitte\Core\Http\ApiRequest;
use Apitte\Core\Http\ApiResponse;
use Contributte\Middlewares\Application\IApplication;
use Contributte\Psr7\Psr7Response;
use Contributte\Psr7\Psr7ServerRequest;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ControllerTester
Expand All @@ -18,10 +21,13 @@ class ControllerTester

private IErrorHandler $errorHandler;

public function __construct(IDispatcher $dispatcher, IErrorHandler $errorHandler)
private ?IApplication $middlewaresApplication = null;

public function __construct(IDispatcher $dispatcher, IErrorHandler $errorHandler, ?IApplication $middlewaresApplication = null)
{
$this->dispatcher = $dispatcher;
$this->errorHandler = $errorHandler;
$this->middlewaresApplication = $middlewaresApplication;
}

public function createRequest(string $uri): TestControllerRequest
Expand All @@ -34,6 +40,18 @@ public function execute(TestControllerRequest $testControllerRequest): TestContr
$request = $this->createApiRequest($testControllerRequest);
$response = new ApiResponse(new Psr7Response());

if ($this->middlewaresApplication !== null && method_exists($this->middlewaresApplication, 'runWith')) {
ob_start();
$response = $this->middlewaresApplication->runWith($request);
ob_end_clean();

if (!$response instanceof ResponseInterface) {
throw new Exception(sprintf('Unsupported type of response: \'%s\'.', gettype($response)));
}

return new TestControllerResult(new ApiResponse($response));
}

try {
$response = $this->dispatcher->dispatch($request, $response);
} catch (Throwable $exception) {
Expand Down

0 comments on commit b32f2ae

Please sign in to comment.