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 PHPStan to test environment #200

Merged
merged 2 commits into from
Oct 24, 2022
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: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# exclude dev files from export to reduce archive download size
/.gitattributes export-ignore
/.github/ISSUE_TEMPLATE/ export-ignore
/.github/workflows/ export-ignore
/.gitignore export-ignore
/docs/ export-ignore
/examples/ export-ignore
/mkdocs.yml export-ignore
/phpstan.neon.dist export-ignore
/phpunit.xml.dist export-ignore
/phpunit.xml.legacy export-ignore
/tests/ export-ignore
Expand Down
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,28 @@ jobs:
- run: vendor/bin/phpunit --coverage-text --stderr -c phpunit.xml.legacy
if: ${{ matrix.php < 7.3 }}

PHPStan:
name: PHPStan (PHP ${{ matrix.php }})
runs-on: ubuntu-22.04
strategy:
matrix:
php:
- 8.2
- 8.1
- 8.0
- 7.4
- 7.3
- 7.2
- 7.1
steps:
- uses: actions/checkout@v3
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
- run: composer install
- run: vendor/bin/phpstan

Built-in-webserver:
name: Built-in webserver (PHP ${{ matrix.php }})
runs-on: ubuntu-22.04
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"react/promise": "^3 || ^2.7"
},
"require-dev": {
"phpstan/phpstan": "1.8.10 || 1.4.10",
"phpunit/phpunit": "^9.5 || ^7.5",
"psr/container": "^2 || ^1"
},
Expand Down
6 changes: 3 additions & 3 deletions examples/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@
return new React\Http\Message\Response(
React\Http\Message\Response::STATUS_OK,
[
'Content-Length' => 5,
'Content-Length' => '5',
'Content-Type' => 'text/plain; charset=utf-8',
'X-Is-Head' => 'true'
]
Expand Down Expand Up @@ -161,7 +161,7 @@
React\Http\Message\Response::STATUS_NOT_MODIFIED,
[
'ETag' => $etag,
'Content-Length' => strlen($etag) - 1
'Content-Length' => (string) (strlen($etag) - 1)
]
);
}
Expand Down Expand Up @@ -193,7 +193,7 @@
$app->get('/error/yield', function () {
yield null;
});
$app->get('/error/class', 'Acme\Http\UnknownDeleteUserController');
$app->get('/error/class', 'Acme\Http\UnknownDeleteUserController'); // @phpstan-ignore-line

// OPTIONS *
$app->options('', function () {
Expand Down
17 changes: 17 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
parameters:
level: 5

paths:
- examples/
- src/
- tests/

reportUnmatchedIgnoredErrors: false
ignoreErrors:
# ignore generic usage like `PromiseInterface<ResponseInterface>` until fixed upstream
- '/^PHPDoc tag @return contains generic type React\\Promise\\PromiseInterface<Psr\\Http\\Message\\ResponseInterface> but interface React\\Promise\\PromiseInterface is not generic\.$/'
# ignore unknown `Fiber` class (PHP 8.1+)
- '/^Instantiated class Fiber not found\.$/'
- '/^Call to method (start|isTerminated|getReturn)\(\) on an unknown class Fiber\.$/'
# ignore incomplete type information for mocks in legacy PHPUnit 7.5
- '/^Parameter #\d+ \$.+ of class .+ constructor expects .+, PHPUnit\\Framework\\MockObject\\MockObject given\.$/'
5 changes: 3 additions & 2 deletions src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ private function runLoop()
} while (true);

// remove signal handlers when loop stops (if registered)
Loop::removeSignal(\defined('SIGINT') ? \SIGINT : 2, $f1);
Loop::removeSignal(\defined('SIGINT') ? \SIGINT : 2, $f1 ?? 'printf');
Loop::removeSignal(\defined('SIGTERM') ? \SIGTERM : 15, $f2 ?? 'printf');
}

Expand All @@ -309,11 +309,12 @@ private function runOnce()

/**
* @param ServerRequestInterface $request
* @return ResponseInterface|PromiseInterface<ResponseInterface,void>
* @return ResponseInterface|PromiseInterface<ResponseInterface>
* Returns a response or a Promise which eventually fulfills with a
* response. This method never throws or resolves a rejected promise.
* If the request can not be routed or the handler fails, it will be
* turned into a valid error response before returning.
* @throws void
*/
private function handleRequest(ServerRequestInterface $request)
{
Expand Down
4 changes: 3 additions & 1 deletion src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ class Container
/** @var array<string,object|callable():(object|scalar|null)|scalar|null>|ContainerInterface */
private $container;

/** @var array<string,callable():(object|scalar|null) | object | scalar | null>|ContainerInterface $loader */
/** @param array<string,callable():(object|scalar|null) | object | scalar | null>|ContainerInterface $loader */
public function __construct($loader = [])
{
/** @var mixed $loader explicit type check for mixed if user ignores parameter type */
if (!\is_array($loader) && !$loader instanceof ContainerInterface) {
throw new \TypeError(
'Argument #1 ($loader) must be of type array|Psr\Container\ContainerInterface, ' . (\is_object($loader) ? get_class($loader) : gettype($loader)) . ' given'
Expand Down Expand Up @@ -233,6 +234,7 @@ private function loadParameter(\ReflectionParameter $parameter, int $depth, bool
$hasDefault = $parameter->isDefaultValueAvailable() || ((!$type instanceof \ReflectionNamedType || $type->getName() !== 'mixed') && $parameter->allowsNull());

// abort for union types (PHP 8.0+) and intersection types (PHP 8.1+)
// @phpstan-ignore-next-line for PHP < 8
if ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) { // @codeCoverageIgnoreStart
if ($hasDefault) {
return $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null;
Expand Down
2 changes: 1 addition & 1 deletion src/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public function __construct()
}

/**
* @return ResponseInterface|PromiseInterface<ResponseInterface,void>|\Generator
* @return ResponseInterface|PromiseInterface<ResponseInterface>|\Generator
* Returns a response, a Promise which eventually fulfills with a
* response or a Generator which eventually returns a response. This
* method never throws or resolves a rejected promise. If the next
Expand Down
7 changes: 6 additions & 1 deletion src/Io/FiberHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
class FiberHandler
{
/**
* @return ResponseInterface|PromiseInterface<ResponseInterface,void>|\Generator
* @return ResponseInterface|PromiseInterface<ResponseInterface>|\Generator
* Returns a `ResponseInterface` from the next request handler in the
* chain. If the next request handler returns immediately, this method
* will return immediately. If the next request handler suspends the
Expand All @@ -42,15 +42,20 @@ public function __invoke(ServerRequestInterface $request, callable $next): mixed
$response = $next($request);
assert($response instanceof ResponseInterface || $response instanceof PromiseInterface || $response instanceof \Generator);

// if the next request handler returns immediately, the fiber can terminate immediately without using a Deferred
// if the next request handler suspends the fiber, we only reach this point after resuming the fiber, so the code below will have assigned a Deferred
/** @var ?Deferred $deferred */
if ($deferred !== null) {
$deferred->resolve($response);
}

return $response;
});

/** @throws void because the next handler will always be an `ErrorHandler` */
$fiber->start();
if ($fiber->isTerminated()) {
/** @throws void because fiber is known to have terminated successfully */
return $fiber->getReturn();
}

Expand Down
41 changes: 25 additions & 16 deletions src/Io/RouteHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,28 +76,37 @@ public function map(array $methods, string $route, $handler, ...$handlers): void
public function __invoke(ServerRequestInterface $request)
{
if ($request->getRequestTarget()[0] !== '/' && $request->getRequestTarget() !== '*') {
return $this->errorHandler->requestProxyUnsupported($request);
return $this->errorHandler->requestProxyUnsupported();
}

if ($this->routeDispatcher === null) {
$this->routeDispatcher = new RouteDispatcher($this->routeCollector->getData());
}

$routeInfo = $this->routeDispatcher->dispatch($request->getMethod(), $request->getUri()->getPath());
switch ($routeInfo[0]) {
case \FastRoute\Dispatcher::NOT_FOUND:
return $this->errorHandler->requestNotFound($request);
case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
return $this->errorHandler->requestMethodNotAllowed($routeInfo[1]);
case \FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];

foreach ($vars as $key => $value) {
$request = $request->withAttribute($key, rawurldecode($value));
}

return $handler($request);
assert(\is_array($routeInfo) && isset($routeInfo[0]));

// happy path: matching route found, assign route attributes and invoke request handler
if ($routeInfo[0] === \FastRoute\Dispatcher::FOUND) {
$handler = $routeInfo[1];
$vars = $routeInfo[2];

foreach ($vars as $key => $value) {
$request = $request->withAttribute($key, rawurldecode($value));
}

return $handler($request);
}
} // @codeCoverageIgnore

// no matching route found: report error `404 Not Found`
if ($routeInfo[0] === \FastRoute\Dispatcher::NOT_FOUND) {
return $this->errorHandler->requestNotFound();
}

// unexpected request method for route: report error `405 Method Not Allowed`
assert($routeInfo[0] === \FastRoute\Dispatcher::METHOD_NOT_ALLOWED);
assert(\is_array($routeInfo[1]) && \count($routeInfo[1]) > 0);

return $this->errorHandler->requestMethodNotAllowed($routeInfo[1]);
}
}
2 changes: 1 addition & 1 deletion src/Io/SapiHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function requestFromGlobals(): ServerRequestInterface
$target = ($_SERVER['REQUEST_URI'] ?? '/');
$url = $target;
if (($target[0] ?? '/') === '/' || $target === '*') {
$url = ($_SERVER['HTTPS'] ?? null === 'on' ? 'https://' : 'http://') . ($host ?? 'localhost') . ($target === '*' ? '' : $target);
$url = (($_SERVER['HTTPS'] ?? null) === 'on' ? 'https://' : 'http://') . ($host ?? 'localhost') . ($target === '*' ? '' : $target);
}

$body = file_get_contents('php://input');
Expand Down
2 changes: 1 addition & 1 deletion tests/AccessLogHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ public function testInvokeWithCoroutineNextPrintsRequestLogWithCurrentDateAndTim
$response = new Response(200, [], "Hello\n");

$generator = $handler($request, function () use ($response) {
if (false) {
if (false) { // @phpstan-ignore-line
yield;
}
return $response;
Expand Down
6 changes: 3 additions & 3 deletions tests/AppTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1230,7 +1230,7 @@ public function testHandleRequestWithMatchingRouteReturnsResponseWhenHandlerRetu
$app = $this->createAppWithoutLogger();

$app->get('/users', function () {
if (false) {
if (false) { // @phpstan-ignore-line
yield;
}

Expand Down Expand Up @@ -1611,7 +1611,7 @@ public function testHandleRequestWithMatchingRouteReturnsInternalServerErrorResp

$line = __LINE__ + 5;
$app->get('/users', function () {
if (false) {
if (false) { // @phpstan-ignore-line
yield;
}
throw new \RuntimeException('Foo');
Expand Down Expand Up @@ -1837,7 +1837,7 @@ public function testHandleRequestWithMatchingRouteReturnsInternalServerErrorResp
{
$app = $this->createAppWithoutLogger();

$app->get('/users', 'UnknownClass');
$app->get('/users', 'UnknownClass'); // @phpstan-ignore-line

$request = new ServerRequest('GET', 'http://localhost/users');

Expand Down
20 changes: 12 additions & 8 deletions tests/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,11 @@ public function testCallableReturnsCallableForUnionWithNullViaAutowiringWillDefa
{
$request = new ServerRequest('GET', 'http://example.com/');

// @phpstan-ignore-next-line for PHP < 8
$controller = new class(null) {
private $data = false;

#[PHP8] public function __construct(string|int|null $data) { $this->data = $data; }
#[PHP8] public function __construct(string|int|null $data) { $this->data = $data; } // @phpstan-ignore-line

public function __invoke(ServerRequestInterface $request)
{
Expand Down Expand Up @@ -223,10 +224,11 @@ public function testCallableReturnsCallableForUnionWithIntDefaultValueViaAutowir
{
$request = new ServerRequest('GET', 'http://example.com/');

// @phpstan-ignore-next-line for PHP < 8
$controller = new class(null) {
private $data = false;

#[PHP8] public function __construct(string|int|null $data = 42) { $this->data = $data; }
#[PHP8] public function __construct(string|int|null $data = 42) { $this->data = $data; } // @phpstan-ignore-line

public function __invoke(ServerRequestInterface $request)
{
Expand Down Expand Up @@ -281,10 +283,11 @@ public function testCallableReturnsCallableForMixedWithStringDefaultViaAutowirin
{
$request = new ServerRequest('GET', 'http://example.com/');

// @phpstan-ignore-next-line for PHP < 8
$controller = new class(null) {
private $data = false;

#[PHP8] public function __construct(mixed $data = 'empty') { $this->data = $data; }
#[PHP8] public function __construct(mixed $data = 'empty') { $this->data = $data; } // @phpstan-ignore-line

public function __invoke(ServerRequestInterface $request)
{
Expand Down Expand Up @@ -773,7 +776,8 @@ public function __invoke()
}
};

$fn = #[PHP8] fn(mixed $data = 42) => new Response(200, [], json_encode($data));
$fn = null;
$fn = #[PHP8] fn(mixed $data = 42) => new Response(200, [], json_encode($data)); // @phpstan-ignore-line
$container = new Container([
ResponseInterface::class => $fn,
'data' => null
Expand Down Expand Up @@ -844,7 +848,7 @@ public function __invoke()
ResponseInterface::class => function (?\stdClass $user, ?\stdClass $data) {
return new Response(200, [], json_encode(['user' => $user, 'data' => $data]));
},
'user' => function (): ?\stdClass {
'user' => function (): ?\stdClass { // @phpstan-ignore-line
return (object) [];
}
]);
Expand Down Expand Up @@ -1717,7 +1721,7 @@ public function testCtorThrowsWhenMapContainsInvalidArray()
$this->expectException(\BadMethodCallException::class);
$this->expectExceptionMessage('Map for all contains unexpected array');

new Container([
new Container([ // @phpstan-ignore-line
'all' => []
]);
}
Expand Down Expand Up @@ -1944,7 +1948,7 @@ public function testCallableReturnsCallableThatThrowsWhenFactoryReturnsInvalidCl

$container = new Container($psr);

$callable = $container->callable('FooBar');
$callable = $container->callable('FooBar'); // @phpstan-ignore-line

$this->expectException(\BadMethodCallException::class);
$this->expectExceptionMessage('Request handler class FooBar failed to load: Unable to load class');
Expand Down Expand Up @@ -2175,6 +2179,6 @@ public function testCtorWithInvalidValueThrows()
{
$this->expectException(\TypeError::class);
$this->expectExceptionMessage('Argument #1 ($loader) must be of type array|Psr\Container\ContainerInterface, stdClass given');
new Container((object) []);
new Container((object) []); // @phpstan-ignore-line
}
}
6 changes: 3 additions & 3 deletions tests/ErrorHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function testInvokeWithHandlerReturningGeneratorReturningResponseReturnsG
$response = new Response();

$generator = $handler($request, function () use ($response) {
if (false) {
if (false) { // @phpstan-ignore-line
yield;
}
return $response;
Expand Down Expand Up @@ -166,7 +166,7 @@ public function testInvokeWithHandlerReturningGeneratorThrowingExceptionReturnsG
$request = new ServerRequest('GET', 'http://example.com/');

$generator = $handler($request, function () {
if (false) {
if (false) { // @phpstan-ignore-line
yield;
}
throw new \RuntimeException();
Expand Down Expand Up @@ -324,7 +324,7 @@ public function testInvokeWithHandlerReturningGeneratorReturningNullReturnsGener
$request = new ServerRequest('GET', 'http://example.com/');

$generator = $handler($request, function () {
if (false) {
if (false) { // @phpstan-ignore-line
yield;
}
return null;
Expand Down
1 change: 1 addition & 0 deletions tests/Fixtures/InvalidConstructorInt.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ class InvalidConstructorInt
{
public function __construct(int $value)
{
assert(is_int($value));
}
}
Loading