Skip to content

Commit

Permalink
Merge pull request #33 from samsonasik/apply-php80
Browse files Browse the repository at this point in the history
Apply PHP 8.0 Syntax and constructor promotion
  • Loading branch information
Ocramius authored Oct 15, 2022
2 parents ee10fe6 + 6152adb commit e2c1a5e
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 86 deletions.
9 changes: 3 additions & 6 deletions src/ProblemDetailsMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,8 @@ class ProblemDetailsMiddleware implements MiddlewareInterface
/** @var callable[] */
private array $listeners = [];

private ProblemDetailsResponseFactory $responseFactory;

public function __construct(ProblemDetailsResponseFactory $responseFactory)
public function __construct(private ProblemDetailsResponseFactory $responseFactory)
{
$this->responseFactory = $responseFactory;
}

/**
Expand Down Expand Up @@ -107,7 +104,7 @@ private function createErrorHandler(): callable
* @param int $errline
* @throws ErrorException if error is not within the error_reporting mask.
*/
return function (int $errno, string $errstr, string $errfile, int $errline): void {
return static function (int $errno, string $errstr, string $errfile, int $errline): void {
if (! (error_reporting() & $errno)) {
// error_reporting does not include this error
return;
Expand All @@ -125,7 +122,7 @@ private function triggerListeners(
ServerRequestInterface $request,
ResponseInterface $response
): void {
array_walk($this->listeners, function ($listener) use ($error, $request, $response) {
array_walk($this->listeners, static function ($listener) use ($error, $request, $response): void {
$listener($error, $request, $response);
});
}
Expand Down
5 changes: 1 addition & 4 deletions src/ProblemDetailsNotFoundHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,12 @@

class ProblemDetailsNotFoundHandler implements MiddlewareInterface
{
private ProblemDetailsResponseFactory $responseFactory;

/**
* @param ProblemDetailsResponseFactory $responseFactory Factory to create a response to
* update and return when returning an 404 response.
*/
public function __construct(ProblemDetailsResponseFactory $responseFactory)
public function __construct(private ProblemDetailsResponseFactory $responseFactory)
{
$this->responseFactory = $responseFactory;
}

/**
Expand Down
74 changes: 31 additions & 43 deletions src/ProblemDetailsResponseFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
use function preg_replace;
use function print_r;
use function sprintf;
use function str_contains;
use function str_replace;
use function strpos;

use const JSON_PARTIAL_OUTPUT_ON_ERROR;
use const JSON_PRESERVE_ZERO_FRACTION;
Expand Down Expand Up @@ -149,15 +149,6 @@ class ProblemDetailsResponseFactory
'application/*+xml',
];

/**
* Whether or not to include debug details.
*
* Debug details are only included for responses created from throwables,
* and include full exception details and previous exceptions and their
* details.
*/
private bool $isDebug;

/**
* JSON flags to use when generating JSON response payload.
*
Expand All @@ -177,38 +168,39 @@ class ProblemDetailsResponseFactory
*/
private ResponseFactoryInterface $responseFactory;

/**
* Flag to enable show exception details in detail field.
*
* Disabled by default for security reasons.
*/
private bool $exceptionDetailsInResponse;

/**
* Default detail field value. Will be visible when
* $exceptionDetailsInResponse disabled.
*
* Empty string by default
*/
private string $defaultDetailMessage;

/**
* A map used to infer the "type" property based on the status code.
*
* Defaults to an empty map.
*/
private array $defaultTypesMap;

/**
* @param (callable():ResponseInterface)|ResponseFactoryInterface $responseFactory
*/
public function __construct(
$responseFactory,
bool $isDebug = self::EXCLUDE_THROWABLE_DETAILS,
/**
* Whether or not to include debug details.
*
* Debug details are only included for responses created from throwables,
* and include full exception details and previous exceptions and their
* details.
*/
private bool $isDebug = self::EXCLUDE_THROWABLE_DETAILS,
?int $jsonFlags = null,
bool $exceptionDetailsInResponse = false,
string $defaultDetailMessage = self::DEFAULT_DETAIL_MESSAGE,
array $defaultTypesMap = []
/**
* Flag to enable show exception details in detail field.
*
* Disabled by default for security reasons.
*/
private bool $exceptionDetailsInResponse = false,
/**
* Default detail field value. Will be visible when
* $exceptionDetailsInResponse disabled.
*
* Empty string by default
*/
private string $defaultDetailMessage = self::DEFAULT_DETAIL_MESSAGE,
/**
* A map used to infer the "type" property based on the status code.
*
* Defaults to an empty map.
*/
private array $defaultTypesMap = []
) {
if (is_callable($responseFactory)) {
$responseFactory = new CallableResponseFactoryDecorator(
Expand All @@ -217,7 +209,6 @@ public function __construct(
}
// Ensures type safety of the composed factory
$this->responseFactory = $responseFactory;
$this->isDebug = $isDebug;
if (! $jsonFlags) {
$jsonFlags = JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
Expand All @@ -227,10 +218,7 @@ public function __construct(
$jsonFlags = JSON_PRETTY_PRINT | $jsonFlags;
}
}
$this->jsonFlags = $jsonFlags;
$this->exceptionDetailsInResponse = $exceptionDetailsInResponse;
$this->defaultDetailMessage = $defaultDetailMessage;
$this->defaultTypesMap = $defaultTypesMap;
$this->jsonFlags = $jsonFlags;
}

public function createResponse(
Expand All @@ -254,7 +242,7 @@ public function createResponse(

if ($additional) {
// ensure payload can be json_encoded
array_walk_recursive($additional, function (&$value) {
array_walk_recursive($additional, static function (&$value): void {
if (is_resource($value)) {
$value = print_r($value, true) . ' of type ' . get_resource_type($value);
}
Expand Down Expand Up @@ -374,7 +362,7 @@ private function getResponseGenerator(ServerRequestInterface $request): callable
$accept = $request->getHeaderLine('Accept') ?: '*/*';
$mediaType = (new Negotiator())->getBest($accept, self::NEGOTIATION_PRIORITIES);

return ! $mediaType || false === strpos($mediaType->getValue(), 'json')
return ! $mediaType || ! str_contains($mediaType->getValue(), 'json')
? Closure::fromCallable([$this, 'generateXmlResponse'])
: Closure::fromCallable([$this, 'generateJsonResponse']);
}
Expand Down
3 changes: 1 addition & 2 deletions test/InMemoryContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ public function has($id): bool
return array_key_exists($id, $this->services);
}

/** @param mixed $item */
public function set(string $id, $item): void
public function set(string $id, mixed $item): void
{
$this->services[$id] = $item;
}
Expand Down
6 changes: 3 additions & 3 deletions test/ProblemDetailsAssertionsTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public function preparePayloadForJsonResponse(MockObject $stream, callable $asse
$stream
->expects($this->any())
->method('write')
->with($this->callback(function ($body) use ($assertion) {
->with($this->callback(static function ($body) use ($assertion): bool {
Assert::assertIsString($body);
$data = json_decode($body, true);
$assertion($data);
Expand All @@ -99,7 +99,7 @@ public function preparePayloadForXmlResponse(MockObject $stream, callable $asser
$stream
->expects($this->any())
->method('write')
->with($this->callback(function ($body) use ($assertion) {
->with($this->callback(function ($body) use ($assertion): bool {
Assert::assertIsString($body);
$data = $this->deserializeXmlPayload($body);
$assertion($data);
Expand All @@ -114,7 +114,7 @@ public function deserializeXmlPayload(string $xml): array
$payload = json_decode($json, true);

// Ensure ints and floats are properly represented
array_walk_recursive($payload, function (&$item) {
array_walk_recursive($payload, static function (&$item): void {
if ((string) (int) $item === $item) {
$item = (int) $item;
return;
Expand Down
6 changes: 3 additions & 3 deletions test/ProblemDetailsMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,14 @@ public function testMiddlewareRegistersErrorHandlerToConvertErrorsToProblemDetai
$handler
->method('handle')
->with($this->request)
->willReturnCallback(function () {
->willReturnCallback(static function (): void {
trigger_error('Triggered error!', E_USER_ERROR);
});

$expected = $this->createMock(ResponseInterface::class);
$this->responseFactory
->method('createResponseFromThrowable')
->with($this->request, $this->callback(function ($e) {
->with($this->request, $this->callback(function ($e): bool {
$this->assertInstanceOf(ErrorException::class, $e);
$this->assertEquals(E_USER_ERROR, $e->getSeverity());
$this->assertEquals('Triggered error!', $e->getMessage());
Expand Down Expand Up @@ -168,7 +168,7 @@ public function testErrorHandlingTriggersListeners(string $accept): void
->with($this->request, $exception)
->willReturn($expected);

$listener = function ($error, $request, $response) use ($exception, $expected) {
$listener = function ($error, $request, $response) use ($exception, $expected): void {
$this->assertSame($exception, $error, 'Listener did not receive same exception as was raised');
$this->assertSame($this->request, $request, 'Listener did not receive same request');
$this->assertSame($expected, $response, 'Listener did not receive same response');
Expand Down
8 changes: 4 additions & 4 deletions test/ProblemDetailsResponseFactoryFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public function testUsesPrettyPrintFlagOnEnabledDebugMode(): void
['config', ['debug' => true]],
[
ResponseInterface::class,
function () {
static function (): void {
},
],
]);
Expand All @@ -154,7 +154,7 @@ public function testUsesDebugSettingFromConfigWhenPresent(): void
['config', ['debug' => true]],
[
ResponseInterface::class,
function () {
static function (): void {
},
],
]);
Expand Down Expand Up @@ -185,7 +185,7 @@ public function testUsesJsonFlagsSettingFromConfigWhenPresent(): void
['config', ['problem-details' => ['json_flags' => JSON_PRETTY_PRINT]]],
[
ResponseInterface::class,
function () {
static function (): void {
},
],
]);
Expand Down Expand Up @@ -216,7 +216,7 @@ public function testUsesDefaultTypesSettingFromConfigWhenPresent(): void
['config', ['problem-details' => ['default_types_map' => $expectedDefaultTypes]]],
[
ResponseInterface::class,
function () {
static function (): void {
},
],
]);
Expand Down
Loading

0 comments on commit e2c1a5e

Please sign in to comment.