Skip to content
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

Class properties that have types should not require a DocBlock #406

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ class ClassPropertyPHPDocFormattingSniff extends AbstractVariableSniff
*/
private $PHPDocFormattingValidator;

/**
* @var array
*/
private $invalidTypes = [
'null',
'false',
'true',
'self'
];

/**
* Constructs an ClassPropertyPHPDocFormattingSniff.
*/
Expand All @@ -62,7 +72,15 @@ public function processMemberVar(File $phpcsFile, $stackPtr)
);

if ($commentEnd === false || $tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG) {
$phpcsFile->addWarning('Missing PHP DocBlock for class property.', $stackPtr, 'Missing');
// if the property has a valid type definition, we don't require a doc block
if (!$this->hasValidType($phpcsFile, $stackPtr)) {
$phpcsFile->addWarning(
'Missing PHP DocBlock for class property without valid type.',
$stackPtr,
'Missing'
);
}
// no comment, so nothing further to process
return;
}

Expand Down Expand Up @@ -143,6 +161,30 @@ public function processMemberVar(File $phpcsFile, $stackPtr)
$this->processPropertyShortDescription($phpcsFile, $stackPtr, $varAnnotationPosition, $commentStart);
}

/**
* Check if class property has a valid (not specifically invalid) type
*
* @param File $phpcsFile
* @param int $propertyPosition
* @return bool
*/
private function hasValidType(File $phpcsFile, int $propertyPosition): bool
{
// type token should be 2 before property. If not present, visibility token should be in its place
$typePosition = $phpcsFile->findPrevious(
[T_STRING],
$propertyPosition,
$propertyPosition - 2
);

if (!$typePosition) {
return false;
}

$type = $phpcsFile->getTokensAsString($typePosition, 1);
return !in_array(strtolower($type), $this->invalidTypes);
}

/**
* Check if class has already have meaningful description before var tag
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,17 @@ class correctlyFormattedClassMemberDocBlock
* @see Message with some reference
*/
protected string $itIsCorrect;
private string $typedPropertyWithoutComment;
aligent-lturner marked this conversation as resolved.
Show resolved Hide resolved

private string $typedPropertyWithoutComment2;

private ?string $typedPropertyWithoutComment3;

private string|int $typedPropertyWithoutComment4;

private Test $typedPropertyWithoutComment5;

private Test|Test2 $typedPropertyWithoutComment6;

private ?Test $typedPropertyWithoutComment7;
}