Skip to content

Commit 4b2d0f6

Browse files
committed
refactor: Improve the code quality
Signed-off-by: provokateurin <[email protected]>
1 parent cedea35 commit 4b2d0f6

File tree

7 files changed

+54
-63
lines changed

7 files changed

+54
-63
lines changed

generate-spec.php

Lines changed: 27 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -84,11 +84,7 @@
8484

8585
$appIsCore = false;
8686
$appID = (string)$xml->id;
87-
if ($xml->namespace) {
88-
$readableAppID = (string)$xml->namespace;
89-
} else {
90-
$readableAppID = Helpers::generateReadableAppID($appID);
91-
}
87+
$readableAppID = $xml->namespace ? (string)$xml->namespace : Helpers::generateReadableAppID($appID);
9288
$appSummary = (string)$xml->summary;
9389
$appVersion = (string)$xml->version;
9490
$appLicence = (string)$xml->licence;
@@ -182,8 +178,8 @@
182178
* @var Class_ $node
183179
*/
184180
foreach ($nodeFinder->findInstanceOf($astParser->parse(file_get_contents($path)), Class_::class) as $node) {
185-
$implementsCapability = count(array_filter($node->implements, fn (Name $name): bool => $name->getLast() == 'ICapability')) > 0;
186-
$implementsPublicCapability = count(array_filter($node->implements, fn (Name $name): bool => $name->getLast() == 'IPublicCapability')) > 0;
181+
$implementsCapability = array_filter($node->implements, fn (Name $name): bool => $name->getLast() === 'ICapability') !== [];
182+
$implementsPublicCapability = array_filter($node->implements, fn (Name $name): bool => $name->getLast() === 'IPublicCapability') !== [];
187183
if (!$implementsCapability && !$implementsPublicCapability) {
188184
continue;
189185
}
@@ -327,7 +323,7 @@
327323
}
328324
}
329325

330-
if (count($parsedRoutes) === 0) {
326+
if ($parsedRoutes === []) {
331327
Logger::warning('Routes', 'No routes were loaded');
332328
}
333329

@@ -343,7 +339,7 @@
343339
foreach ($value as $route) {
344340
$routeName = $route['name'];
345341

346-
$postfix = array_key_exists('postfix', $route) ? $route['postfix'] : null;
342+
$postfix = $route['postfix'] ?? null;
347343
$verb = array_key_exists('verb', $route) ? $route['verb'] : 'GET';
348344
$requirements = array_key_exists('requirements', $route) ? $route['requirements'] : [];
349345
$defaults = array_key_exists('defaults', $route) ? $route['defaults'] : [];
@@ -358,7 +354,7 @@
358354
$url = $pathPrefix . $root . $url;
359355

360356
$methodName = lcfirst(str_replace('_', '', ucwords(explode('#', (string)$routeName)[1], '_')));
361-
if ($methodName == 'preflightedCors') {
357+
if ($methodName === 'preflightedCors') {
362358
continue;
363359
}
364360

@@ -390,7 +386,7 @@
390386

391387
$controllerScopes = Helpers::getOpenAPIAttributeScopes($controllerClass, $routeName);
392388
if (Helpers::classMethodHasAnnotationOrAttribute($controllerClass, 'IgnoreOpenAPI')) {
393-
if (count($controllerScopes) === 0 || (in_array('ignore', $controllerScopes, true) && count($controllerScopes) === 1)) {
389+
if ($controllerScopes === [] || (in_array('ignore', $controllerScopes, true) && count($controllerScopes) === 1)) {
394390
Logger::debug($routeName, "Controller '" . $controllerName . "' ignored because of IgnoreOpenAPI attribute");
395391
continue;
396392
}
@@ -409,24 +405,24 @@
409405

410406
$tagName = implode('_', array_map(fn (string $s) => strtolower($s), Helpers::splitOnUppercaseFollowedByNonUppercase($controllerName)));
411407
$doc = $controllerClass->getDocComment()?->getText();
412-
if ($doc != null && count(array_filter($tags, fn (array $tag): bool => $tag['name'] == $tagName)) == 0) {
408+
if ($doc != null && count(array_filter($tags, fn (array $tag): bool => $tag['name'] === $tagName)) == 0) {
413409
$classDescription = [];
414410

415411
$docNodes = $phpDocParser->parse(new TokenIterator($lexer->tokenize($doc)))->children;
416412
foreach ($docNodes as $docNode) {
417413
if ($docNode instanceof PhpDocTextNode) {
418414
$block = Helpers::cleanDocComment($docNode->text);
419-
if ($block == '') {
415+
if ($block === '') {
420416
continue;
421417
}
422418
$classDescription[] = $block;
423419
}
424420
}
425421

426-
if (count($classDescription) > 0) {
422+
if ($classDescription !== []) {
427423
$tags[] = [
428424
'name' => $tagName,
429-
'description' => join("\n", $classDescription),
425+
'description' => implode("\n", $classDescription),
430426
];
431427
}
432428
}
@@ -454,7 +450,7 @@
454450
$scopes = Helpers::getOpenAPIAttributeScopes($classMethod, $routeName);
455451

456452
if ($isIgnored) {
457-
if (count($scopes) === 0 || (in_array('ignore', $scopes, true) && count($scopes) === 1)) {
453+
if ($scopes === [] || (in_array('ignore', $scopes, true) && count($scopes) === 1)) {
458454
Logger::debug($routeName, 'Route ignored because of IgnoreOpenAPI attribute');
459455
continue;
460456
}
@@ -503,7 +499,7 @@
503499
}
504500

505501
$classMethodInfo = ControllerMethod::parse($routeName, $definitions, $methodFunction, $isAdmin, $isDeprecated, $isPasswordConfirmation);
506-
if (count($classMethodInfo->returns) > 0) {
502+
if ($classMethodInfo->returns !== []) {
507503
Logger::error($routeName, 'Returns an invalid response');
508504
continue;
509505
}
@@ -527,7 +523,7 @@
527523
$docStatusCodes = array_map(fn (ControllerMethodResponse $response): int => $response->statusCode, array_filter($classMethodInfo->responses, fn (?ControllerMethodResponse $response): bool => $response != null));
528524
$missingDocStatusCodes = array_unique(array_filter(array_diff($codeStatusCodes, $docStatusCodes), fn (int $code): bool => $code < 500));
529525

530-
if (count($missingDocStatusCodes) > 0) {
526+
if ($missingDocStatusCodes !== []) {
531527
Logger::error($routeName, 'Returns undocumented status codes: ' . implode(', ', $missingDocStatusCodes));
532528
continue;
533529
}
@@ -593,7 +589,7 @@
593589

594590
foreach ($urlParameters as $urlParameter) {
595591
$matchingParameters = array_filter($route->controllerMethod->parameters, fn (ControllerMethodParameter $param): bool => $param->name == $urlParameter);
596-
$requirement = array_key_exists($urlParameter, $route->requirements) ? $route->requirements[$urlParameter] : null;
592+
$requirement = $route->requirements[$urlParameter] ?? null;
597593
if (count($matchingParameters) == 1) {
598594
$parameter = $matchingParameters[array_keys($matchingParameters)[0]];
599595
if ($parameter?->methodParameter == null && ($route->requirements == null || !array_key_exists($urlParameter, $route->requirements))) {
@@ -615,7 +611,7 @@
615611
$requirement = '^' . $requirement;
616612
}
617613
if (!str_ends_with((string)$requirement, '$')) {
618-
$requirement = $requirement . '$';
614+
$requirement .= '$';
619615
}
620616
}
621617

@@ -677,7 +673,7 @@
677673

678674
$mergedResponses = [];
679675
foreach (array_unique(array_map(fn (ControllerMethodResponse $response): int => $response->statusCode, array_filter($route->controllerMethod->responses, fn (?ControllerMethodResponse $response): bool => $response != null))) as $statusCode) {
680-
if ($firstStatusCode && count($mergedResponses) > 0) {
676+
if ($firstStatusCode && $mergedResponses !== []) {
681677
break;
682678
}
683679

@@ -691,14 +687,14 @@
691687

692688
$mergedContentTypeResponses = [];
693689
foreach (array_unique(array_map(fn (ControllerMethodResponse $response): ?string => $response->contentType, array_filter($statusCodeResponses, fn (ControllerMethodResponse $response): bool => $response->contentType != null))) as $contentType) {
694-
if ($firstContentType && count($mergedContentTypeResponses) > 0) {
690+
if ($firstContentType && $mergedContentTypeResponses !== []) {
695691
break;
696692
}
697693

698694
/** @var ControllerMethodResponse[] $contentTypeResponses */
699695
$contentTypeResponses = array_values(array_filter($statusCodeResponses, fn (ControllerMethodResponse $response): bool => $response->contentType == $contentType));
700696

701-
$hasEmpty = count(array_filter($contentTypeResponses, fn (ControllerMethodResponse $response): bool => $response->type == null)) > 0;
697+
$hasEmpty = array_filter($contentTypeResponses, fn (ControllerMethodResponse $response): bool => $response->type == null) !== [];
702698
$uniqueResponses = array_values(array_intersect_key($contentTypeResponses, array_unique(array_map(fn (ControllerMethodResponse $response): array|\stdClass => $response->type->toArray(), array_filter($contentTypeResponses, fn (ControllerMethodResponse $response): bool => $response->type != null)), SORT_REGULAR)));
703699
if (count($uniqueResponses) == 1) {
704700
if ($hasEmpty) {
@@ -722,7 +718,7 @@
722718
$response = [
723719
'description' => array_key_exists($statusCode, $route->controllerMethod->responseDescription) ? $route->controllerMethod->responseDescription[$statusCode] : '',
724720
];
725-
if (count($headers) > 0) {
721+
if ($headers !== []) {
726722
$response['headers'] = array_combine(
727723
array_keys($headers),
728724
array_map(
@@ -733,7 +729,7 @@
733729
),
734730
);
735731
}
736-
if (count($mergedContentTypeResponses) > 0) {
732+
if ($mergedContentTypeResponses !== []) {
737733
$response['content'] = $mergedContentTypeResponses;
738734
}
739735
$mergedResponses[$statusCode] = $response;
@@ -757,7 +753,7 @@
757753
if ($route->controllerMethod->summary !== null) {
758754
$operation['summary'] = $route->controllerMethod->summary;
759755
}
760-
if (count($route->controllerMethod->description) > 0) {
756+
if ($route->controllerMethod->description !== []) {
761757
$operation['description'] = implode("\n", $route->controllerMethod->description);
762758
}
763759
if ($route->controllerMethod->isDeprecated) {
@@ -768,7 +764,7 @@
768764
}
769765
$operation['security'] = $security;
770766

771-
if (count($bodyParameters) > 0) {
767+
if ($bodyParameters !== []) {
772768
$requiredBodyParameters = [];
773769

774770
foreach ($bodyParameters as $bodyParameter) {
@@ -778,7 +774,7 @@
778774
}
779775
}
780776

781-
$required = count($requiredBodyParameters) > 0;
777+
$required = $requiredBodyParameters !== [];
782778

783779
$schema = [
784780
'type' => 'object',
@@ -829,7 +825,7 @@
829825
],
830826
];
831827
}
832-
if (count($parameters) > 0) {
828+
if ($parameters !== []) {
833829
$operation['parameters'] = $parameters;
834830
}
835831

@@ -925,7 +921,7 @@
925921

926922
if (!$hasSingleScope) {
927923
$scopePaths['full'] = [];
928-
} elseif (count($scopePaths) === 0) {
924+
} elseif ($scopePaths === []) {
929925
if (isset($schemas['Capabilities']) || isset($schemas['PublicCapabilities'])) {
930926
Logger::debug('app', 'Generating default scope without routes to populate capabilities');
931927
$scopePaths['default'] = [];
@@ -994,7 +990,7 @@
994990
$scopedSchemas['PublicCapabilities'] = $schemas['PublicCapabilities'];
995991
}
996992

997-
if (count($scopedSchemas) === 0) {
993+
if ($scopedSchemas === []) {
998994
$scopedSchemas = new stdClass();
999995
} else {
1000996
ksort($scopedSchemas);

merge-specs.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ function rewriteSchemaNames(array $spec): array {
129129
$schemas = $spec['components']['schemas'];
130130
$readableAppID = Helpers::generateReadableAppID($spec['info']['title']);
131131
return array_combine(
132-
array_map(fn (string $key): string => $key == 'OCSMeta' ? $key : $readableAppID . $key, array_keys($schemas)),
132+
array_map(fn (string $key): string => $key === 'OCSMeta' ? $key : $readableAppID . $key, array_keys($schemas)),
133133
array_values($schemas),
134134
);
135135
}
@@ -164,7 +164,8 @@ function rewriteOperations(array $spec): array {
164164
$operation['responses'] = [$value => $operation['responses'][$value]];
165165
}
166166
if (array_key_exists('security', $operation)) {
167-
for ($i = 0; $i < count($operation['security']); $i++) {
167+
$counter = count($operation['security']);
168+
for ($i = 0; $i < $counter; $i++) {
168169
if (count($operation['security'][$i]) == 0) {
169170
$operation['security'][$i] = new stdClass(); // When reading {} will be converted to [], so we have to fix it
170171
}

rector.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
->withPhpSets()
1616
->withPreparedSets(
1717
deadCode: true,
18+
codeQuality: true,
1819
typeDeclarations: true,
1920
strictBooleans: true,
2021
);

src/ControllerMethod.php

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,14 @@ public static function parse(string $context, array $definitions, ClassMethod $m
5454
foreach ($docNodes as $docNode) {
5555
if ($docNode instanceof PhpDocTextNode) {
5656
$block = Helpers::cleanDocComment($docNode->text);
57-
if ($block == '') {
57+
if ($block === '') {
5858
continue;
5959
}
60-
$pattern = '/([0-9]{3}): /';
60+
$pattern = '/(\d{3}): /';
6161
if (preg_match($pattern, $block)) {
6262
$parts = preg_split($pattern, $block, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
63-
for ($i = 0; $i < count($parts); $i += 2) {
63+
$counter = count($parts);
64+
for ($i = 0; $i < $counter; $i += 2) {
6465
$statusCode = intval($parts[$i]);
6566
$responseDescriptions[$statusCode] = trim($parts[$i + 1]);
6667
}
@@ -109,7 +110,7 @@ public static function parse(string $context, array $definitions, ClassMethod $m
109110

110111
if (!$allowMissingDocs) {
111112
foreach (array_unique(array_map(fn (ControllerMethodResponse $response): int => $response->statusCode, array_filter($responses, fn (?ControllerMethodResponse $response): bool => $response != null))) as $statusCode) {
112-
if ($statusCode < 500 && (!array_key_exists($statusCode, $responseDescriptions) || $responseDescriptions[$statusCode] == '')) {
113+
if ($statusCode < 500 && (!array_key_exists($statusCode, $responseDescriptions) || $responseDescriptions[$statusCode] === '')) {
113114
Logger::error($context, 'Missing description for status code ' . $statusCode);
114115
}
115116
}
@@ -136,7 +137,7 @@ public static function parse(string $context, array $definitions, ClassMethod $m
136137
}
137138
}
138139

139-
if ($paramTag !== null && $psalmParamTag !== null) {
140+
if ($paramTag instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode && $psalmParamTag instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode) {
140141
// Use all the type information from @psalm-param because it is more specific,
141142
// but pull the description from @param and @psalm-param because usually only one of them has it.
142143
if ($psalmParamTag->description !== '') {
@@ -176,10 +177,10 @@ public static function parse(string $context, array $definitions, ClassMethod $m
176177
}
177178

178179
$param = new ControllerMethodParameter($context, $definitions, $methodParameterName, $methodParameter, $type);
179-
} elseif ($psalmParamTag !== null) {
180+
} elseif ($psalmParamTag instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode) {
180181
$type = OpenApiType::resolve($context . ': @param: ' . $methodParameterName, $definitions, $psalmParamTag);
181182
$param = new ControllerMethodParameter($context, $definitions, $methodParameterName, $methodParameter, $type);
182-
} elseif ($paramTag !== null) {
183+
} elseif ($paramTag instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode) {
183184
$type = OpenApiType::resolve($context . ': @param: ' . $methodParameterName, $definitions, $paramTag);
184185
$param = new ControllerMethodParameter($context, $definitions, $methodParameterName, $methodParameter, $type);
185186
} elseif ($allowMissingDocs) {

src/Helpers.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ public static function mergeSchemas(array $schemas): mixed {
7373
if (!in_array(true, array_map(fn ($schema): bool => is_array($schema), $schemas))) {
7474
$results = array_values(array_unique($schemas));
7575
if (count($results) > 1) {
76-
throw new Exception('Incompatibles types: ' . join(', ', $results));
76+
throw new Exception('Incompatibles types: ' . implode(', ', $results));
7777
}
7878
return $results[0];
7979
}
@@ -205,7 +205,7 @@ public static function getOpenAPIAttributeScopes(ClassMethod|Class_|Node $node,
205205
foreach ($node->attrGroups as $attrGroup) {
206206
foreach ($attrGroup->attrs as $attr) {
207207
if ($attr->name->getLast() === self::OPENAPI_ATTRIBUTE_CLASSNAME) {
208-
if (empty($attr->args)) {
208+
if ($attr->args === []) {
209209
$scopes[] = 'default';
210210
continue;
211211
}
@@ -230,7 +230,7 @@ public static function getOpenAPIAttributeTagsByScope(ClassMethod|Class_|Node $n
230230
foreach ($node->attrGroups as $attrGroup) {
231231
foreach ($attrGroup->attrs as $attr) {
232232
if ($attr->name->getLast() === self::OPENAPI_ATTRIBUTE_CLASSNAME) {
233-
if (empty($attr->args)) {
233+
if ($attr->args === []) {
234234
$tags[$defaultScope] = [$defaultTag];
235235
continue;
236236
}

0 commit comments

Comments
 (0)