Skip to content

Commit

Permalink
Merge pull request #1 from davisenra/feature/cors
Browse files Browse the repository at this point in the history
feature/cors
  • Loading branch information
davisenra committed Mar 24, 2024
2 parents dcc866e + 475eaa5 commit afb31bc
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 19 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
APP_ENV="development"
DOMAIN="https://localhost"
DB_DRIVER="pdo_sqlite"
DB_NAME="database.sqlite"
DB_USER=""
Expand Down
41 changes: 26 additions & 15 deletions config/container.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,46 @@

declare(strict_types=1);

use Slim\App;
use App\Middleware\CorsMiddleware;
use DI\Container;
use Monolog\Logger;
use Doctrine\ORM\ORMSetup;
use Psr\Log\LoggerInterface;
use Slim\Factory\AppFactory;
use Doctrine\ORM\EntityManager;
use Doctrine\DBAL\DriverManager;
use Symfony\Component\Dotenv\Dotenv;
use Nyholm\Psr7\Factory\Psr17Factory;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMSetup;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Log\LoggerInterface;
use Slim\App;
use Slim\Factory\AppFactory;
use Symfony\Component\Dotenv\Dotenv;

return [

App::class => function (Container $container): App {
$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/../.env');
$dotenv->load(__DIR__ . '/../.env');
$isDevEnvironment = $_ENV['APP_ENV'] === 'development';

$app = AppFactory::createFromContainer($container);

if (!$isDevEnvironment) {
$routeCollector = $app->getRouteCollector();
$routeCollector->setCacheFile(__DIR__ . '/../var/routes.cache');
}

$app->addErrorMiddleware(
displayErrorDetails: true,
displayErrorDetails: $isDevEnvironment === true,
logErrors: true,
logErrorDetails: true,
logger: $container->get(LoggerInterface::class)
);

(require __DIR__.'/routes.php')($app);
$app->add(CorsMiddleware::class);
$app->addRoutingMiddleware();

(require __DIR__ . '/routes.php')($app);

return $app;
},
Expand All @@ -39,19 +50,19 @@
return $container->get(Psr17Factory::class);
},

LoggerInterface::class => function (Container $container) {
LoggerInterface::class => function () {
return new Logger(
name: 'app',
handlers: [
new RotatingFileHandler(sprintf('%s/app.log', __DIR__.'/../var/')),
new RotatingFileHandler(sprintf('%s/app.log', __DIR__ . '/../var/')),
],
processors: [],
);
},

EntityManagerInterface::class => function (Container $container) {
EntityManagerInterface::class => function () {
$config = ORMSetup::createAttributeMetadataConfiguration(
paths: [__DIR__.'/../src/Entity'],
paths: [__DIR__ . '/../src/Entity'],
isDevMode: true,
);

Expand Down
9 changes: 9 additions & 0 deletions config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,16 @@

use App\Controller\HealthCheckController;
use Slim\App;
use Slim\Exception\HttpNotFoundException;

return function (App $app) {
$app->get('/healthcheck', HealthCheckController::class);

$app->options('/{routes:.+}', fn ($request, $response) => $response);

$app->map(
['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
'/{routes:.+}',
fn ($request) => throw new HttpNotFoundException($request)
);
};
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ services:
- "443:443"
- "80:80"
volumes:
- "./:/app"
- "$PWD/:/app"
- "./docker/caddy/caddy_data:/data"
- "./docker/caddy/caddy_config:/config"

Expand Down
4 changes: 2 additions & 2 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
<directory>tests/Integration</directory>
</testsuite>

<testsuite name="infrastructure">
<directory>tests/Infrastructure</directory>
<testsuite name="application">
<directory>tests/Application</directory>
</testsuite>
</testsuites>

Expand Down
21 changes: 21 additions & 0 deletions src/Middleware/CorsMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CorsMiddleware
{
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
return $handler->handle($request)
->withHeader('Access-Control-Allow-Origin', $_ENV['DOMAIN'])
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
->withHeader('Access-Control-Allow-Credentials', 'true');
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace Tests\Infrastructure;
namespace Tests\Application;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
Expand Down
36 changes: 36 additions & 0 deletions tests/Application/Middleware/CorsMiddlewareTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Tests\Application\Middleware;

use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Tests\Traits\AppTestTrait;

class CorsMiddlewareTest extends TestCase
{
use AppTestTrait;

#[Test]
public function itAddsCorsHeaders(): void
{
$request = $this->createJsonRequest('GET', '/healthcheck');
$response = $this->app->handle($request);

$this->assertEquals(
$_ENV['DOMAIN'],
$response->getHeaderLine('Access-Control-Allow-Origin')
);
$this->assertEquals(
'X-Requested-With, Content-Type, Accept, Origin, Authorization',
$response->getHeaderLine('Access-Control-Allow-Headers')
);
$this->assertEquals(
'GET, POST, PUT, DELETE, PATCH, OPTIONS',
$response->getHeaderLine('Access-Control-Allow-Methods')
);
$this->assertEquals(
'true',
$response->getHeaderLine('Access-Control-Allow-Credentials')
);
}
}

0 comments on commit afb31bc

Please sign in to comment.