Skip to content

Commit f604bd8

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

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

@@ -344,7 +340,7 @@
344340
foreach ($value as $route) {
345341
$routeName = $route['name'];
346342

347-
$postfix = array_key_exists('postfix', $route) ? $route['postfix'] : null;
343+
$postfix = $route['postfix'] ?? null;
348344
$verb = array_key_exists('verb', $route) ? $route['verb'] : 'GET';
349345
$requirements = array_key_exists('requirements', $route) ? $route['requirements'] : [];
350346
$defaults = array_key_exists('defaults', $route) ? $route['defaults'] : [];
@@ -364,7 +360,7 @@
364360
}
365361

366362
$methodName = lcfirst(str_replace('_', '', ucwords(explode('#', (string)$routeName)[1], '_')));
367-
if ($methodName == 'preflightedCors') {
363+
if ($methodName === 'preflightedCors') {
368364
continue;
369365
}
370366

@@ -384,7 +380,7 @@
384380

385381
$controllerScopes = Helpers::getOpenAPIAttributeScopes($controllerClass, $routeName);
386382
if (Helpers::classMethodHasAnnotationOrAttribute($controllerClass, 'IgnoreOpenAPI')) {
387-
if (count($controllerScopes) === 0 || (in_array('ignore', $controllerScopes, true) && count($controllerScopes) === 1)) {
383+
if ($controllerScopes === [] || (in_array('ignore', $controllerScopes, true) && count($controllerScopes) === 1)) {
388384
Logger::debug($routeName, "Controller '" . $controllerName . "' ignored because of IgnoreOpenAPI attribute");
389385
continue;
390386
}
@@ -403,24 +399,24 @@
403399

404400
$tagName = implode('_', array_map(fn (string $s) => strtolower($s), Helpers::splitOnUppercaseFollowedByNonUppercase($controllerName)));
405401
$doc = $controllerClass->getDocComment()?->getText();
406-
if ($doc != null && count(array_filter($tags, fn (array $tag): bool => $tag['name'] == $tagName)) == 0) {
402+
if ($doc != null && count(array_filter($tags, fn (array $tag): bool => $tag['name'] === $tagName)) == 0) {
407403
$classDescription = [];
408404

409405
$docNodes = $phpDocParser->parse(new TokenIterator($lexer->tokenize($doc)))->children;
410406
foreach ($docNodes as $docNode) {
411407
if ($docNode instanceof PhpDocTextNode) {
412408
$block = Helpers::cleanDocComment($docNode->text);
413-
if ($block == '') {
409+
if ($block === '') {
414410
continue;
415411
}
416412
$classDescription[] = $block;
417413
}
418414
}
419415

420-
if (count($classDescription) > 0) {
416+
if ($classDescription !== []) {
421417
$tags[] = [
422418
'name' => $tagName,
423-
'description' => join("\n", $classDescription),
419+
'description' => implode("\n", $classDescription),
424420
];
425421
}
426422
}
@@ -448,7 +444,7 @@
448444
$scopes = Helpers::getOpenAPIAttributeScopes($classMethod, $routeName);
449445

450446
if ($isIgnored) {
451-
if (count($scopes) === 0 || (in_array('ignore', $scopes, true) && count($scopes) === 1)) {
447+
if ($scopes === [] || (in_array('ignore', $scopes, true) && count($scopes) === 1)) {
452448
Logger::debug($routeName, 'Route ignored because of IgnoreOpenAPI attribute');
453449
continue;
454450
}
@@ -497,7 +493,7 @@
497493
}
498494

499495
$classMethodInfo = ControllerMethod::parse($routeName, $definitions, $methodFunction, $isAdmin, $isDeprecated, $isPasswordConfirmation);
500-
if (count($classMethodInfo->returns) > 0) {
496+
if ($classMethodInfo->returns !== []) {
501497
Logger::error($routeName, 'Returns an invalid response');
502498
continue;
503499
}
@@ -521,7 +517,7 @@
521517
$docStatusCodes = array_map(fn (ControllerMethodResponse $response): int => $response->statusCode, array_filter($classMethodInfo->responses, fn (?ControllerMethodResponse $response): bool => $response != null));
522518
$missingDocStatusCodes = array_unique(array_filter(array_diff($codeStatusCodes, $docStatusCodes), fn (int $code): bool => $code < 500));
523519

524-
if (count($missingDocStatusCodes) > 0) {
520+
if ($missingDocStatusCodes !== []) {
525521
Logger::error($routeName, 'Returns undocumented status codes: ' . implode(', ', $missingDocStatusCodes));
526522
continue;
527523
}
@@ -587,7 +583,7 @@
587583

588584
foreach ($urlParameters as $urlParameter) {
589585
$matchingParameters = array_filter($route->controllerMethod->parameters, fn (ControllerMethodParameter $param): bool => $param->name == $urlParameter);
590-
$requirement = array_key_exists($urlParameter, $route->requirements) ? $route->requirements[$urlParameter] : null;
586+
$requirement = $route->requirements[$urlParameter] ?? null;
591587
if (count($matchingParameters) == 1) {
592588
$parameter = $matchingParameters[array_keys($matchingParameters)[0]];
593589
if ($parameter?->methodParameter == null && ($route->requirements == null || !array_key_exists($urlParameter, $route->requirements))) {
@@ -609,7 +605,7 @@
609605
$requirement = '^' . $requirement;
610606
}
611607
if (!str_ends_with((string)$requirement, '$')) {
612-
$requirement = $requirement . '$';
608+
$requirement .= '$';
613609
}
614610
}
615611

@@ -671,7 +667,7 @@
671667

672668
$mergedResponses = [];
673669
foreach (array_unique(array_map(fn (ControllerMethodResponse $response): int => $response->statusCode, array_filter($route->controllerMethod->responses, fn (?ControllerMethodResponse $response): bool => $response != null))) as $statusCode) {
674-
if ($firstStatusCode && count($mergedResponses) > 0) {
670+
if ($firstStatusCode && $mergedResponses !== []) {
675671
break;
676672
}
677673

@@ -685,14 +681,14 @@
685681

686682
$mergedContentTypeResponses = [];
687683
foreach (array_unique(array_map(fn (ControllerMethodResponse $response): ?string => $response->contentType, array_filter($statusCodeResponses, fn (ControllerMethodResponse $response): bool => $response->contentType != null))) as $contentType) {
688-
if ($firstContentType && count($mergedContentTypeResponses) > 0) {
684+
if ($firstContentType && $mergedContentTypeResponses !== []) {
689685
break;
690686
}
691687

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

695-
$hasEmpty = count(array_filter($contentTypeResponses, fn (ControllerMethodResponse $response): bool => $response->type == null)) > 0;
691+
$hasEmpty = array_filter($contentTypeResponses, fn (ControllerMethodResponse $response): bool => $response->type == null) !== [];
696692
$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)));
697693
if (count($uniqueResponses) == 1) {
698694
if ($hasEmpty) {
@@ -716,7 +712,7 @@
716712
$response = [
717713
'description' => array_key_exists($statusCode, $route->controllerMethod->responseDescription) ? $route->controllerMethod->responseDescription[$statusCode] : '',
718714
];
719-
if (count($headers) > 0) {
715+
if ($headers !== []) {
720716
$response['headers'] = array_combine(
721717
array_keys($headers),
722718
array_map(
@@ -727,7 +723,7 @@
727723
),
728724
);
729725
}
730-
if (count($mergedContentTypeResponses) > 0) {
726+
if ($mergedContentTypeResponses !== []) {
731727
$response['content'] = $mergedContentTypeResponses;
732728
}
733729
$mergedResponses[$statusCode] = $response;
@@ -751,7 +747,7 @@
751747
if ($route->controllerMethod->summary !== null) {
752748
$operation['summary'] = $route->controllerMethod->summary;
753749
}
754-
if (count($route->controllerMethod->description) > 0) {
750+
if ($route->controllerMethod->description !== []) {
755751
$operation['description'] = implode("\n", $route->controllerMethod->description);
756752
}
757753
if ($route->controllerMethod->isDeprecated) {
@@ -762,7 +758,7 @@
762758
}
763759
$operation['security'] = $security;
764760

765-
if (count($bodyParameters) > 0) {
761+
if ($bodyParameters !== []) {
766762
$requiredBodyParameters = [];
767763

768764
foreach ($bodyParameters as $bodyParameter) {
@@ -772,7 +768,7 @@
772768
}
773769
}
774770

775-
$required = count($requiredBodyParameters) > 0;
771+
$required = $requiredBodyParameters !== [];
776772

777773
$schema = [
778774
'type' => 'object',
@@ -823,7 +819,7 @@
823819
],
824820
];
825821
}
826-
if (count($parameters) > 0) {
822+
if ($parameters !== []) {
827823
$operation['parameters'] = $parameters;
828824
}
829825

@@ -919,7 +915,7 @@
919915

920916
if (!$hasSingleScope) {
921917
$scopePaths['full'] = [];
922-
} elseif (count($scopePaths) === 0) {
918+
} elseif ($scopePaths === []) {
923919
if (isset($schemas['Capabilities']) || isset($schemas['PublicCapabilities'])) {
924920
Logger::debug('app', 'Generating default scope without routes to populate capabilities');
925921
$scopePaths['default'] = [];
@@ -988,7 +984,7 @@
988984
$scopedSchemas['PublicCapabilities'] = $schemas['PublicCapabilities'];
989985
}
990986

991-
if (count($scopedSchemas) === 0) {
987+
if ($scopedSchemas === []) {
992988
$scopedSchemas = new stdClass();
993989
} else {
994990
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)