$params
- * @return string
*/
protected function getRouteUri(string $routeName, array $params = []): string
{
return $this->router->generate($routeName, $params);
}
- /**
- * @param string $name
- * @return bool
- */
protected function hasParameter(string $name): bool
{
return isset($this->route[$name]);
}
/**
- * @param string $name
* @param string|int|bool|float|null $default
- * @return mixed|null
*/
- protected function getParameter(string $name, $default = null)
+ protected function getParameter(string $name, mixed $default = null): mixed
{
return $this->route[$name] ?? $default;
}
diff --git a/src/Traits/ServerRequestAwareTrait.php b/src/Traits/ServerRequestAwareTrait.php
index 2631ddd..d7badc9 100644
--- a/src/Traits/ServerRequestAwareTrait.php
+++ b/src/Traits/ServerRequestAwareTrait.php
@@ -11,127 +11,54 @@
namespace Eureka\Kernel\Http\Traits;
-use Eureka\Kernel\Http\Service\DataCollection;
use Psr\Http\Message\ServerRequestInterface;
-/**
- * Trait ServerRequestAwareTrait
- *
- * @author Romain Cottard
- */
trait ServerRequestAwareTrait
{
- /** @var ServerRequestInterface $serverRequest */
protected ServerRequestInterface $serverRequest;
- /**
- * @param ServerRequestInterface $serverRequest
- * @return void
- */
public function setServerRequest(ServerRequestInterface $serverRequest): void
{
$this->serverRequest = $serverRequest;
}
- /**
- * @return ServerRequestInterface
- */
protected function getServerRequest(): ServerRequestInterface
{
return $this->serverRequest;
}
- /**
- * @return DataCollection
- */
- protected function getQueryParameters(): DataCollection
- {
- return new DataCollection($this->serverRequest->getQueryParams());
- }
-
- /**
- * @return DataCollection
- */
- protected function getBodyParameters(): DataCollection
- {
- return new DataCollection((array) $this->serverRequest->getParsedBody());
- }
-
- /**
- * @return bool
- */
- protected function isHttpGetMethod(): bool
- {
- return (strtoupper($this->serverRequest->getMethod()) === 'GET');
- }
-
- /**
- * @return bool
- */
- protected function isHttpPutMethod(): bool
- {
- return (strtoupper($this->serverRequest->getMethod()) === 'PUT');
- }
-
- /**
- * @return bool
- */
- protected function isHttpPatchMethod(): bool
- {
- return (strtoupper($this->serverRequest->getMethod()) === 'PATCH');
- }
-
- /**
- * @return bool
- */
- protected function isHttpPostMethod(): bool
- {
- return (strtoupper($this->serverRequest->getMethod()) === 'POST');
- }
-
- /**
- * @return bool
- */
- protected function isHttpDeleteMethod(): bool
+ public function isHttpMethod(string $method): bool
{
- return (strtoupper($this->serverRequest->getMethod()) === 'DELETE');
+ return \strtoupper($this->serverRequest->getMethod()) === \strtoupper($method);
}
- /**
- * @return bool
- */
- protected function isAjax(): bool
+ protected function isAjaxRequest(): bool
{
$server = $this->serverRequest->getServerParams();
- if (empty($server['HTTP_X_REQUESTED_WITH'])) {
+ $requestedWith = $server['HTTP_X_REQUESTED_WITH'] ?? '';
+ if (!\is_string($requestedWith) || $requestedWith === '') {
return false;
}
- return (strtolower($server['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
+ return \strtolower($requestedWith) === 'xmlhttprequest';
}
- /**
- * @return bool
- */
protected function isJsonRequest(): bool
{
if (!$this->serverRequest->hasHeader('Content-Type')) {
return false;
}
- return (strtolower($this->serverRequest->getHeaderLine('Content-Type')) === 'application/json');
+ return \strtolower($this->serverRequest->getHeaderLine('Content-Type')) === 'application/json';
}
- /**
- * @return bool
- */
protected function acceptJsonResponse(): bool
{
if (!$this->serverRequest->hasHeader('Accept')) {
return false;
}
- return (strtolower($this->serverRequest->getHeaderLine('Accept')) === 'application/json');
+ return \strtolower($this->serverRequest->getHeaderLine('Accept')) === 'application/json';
}
}
diff --git a/tests/Integration/.gitkeep b/tests/Integration/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/tests/unit/ApplicationTest.php b/tests/Unit/ApplicationTest.php
similarity index 71%
rename from tests/unit/ApplicationTest.php
rename to tests/Unit/ApplicationTest.php
index 1b58bab..4d138b2 100644
--- a/tests/unit/ApplicationTest.php
+++ b/tests/Unit/ApplicationTest.php
@@ -21,32 +21,37 @@
use Eureka\Kernel\Http\Exception\HttpTooManyRequestsException;
use Eureka\Kernel\Http\Exception\HttpUnauthorizedException;
use Eureka\Kernel\Http\Kernel;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
-/**
- * Class ApplicationTest
- *
- * @author Romain Cottard
- */
class ApplicationTest extends TestCase
{
/**
- * @return void
* @throws \Exception
*/
- public function testCanInstantiateApplication(): void
+ public function testCanRunApplicationWithJsonResponse(): void
{
- self::assertInstanceOf(ApplicationInterface::class, $this->getApplication());
+ //~ Define current route
+ $_SERVER['REQUEST_URI'] = '/test/json';
+ $_SERVER['REQUEST_METHOD'] = 'GET';
+
+ //~ Run Application
+ ob_start();
+ $application = $this->getApplication();
+ $application->send($application->run());
+ $output = ob_get_clean();
+
+ self::assertSame('"ok"', $output);
}
/**
- * @return void
* @throws \Exception
*/
- public function testCanRunApplicationWithJsonResponse(): void
+ public function testCanRunApplicationWithHtmlResponse(): void
{
//~ Define current route
- $_SERVER['REQUEST_URI'] = '/test/json';
+ $_SERVER['REQUEST_URI'] = '/test/html';
+ $_SERVER['REQUEST_METHOD'] = 'GET';
//~ Run Application
ob_start();
@@ -54,17 +59,17 @@ public function testCanRunApplicationWithJsonResponse(): void
$application->send($application->run());
$output = ob_get_clean();
- self::assertSame('"ok"', $output);
+ self::assertSame('ok', $output);
}
/**
- * @return void
* @throws \Exception
*/
- public function testCanRunApplicationWithHtmlResponse(): void
+ public function testCanRunApplicationWithUrlParameters(): void
{
//~ Define current route
- $_SERVER['REQUEST_URI'] = '/test/html';
+ $_SERVER['REQUEST_URI'] = '/test/entities/1/super-title';
+ $_SERVER['REQUEST_METHOD'] = 'GET';
//~ Run Application
ob_start();
@@ -72,17 +77,17 @@ public function testCanRunApplicationWithHtmlResponse(): void
$application->send($application->run());
$output = ob_get_clean();
- self::assertSame('ok', $output);
+ self::assertSame('entity id: 1, title: super-title, someString: value, someBool: true, someInt: 42', $output);
}
/**
- * @return void
* @throws \Exception
*/
public function testCanRunApplicationWithRouteNotFoundResponse(): void
{
//~ Define current route
- $_SERVER['REQUEST_URI'] = '/test/error/not-found';
+ $_SERVER['REQUEST_URI'] = '/test/error/not-found';
+ $_SERVER['REQUEST_METHOD'] = 'GET';
//~ Run Application
ob_start();
@@ -91,17 +96,17 @@ public function testCanRunApplicationWithRouteNotFoundResponse(): void
$output = ob_get_clean();
$expected = "exception[Eureka\Kernel\Http\Exception\HttpNotFoundException]: \nNo routes found for \"/test/error/not-found\".\n\n
";
- self::assertEquals($expected, $output);
+ self::assertSame($expected, $output);
}
/**
- * @return void
* @throws \Exception
*/
public function testCanRunApplicationWhichGenerateTooManyRequestsWhenQuotaIsReach(): void
{
//~ Define current route
- $_SERVER['REQUEST_URI'] = '/test/json/limited';
+ $_SERVER['REQUEST_URI'] = '/test/json/limited';
+ $_SERVER['REQUEST_METHOD'] = 'GET';
//~ Run Application
ob_start();
@@ -116,11 +121,10 @@ public function testCanRunApplicationWhichGenerateTooManyRequestsWhenQuotaIsReac
$output = ob_get_clean();
$expected = "exception[" . HttpTooManyRequestsException::class . "]: \nToo Many Requests\n\n
";
- self::assertEquals($expected, $output);
+ self::assertSame($expected, $output);
}
/**
- * @return void
* @throws \Exception
*/
public function testCanRunApplicationWhichGenerateAppropriateErrorResponseForNotAllowedMethod(): void
@@ -136,23 +140,40 @@ public function testCanRunApplicationWhichGenerateAppropriateErrorResponseForNot
$output = ob_get_clean();
$expected = "exception[Eureka\Kernel\Http\Exception\HttpMethodNotAllowedException]: \nAllowed method(s): GET\n\n
";
- self::assertEquals($expected, $output);
+ self::assertSame($expected, $output);
}
/**
- * @param string $uri
- * @param string $exceptionClass
- * @return void
* @throws \Exception
- *
- * @dataProvider uriExceptionDataProvider
*/
+ public function testCanRunApplicationAndGetErrorResponseWhenNonCaughtErrorIsThrown(): void
+ {
+ //~ Define current route
+ $_SERVER['REQUEST_URI'] = '/test/error/html/internal-server-error';
+ $_SERVER['REQUEST_METHOD'] = 'POST';
+
+ $application = new Application(new Kernel((string) realpath(__DIR__ . '/../..'), 'test', true));
+
+ //~ Run Application
+ ob_start();
+ $application->send($application->run());
+ $output = ob_get_clean();
+
+ $expected = "exception[Eureka\Kernel\Http\Exception\HttpMethodNotAllowedException]: \nAllowed method(s): GET\n\n
";
+ self::assertSame($expected, $output);
+ }
+
+ /**
+ * @throws \Exception
+ */
+ #[DataProvider('uriExceptionDataProvider')]
public function testCanRunApplicationWhichGenerateAppropriateErrorResponseForGivenError(string $uri, string $exceptionClass): void
{
//~ Define current route
- $_SERVER['REQUEST_URI'] = $uri;
- $_SERVER['SERVER_NAME'] = 'any';
- $_SERVER['HTTP_ACCEPT'] = 'application/json';
+ $_SERVER['REQUEST_URI'] = $uri;
+ $_SERVER['SERVER_NAME'] = 'any';
+ $_SERVER['HTTP_ACCEPT'] = 'application/json';
+ $_SERVER['REQUEST_METHOD'] = 'GET';
//~ Run Application
ob_start();
@@ -160,12 +181,11 @@ public function testCanRunApplicationWhichGenerateAppropriateErrorResponseForGiv
$application->send($application->run());
$output = ob_get_clean();
- $expected = "exception[${exceptionClass}]: \nthrow an error (html)\n\n";
- self::assertEquals($expected, $output);
+ $expected = "exception[{$exceptionClass}]: \nthrow an error (html)\n\n";
+ self::assertSame($expected, $output);
}
/**
- * @return void
* @throws \Exception
*/
public function testCanRunApplicationWhichGenerateAppropriateErrorResponseForNotExistingActionMethod(): void
@@ -176,7 +196,8 @@ public function testCanRunApplicationWhichGenerateAppropriateErrorResponseForNot
$_SERVER['SERVER_PORT'] = 443;
$_SERVER['QUERY_STRING'] = 'foo=bar';
- $_SERVER['REQUEST_URI'] = '/test/error/action-not-exists';
+ $_SERVER['REQUEST_URI'] = '/test/error/action-not-exists';
+ $_SERVER['REQUEST_METHOD'] = 'GET';
//~ Run Application
ob_start();
@@ -185,11 +206,10 @@ public function testCanRunApplicationWhichGenerateAppropriateErrorResponseForNot
$output = ob_get_clean();
$expected = "exception[DomainException]: \nAction controller does not exists! (Eureka\Kernel\Http\Tests\Unit\Mock\TestController::testErrorHtmlActionNotExists\n\n
";
- self::assertEquals($expected, $output);
+ self::assertSame($expected, $output);
}
/**
- * @return ApplicationInterface
* @throws \Exception
*/
private function getApplication(): ApplicationInterface
@@ -233,7 +253,7 @@ public static function uriExceptionDataProvider(): array
],
'TypeError' => [
'/test/error/html/type-error',
- HttpInternalServerErrorException::class,
+ \TypeError::class,
],
];
}
diff --git a/tests/unit/ControllerTest.php b/tests/Unit/ControllerTest.php
similarity index 90%
rename from tests/unit/ControllerTest.php
rename to tests/Unit/ControllerTest.php
index 3c2347a..d112864 100644
--- a/tests/unit/ControllerTest.php
+++ b/tests/Unit/ControllerTest.php
@@ -11,30 +11,24 @@
namespace Eureka\Kernel\Http\Tests\Unit;
-use Eureka\Kernel\Http\Controller\ControllerInterface;
use Eureka\Kernel\Http\Kernel;
use Eureka\Kernel\Http\Tests\Unit\Mock\TestController;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestFactoryInterface;
-/**
- * Class ControllerTest
- *
- * @author Romain Cottard
- */
class ControllerTest extends TestCase
{
/**
- * @return void
* @throws \Exception
*/
public function testKernelCanAutowireAController(): void
{
- self::assertInstanceOf(ControllerInterface::class, $this->getTestController());
+ $this->getTestController();
+
+ $this->expectNotToPerformAssertions();
}
/**
- * @return void
* @throws \Exception
*/
public function testControllerTraitHttpFactories(): void
@@ -45,7 +39,6 @@ public function testControllerTraitHttpFactories(): void
}
/**
- * @return void
* @throws \Exception
*/
public function testControllerHasLogger(): void
@@ -56,7 +49,6 @@ public function testControllerHasLogger(): void
}
/**
- * @return void
* @throws \Exception
*/
public function testControllerHasRoutingHelperAvailable(): void
@@ -67,7 +59,6 @@ public function testControllerHasRoutingHelperAvailable(): void
}
/**
- * @return void
* @throws \Exception
*/
public function testControllerHasServerRequestHelperAvailable(): void
@@ -87,10 +78,10 @@ public function testControllerHasServerRequestHelperAvailable(): void
;
self::assertTrue($controller->assertHasServerRequestHelperAvailable($serverRequest));
+ self::assertTrue($controller->assertIsAjaxRequest($serverRequest));
}
/**
- * @return void
* @throws \Exception
*/
public function testControllerAbstractMethods(): void
@@ -102,7 +93,6 @@ public function testControllerAbstractMethods(): void
}
/**
- * @return void
* @throws \Exception
*/
public function testICanCheckWhenRequestIsNotJsonNorAjax(): void
@@ -117,7 +107,6 @@ public function testICanCheckWhenRequestIsNotJsonNorAjax(): void
}
/**
- * @return TestController
* @throws \Exception
*/
private function getTestController(): TestController
@@ -132,7 +121,6 @@ private function getTestController(): TestController
}
/**
- * @return Kernel
* @throws \Exception
*/
private function getKernel(): Kernel
diff --git a/tests/unit/KernelTest.php b/tests/Unit/KernelTest.php
similarity index 67%
rename from tests/unit/KernelTest.php
rename to tests/Unit/KernelTest.php
index 4565d38..6a4aa0e 100644
--- a/tests/unit/KernelTest.php
+++ b/tests/Unit/KernelTest.php
@@ -13,17 +13,10 @@
use Eureka\Kernel\Http\Kernel;
use PHPUnit\Framework\TestCase;
-use Psr\Container\ContainerInterface;
-/**
- * Class KernelTest
- *
- * @author Romain Cottard
- */
class KernelTest extends TestCase
{
/**
- * @return void
* @throws \Exception
*/
public function testCanInstantiateKernel(): void
@@ -32,13 +25,12 @@ public function testCanInstantiateKernel(): void
$env = 'dev';
$debug = true;
- $kernel = new Kernel($root, $env, $debug);
+ new Kernel($root, $env, $debug);
- self::assertInstanceOf(Kernel::class, $kernel);
+ $this->expectNotToPerformAssertions();
}
/**
- * @return void
* @throws \Exception
*/
public function testCanGetContainer(): void
@@ -47,8 +39,8 @@ public function testCanGetContainer(): void
$env = 'dev';
$debug = true;
- $kernel = new Kernel($root, $env, $debug);
+ new Kernel($root, $env, $debug);
- self::assertInstanceOf(ContainerInterface::class, $kernel->getContainer());
+ $this->expectNotToPerformAssertions();
}
}
diff --git a/tests/unit/Mock/TestController.php b/tests/Unit/Mock/TestController.php
similarity index 56%
rename from tests/unit/Mock/TestController.php
rename to tests/Unit/Mock/TestController.php
index 08cd83a..fb8ebfb 100644
--- a/tests/unit/Mock/TestController.php
+++ b/tests/Unit/Mock/TestController.php
@@ -18,146 +18,90 @@
use Eureka\Kernel\Http\Exception\HttpInternalServerErrorException;
use Eureka\Kernel\Http\Exception\HttpServiceUnavailableException;
use Eureka\Kernel\Http\Exception\HttpUnauthorizedException;
-use Eureka\Kernel\Http\Service\DataCollection;
-use Psr\Http\Message\RequestFactoryInterface;
-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\UriFactoryInterface;
-use Psr\Log\LoggerInterface;
-use Symfony\Component\Routing\RouterInterface;
-/**
- * Controller class
- *
- * @author Romain Cottard
- */
class TestController extends Controller
{
- private const EXCEPTION_MESSAGE = 'throw an error (html)';
+ private const string EXCEPTION_MESSAGE = 'throw an error (html)';
- /**
- * @return ResponseInterface
- */
public function testJsonAction(): ResponseInterface
{
return $this->getResponseJson('ok');
}
- /**
- * @return ResponseInterface
- */
public function testHtmlAction(): ResponseInterface
{
return $this->getResponse('ok');
}
- /**
- * @return ResponseInterface
- */
+ public function testUrlAction(
+ ServerRequestInterface $serverRequest,
+ string $someString,
+ bool $someBool,
+ int $someInt,
+ string $id,
+ string $title,
+ ): ResponseInterface {
+ return $this->getResponse("entity id: $id, title: $title, someString: $someString, someBool: " . ($someBool ? 'true' : 'false') . ", someInt: $someInt");
+ }
+
public function testInternalServerErrorHtmlAction(): ResponseInterface
{
throw new HttpInternalServerErrorException(self::EXCEPTION_MESSAGE, 99);
}
- /**
- * @return ResponseInterface
- */
public function testBadRequestErrorHtmlAction(): ResponseInterface
{
throw new HttpBadRequestException(self::EXCEPTION_MESSAGE, 99);
}
- /**
- * @return ResponseInterface
- */
public function testUnauthorizedErrorHtmlAction(): ResponseInterface
{
throw new HttpUnauthorizedException(self::EXCEPTION_MESSAGE, 99);
}
- /**
- * @return ResponseInterface
- */
public function testForbiddenErrorHtmlAction(): ResponseInterface
{
throw new HttpForbiddenException(self::EXCEPTION_MESSAGE, 99);
}
- /**
- * @return ResponseInterface
- */
public function testServiceUnavailableErrorHtmlAction(): ResponseInterface
{
throw new HttpServiceUnavailableException(self::EXCEPTION_MESSAGE, 99);
}
- /**
- * @return ResponseInterface
- */
public function testConflictErrorHtmlAction(): ResponseInterface
{
throw new HttpConflictException(self::EXCEPTION_MESSAGE, 99);
}
- /**
- * @return ResponseInterface
- */
public function testTypeErrorHtmlAction(): ResponseInterface
{
throw new \TypeError(self::EXCEPTION_MESSAGE, 99);
}
- /**
- * @return bool
- */
public function assertHasAllFactories(): bool
{
- if (!($this->getServerRequestFactory() instanceof ServerRequestFactoryInterface)) {
- throw new \RuntimeException('ServerRequest Factory not available!');
- }
-
- if (!($this->getResponseFactory() instanceof ResponseFactoryInterface)) {
- throw new \RuntimeException('Response Factory not available!');
- }
-
- if (!($this->getStreamFactory() instanceof StreamFactoryInterface)) {
- throw new \RuntimeException('Stream Factory not available!');
- }
-
- if (!($this->getUriFactory() instanceof UriFactoryInterface)) {
- throw new \RuntimeException('Uri Factory not available!');
- }
-
- if (!($this->getRequestFactory() instanceof RequestFactoryInterface)) {
- throw new \RuntimeException('Request Factory not available!');
- }
+ $serverRequestFactory = $this->getServerRequestFactory();
+ $responseFactory = $this->getResponseFactory();
+ $streamFactory = $this->getStreamFactory();
+ $uriFactory = $this->getUriFactory();
+ $requestFactory = $this->getRequestFactory();
return true;
}
- /**
- * @return bool
- */
public function assertHasLogger(): bool
{
- if (!($this->getLogger() instanceof LoggerInterface)) {
- throw new \RuntimeException('Request Factory not available!');
- }
+ $logger = $this->getLogger();
return true;
}
- /**
- * @return bool
- */
public function assertHasRoutingHelperAvailable(): bool
{
- if (!($this->getRouter() instanceof RouterInterface)) {
- throw new \RuntimeException('Router not available!');
- }
+ $router = $this->getRouter();
//~ Not defined when controller is not called from middleware, so just call to check method availability
$route = $this->getRoute();
@@ -177,87 +121,57 @@ public function assertHasRoutingHelperAvailable(): bool
return true;
}
- /**
- * @param ServerRequestInterface $serverRequest
- * @return bool
- */
public function assertHasServerRequestHelperAvailable(ServerRequestInterface $serverRequest): bool
{
$this->setServerRequest($serverRequest);
- if (!($this->getServerRequest() instanceof ServerRequestInterface)) {
- throw new \RuntimeException('Invalid server request!');
- }
-
- if (!($this->getQueryParameters() instanceof DataCollection)) {
- throw new \RuntimeException('Invalid query parameters server request!');
- }
-
- if (!($this->getBodyParameters() instanceof DataCollection)) {
- throw new \RuntimeException('Invalid body parameters from server request!');
- }
-
- if ($this->isHttpGetMethod() !== false) {
- throw new \RuntimeException('Invalid Http method GET! Should be a POST method!');
- }
-
- if ($this->isHttpPatchMethod() !== false) {
- throw new \RuntimeException('Invalid Http method PATCH! Should be a POST method!');
- }
+ $serverRequest = $this->getServerRequest();
- if ($this->isHttpPutMethod() !== false) {
- throw new \RuntimeException('Invalid Http method PUT! Should be a POST method!');
+ if ($this->isHttpMethod('POST') !== true) {
+ throw new \RuntimeException('Invalid Http method! Should be a POST method!');
}
- if ($this->isHttpDeleteMethod() !== false) {
- throw new \RuntimeException('Invalid Http method DELETE! Should be a POST method!');
- }
+ return true;
+ }
- if ($this->isHttpPostMethod() !== true) {
- throw new \RuntimeException('Invalid Http method! Should be a POST method!');
- }
+ public function assertIsNotJsonNorAjaxRequest(ServerRequestInterface $serverRequest): bool
+ {
+ $this->setServerRequest($serverRequest);
- if ($this->isAjax() === false) {
- throw new \RuntimeException('Invalid request. Should be an ajax request!');
+ if ($this->isJsonRequest() === true) {
+ throw new \RuntimeException('Invalid request. Should not be a json request!');
}
- if ($this->isJsonRequest() === false) {
- throw new \RuntimeException('Invalid request. Should be a json request!');
+ if ($this->acceptJsonResponse() === true) {
+ throw new \RuntimeException('Invalid request. Should not be accept json response!');
}
- if ($this->acceptJsonResponse() === false) {
- throw new \RuntimeException('Invalid request. Should be accept json response!');
+ if ($this->isAjaxRequest() === true) {
+ throw new \RuntimeException('Invalid request. Should not be an ajax request!');
}
return true;
}
- /**
- * @param ServerRequestInterface $serverRequest
- * @return bool
- */
- public function assertIsNotJsonNorAjaxRequest(ServerRequestInterface $serverRequest): bool
+ public function assertIsAjaxRequest(ServerRequestInterface $serverRequest): bool
{
$this->setServerRequest($serverRequest);
- if ($this->isJsonRequest() === true) {
- throw new \RuntimeException('Invalid request. Should not be a json request!');
+ if ($this->isJsonRequest() !== true) {
+ throw new \RuntimeException('Invalid request. Should be a json request!');
}
- if ($this->acceptJsonResponse() === true) {
- throw new \RuntimeException('Invalid request. Should not be accept json response!');
+ if ($this->acceptJsonResponse() !== true) {
+ throw new \RuntimeException('Invalid request. Should accept json response!');
}
- if ($this->isAjax() === true) {
- throw new \RuntimeException('Invalid request. Should not be an ajax request!');
+ if ($this->isAjaxRequest() !== true) {
+ throw new \RuntimeException('Invalid request. Should be an ajax request!');
}
return true;
}
- /**
- * @return bool
- */
public function assertHasPropertiesCorrectlySet(): bool
{
if ($this->isDev() === false) {
diff --git a/tests/unit/RateLimiter/CacheCounterTest.php b/tests/Unit/RateLimiter/CacheCounterTest.php
similarity index 68%
rename from tests/unit/RateLimiter/CacheCounterTest.php
rename to tests/Unit/RateLimiter/CacheCounterTest.php
index fbc6375..0a5b8ea 100644
--- a/tests/unit/RateLimiter/CacheCounterTest.php
+++ b/tests/Unit/RateLimiter/CacheCounterTest.php
@@ -16,28 +16,12 @@
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
-/**
- * Class CacheCounterTest
- *
- * @author Romain Cottard
- */
class CacheCounterTest extends TestCase
{
- /** @var string COUNTER_ID */
- private const COUNTER_ID = 'counter.id';
-
- /**
- * @return void
- */
- public function testICanInstantiateCacheCounterClass(): void
- {
- $cacheCounter = new CacheCounter(new ArrayAdapter(100), 5);
-
- self::assertInstanceOf(CacheCounter::class, $cacheCounter);
- }
+ private const string COUNTER_ID = 'counter.id';
/**
- * @return void
+ * @throws InvalidArgumentException
*/
public function testICanAddValueOneTwiceAndGetTwoAsValue(): void
{
@@ -45,11 +29,10 @@ public function testICanAddValueOneTwiceAndGetTwoAsValue(): void
$cacheCounter->increment(self::COUNTER_ID, 1);
$cacheCounter->increment(self::COUNTER_ID, 1);
- self::assertEquals(2, $cacheCounter->current(self::COUNTER_ID));
+ self::assertSame(2, $cacheCounter->current(self::COUNTER_ID));
}
/**
- * @return void
* @throws InvalidArgumentException
*/
public function testICanAddValueOneTwiceAndGetOneAsValueWhenFirstElementIsOutOfTTL(): void
@@ -59,11 +42,10 @@ public function testICanAddValueOneTwiceAndGetOneAsValueWhenFirstElementIsOutOfT
sleep(2);
$cacheCounter->increment(self::COUNTER_ID, 1);
- self::assertEquals(1, $cacheCounter->current(self::COUNTER_ID));
+ self::assertSame(1, $cacheCounter->current(self::COUNTER_ID));
}
/**
- * @return void
* @throws InvalidArgumentException
*/
public function testICanAddValueOneTwiceAndGetZeroAsValueWhenAllElementsAreOutOfTTL(): void
@@ -73,11 +55,10 @@ public function testICanAddValueOneTwiceAndGetZeroAsValueWhenAllElementsAreOutOf
$cacheCounter->increment(self::COUNTER_ID, 1);
sleep(2);
- self::assertEquals(0, $cacheCounter->current(self::COUNTER_ID));
+ self::assertSame(0, $cacheCounter->current(self::COUNTER_ID));
}
/**
- * @return void
* @throws InvalidArgumentException
*/
public function testICanAddValueOneTwiceAndGetZeroAfterDeletionOfCounter(): void
@@ -86,20 +67,17 @@ public function testICanAddValueOneTwiceAndGetZeroAfterDeletionOfCounter(): void
$cacheCounter->increment(self::COUNTER_ID, 1);
$cacheCounter->increment(self::COUNTER_ID, 1);
- self::assertEquals(2, $cacheCounter->current(self::COUNTER_ID));
+ self::assertSame(2, $cacheCounter->current(self::COUNTER_ID));
$cacheCounter->delete(self::COUNTER_ID);
- self::assertEquals(0, $cacheCounter->current(self::COUNTER_ID));
+ self::assertSame(0, $cacheCounter->current(self::COUNTER_ID));
}
- /**
- * @return void
- */
public function testICanGetCounterTTLValue(): void
{
$cacheCounter = new CacheCounter(new ArrayAdapter(100), 10);
- self::assertEquals(10, $cacheCounter->getTTL());
+ self::assertSame(10, $cacheCounter->getTTL());
}
}
diff --git a/tests/unit/RateLimiter/LimiterProviderTest.php b/tests/Unit/RateLimiter/LimiterProviderTest.php
similarity index 83%
rename from tests/unit/RateLimiter/LimiterProviderTest.php
rename to tests/Unit/RateLimiter/LimiterProviderTest.php
index b998ca3..e72ed05 100644
--- a/tests/unit/RateLimiter/LimiterProviderTest.php
+++ b/tests/Unit/RateLimiter/LimiterProviderTest.php
@@ -17,29 +17,10 @@
use PHPUnit\Framework\TestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
-/**
- * Class LimiterProviderTest
- *
- * @author Romain Cottard
- */
class LimiterProviderTest extends TestCase
{
- private const LOCAL_IP = '127.0.0.1';
-
- /**
- * @return void
- */
- public function testICanInstantiateRouteQuotaLimiterProviderClass(): void
- {
- $cacheCounter = new CacheCounter(new ArrayAdapter(100), 5);
- $limiterProvider = new RouteQuotaLimiterProvider($cacheCounter, 2);
-
- self::assertInstanceOf(RouteQuotaLimiterProvider::class, $limiterProvider);
- }
+ private const string LOCAL_IP = '127.0.0.1';
- /**
- * @return void
- */
public function testICanAssertTwiceQuotaIsNotReachedWithTwoAsQuota(): void
{
$cacheCounter = new CacheCounter(new ArrayAdapter(100), 5);
@@ -53,12 +34,9 @@ public function testICanAssertTwiceQuotaIsNotReachedWithTwoAsQuota(): void
$limiterProvider->getQuotaLimiter($parameters)->assertQuotaNotReached();
$limiterProvider->getQuotaLimiter($parameters)->assertQuotaNotReached();
- self::assertTrue(true);
+ $this->expectNotToPerformAssertions();
}
- /**
- * @return void
- */
public function testAnExceptionIsThrownWhenTryToAssertTriceWithTwoAsQuota(): void
{
$cacheCounter = new CacheCounter(new ArrayAdapter(100), 5);
@@ -77,9 +55,6 @@ public function testAnExceptionIsThrownWhenTryToAssertTriceWithTwoAsQuota(): voi
$limiterProvider->getQuotaLimiter($parameters)->assertQuotaNotReached();
}
- /**
- * @return void
- */
public function testAnExceptionIsThrownWhenTryToGetQuotaLimiterWithoutRequiredRouteParameters(): void
{
$cacheCounter = new CacheCounter(new ArrayAdapter(100), 5);
@@ -95,9 +70,6 @@ public function testAnExceptionIsThrownWhenTryToGetQuotaLimiterWithoutRequiredRo
$limiterProvider->getQuotaLimiter($parameters);
}
- /**
- * @return void
- */
public function testAnExceptionIsThrownWhenTryToGetQuotaLimiterWithoutRequiredIpParameters(): void
{
$cacheCounter = new CacheCounter(new ArrayAdapter(100), 5);
diff --git a/tests/unit/Service/IpResolverTest.php b/tests/Unit/Service/IpResolverTest.php
similarity index 69%
rename from tests/unit/Service/IpResolverTest.php
rename to tests/Unit/Service/IpResolverTest.php
index 6dbf217..044c33e 100644
--- a/tests/unit/Service/IpResolverTest.php
+++ b/tests/Unit/Service/IpResolverTest.php
@@ -16,16 +16,8 @@
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestInterface;
-/**
- * Class IpTest
- *
- * @author Romain Cottard
- */
class IpResolverTest extends TestCase
{
- /**
- * @return void
- */
public function testIGetEmptyIpFromUtilsWhenUseLocalhostIp(): void
{
$serverRequest = $this->getServerRequest('127.0.0.1');
@@ -33,29 +25,27 @@ public function testIGetEmptyIpFromUtilsWhenUseLocalhostIp(): void
self::assertEmpty((new IpResolver())->resolve($serverRequest));
}
- /**
- * @return void
- */
public function testIGetMyIpFromUtilsWhenUseMyIp(): void
{
$serverRequest = $this->getServerRequest('1.2.3.4');
- self::assertEquals('1.2.3.4', (new IpResolver())->resolve($serverRequest));
+ self::assertSame('1.2.3.4', (new IpResolver())->resolve($serverRequest));
+ }
+
+ public function testIGetMyIpFromUtilsWhenUseMyIpWithXForwardedForIps(): void
+ {
+ $serverRequest = $this->getServerRequest('1.2.3.4', '1.2.3.5,1.2.3.6');
+
+ self::assertSame('1.2.3.5', (new IpResolver())->resolve($serverRequest));
}
- /**
- * @return void
- */
public function testIGetMyPrivateIpFromUtilsWhenUseMyPrivateIp(): void
{
$serverRequest = $this->getServerRequest('172.16.1.2');
- self::assertEquals('172.16.1.2', (new IpResolver())->resolve($serverRequest));
+ self::assertSame('172.16.1.2', (new IpResolver())->resolve($serverRequest));
}
- /**
- * @return void
- */
public function testIGetEmptyIpFromUtilsWithExcludedPrivateIpWhenUseMyPrivateIp(): void
{
$serverRequest = $this->getServerRequest('172.16.1.3');
@@ -63,15 +53,15 @@ public function testIGetEmptyIpFromUtilsWithExcludedPrivateIpWhenUseMyPrivateIp(
self::assertEmpty((new IpResolver())->resolve($serverRequest, true));
}
- /**
- * @param string $ip
- * @return ServerRequestInterface
- */
- private function getServerRequest(string $ip): ServerRequestInterface
+ private function getServerRequest(string $ip, string $xForwardedFor = ''): ServerRequestInterface
{
$server = $_SERVER;
$server['HTTP_X_FORWARDED'] = $ip;
+ if ($xForwardedFor !== '') {
+ $server['HTTP_X_FORWARDED_FOR'] = $xForwardedFor;
+ }
+
$httpFactory = new Psr17Factory();
return $httpFactory->createServerRequest('GET', $httpFactory->createUri('/'), $server);
}
diff --git a/tests/unit/Service/DataCollectionTest.php b/tests/unit/Service/DataCollectionTest.php
deleted file mode 100644
index 9db88b5..0000000
--- a/tests/unit/Service/DataCollectionTest.php
+++ /dev/null
@@ -1,52 +0,0 @@
- 1, 'two' => 2];
- $collection = new DataCollection($data);
-
- self::assertEquals(2, $collection->length());
-
- foreach ($collection as $key => $value) {
- self::assertEquals($data[$key], $value);
- }
-
- $collection->reset();
-
- self::assertEquals($data, $collection->toArray());
- }
-}