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

Add support for PSR-3 #2937

Merged
merged 4 commits into from
Apr 4, 2020
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
14 changes: 9 additions & 5 deletions Slim/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use Slim\Factory\ServerRequestCreatorFactory;
use Slim\Interfaces\CallableResolverInterface;
use Slim\Interfaces\MiddlewareDispatcherInterface;
Expand Down Expand Up @@ -140,23 +141,26 @@ public function addRoutingMiddleware(): RoutingMiddleware
/**
* Add the Slim built-in error middleware to the app middleware stack
*
* @param bool $displayErrorDetails
* @param bool $logErrors
* @param bool $logErrorDetails
* @param bool $displayErrorDetails
* @param bool $logErrors
* @param bool $logErrorDetails
* @param LoggerInterface|null $logger
*
* @return ErrorMiddleware
*/
public function addErrorMiddleware(
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
bool $logErrorDetails,
?LoggerInterface $logger = null
): ErrorMiddleware {
$errorMiddleware = new ErrorMiddleware(
$this->getCallableResolver(),
$this->getResponseFactory(),
$displayErrorDetails,
$logErrors,
$logErrorDetails
$logErrorDetails,
$logger
);
$this->add($errorMiddleware);
return $errorMiddleware;
Expand Down
28 changes: 25 additions & 3 deletions Slim/Handlers/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Slim\Error\Renderers\HtmlErrorRenderer;
use Slim\Error\Renderers\JsonErrorRenderer;
Expand All @@ -23,6 +24,7 @@
use Slim\Interfaces\CallableResolverInterface;
use Slim\Interfaces\ErrorHandlerInterface;
use Slim\Interfaces\ErrorRendererInterface;
use Slim\Logger;
use Throwable;

use function array_intersect;
Expand Down Expand Up @@ -121,14 +123,24 @@ class ErrorHandler implements ErrorHandlerInterface
*/
protected $responseFactory;

/*
* @var LoggerInterface
*/
protected $logger;

/**
* @param CallableResolverInterface $callableResolver
* @param ResponseFactoryInterface $responseFactory
* @param LoggerInterface|null $logger
*/
public function __construct(CallableResolverInterface $callableResolver, ResponseFactoryInterface $responseFactory)
{
public function __construct(
CallableResolverInterface $callableResolver,
ResponseFactoryInterface $responseFactory,
?LoggerInterface $logger = null
) {
$this->callableResolver = $callableResolver;
$this->responseFactory = $responseFactory;
$this->logger = $logger ?: $this->getDefaultLogger();
}

/**
Expand Down Expand Up @@ -311,7 +323,17 @@ protected function writeToErrorLog(): void
*/
protected function logError(string $error): void
{
error_log($error);
$this->logger->error($error);
}

/**
* Returns a default logger implementation.
*
* @return LoggerInterface
*/
protected function getDefaultLogger(): LoggerInterface
{
return new Logger();
}

/**
Expand Down
31 changes: 31 additions & 0 deletions Slim/Logger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

elazar marked this conversation as resolved.
Show resolved Hide resolved
/**
* Slim Framework (https://slimframework.com)
*
* @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
*/

declare(strict_types=1);

namespace Slim;

use Psr\Log\AbstractLogger;
use Psr\Log\InvalidArgumentException;

class Logger extends AbstractLogger
{
/**
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*
* @throws InvalidArgumentException
*/
public function log($level, $message, array $context = [])
{
error_log($message);
}
}
17 changes: 15 additions & 2 deletions Slim/Middleware/ErrorMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use Slim\Exception\HttpException;
use Slim\Handlers\ErrorHandler;
use Slim\Interfaces\CallableResolverInterface;
Expand Down Expand Up @@ -51,6 +52,11 @@ class ErrorMiddleware implements MiddlewareInterface
*/
protected $logErrorDetails;

/**
* @var LoggerInterface|null
*/
protected $logger;

/**
* @var ErrorHandlerInterface[]|callable[]
*/
Expand All @@ -72,19 +78,22 @@ class ErrorMiddleware implements MiddlewareInterface
* @param bool $displayErrorDetails
* @param bool $logErrors
* @param bool $logErrorDetails
* @param LoggerInterface|null $logger
*/
public function __construct(
CallableResolverInterface $callableResolver,
ResponseFactoryInterface $responseFactory,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
bool $logErrorDetails,
?LoggerInterface $logger = null
) {
$this->callableResolver = $callableResolver;
$this->responseFactory = $responseFactory;
$this->displayErrorDetails = $displayErrorDetails;
$this->logErrors = $logErrors;
$this->logErrorDetails = $logErrorDetails;
$this->logger = $logger;
}

/**
Expand Down Expand Up @@ -150,7 +159,11 @@ public function getErrorHandler(string $type)
public function getDefaultErrorHandler()
{
if ($this->defaultErrorHandler === null) {
$this->defaultErrorHandler = new ErrorHandler($this->callableResolver, $this->responseFactory);
$this->defaultErrorHandler = new ErrorHandler(
$this->callableResolver,
$this->responseFactory,
$this->logger
);
}

return $this->callableResolver->resolve($this->defaultErrorHandler);
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"psr/http-factory": "^1.0",
"psr/http-message": "^1.0",
"psr/http-server-handler": "^1.0",
"psr/http-server-middleware": "^1.0"
"psr/http-server-middleware": "^1.0",
"psr/log": "^1.1"
},
"require-dev": {
"ext-simplexml": "*",
Expand Down
6 changes: 5 additions & 1 deletion tests/AppTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Psr\Http\Message\UriInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use ReflectionClass;
use ReflectionProperty;
use RuntimeException;
Expand Down Expand Up @@ -724,11 +725,14 @@ public function testAddErrorMiddleware()
/** @var ResponseFactoryInterface $responseFactory */
$responseFactory = $this->prophesize(ResponseFactoryInterface::class)->reveal();

/** @var LoggerInterface $logger */
$logger = $this->prophesize(LoggerInterface::class)->reveal();

// Create the app.
$app = new App($responseFactory);

// Add the error middleware.
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
$errorMiddleware = $app->addErrorMiddleware(true, true, true, $logger);

// Check that the error middleware really has been added to the tip of the app middleware stack.
$middlewareDispatcherProperty = new ReflectionProperty(App::class, 'middlewareDispatcher');
Expand Down
42 changes: 24 additions & 18 deletions tests/Handlers/ErrorHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
namespace Slim\Tests\Handlers;

use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
Expand All @@ -28,6 +29,11 @@

class ErrorHandlerTest extends TestCase
{
private function getMockLogger(): LoggerInterface
{
return $this->createMock(LoggerInterface::class);
}

public function testDetermineRenderer()
{
$handler = $this
Expand Down Expand Up @@ -303,16 +309,16 @@ public function testWriteToErrorLog()
->createServerRequest('/', 'GET')
->withHeader('Accept', 'application/json');

$handler = $this->getMockBuilder(ErrorHandler::class)
->setConstructorArgs([
'callableResolver' => $this->getCallableResolver(),
'responseFactory' => $this->getResponseFactory(),
])
->setMethods(['logError'])
->getMock();
$logger = $this->getMockLogger();

$handler->expects(self::once())
->method('logError')
$handler = new ErrorHandler(
$this->getCallableResolver(),
$this->getResponseFactory(),
$logger
);

$logger->expects(self::once())
->method('error')
->willReturnCallback(static function (string $error) {
self::assertStringNotContainsString(
'set "displayErrorDetails" to true in the ErrorHandler constructor',
Expand All @@ -330,16 +336,16 @@ public function testWriteToErrorLogShowTip()
->createServerRequest('/', 'GET')
->withHeader('Accept', 'application/json');

$handler = $this->getMockBuilder(ErrorHandler::class)
->setConstructorArgs([
'callableResolver' => $this->getCallableResolver(),
'responseFactory' => $this->getResponseFactory(),
])
->setMethods(['logError'])
->getMock();
$logger = $this->getMockLogger();

$handler = new ErrorHandler(
$this->getCallableResolver(),
$this->getResponseFactory(),
$logger
);

$handler->expects(self::once())
->method('logError')
$logger->expects(self::once())
->method('error')
->willReturnCallback(static function (string $error) {
self::assertStringContainsString(
'set "displayErrorDetails" to true in the ErrorHandler constructor',
Expand Down
Loading