Skip to content

Fix https://github.com/slevomat/coding-standard/issues/1768 non-empty-lowercase-string, non-empty-array #1769

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
15 changes: 11 additions & 4 deletions SlevomatCodingStandard/Helpers/AnnotationHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,14 @@ public static function isAnnotationUseless(
);
}

if ($annotationType instanceof UnionTypeNode) {
return false;
}

if ($annotationType instanceof IntersectionTypeNode) {
return false;
}

if ($annotationType instanceof ObjectShapeNode) {
return false;
}
Expand Down Expand Up @@ -293,11 +301,10 @@ public static function isAnnotationUseless(
return $enableStandaloneNullTrueFalseTypeHints;
}

if (in_array(
if (TypeHintHelper::isSimpleUnofficialTypeHints(
strtolower($annotationType->name),
['class-string', 'trait-string', 'callable-string', 'numeric-string', 'non-empty-string', 'non-falsy-string', 'literal-string', 'positive-int', 'negative-int'],
true,
)) {
) && !in_array($annotationType->name, ['object', 'mixed'], true)
) {
return false;
}
}
Expand Down
79 changes: 74 additions & 5 deletions SlevomatCodingStandard/Helpers/AnnotationTypeHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace SlevomatCodingStandard\Helpers;

use InvalidArgumentException;
use PHP_CodeSniffer\Files\File;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
Expand All @@ -21,7 +22,10 @@
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
use function count;
use function get_class;
use function in_array;
use function preg_match;
use function sprintf;
use function strtolower;

/**
Expand Down Expand Up @@ -291,7 +295,16 @@ public static function getTypeHintFromOneType(
return 'array';
}

return $genericName;
if ((bool) preg_match(
'/^\\\\?[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*(?:\\\\[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)*$/',
$genericName,
)) {
return $genericName;
}

throw new InvalidArgumentException(
sprintf('Invalid type "%1$s" of class %2$s given', $genericName, get_class($typeNode)),
);
}

if ($typeNode instanceof IdentifierTypeNode) {
Expand All @@ -303,19 +316,61 @@ public static function getTypeHintFromOneType(
return $enableUnionTypeHint || $enableStandaloneNullTrueFalseTypeHints ? 'false' : 'bool';
}

if (in_array(strtolower($typeNode->name), ['positive-int', 'negative-int'], true)) {
if (in_array(
strtolower($typeNode->name),
['positive-int', 'non-positive-int', 'negative-int', 'non-negative-int', 'literal-int', 'int-mask'],
true,
)) {
return 'int';
}

if (in_array(
strtolower($typeNode->name),
['class-string', 'trait-string', 'callable-string', 'numeric-string', 'non-empty-string', 'non-falsy-string', 'literal-string'],
['callable-array', 'callable-string'],
true,
)) {
return 'callable';
}

// see https://psalm.dev/docs/annotating_code/type_syntax/scalar_types/#class-string-interface-string
if ((bool) preg_match('/-string$/i', $typeNode->name)) {
return 'string';
}

return $typeNode->name;
// here when used literally e.g. as type non-empty-array|null
if (in_array(
strtolower($typeNode->name),
['non-empty-array', 'list', 'non-empty-list'],
true,
)) {
return 'array';
}

if (strtolower($typeNode->name) === 'array-key') {
return $enableUnionTypeHint ? 'int|string' : 'mixed';
}

if (TypeHintHelper::isNeverTypeHint(strtolower($typeNode->name))) {
// don't set a type hint at all if it's not supported by the PHP version yet
return $enableStandaloneNullTrueFalseTypeHints ? 'never' : 'never-returns';
}

if (strtolower($typeNode->name) === 'static') {
// don't set a type hint at all (instead of "self") if it's not supported by the PHP version yet
// use $this to fake it
return $enableUnionTypeHint ? 'static' : '$this';
}

if ((bool) preg_match(
'/^\\\\?[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*(?:\\\\[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)*$/',
$typeNode->name,
)) {
return $typeNode->name;
}

throw new InvalidArgumentException(
sprintf('Invalid type "%1$s" of class %2$s given', $typeNode->name, get_class($typeNode)),
);
}

if ($typeNode instanceof CallableTypeNode) {
Expand All @@ -334,6 +389,11 @@ public static function getTypeHintFromOneType(
return 'object';
}

// $this and self are not strictly equal
if ($typeNode instanceof ThisTypeNode) {
return (string) $typeNode;
}

if ($typeNode instanceof ConstTypeNode) {
if ($typeNode->constExpr instanceof ConstExprIntegerNode) {
return 'int';
Expand All @@ -348,7 +408,16 @@ public static function getTypeHintFromOneType(
}
}

return (string) $typeNode;
if ((bool) preg_match(
'/^\\\\?[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*(?:\\\\[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)*$/',
(string) $typeNode,
)) {
return (string) $typeNode;
}

throw new InvalidArgumentException(
sprintf('Invalid type "%1$s" of class %2$s given', (string) $typeNode, get_class($typeNode)),
);
}

/**
Expand Down
24 changes: 14 additions & 10 deletions SlevomatCodingStandard/Helpers/TypeHintHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use function count;
use function implode;
use function in_array;
use function preg_match;
use function preg_split;
use function sort;
use function sprintf;
Expand Down Expand Up @@ -79,7 +80,7 @@ public static function convertLongSimpleTypeHintToShort(string $typeHint): strin

public static function isUnofficialUnionTypeHint(string $typeHint): bool
{
return in_array($typeHint, ['scalar', 'numeric'], true);
return in_array($typeHint, ['scalar', 'numeric', 'array-key'], true);
}

public static function isVoidTypeHint(string $typeHint): bool
Expand All @@ -99,7 +100,8 @@ public static function convertUnofficialUnionTypeHintToOfficialTypeHints(string
{
$conversion = [
'scalar' => ['string', 'int', 'float', 'bool'],
'numeric' => ['int', 'float'],
'numeric' => ['int', 'float', 'string'],
'array-key' => ['int', 'string'],
];

return $conversion[$typeHint];
Expand Down Expand Up @@ -170,6 +172,7 @@ public static function isSimpleUnofficialTypeHints(string $typeHint): bool
static $simpleUnofficialTypeHints;

if ($simpleUnofficialTypeHints === null) {
// see https://psalm.dev/docs/annotating_code/type_syntax/atomic_types/
$simpleUnofficialTypeHints = [
'null',
'mixed',
Expand All @@ -180,24 +183,25 @@ public static function isSimpleUnofficialTypeHints(string $typeHint): bool
'resource',
'static',
'$this',
'class-string',
'trait-string',
'callable-string',
'numeric-string',
'non-empty-string',
'non-falsy-string',
'literal-string',
'array-key',
'list',
'non-empty-array',
'non-empty-list',
'empty',
'positive-int',
'non-positive-int',
'negative-int',
'non-negative-int',
'literal-int',
'int-mask',
'min',
'max',
'callable-array',
'callable-string',
];
}

return in_array($typeHint, $simpleUnofficialTypeHints, true);
return in_array($typeHint, $simpleUnofficialTypeHints, true) || (bool) preg_match('/-string$/', $typeHint);
}

/**
Expand Down
26 changes: 15 additions & 11 deletions SlevomatCodingStandard/Sniffs/PHP/RequireExplicitAssertionSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use function count;
use function implode;
use function in_array;
use function preg_match;
use function sprintf;
use function strpos;
use function trim;
Expand Down Expand Up @@ -417,8 +418,7 @@ private function createConditions(string $variableName, TypeNode $typeNode): arr

if ($typeNode->name === 'numeric') {
return [
sprintf('\is_int(%s)', $variableName),
sprintf('\is_float(%s)', $variableName),
sprintf('\is_numeric(%s)', $variableName),
];
}

Expand All @@ -432,29 +432,33 @@ private function createConditions(string $variableName, TypeNode $typeNode): arr
}

if ($this->enableIntegerRanges) {
if ($typeNode->name === 'positive-int') {
if ($typeNode->name === 'positive-int' || $typeNode->name === 'non-negative-int') {
return [sprintf('\is_int(%1$s) && %1$s > 0', $variableName)];
}

if ($typeNode->name === 'negative-int') {
if ($typeNode->name === 'negative-int' || $typeNode->name === 'non-positive-int') {
return [sprintf('\is_int(%1$s) && %1$s < 0', $variableName)];
}

if ($typeNode->name === 'literal-int') {
return [sprintf('\is_int(%1$s)', $variableName)];
}
}

if (
$this->enableAdvancedStringTypes
&& in_array($typeNode->name, ['non-empty-string', 'non-falsy-string', 'callable-string', 'numeric-string'], true)
&& (bool) preg_match('/-string$/i', $typeNode->name)
) {
$conditions = [sprintf('\is_string(%s)', $variableName)];

if ($typeNode->name === 'non-empty-string') {
$conditions[] = sprintf("%s !== ''", $variableName);
} elseif ($typeNode->name === 'non-falsy-string') {
$conditions[] = sprintf('(bool) %s === true', $variableName);
} elseif ($typeNode->name === 'callable-string') {
if ($typeNode->name === 'callable-string') {
$conditions[] = sprintf('\is_callable(%s)', $variableName);
} else {
} elseif ($typeNode->name === 'numeric-string') {
$conditions[] = sprintf('\is_numeric(%s)', $variableName);
} elseif ((bool) preg_match('/^non-empty-/i', $typeNode->name)) {
$conditions[] = sprintf("%s !== ''", $variableName);
} elseif ((bool) preg_match('/^non-falsy-/i', $typeNode->name)) {
$conditions[] = sprintf('(bool) %s === true', $variableName);
}

return [implode(' && ', $conditions)];
Expand Down
26 changes: 24 additions & 2 deletions SlevomatCodingStandard/Sniffs/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,35 @@ protected static function checkFile(string $filePath, array $sniffProperties = [
protected static function assertNoSniffErrorInFile(File $phpcsFile): void
{
$errors = $phpcsFile->getErrors();
self::assertEmpty($errors, sprintf('No errors expected, but %d errors found.', count($errors)));
$text = sprintf('No errors expected, but %d errors found:', count($errors));
foreach ($errors as $line => $error) {
$text .= sprintf(
'%sLine %d:%s%s',
PHP_EOL,
$line,
PHP_EOL,
self::getFormattedErrors($error),
);
}

self::assertEmpty($errors, $text);
}

protected static function assertNoSniffWarningInFile(File $phpcsFile): void
{
$warnings = $phpcsFile->getWarnings();
self::assertEmpty($warnings, sprintf('No warnings expected, but %d warnings found.', count($warnings)));
$text = sprintf('No warnings expected, but %d warnings found:', count($warnings));
foreach ($warnings as $line => $warning) {
$text .= sprintf(
'%sLine %d:%s%s',
PHP_EOL,
$line,
PHP_EOL,
self::getFormattedErrors($warning),
);
}

self::assertEmpty($warnings, $text);
}

protected static function assertSniffError(File $phpcsFile, int $line, string $code, ?string $message = null): void
Expand Down
15 changes: 15 additions & 0 deletions tests/Helpers/TypeHintHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@ public static function dataIsSimpleUnofficialTypeHint(): array
['resource', true],
['static', true],
['$this', true],
['array-key', true],
['list', true],
['non-empty-array', true],
['non-empty-list', true],
['empty', true],
['positive-int', true],
['non-positive-int', true],
['negative-int', true],
['non-negative-int', true],
['literal-int', true],
['int-mask', true],
['callable-array', true],
['callable-string', true],

['\Traversable', false],
['int', false],
Expand Down Expand Up @@ -379,6 +392,8 @@ public static function dataTypeHintEqualsAnnotation(): array
return [
['scalar', true],
['unionIsNotIntersection', false],
['fooFunctionWithReturnAnnotationComplexString', false],
['fooFunctionWithReturnAnnotationSimpleHyphenedIterable', false],
];
}

Expand Down
16 changes: 16 additions & 0 deletions tests/Helpers/data/typeHintEqualsAnnotation.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,19 @@ function scalar(): int|bool|float|string
function unionIsNotIntersection(): Foo|Bar
{
}

/**
* @return non-empty-lowercase-string
*/
function fooFunctionWithReturnAnnotationComplexString(): string
{

}

/**
* @return non-empty-array|null
*/
function fooFunctionWithReturnAnnotationSimpleHyphenedIterable(): ?array
{

}
Loading
Loading