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

Simplify configuration, logging creation #67

Merged
merged 3 commits into from
Feb 17, 2024
Merged
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
2 changes: 1 addition & 1 deletion dummy_app/DummyApplicationFeatures.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use Labrador\Web\Application\ApplicationFeatures;
use Labrador\Web\Application\StaticAssetSettings;

#[Service(primary: true)]
#[Service]
final class DummyApplicationFeatures implements ApplicationFeatures {

public function getSessionMiddleware() : ?SessionMiddleware {
Expand Down
25 changes: 0 additions & 25 deletions dummy_app/DummyLoggerFactory.php

This file was deleted.

24 changes: 24 additions & 0 deletions dummy_app/DummyMonologInitializer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php declare(strict_types=1);

namespace Labrador\DummyApp;

use Cspray\AnnotatedContainer\Attribute\Service;
use Labrador\Logging\LoggerType;
use Labrador\Logging\MonologLoggerInitializer;
use Monolog\Handler\TestHandler;
use Monolog\Logger;
use Monolog\Processor\PsrLogMessageProcessor;

#[Service]
class DummyMonologInitializer implements MonologLoggerInitializer {

public function __construct(
public readonly TestHandler $testHandler
) {}

public function initialize(Logger $logger, LoggerType $loggerType) : void {
$logger->pushProcessor(new PsrLogMessageProcessor());
$logger->pushHandler($this->testHandler);
}

}
37 changes: 32 additions & 5 deletions known-issues.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="5.12.0@f90118cdeacd0088e7215e64c0c99ceca819e176">
<files psalm-version="5.17.0@c620f6e80d0abfca532b00bda366062aaedf6e5d">
<file src="src/Util/ReflectionCache.php">
<InvalidArrayOffset>
<code>self::$cache[$class]</code>
</InvalidArrayOffset>
<PropertyTypeCoercion>
<code>[]</code>
<code>self::$cache</code>
</PropertyTypeCoercion>
</file>
<file src="src/Validation/EntityValidator.php">
<ArgumentTypeCoercion>
<code>$errors</code>
</ArgumentTypeCoercion>
<MixedAssignment>
<code>$value</code>
</MixedAssignment>
</file>
<file src="src/Validation/PropertyValidateMap.php">
<InvalidArgument>
<code>$map</code>
</InvalidArgument>
</file>
<file src="src/Web/Application/Analytics/RequestBenchmark.php">
<PossiblyNullOperand>
<code><![CDATA[$this->middlewareCompleted]]></code>
Expand All @@ -14,6 +36,11 @@
<code><![CDATA[$this->profiles]]></code>
</ArgumentTypeCoercion>
</file>
<file src="src/Web/Controller/MiddlewareController.php">
<RedundantCondition>
<code><![CDATA[$toString !== '']]></code>
</RedundantCondition>
</file>
<file src="src/Web/Controller/StaticAssetController.php">
<MixedOperand>
<code><![CDATA[$request->getAttribute('path')]]></code>
Expand All @@ -25,6 +52,10 @@
</ArgumentTypeCoercion>
</file>
<file src="src/Web/Security/CsrfTokenManager.php">
<MixedArgument>
<code><![CDATA[$session->get('csrfTokens')]]></code>
<code><![CDATA[$session->get('csrfTokens')]]></code>
</MixedArgument>
<MixedArrayAccess>
<code>$tokens[$index]</code>
</MixedArrayAccess>
Expand All @@ -40,9 +71,5 @@
<code>$tokens</code>
<code>$tokens</code>
</MixedAssignment>
<PossiblyNullArgument>
<code><![CDATA[$session->get('csrfTokens')]]></code>
<code><![CDATA[$session->get('csrfTokens')]]></code>
</PossiblyNullArgument>
</file>
</files>
15 changes: 15 additions & 0 deletions src/Logging/ApplicationLoggerProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php declare(strict_types=1);

namespace Labrador\Logging;

use Cspray\AnnotatedContainer\Attribute\ServiceDelegate;
use Psr\Log\LoggerInterface;

class ApplicationLoggerProvider {

#[ServiceDelegate]
public static function createLogger(LoggerFactory $loggerFactory) : LoggerInterface {
return $loggerFactory->createLogger(LoggerType::Application);
}

}
1 change: 0 additions & 1 deletion src/Logging/MonologLoggerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ public function __construct(
public function createLogger(LoggerType $loggerType) : LoggerInterface {
if (!array_key_exists($loggerType->value, $this->cache)) {
$logger = new Logger($loggerType->value);
$logger->pushProcessor(new PsrLogMessageProcessor());

$this->loggerInitializer->initialize($logger, $loggerType);

Expand Down
26 changes: 0 additions & 26 deletions src/Logging/StdoutMonologLoggerInitializer.php

This file was deleted.

17 changes: 14 additions & 3 deletions src/Util/ReflectionCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,27 @@

namespace Labrador\Util;

use ReflectionClass;
use ReflectionException;

final class ReflectionCache {

/**
* @var array{class-string, ReflectionClass}
*/
private static array $cache = [];

/**
* @param class-string $class
* @return \ReflectionClass
* @return ReflectionClass
* @throws ReflectionException
*/
public static function fromClass(string $class) : \ReflectionClass {
return self::$cache[$class] ??= new \ReflectionClass($class);
public static function fromClass(string $class) : ReflectionClass {
$reflection = self::$cache[$class] ??= new ReflectionClass($class);

assert($reflection instanceof ReflectionClass);

return $reflection;
}

}
9 changes: 0 additions & 9 deletions src/Web/Application/AmpApplication.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,6 @@ public function stop() : void {
}

public function handleRequest(Request $request) : Response {
if ($this->features->autoRedirectHttpToHttps() && $request->getUri()->getScheme() === 'http') {
$uri = $request->getUri()->withScheme('https');
$uri = $uri->withPort($this->features->getHttpsRedirectPort());
return new Response(
status: HttpStatus::MOVED_PERMANENTLY,
headers: ['Location' => (string) $uri]
);
}

$benchmark = RequestBenchmark::requestReceived($request, $this->preciseTime);

try {
Expand Down
4 changes: 0 additions & 4 deletions src/Web/Application/ApplicationFeatures.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@ interface ApplicationFeatures {

public function getSessionMiddleware() : ?SessionMiddleware;

public function autoRedirectHttpToHttps() : bool;

public function getHttpsRedirectPort() : ?int;

public function getStaticAssetSettings() : ?StaticAssetSettings;

}
26 changes: 0 additions & 26 deletions src/Web/Application/NoApplicationFeatures.php

This file was deleted.

2 changes: 1 addition & 1 deletion src/Web/Application/StaticAssetSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ final class StaticAssetSettings {

public function __construct(
public readonly string $assetDir,
public readonly string $pathPrefix = 'assets'
public readonly string $pathPrefix
) {}

}
18 changes: 18 additions & 0 deletions test/Helper/StubApplicationFeatures.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php declare(strict_types=1);

namespace Labrador\Test\Helper;

use Amp\Http\Server\Session\SessionMiddleware;
use Labrador\Web\Application\ApplicationFeatures;
use Labrador\Web\Application\StaticAssetSettings;

class StubApplicationFeatures implements ApplicationFeatures {

public function getSessionMiddleware() : ?SessionMiddleware {
return null;
}

public function getStaticAssetSettings() : ?StaticAssetSettings {
return null;
}
}
41 changes: 34 additions & 7 deletions test/Integration/BootstrapTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Labrador\AsyncEvent\AmpEventEmitter;
use Labrador\AsyncEvent\EventEmitter;
use Labrador\DummyApp\Controller\CheckDtoController;
use Labrador\DummyApp\DummyMonologInitializer;
use Labrador\DummyApp\Middleware\BarMiddleware;
use Labrador\DummyApp\Middleware\BazMiddleware;
use Labrador\DummyApp\Middleware\FooMiddleware;
Expand All @@ -26,9 +27,11 @@
use Labrador\Validation\Filter;
use Labrador\Web\Bootstrap;
use Labrador\Web\ErrorHandlerFactory;
use Labrador\Web\Middleware\Priority;
use Labrador\Web\Router\LoggingRouter;
use Labrador\Web\Router\Route;
use Labrador\Web\Router\Router;
use Monolog\Handler\TestHandler;
use Monolog\Logger;
use org\bovigo\vfs\vfsStream as VirtualFilesystem;
use org\bovigo\vfs\vfsStreamDirectory as VirtualDirectory;
Expand Down Expand Up @@ -96,7 +99,12 @@ public function testCorrectlyConfiguredAnnotatedContainerReturnsLogger() : void
self::assertInstanceOf(Logger::class, $logger);

$logger->info('This is a test message');
self::assertStringContainsString('This is a test message', StreamBuffer::output($this->stdout));

$handler = $this->container->get(DummyMonologInitializer::class)->testHandler;
self::assertInstanceOf(TestHandler::class, $handler);
self::assertTrue(
$handler->hasInfoThatContains('This is a test message')
);
}

public function testCorrectlyConfiguredAnnotatedContainerReturnsRouter() : void {
Expand Down Expand Up @@ -155,17 +163,36 @@ public function testApplicationAutowiringControllersLogged() : void {

$bootstrap->bootstrapApplication();

self::assertStringContainsString('Autowiring route GET /hello/world to HelloWorld controller.', StreamBuffer::output($this->stdout));
$handler = $this->container->get(DummyMonologInitializer::class)->testHandler;
self::assertInstanceOf(TestHandler::class, $handler);

self::assertTrue(
$handler->hasInfoThatContains('Autowiring route GET /hello/world to HelloWorld controller.')
);
}

public static function expectedMiddlewareProvider() : array {
return [
BarMiddleware::class => [BarMiddleware::class, Priority::Low],
BazMiddleware::class => [BazMiddleware::class, Priority::Medium],
FooMiddleware::class => [FooMiddleware::class, Priority::High],
QuxMiddleware::class => [QuxMiddleware::class, Priority::Critical]
];
}

public function testApplicationAutowiringApplicationMiddlewareLogged() : void {
/**
* @dataProvider expectedMiddlewareProvider
*/
public function testApplicationAutowiringApplicationMiddlewareLogged(string $middlewareClass, Priority $priority) : void {
$bootstrap = new Bootstrap($this->containerBootstrap, profiles: ['default', 'integration-test']);
$bootstrap->bootstrapApplication();

self::assertStringContainsString('Adding ' . BarMiddleware::class . ' to application with Low priority.', StreamBuffer::output($this->stdout));
self::assertStringContainsString('Adding ' . BazMiddleware::class . ' to application with Medium priority.', StreamBuffer::output($this->stdout));
self::assertStringContainsString('Adding ' . FooMiddleware::class . ' to application with High priority.', StreamBuffer::output($this->stdout));
self::assertStringContainsString('Adding ' . QuxMiddleware::class . ' to application with Critical priority.', StreamBuffer::output($this->stdout));
$handler = $this->container->get(DummyMonologInitializer::class)->testHandler;
self::assertInstanceOf(TestHandler::class, $handler);

self::assertTrue(
$handler->hasInfoThatContains('Adding ' . $middlewareClass . ' to application with ' . $priority->name . ' priority.')
);
}

}
Loading
Loading