Skip to content

📦 Drop some type hint support to improve the way it works #99

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

Merged
merged 1 commit into from
Dec 26, 2019
Merged
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
134 changes: 84 additions & 50 deletions SymfonyCustom/Sniffs/NamingConventions/ValidTypeHintSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,38 @@ class ValidTypeHintSniff implements Sniff
private const CLOSER = '\>|\]|\}|\)';
private const SEPARATOR = '\&|\|';

/*
* <simple> is any non-array, non-generic, non-alternated type, eg `int` or `\Foo`
* <array> is array of <simple>, eg `int[]` or `\Foo[]`
* <generic> is generic collection type, like `array<string, int>`, `Collection<Item>` and more complex like `Collection<int, \null|SubCollection<string>>`
* <type> is <simple>, <array> or <generic> type, like `int`, `bool[]` or `Collection<ItemKey, ItemVal>`
* <types> is one or more types alternated via `|`, like `int|bool[]|Collection<ItemKey, ItemVal>`
*/
private const REGEX_TYPES = '
(?<types>
(?<type>
(?<array>
(?&simple)(\[\])*
)
|
(?<simple>
[@$?]?[\\\\\w]+
)
|
(?<generic>
(?<genericName>(?&simple))
<
(?:(?<genericKey>(?&types)),\s*)?(?<genericValue>(?&types)|(?&generic))
>
)
)
(?:
\|
(?:(?&simple)|(?&array)|(?&generic))
)*
)
';

/**
* @return array
*/
Expand All @@ -37,90 +69,92 @@ public function process(File $phpcsFile, $stackPtr): void
$tokens = $phpcsFile->getTokens();

if (in_array($tokens[$stackPtr]['content'], SniffHelper::TAGS_WITH_TYPE)) {
preg_match(
'`^((?:'
.'(?:'.self::OPENER.'|'.self::MIDDLE.'|'.self::SEPARATOR.')\s+'
.'(?='.self::TEXT.'|'.self::OPENER.'|'.self::MIDDLE.'|'.self::CLOSER.'|'.self::SEPARATOR.')'
.'|'.self::OPENER.'|'.self::MIDDLE.'|'.self::SEPARATOR
.'|(?:'.self::TEXT.'|'.self::CLOSER.')\s+'
.'(?='.self::OPENER.'|'.self::MIDDLE.'|'.self::CLOSER.'|'.self::SEPARATOR.')'
.'|'.self::TEXT.'|'.self::CLOSER.''
.')+)(.*)?`i',
$tokens[($stackPtr + 2)]['content'],
$match
$matchingResult = preg_match(
'{^'.self::REGEX_TYPES.'(?:[ \t].*)?$}sx',
$tokens[$stackPtr + 2]['content'],
$matches
);

if (isset($match[1]) === false) {
return;
}
$content = 1 === $matchingResult ? $matches['types'] : '';
$endOfContent = preg_replace('/'.preg_quote($content, '/').'/', '', $tokens[$stackPtr + 2]['content'], 1);

$type = $match[1];
$suggestedType = $this->getValidTypeName($type);
if ($type !== $suggestedType) {
$suggestedType = $this->getValidTypes($content);

if ($content !== $suggestedType) {
$fix = $phpcsFile->addFixableError(
'For type-hinting in PHPDocs, use %s instead of %s',
$stackPtr + 2,
'Invalid',
[$suggestedType, $type]
[$suggestedType, $content]
);

if ($fix) {
$replacement = $suggestedType;
if (isset($match[2])) {
$replacement .= $match[2];
}

$phpcsFile->fixer->replaceToken($stackPtr + 2, $replacement);
$phpcsFile->fixer->replaceToken($stackPtr + 2, $suggestedType.$endOfContent);
}
}
}
}

/**
* @param string $typeName
* @param string $content
*
* @return array
*/
private function getTypes(string $content): array
{
$types = [];
while ('' !== $content && false !== $content) {
preg_match('{^'.self::REGEX_TYPES.'$}x', $content, $matches);

$types[] = $matches['type'];
$content = substr($content, strlen($matches['type']) + 1);
}

return $types;
}

/**
* @param string $content
*
* @return string
*/
private function getValidTypeName(string $typeName): string
private function getValidTypes(string $content): string
{
$typeNameWithoutSpace = str_replace(' ', '', $typeName);
$parts = preg_split(
'/('.self::OPENER.'|'.self::MIDDLE.'|'.self::CLOSER.'|'.self::SEPARATOR.')/',
$typeNameWithoutSpace,
-1,
PREG_SPLIT_DELIM_CAPTURE
);
$partsNumber = count($parts) - 1;

$validType = '';
for ($i = 0; $i < $partsNumber; $i += 2) {
$validType .= $this->suggestType($parts[$i]);

if ('=>' === $parts[$i + 1]) {
$validType .= ' ';
}
$types = $this->getTypes($content);

foreach ($types as $index => $type) {
$type = str_replace(' ', '', $type);

$validType .= $parts[$i + 1];
preg_match('{^'.self::REGEX_TYPES.'$}x', $type, $matches);
if (isset($matches['generic'])) {
$validType = $this->getValidType($matches['genericName']).'<';

if (preg_match('/'.self::MIDDLE.'/', $parts[$i + 1])) {
$validType .= ' ';
if ('' !== $matches['genericKey']) {
$validType .= $this->getValidTypes($matches['genericKey']).', ';
}

$validType .= $this->getValidTypes($matches['genericValue']).'>';
} else {
$validType = $this->getValidType($type);
}
}

if ('' !== $parts[$partsNumber]) {
$validType .= $this->suggestType($parts[$partsNumber]);
$types[$index] = $validType;
}

return trim($validType);
return implode('|', $types);
}

/**
* @param string $typeName
*
* @return string
*/
private function suggestType(string $typeName): string
private function getValidType(string $typeName): string
{
if ('[]' === substr($typeName, -2)) {
return $this->getValidType(substr($typeName, 0, -2)).'[]';
}

$lowerType = strtolower($typeName);
switch ($lowerType) {
case 'bool':
Expand Down
16 changes: 1 addition & 15 deletions SymfonyCustom/Tests/NamingConventions/ValidTypeHintUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,4 @@ echo ( float ) $a;

/** @method integer|string */
/** @method array<integer,boolean>|integer[]|array<integer> truc */
/** @method array<integer, boolean>| integer[] |string|(integer|boolean)[] truc */
/** @method array{scheme:string,host:string} truc */
/** @method array(int=>string) truc */

/**
* Avoid weird bug
*
* @method array{
* @method array{scheme:integer,host:
* @method array<
* @method array<integer,
* @method array|
*/
/** @method array<integer, */
/** @method array<integer, $truc */
/** @method array<integer, boolean|null>|integer[]|array<array<integer>> truc */
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,4 @@ echo ( float ) $a;

/** @method int|string */
/** @method array<int, bool>|int[]|array<int> truc */
/** @method array<int, bool>|int[]|string|(int|bool)[] truc */
/** @method array{scheme: string, host: string} truc */
/** @method array(int => string) truc */

/**
* Avoid weird bug
*
* @method array{
* @method array{scheme: int, host:
* @method array<
* @method array<int,
* @method array|
*/
/** @method array<int, */
/** @method array<int, $truc */
/** @method array<int, bool|null>|int[]|array<array<int>> truc */
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,6 @@ protected function getErrorList(): array
45 => 1,
46 => 1,
47 => 1,
48 => 1,
49 => 1,
55 => 1,
57 => 1,
60 => 1,
61 => 1,
];
}

Expand Down