Skip to content

Commit

Permalink
Upgrade to PHPStan 1 (#1022)
Browse files Browse the repository at this point in the history
  • Loading branch information
spawnia committed Dec 2, 2021
1 parent f7607c0 commit d36e809
Show file tree
Hide file tree
Showing 27 changed files with 264 additions and 271 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ You can find and compare releases at the [GitHub release page](https://github.co
- Rename `ServerConfig` option `persistentQueryLoader` to `persistedQueryLoader`
- Call previously unused methods `EnumType::parseValue()` and `EnumType::parseLiteral()`
- Strongly type `PromiseAdapter::createRejected()` to require `\Throwable`
- Store rules exclusively by class name in `DocumentValidator`

### Added

Expand Down Expand Up @@ -80,6 +81,8 @@ You can find and compare releases at the [GitHub release page](https://github.co
- Remove `OperationParams` method `isReadOnly()` in favor of public property `$readOnly`
- Remove `Utils::withErrorHandling()`
- Remove `TypeComparators::doTypesOverlap()`
- Remove `DocumentValidator::isError()`
- Remove `DocumentValidator::append()`

## 14.11.3

Expand Down
22 changes: 11 additions & 11 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,21 @@
"homepage": "https://github.com/webonyx/graphql-php",
"license": "MIT",
"require": {
"php": "^7.4 || ^8.0",
"php": "^7.4 || ^8",
"ext-json": "*",
"ext-mbstring": "*"
},
"require-dev": {
"amphp/amp": "^2.3",
"dms/phpunit-arraysubset-asserts": "^0.2.1",
"doctrine/coding-standard": "^9.0",
"ergebnis/composer-normalize": "^2.13",
"nyholm/psr7": "^1.2",
"phpbench/phpbench": "^1",
"phpstan/extension-installer": "^1",
"phpstan/phpstan": "0.12.99",
"phpstan/phpstan-phpunit": "0.12.22",
"phpstan/phpstan-strict-rules": "0.12.11",
"amphp/amp": "^2.6",
"dms/phpunit-arraysubset-asserts": "^0.3",
"doctrine/coding-standard": "^9",
"ergebnis/composer-normalize": "^2.16",
"nyholm/psr7": "^1.4",
"phpbench/phpbench": "^1.2",
"phpstan/extension-installer": "^1.1",
"phpstan/phpstan": "^1.2",
"phpstan/phpstan-phpunit": "^1",
"phpstan/phpstan-strict-rules": "^1",
"phpunit/phpunit": "^9.5",
"psr/http-message": "^1",
"react/promise": "^2",
Expand Down
7 changes: 6 additions & 1 deletion examples/01-blog/Blog/Type/QueryType.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,12 @@ public function viewer($rootValue, array $args, AppContext $context): User
*/
public function stories($rootValue, array $args): array
{
return DataSource::findStories($args['limit'], (int) $args['after'] ?? null);
return DataSource::findStories(
$args['limit'],
isset($args['after'])
? (int) $args['after']
: null
);
}

public function lastStoryPosted(): ?Story
Expand Down
8 changes: 7 additions & 1 deletion examples/01-blog/Blog/Type/StoryType.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,13 @@ public function resolveTotalCommentCount(Story $story): int
*/
public function resolveComments(Story $story, array $args): array
{
return DataSource::findComments($story->id, $args['limit'], (int) $args['after'] ?? null);
return DataSource::findComments(
$story->id,
$args['limit'],
isset($args['after'])
? (int) $args['after']
: null
);
}

/**
Expand Down
28 changes: 14 additions & 14 deletions examples/01-blog/Blog/Types.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,72 +36,72 @@
* As simplistic as possible for the sake of clarity of this example.
* Your own may be more dynamic (or even code-generated).
*/
class Types
final class Types
{
/** @var array<string, Type> */
private static array $types = [];

public static function user(): callable
{
return static::get(UserType::class);
return self::get(UserType::class);
}

public static function story(): callable
{
return static::get(StoryType::class);
return self::get(StoryType::class);
}

public static function comment(): callable
{
return static::get(CommentType::class);
return self::get(CommentType::class);
}

public static function image(): callable
{
return static::get(ImageType::class);
return self::get(ImageType::class);
}

public static function node(): callable
{
return static::get(NodeType::class);
return self::get(NodeType::class);
}

public static function mention(): callable
{
return static::get(SearchResultType::class);
return self::get(SearchResultType::class);
}

public static function imageSize(): callable
{
return static::get(ImageSizeType::class);
return self::get(ImageSizeType::class);
}

public static function contentFormat(): callable
{
return static::get(ContentFormatType::class);
return self::get(ContentFormatType::class);
}

public static function storyAffordances(): callable
{
return static::get(StoryAffordancesType::class);
return self::get(StoryAffordancesType::class);
}

public static function email(): callable
{
return static::get(EmailType::class);
return self::get(EmailType::class);
}

public static function url(): callable
{
return static::get(UrlType::class);
return self::get(UrlType::class);
}

/**
* @return Closure(): Type
*/
private static function get(string $classname): Closure
{
return static fn () => static::byClassName($classname);
return static fn () => self::byClassName($classname);
}

private static function byClassName(string $classname): Type
Expand Down Expand Up @@ -138,7 +138,7 @@ public static function byTypeName(string $shortName): Type
}

$method = lcfirst($shortName);
if (method_exists(static::class, $method)) {
if (method_exists(self::class, $method)) {
$type = self::{$method}();
}

Expand Down
5 changes: 5 additions & 0 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,8 @@ parameters:
count: 1
path: src/Utils/Utils.php

-
message: "#^Property GraphQL\\\\Tests\\\\Type\\\\SchemaTest\\:\\:\\$implementingType is never read, only written\\.$#"
count: 1
path: tests/Type/SchemaTest.php

6 changes: 6 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ parameters:
# allow partial parsing of language fragments.
- "~Variable method call on GraphQL\\\\Language\\\\Parser\\.~"

# We utilize lazy initialization of non-nullable properties
- "~Property .+? in isset\\(\\) is not nullable~"
- "~Static property .+? in isset\\(\\) is not nullable~"
- "~Property .+? on left side of \\?\\?= is not nullable~"
- "~Static property .+? on left side of \\?\\?= is not nullable~"

# Useful/necessary in the default field resolver, deals with arbitrary user data
-
message: "~Variable property access on object~"
Expand Down
8 changes: 4 additions & 4 deletions src/Error/FormattedError.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Countable;
use ErrorException;
use GraphQL\Executor\ExecutionResult;
use GraphQL\Language\AST\Node;
use GraphQL\Language\Source;
use GraphQL\Language\SourceLocation;
Expand All @@ -30,7 +31,6 @@
use function is_string;
use function mb_strlen;
use function preg_split;
use function sprintf;
use function str_repeat;
use function strlen;

Expand All @@ -45,6 +45,7 @@
* path?: array<int, int|string>,
* extensions?: array<string, mixed>,
* }
* @phpstan-import-type ErrorFormatter from ExecutionResult
*/
class FormattedError
{
Expand Down Expand Up @@ -116,7 +117,7 @@ private static function highlightSourceAtLocation(Source $source, SourceLocation
$lines[0] = self::whitespace($source->locationOffset->column - 1) . $lines[0];

$outputLines = [
sprintf('%s (%s:%s)', $source->name, $contextLine, $contextColumn),
"{$source->name} ({$contextLine}:{$contextColumn})",
$line >= 2 ? (self::lpad($padLen, $prevLineNum) . ': ' . $lines[$line - 2]) : null,
self::lpad($padLen, $lineNum) . ': ' . $lines[$line - 1],
self::whitespace(2 + $padLen + $contextColumn - 1) . '^',
Expand Down Expand Up @@ -199,7 +200,6 @@ public static function createFromException(Throwable $exception, int $debugFlag
* phpcs:disable SlevomatCodingStandard.Commenting.DocCommentSpacing.IncorrectAnnotationsGroup
* @param int $debugFlag For available flags @see \GraphQL\Error\DebugFlag
*
* phpcs:disable SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingTraversableTypeHintSpecification
* @param FormattedErrorArray $formattedError
*
* @return FormattedErrorArray
Expand Down Expand Up @@ -251,7 +251,7 @@ public static function addDebugEntries(array $formattedError, Throwable $e, int
*
* If initial formatter is not set, FormattedError::createFromException is used.
*
* @param callable(Throwable): array<string, mixed> $formatter
* @phpstan-param ErrorFormatter|null $formatter
*/
public static function prepareFormatter(?callable $formatter, int $debug): callable
{
Expand Down
68 changes: 44 additions & 24 deletions src/Executor/ExecutionResult.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use JsonSerializable;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use Throwable;

use function array_map;
use function count;
Expand All @@ -20,17 +21,27 @@
* (with errors collected in `errors` prop)
*
* Could be converted to [spec-compliant](https://facebook.github.io/graphql/#sec-Response-Format)
* serializable array using `toArray()`
* serializable array using `toArray()`.
*
* @phpstan-type SerializableError array<string, mixed>
* @phpstan-type SerializableErrors array<int, SerializableError>
* @phpstan-type SerializableResult array{
* data?: array<string, mixed>,
* errors?: SerializableErrors,
* extensions?: array<string, mixed>,
* }
* @phpstan-type ErrorFormatter callable(Throwable): SerializableError
* @phpstan-type ErrorsHandler callable(array<Error> $errors, ErrorFormatter $formatter): SerializableErrors
*/
class ExecutionResult implements JsonSerializable
{
/**
* Data collected from resolvers during query execution
* Data collected from resolvers during query execution.
*
* @api
* @var mixed[]
* @var array<string, mixed>|null
*/
public $data;
public ?array $data = null;

/**
* Errors registered during query execution.
Expand All @@ -39,31 +50,36 @@ class ExecutionResult implements JsonSerializable
* contain original exception.
*
* @api
* @var Error[]
* @var array<Error>
*/
public $errors;
public array $errors = [];

/**
* User-defined serializable array of extensions included in serialized result.
* Conforms to
*
* @api
* @var mixed[]
* @var array<string, mixed>|null
*/
public $extensions;
public ?array $extensions = null;

/** @var callable */
private $errorFormatter;
/**
* @var callable|null
* @phpstan-var ErrorFormatter|null
*/
private $errorFormatter = null;

/** @var callable */
private $errorsHandler;
/**
* @var callable|null
* @phpstan-var ErrorsHandler|null
*/
private $errorsHandler = null;

/**
* @param mixed[] $data
* @param Error[] $errors
* @param mixed[] $extensions
* @param array<string, mixed>|null $data
* @param array<Error> $errors
* @param array<string, mixed> $extensions
*/
public function __construct($data = null, array $errors = [], array $extensions = [])
public function __construct(?array $data = null, array $errors = [], array $extensions = [])
{
$this->data = $data;
$this->errors = $errors;
Expand All @@ -83,9 +99,11 @@ public function __construct($data = null, array $errors = [], array $extensions
* // ... other keys
* );
*
* @phpstan-param ErrorFormatter|null $errorFormatter
*
* @api
*/
public function setErrorFormatter(callable $errorFormatter): self
public function setErrorFormatter(?callable $errorFormatter): self
{
$this->errorFormatter = $errorFormatter;

Expand All @@ -102,17 +120,19 @@ public function setErrorFormatter(callable $errorFormatter): self
* return array_map($formatter, $errors);
* }
*
* @phpstan-param ErrorsHandler|null $errorsHandler
*
* @api
*/
public function setErrorsHandler(callable $handler): self
public function setErrorsHandler(?callable $errorsHandler): self
{
$this->errorsHandler = $handler;
$this->errorsHandler = $errorsHandler;

return $this;
}

/**
* @return mixed[]
* @phpstan-return SerializableResult
*/
#[ReturnTypeWillChange]
public function jsonSerialize(): array
Expand All @@ -129,15 +149,15 @@ public function jsonSerialize(): array
*
* $debug argument must sum of flags from @see \GraphQL\Error\DebugFlag
*
* @return mixed[]
* @phpstan-return SerializableResult
*
* @api
*/
public function toArray(int $debug = DebugFlag::NONE): array
{
$result = [];

if (count($this->errors ?? []) > 0) {
if (count($this->errors) > 0) {
$errorsHandler = $this->errorsHandler ?? static function (array $errors, callable $formatter): array {
return array_map($formatter, $errors);
};
Expand All @@ -157,7 +177,7 @@ public function toArray(int $debug = DebugFlag::NONE): array
$result['data'] = $this->data;
}

if (count($this->extensions ?? []) > 0) {
if ($this->extensions !== null && count($this->extensions) > 0) {
$result['extensions'] = $this->extensions;
}

Expand Down
Loading

0 comments on commit d36e809

Please sign in to comment.