From 6d825eab6f0f30d04390955a2b9328ef57b82b67 Mon Sep 17 00:00:00 2001 From: DerManoMann Date: Wed, 1 May 2024 09:20:58 +1200 Subject: [PATCH] Add rector and apply some basic rules --- composer.json | 8 ++++- phpstan-baseline.neon | 5 --- rector.php | 34 ++++++++++++++++++++ src/Analysers/AttributeAnnotationFactory.php | 2 +- src/Analysers/ReflectionAnalyser.php | 5 ++- src/Analysers/TokenAnalyser.php | 8 +++-- src/Analysers/TokenScanner.php | 8 ++--- src/Analysis.php | 8 ++--- src/Annotations/AbstractAnnotation.php | 24 ++++++-------- src/Annotations/Flow.php | 2 +- src/Annotations/OpenApi.php | 14 +++----- src/Annotations/Operation.php | 2 +- src/Context.php | 15 +++------ src/Loggers/ConsoleLogger.php | 7 ++-- src/Loggers/DefaultLogger.php | 6 +--- src/Processors/AugmentParameters.php | 2 +- src/Processors/AugmentSchemas.php | 8 ++--- src/Processors/CleanUnmerged.php | 4 +-- src/Processors/Concerns/DocblockTrait.php | 8 ++--- src/Processors/ExpandClasses.php | 2 +- src/Processors/ExpandEnums.php | 8 ++--- src/Processors/ExpandInterfaces.php | 2 +- src/Processors/ExpandTraits.php | 4 +-- src/Processors/OperationId.php | 8 ++--- src/Serializer.php | 2 +- src/Util.php | 6 ++-- 26 files changed, 106 insertions(+), 96 deletions(-) create mode 100644 rector.php diff --git a/composer.json b/composer.json index db2b2e671..0a4912b2d 100644 --- a/composer.json +++ b/composer.json @@ -62,6 +62,7 @@ "friendsofphp/php-cs-fixer": "^3.48", "phpstan/phpstan": "^1.6", "phpunit/phpunit": "^9.0", + "rector/rector": "^1.0", "vimeo/psalm": "^4.30" }, "suggest": { @@ -79,6 +80,7 @@ }, "scripts-descriptions": { "cs": "Fix all codestyle issues", + "rector": "Automatic refactoring", "lint": "Test codestyle", "test": "Run all non-legacy and codestyle tests", "testlegacy": "Run tests using the legacy TokenAnalyser", @@ -93,7 +95,11 @@ }, "scripts": { "cs": "export XDEBUG_MODE=off && php-cs-fixer fix --allow-risky=yes", - "lint": "@cs --dry-run", + "rector": "rector process src", + "lint": [ + "@cs --dry-run", + "@rector --dry-run" + ], "test": [ "export XDEBUG_MODE=off && phpunit", "@lint" diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 925486522..abd69448b 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -65,11 +65,6 @@ parameters: count: 1 path: src/Annotations/Schema.php - - - message: "#^Variable \\$logLine in empty\\(\\) always exists and is not falsy\\.$#" - count: 1 - path: src/Loggers/ConsoleLogger.php - - message: "#^Call to function is_array\\(\\) with bool\\|OpenApi\\\\Annotations\\\\AdditionalProperties will always evaluate to false\\.$#" count: 1 diff --git a/rector.php b/rector.php new file mode 100644 index 000000000..e0a7c581b --- /dev/null +++ b/rector.php @@ -0,0 +1,34 @@ +withRules([ + TypedPropertyFromStrictConstructorRector::class + ]) + ->withSkip([ + CombineIfRector::class, + ExplicitBoolCompareRector::class, + ExplicitReturnNullRector::class => [ + __DIR__ . '/src/Analysers/TokenAnalyser.php', + ], + ForRepeatedCountToOwnVariableRector::class, + RemoveAlwaysTrueIfConditionRector::class => [ + __DIR__ . '/src/Processors/ExpandEnums.php', + ] , + RemoveDeadInstanceOfRector::class => [ + __DIR__ . '/src/Processors/ExpandEnums.php', + ], + ShortenElseIfRector::class, + ]) + ->withPreparedSets(true, true) + ->withPhpVersion(PhpVersion::PHP_74); diff --git a/src/Analysers/AttributeAnnotationFactory.php b/src/Analysers/AttributeAnnotationFactory.php index a457da7d2..da21fd7fb 100644 --- a/src/Analysers/AttributeAnnotationFactory.php +++ b/src/Analysers/AttributeAnnotationFactory.php @@ -123,7 +123,7 @@ public function build(\Reflector $reflector, Context $context): array } // Property can be nested... - return $annotation->getRoot() != $possibleParent->getRoot() + return $annotation->getRoot() !== $possibleParent->getRoot() && ($explicitParent || ($isAttachable && $isParentAllowed)); }; diff --git a/src/Analysers/ReflectionAnalyser.php b/src/Analysers/ReflectionAnalyser.php index 8d2e5148b..5dfbe652b 100644 --- a/src/Analysers/ReflectionAnalyser.php +++ b/src/Analysers/ReflectionAnalyser.php @@ -24,14 +24,13 @@ class ReflectionAnalyser implements AnalyserInterface use GeneratorAwareTrait; /** @var AnnotationFactoryInterface[] */ - protected array $annotationFactories; + protected array $annotationFactories = []; /** * @param array $annotationFactories */ public function __construct(array $annotationFactories = []) { - $this->annotationFactories = []; foreach ($annotationFactories as $annotationFactory) { if ($annotationFactory->isSupported()) { $this->annotationFactories[] = $annotationFactory; @@ -115,7 +114,7 @@ protected function analyzeFqdn(string $fqdn, Analysis $analysis, array $details) if ($parentClass = $rc->getParentClass()) { $definition['extends'] = $normaliseClass($parentClass->getName()); } - $definition[$contextType == 'class' ? 'implements' : 'extends'] = array_map($normaliseClass, $details['interfaces']); + $definition[$contextType === 'class' ? 'implements' : 'extends'] = array_map($normaliseClass, $details['interfaces']); $definition['traits'] = array_map($normaliseClass, $details['traits']); foreach ($this->annotationFactories as $annotationFactory) { diff --git a/src/Analysers/TokenAnalyser.php b/src/Analysers/TokenAnalyser.php index fdf9b8942..ad2dc0210 100644 --- a/src/Analysers/TokenAnalyser.php +++ b/src/Analysers/TokenAnalyser.php @@ -160,7 +160,9 @@ protected function fromTokens(array $tokens, Context $parseContext): Analysis if ($token[0] === T_IMPLEMENTS) { $schemaContext->implements = $this->parseNamespaceList($tokens, $token, $parseContext); - $classDefinition['implements'] = array_map([$schemaContext, 'fullyQualifiedName'], $schemaContext->implements); + $classDefinition['implements'] = array_map(function (?string $source) use ($schemaContext): string { + return $schemaContext->fullyQualifiedName($source); + }, $schemaContext->implements); } if ($comment) { @@ -201,7 +203,9 @@ protected function fromTokens(array $tokens, Context $parseContext): Analysis if ($token[0] === T_EXTENDS) { $schemaContext->extends = $this->parseNamespaceList($tokens, $token, $parseContext); - $interfaceDefinition['extends'] = array_map([$schemaContext, 'fullyQualifiedName'], $schemaContext->extends); + $interfaceDefinition['extends'] = array_map(function (?string $source) use ($schemaContext): string { + return $schemaContext->fullyQualifiedName($source); + }, $schemaContext->extends); } if ($comment) { diff --git a/src/Analysers/TokenScanner.php b/src/Analysers/TokenScanner.php index d6ec4ff21..8ba9ce9ea 100644 --- a/src/Analysers/TokenScanner.php +++ b/src/Analysers/TokenScanner.php @@ -66,7 +66,7 @@ protected function scanTokens(array $tokens): array break; case '}': array_pop($stack); - if (count($stack) == $unitLevel) { + if (count($stack) === $unitLevel) { $currentName = null; } break; @@ -76,7 +76,7 @@ protected function scanTokens(array $tokens): array switch ($token[0]) { case T_ABSTRACT: - if (count($stack)) { + if ($stack !== []) { $isAbstractFunction = true; } break; @@ -115,7 +115,7 @@ protected function scanTokens(array $tokens): array // unless ... if (is_string($token) && ($token === '(' || $token === '{')) { // new class[()] { ... } - if ('{' == $token) { + if ('{' === $token) { prev($tokens); } break; @@ -254,7 +254,7 @@ protected function resolveFQN(array $names, string $namespace, array $uses): arr protected function skipTo(array &$tokens, string $char, bool $prev = false): void { while (false !== ($token = next($tokens))) { - if (is_string($token) && $token == $char) { + if (is_string($token) && $token === $char) { if ($prev) { prev($tokens); } diff --git a/src/Analysis.php b/src/Analysis.php index d8974aaaf..dd3c87aa9 100644 --- a/src/Analysis.php +++ b/src/Analysis.php @@ -134,7 +134,7 @@ public function addAnalysis(Analysis $analysis): void $this->interfaces = array_merge($this->interfaces, $analysis->interfaces); $this->traits = array_merge($this->traits, $analysis->traits); $this->enums = array_merge($this->enums, $analysis->enums); - if ($this->openapi === null && $analysis->openapi !== null) { + if (!$this->openapi instanceof OA\OpenApi && $analysis->openapi instanceof OA\OpenApi) { $this->openapi = $analysis->openapi; } } @@ -331,7 +331,7 @@ public function getAnnotationForSource(string $fqdn, string $class): ?OA\Abstrac if (is_iterable($definition['context']->annotations)) { /** @var OA\AbstractAnnotation $annotation */ foreach (array_reverse($definition['context']->annotations) as $annotation) { - if (is_a($annotation, $class) && $annotation->isRoot($class) && !$annotation->_context->is('generated')) { + if ($annotation instanceof $class && $annotation->isRoot($class) && !$annotation->_context->is('generated')) { return $annotation; } } @@ -363,7 +363,7 @@ public function getContext(object $annotation): ?Context */ public function merged(): Analysis { - if ($this->openapi === null) { + if (!$this->openapi instanceof OA\OpenApi) { throw new \Exception('No openapi target set. Run the MergeIntoOpenApi processor'); } $unmerged = $this->openapi->_unmerged; @@ -420,7 +420,7 @@ public function process($processors = null): void public function validate(): bool { - if ($this->openapi !== null) { + if ($this->openapi instanceof OA\OpenApi) { return $this->openapi->validate(); } diff --git a/src/Annotations/AbstractAnnotation.php b/src/Annotations/AbstractAnnotation.php index 28a8c8246..9dbb41b41 100644 --- a/src/Annotations/AbstractAnnotation.php +++ b/src/Annotations/AbstractAnnotation.php @@ -37,7 +37,7 @@ abstract class AbstractAnnotation implements \JsonSerializable /** * @var Context|null */ - public $_context = null; + public $_context; /** * Annotations that couldn't be merged by mapping or postprocessing. @@ -240,7 +240,7 @@ public function mergeProperties($object): void $identity = method_exists($object, 'identity') ? $object->identity() : get_class($object); $context1 = $this->_context; $context2 = property_exists($object, '_context') ? $object->_context : 'unknown'; - if (is_object($this->{$property}) && $this->{$property} instanceof AbstractAnnotation) { + if ($this->{$property} instanceof AbstractAnnotation) { $context1 = $this->{$property}->_context; } $this->_context->logger->error('Multiple definitions for ' . $identity . '->' . $property . "\n Using: " . $context1 . "\n Skipping: " . $context2); @@ -303,7 +303,7 @@ public function jsonSerialize() // Correct empty array to empty objects. foreach (static::$_types as $property => $type) { - if ($type === 'object' && is_array($data->{$property}) && empty($data->{$property})) { + if ($type === 'object' && is_array($data->{$property}) && $data->{$property} === []) { $data->{$property} = new \stdClass(); } } @@ -334,11 +334,7 @@ public function jsonSerialize() } else { $key = $item->{$keyField}; if (!Generator::isDefault($key) && empty($object->{$key})) { - if ($item instanceof \JsonSerializable) { - $object->{$key} = $item->jsonSerialize(); - } else { - $object->{$key} = $item; - } + $object->{$key} = $item instanceof \JsonSerializable ? $item->jsonSerialize() : $item; unset($object->{$key}->{$keyField}); } } @@ -370,7 +366,7 @@ public function jsonSerialize() // preserve other properties foreach (get_object_vars($this) as $property => $value) { - if ('_' == $property[0] || in_array($property, ['ref', 'nullable'])) { + if ('_' === $property[0] || in_array($property, ['ref', 'nullable'])) { continue; } if (!Generator::isDefault($value)) { @@ -499,7 +495,7 @@ public function validate(array $stack = [], array $skip = [], string $ref = '', } if (property_exists($this, 'ref') && !Generator::isDefault($this->ref) && is_string($this->ref)) { - if (substr($this->ref, 0, 2) === '#/' && count($stack) > 0 && $stack[0] instanceof OpenApi) { + if (substr($this->ref, 0, 2) === '#/' && $stack !== [] && $stack[0] instanceof OpenApi) { // Internal reference try { $stack[0]->ref($this->ref); @@ -558,7 +554,7 @@ public function validate(array $stack = [], array $skip = [], string $ref = '', } } - return self::_validate($this, $stack, $skip, $ref, $context) ? $valid : false; + return self::_validate($this, $stack, $skip, $ref, $context) && $valid; } /** @@ -664,7 +660,7 @@ public function getRoot(): string */ public function isRoot(string $rootClass): bool { - return get_class($this) == $rootClass || $this->getRoot() == $rootClass; + return get_class($this) === $rootClass || $this->getRoot() === $rootClass; } /** @@ -696,7 +692,7 @@ private function validateType(string $type, $value): bool return false; } $itemType = substr($type, 1, -1); - foreach ($value as $i => $item) { + foreach ($value as $item) { if ($this->validateType($itemType, $item) === false) { return false; } @@ -760,7 +756,7 @@ private function validateArrayType($value): bool return false; } $count = 0; - foreach ($value as $i => $item) { + foreach (array_keys($value) as $i) { // not a array, but a hash/map if ($count !== $i) { return false; diff --git a/src/Annotations/Flow.php b/src/Annotations/Flow.php index 540920626..c94f94460 100644 --- a/src/Annotations/Flow.php +++ b/src/Annotations/Flow.php @@ -97,7 +97,7 @@ class Flow extends AbstractAnnotation #[\ReturnTypeWillChange] public function jsonSerialize() { - if (is_array($this->scopes) && empty($this->scopes)) { + if ($this->scopes === []) { $this->scopes = new \stdClass(); } diff --git a/src/Annotations/OpenApi.php b/src/Annotations/OpenApi.php index 8a5e55a2d..1bba2cfb9 100644 --- a/src/Annotations/OpenApi.php +++ b/src/Annotations/OpenApi.php @@ -178,11 +178,7 @@ public function saveAs(string $filename, string $format = 'auto'): void $format = strtolower(substr($filename, -5)) === '.json' ? 'json' : 'yaml'; } - if (strtolower($format) === 'json') { - $content = $this->toJson(); - } else { - $content = $this->toYaml(); - } + $content = strtolower($format) === 'json' ? $this->toJson() : $this->toYaml(); if (file_put_contents($filename, $content) === false) { throw new \Exception('Failed to saveAs("' . $filename . '", "' . $format . '")'); @@ -229,11 +225,9 @@ private static function resolveRef(string $ref, string $resolved, $container, ar return $container->{$property}; } $mapping = []; - if ($container instanceof AbstractAnnotation) { - foreach ($container::$_nested as $nestedClass => $nested) { - if (is_string($nested) === false && count($nested) === 2 && $nested[0] === $property) { - $mapping[$nestedClass] = $nested[1]; - } + foreach ($container::$_nested as $nestedClass => $nested) { + if (is_string($nested) === false && count($nested) === 2 && $nested[0] === $property) { + $mapping[$nestedClass] = $nested[1]; } } diff --git a/src/Annotations/Operation.php b/src/Annotations/Operation.php index bc089dc17..174072690 100644 --- a/src/Annotations/Operation.php +++ b/src/Annotations/Operation.php @@ -224,7 +224,7 @@ public function validate(array $stack = [], array $skip = [], string $ref = '', if (!Generator::isDefault($this->responses)) { foreach ($this->responses as $response) { - if (!Generator::isDefault($response->response) && $response->response !== 'default' && preg_match('/^([12345]{1}[0-9]{2})|([12345]{1}XX)$/', (string) $response->response) === 0) { + if (!Generator::isDefault($response->response) && $response->response !== 'default' && preg_match('/^([12345]{1}\d{2})|([12345]{1}XX)$/', (string) $response->response) === 0) { $this->_context->logger->warning('Invalid value "' . $response->response . '" for ' . $response->_identity([]) . '->response, expecting "default", a HTTP Status Code or HTTP Status Code range definition in ' . $response->_context); $valid = false; } diff --git a/src/Context.php b/src/Context.php index 9211f2c6a..9320b03e5 100644 --- a/src/Context.php +++ b/src/Context.php @@ -96,7 +96,7 @@ public function with(string $property): ?Context if ($this->is($property)) { return $this; } - if ($this->parent !== null) { + if ($this->parent instanceof Context) { return $this->parent->with($property); } @@ -108,7 +108,7 @@ public function with(string $property): ?Context */ public function root(): Context { - if ($this->parent !== null) { + if ($this->parent instanceof Context) { return $this->parent->root(); } @@ -168,7 +168,7 @@ public function getDebugLocation(): string */ public function __get(string $property) { - if ($this->parent !== null) { + if ($this->parent instanceof Context) { return $this->parent->{$property}; } @@ -213,7 +213,7 @@ public static function detect(int $index = 0): Context if (isset($caller['class'])) { $fqn = explode('\\', $caller['class']); $context->class = array_pop($fqn); - if (count($fqn)) { + if ($fqn !== []) { $context->namespace = implode('\\', $fqn); } } @@ -231,12 +231,7 @@ public function fullyQualifiedName(?string $source): string return ''; } - if ($this->namespace) { - $namespace = str_replace('\\\\', '\\', '\\' . $this->namespace . '\\'); - } else { - // global namespace - $namespace = '\\'; - } + $namespace = $this->namespace ? str_replace('\\\\', '\\', '\\' . $this->namespace . '\\') : '\\'; $thisSource = $this->class ?? $this->interface ?? $this->trait; if ($thisSource && strcasecmp($source, $thisSource) === 0) { diff --git a/src/Loggers/ConsoleLogger.php b/src/Loggers/ConsoleLogger.php index 3bcd5c6e4..a85232a71 100644 --- a/src/Loggers/ConsoleLogger.php +++ b/src/Loggers/ConsoleLogger.php @@ -25,8 +25,7 @@ class ConsoleLogger extends AbstractLogger implements LoggerInterface /** @var bool */ protected $loggedMessageAboveNotice = false; - /** @var bool */ - protected $debug; + protected bool $debug; public function __construct(bool $debug = false) { @@ -64,7 +63,7 @@ public function log($level, $message, array $context = []): void $color = static::COLOR_ERROR; break; } - $stop = !empty($color) ? static::COLOR_STOP : ''; + $stop = empty($color) ? '' : static::COLOR_STOP; if (!in_array($level, self::LOG_LEVELS_UP_TO_NOTICE, true)) { $this->loggedMessageAboveNotice = true; @@ -83,7 +82,7 @@ public function log($level, $message, array $context = []): void if ($this->debug) { if ($exception) { error_log($exception->getTraceAsString()); - } elseif (!empty($logLine)) { + } elseif ($logLine !== '' && $logLine !== '0') { $stack = explode(PHP_EOL, (new \Exception())->getTraceAsString()); // self array_shift($stack); diff --git a/src/Loggers/DefaultLogger.php b/src/Loggers/DefaultLogger.php index e3a0f8e08..75be1833f 100644 --- a/src/Loggers/DefaultLogger.php +++ b/src/Loggers/DefaultLogger.php @@ -18,11 +18,7 @@ public function log($level, $message, array $context = []): void return; } - if (in_array($level, [LogLevel::NOTICE, LogLevel::INFO])) { - $error_level = E_USER_NOTICE; - } else { - $error_level = E_USER_WARNING; - } + $error_level = in_array($level, [LogLevel::NOTICE, LogLevel::INFO]) ? E_USER_NOTICE : E_USER_WARNING; trigger_error($message, $error_level); } diff --git a/src/Processors/AugmentParameters.php b/src/Processors/AugmentParameters.php index cb5818e16..a74c6d634 100644 --- a/src/Processors/AugmentParameters.php +++ b/src/Processors/AugmentParameters.php @@ -15,7 +15,7 @@ class AugmentParameters implements ProcessorInterface { use DocblockTrait; - protected $augmentOperationParameters; + protected bool $augmentOperationParameters; public function __construct(bool $augmentOperationParameters = true) { diff --git a/src/Processors/AugmentSchemas.php b/src/Processors/AugmentSchemas.php index a07b2aa30..ebc4d0b7e 100644 --- a/src/Processors/AugmentSchemas.php +++ b/src/Processors/AugmentSchemas.php @@ -93,13 +93,13 @@ protected function augmentType(Analysis $analysis, array $schemas): void { foreach ($schemas as $schema) { if (Generator::isDefault($schema->type)) { - if (is_array($schema->properties) && count($schema->properties) > 0) { + if (is_array($schema->properties) && $schema->properties !== []) { $schema->type = 'object'; - } elseif (is_array($schema->additionalProperties) && count($schema->additionalProperties) > 0) { + } elseif (is_array($schema->additionalProperties) && $schema->additionalProperties !== []) { $schema->type = 'object'; - } elseif (is_array($schema->patternProperties) && count($schema->patternProperties) > 0) { + } elseif (is_array($schema->patternProperties) && $schema->patternProperties !== []) { $schema->type = 'object'; - } elseif (is_array($schema->propertyNames) && count($schema->propertyNames) > 0) { + } elseif (is_array($schema->propertyNames) && $schema->propertyNames !== []) { $schema->type = 'object'; } } else { diff --git a/src/Processors/CleanUnmerged.php b/src/Processors/CleanUnmerged.php index dacdaa100..6b3e2147d 100644 --- a/src/Processors/CleanUnmerged.php +++ b/src/Processors/CleanUnmerged.php @@ -20,9 +20,9 @@ public function __invoke(Analysis $analysis) /** @var OA\AbstractAnnotation $annotation */ foreach ($analysis->annotations as $annotation) { if (property_exists($annotation, '_unmerged')) { - foreach ($annotation->_unmerged as $i => $item) { + foreach ($annotation->_unmerged as $ii => $item) { if ($merged->contains($item)) { - unset($annotation->_unmerged[$i]); // Property was merged + unset($annotation->_unmerged[$ii]); // Property was merged } } } diff --git a/src/Processors/Concerns/DocblockTrait.php b/src/Processors/Concerns/DocblockTrait.php index 6aff0467a..dd0b32cbd 100644 --- a/src/Processors/Concerns/DocblockTrait.php +++ b/src/Processors/Concerns/DocblockTrait.php @@ -95,8 +95,8 @@ public function extractContent(?string $docblock, ?array &$tags = null): string $comment = preg_split('/(\n|\r\n)/', (string) $docblock); $comment[0] = preg_replace('/[ \t]*\\/\*\*/', '', $comment[0]); // strip '/**' - $i = count($comment) - 1; - $comment[$i] = preg_replace('/\*\/[ \t]*$/', '', $comment[$i]); // strip '*/' + $ii = count($comment) - 1; + $comment[$ii] = preg_replace('/\*\/[ \t]*$/', '', $comment[$ii]); // strip '*/' $lines = []; $append = false; $skip = false; @@ -110,8 +110,8 @@ public function extractContent(?string $docblock, ?array &$tags = null): string continue; } if ($append) { - $i = count($lines) - 1; - $lines[$i] = substr($lines[$i], 0, -1) . $line; + $ii = count($lines) - 1; + $lines[$ii] = substr($lines[$ii], 0, -1) . $line; } else { $lines[] = $line; } diff --git a/src/Processors/ExpandClasses.php b/src/Processors/ExpandClasses.php index 6ede741c8..9ba659736 100644 --- a/src/Processors/ExpandClasses.php +++ b/src/Processors/ExpandClasses.php @@ -33,7 +33,7 @@ public function __invoke(Analysis $analysis) foreach ($ancestors as $ancestor) { $ancestorSchema = $analysis->getSchemaForSource($ancestor['context']->fullyQualifiedName($ancestor['class'])); if ($ancestorSchema) { - $refPath = !Generator::isDefault($ancestorSchema->schema) ? $ancestorSchema->schema : $ancestor['class']; + $refPath = Generator::isDefault($ancestorSchema->schema) ? $ancestor['class'] : $ancestorSchema->schema; $this->inheritFrom($analysis, $schema, $ancestorSchema, $refPath, $ancestor['context']); // one ancestor is enough diff --git a/src/Processors/ExpandEnums.php b/src/Processors/ExpandEnums.php index cbae7a0f2..e890d929d 100644 --- a/src/Processors/ExpandEnums.php +++ b/src/Processors/ExpandEnums.php @@ -37,7 +37,7 @@ protected function expandContextEnum(Analysis $analysis): void foreach ($schemas as $schema) { if ($schema->_context->is('enum')) { $re = new \ReflectionEnum($schema->_context->fullyQualifiedName($schema->_context->enum)); - $schema->schema = !Generator::isDefault($schema->schema) ? $schema->schema : $re->getShortName(); + $schema->schema = Generator::isDefault($schema->schema) ? $re->getShortName() : $schema->schema; $schemaType = $schema->type; $enumType = null; @@ -99,11 +99,7 @@ protected function expandSchemaEnum(Analysis $analysis): void $enums = []; foreach ($cases as $enum) { - if (is_a($enum, \UnitEnum::class)) { - $enums[] = $enum->value ?? $enum->name; - } else { - $enums[] = $enum; - } + $enums[] = is_a($enum, \UnitEnum::class) ? $enum->value ?? $enum->name : $enum; } $schema->enum = $enums; diff --git a/src/Processors/ExpandInterfaces.php b/src/Processors/ExpandInterfaces.php index 8bcc3c25a..2d89ce1b0 100644 --- a/src/Processors/ExpandInterfaces.php +++ b/src/Processors/ExpandInterfaces.php @@ -43,7 +43,7 @@ public function __invoke(Analysis $analysis) $interfaceName = $interface['context']->fullyQualifiedName($interface['interface']); $interfaceSchema = $analysis->getSchemaForSource($interfaceName); if ($interfaceSchema) { - $refPath = !Generator::isDefault($interfaceSchema->schema) ? $interfaceSchema->schema : $interface['interface']; + $refPath = Generator::isDefault($interfaceSchema->schema) ? $interface['interface'] : $interfaceSchema->schema; $this->inheritFrom($analysis, $schema, $interfaceSchema, $refPath, $interface['context']); } else { $this->mergeMethods($schema, $interface, $existing); diff --git a/src/Processors/ExpandTraits.php b/src/Processors/ExpandTraits.php index cd1b4aca7..5cd7e2a45 100644 --- a/src/Processors/ExpandTraits.php +++ b/src/Processors/ExpandTraits.php @@ -32,7 +32,7 @@ public function __invoke(Analysis $analysis) foreach ($traits as $trait) { $traitSchema = $analysis->getSchemaForSource($trait['context']->fullyQualifiedName($trait['trait'])); if ($traitSchema) { - $refPath = !Generator::isDefault($traitSchema->schema) ? $traitSchema->schema : $trait['trait']; + $refPath = Generator::isDefault($traitSchema->schema) ? $trait['trait'] : $traitSchema->schema; $this->inheritFrom($analysis, $schema, $traitSchema, $refPath, $trait['context']); } else { $this->mergeMethods($schema, $trait, $existing); @@ -50,7 +50,7 @@ public function __invoke(Analysis $analysis) foreach ($traits as $trait) { $traitSchema = $analysis->getSchemaForSource($trait['context']->fullyQualifiedName($trait['trait'])); if ($traitSchema) { - $refPath = !Generator::isDefault($traitSchema->schema) ? $traitSchema->schema : $trait['trait']; + $refPath = Generator::isDefault($traitSchema->schema) ? $trait['trait'] : $traitSchema->schema; $this->inheritFrom($analysis, $schema, $traitSchema, $refPath, $trait['context']); } else { $this->mergeMethods($schema, $trait, $existing); diff --git a/src/Processors/OperationId.php b/src/Processors/OperationId.php index 0e799b079..84d7ac60b 100644 --- a/src/Processors/OperationId.php +++ b/src/Processors/OperationId.php @@ -15,7 +15,7 @@ */ class OperationId implements ProcessorInterface { - protected $hash; + protected bool $hash; public function __construct(bool $hash = true) { @@ -57,11 +57,7 @@ public function __invoke(Analysis $analysis) $operationId = null; if ($source) { $method = $context->method ? ('::' . $context->method) : ''; - if ($context->namespace) { - $operationId = $context->namespace . '\\' . $source . $method; - } else { - $operationId = $source . $method; - } + $operationId = $context->namespace ? $context->namespace . '\\' . $source . $method : $source . $method; } elseif ($context->method) { $operationId = $context->method; } diff --git a/src/Serializer.php b/src/Serializer.php index 739461585..94baa9c3a 100644 --- a/src/Serializer.php +++ b/src/Serializer.php @@ -90,7 +90,7 @@ public function deserializeFile(string $filename, string $format = 'json', strin $contents = file_get_contents($filename); $ext = pathinfo($filename, PATHINFO_EXTENSION); - if ('yaml' == $format || in_array($ext, ['yml', 'yaml'])) { + if ('yaml' === $format || in_array($ext, ['yml', 'yaml'])) { $contents = json_encode(Yaml::parse($contents)); } diff --git a/src/Util.php b/src/Util.php index be427b43e..1e7b33f2c 100644 --- a/src/Util.php +++ b/src/Util.php @@ -34,13 +34,13 @@ public static function getRelativePath(string $fullPath, $basePaths): string } else { // an array of paths foreach ($basePaths as $basePath) { $relativePath = self::removePrefix($fullPath, $basePath); - if (!empty($relativePath)) { + if ($relativePath !== null && $relativePath !== '' && $relativePath !== '0') { break; } } } - return !empty($relativePath) ? trim($relativePath, '/') : $fullPath; + return $relativePath === null || $relativePath === '' || $relativePath === '0' ? $fullPath : trim($relativePath, '/'); } /** @@ -48,7 +48,7 @@ public static function getRelativePath(string $fullPath, $basePaths): string */ private static function removePrefix(string $str, string $prefix): ?string { - if (substr($str, 0, strlen($prefix)) == $prefix) { + if (substr($str, 0, strlen($prefix)) === $prefix) { return substr($str, strlen($prefix)); }