Skip to content
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
236 changes: 236 additions & 0 deletions CakePHP/Sniffs/Operators/OperatorSpacingSniff.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://github.com/cakephp/cakephp-codesniffer
* @since CakePHP CodeSniffer 5.2.0
* @license https://www.opensource.org/licenses/mit-license.php MIT License
*/

namespace CakePHP\Sniffs\Operators;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\OperatorSpacingSniff as SquizOperatorSpacingSniff;
use PHP_CodeSniffer\Util\Tokens;

/**
* Verifies that operators have valid spacing surrounding them.
*
* This is a copy of the PSR12.Operators.OperatorSpacing sniff which requires
* no space around the "|" and "&" characters when they are used as
* union/intersection type separators in catch statements.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2023 Squiz Pty Ltd (ABN 77 084 670 600)
* @copyright 2023 PHPCSStandards and contributors
* @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/HEAD/licence.txt BSD Licence
*/
class OperatorSpacingSniff extends SquizOperatorSpacingSniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array<int|string>
*/
public function register(): array
{
parent::register();

$targets = Tokens::COMPARISON_TOKENS;
$targets += Tokens::OPERATORS;
$targets += Tokens::ASSIGNMENT_TOKENS;
$targets += Tokens::BOOLEAN_OPERATORS;
$targets[] = T_INLINE_THEN;
$targets[] = T_INLINE_ELSE;
$targets[] = T_STRING_CONCAT;
$targets[] = T_INSTANCEOF;

// Also register the contexts we want to specifically skip over.
$targets[] = T_DECLARE;

return $targets;
}

/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
* @return int|void Optionally returns a stack pointer. The sniff will not be
* called again on the current file until the returned stack
* pointer is reached. Return `$phpcsFile->numTokens` to skip
* the rest of the file.
*/
public function process(File $phpcsFile, int $stackPtr)
{
$tokens = $phpcsFile->getTokens();

// Skip over declare statements as those should be handled by different sniffs.
if ($tokens[$stackPtr]['code'] === T_DECLARE) {
if (isset($tokens[$stackPtr]['parenthesis_closer']) === false) {
// Parse error / live coding.
return $phpcsFile->numTokens;
}

return $tokens[$stackPtr]['parenthesis_closer'];
}

// Union/intersection type separators in catch statements must not be surrounded by spaces.
if ($this->isCatchTypeOperator($phpcsFile, $stackPtr) === true) {
$this->processCatchTypeOperator($phpcsFile, $stackPtr);

return;
}

if ($this->isOperator($phpcsFile, $stackPtr) === false) {
return;
}

$operator = $tokens[$stackPtr]['content'];

$checkBefore = true;
$checkAfter = true;

// Skip short ternary.
if (
$tokens[$stackPtr]['code'] === T_INLINE_ELSE &&
$tokens[$stackPtr - 1]['code'] === T_INLINE_THEN
) {
$checkBefore = false;
}

// Skip operator with comment on previous line.
if (
$tokens[$stackPtr - 1]['code'] === T_COMMENT &&
$tokens[$stackPtr - 1]['line'] < $tokens[$stackPtr]['line']
) {
$checkBefore = false;
}

if (isset($tokens[$stackPtr + 1]) === true) {
// Skip short ternary.
if (
$tokens[$stackPtr]['code'] === T_INLINE_THEN &&
$tokens[$stackPtr + 1]['code'] === T_INLINE_ELSE
) {
$checkAfter = false;
}
} else {
// Skip partial files.
$checkAfter = false;
}

if ($checkBefore === true && $tokens[$stackPtr - 1]['code'] !== T_WHITESPACE) {
$error = 'Expected at least 1 space before "%s"; 0 found';
$data = [$operator];
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceBefore', $data);
if ($fix === true) {
$phpcsFile->fixer->addContentBefore($stackPtr, ' ');
}
}

if ($checkAfter === true && $tokens[$stackPtr + 1]['code'] !== T_WHITESPACE) {
$error = 'Expected at least 1 space after "%s"; 0 found';
$data = [$operator];
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceAfter', $data);
if ($fix === true) {
$phpcsFile->fixer->addContent($stackPtr, ' ');
}
}
}

/**
* Checks that there is no space around a union/intersection type separator in a catch statement.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked.
* @param int $stackPtr The position of the operator in
* the stack.
* @return void
*/
private function processCatchTypeOperator(File $phpcsFile, int $stackPtr): void
{
$tokens = $phpcsFile->getTokens();
$operator = $tokens[$stackPtr]['content'];

// Allow a newline instead of no space.
if (
$tokens[$stackPtr - 1]['code'] === T_WHITESPACE &&
$tokens[$stackPtr - 1]['line'] === $tokens[$stackPtr]['line']
) {
$error = 'Expected 0 spaces before "%s"; %s found';
$data = [
$operator,
$tokens[$stackPtr - 1]['length'],
];
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceBefore', $data);
if ($fix === true) {
$phpcsFile->fixer->replaceToken($stackPtr - 1, '');
}
}

if (isset($tokens[$stackPtr + 1]) === true) {
// Allow a newline instead of no space.
if (
$tokens[$stackPtr + 1]['code'] === T_WHITESPACE &&
$tokens[$stackPtr + 1]['line'] === $tokens[$stackPtr]['line']
) {
$error = 'Expected 0 spaces after "%s"; %s found';
$data = [
$operator,
$tokens[$stackPtr + 1]['length'],
];
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfter', $data);
if ($fix === true) {
$phpcsFile->fixer->replaceToken($stackPtr + 1, '');
}
}
}
}

/**
* Checks if the token is a union/intersection type separator in a catch statement.
*
* The PHPCS tokenizer does not convert the type separators in catch statements
* to T_TYPE_UNION/T_TYPE_INTERSECTION, so they are still seen as bitwise operators.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked.
* @param int $stackPtr The position of the operator in
* the stack.
* @return bool
*/
private function isCatchTypeOperator(File $phpcsFile, int $stackPtr): bool
{
$tokens = $phpcsFile->getTokens();

if (
$tokens[$stackPtr]['code'] !== T_BITWISE_OR &&
$tokens[$stackPtr]['code'] !== T_BITWISE_AND
) {
return false;
}

if (isset($tokens[$stackPtr]['nested_parenthesis']) === false) {
return false;
}

foreach (array_keys($tokens[$stackPtr]['nested_parenthesis']) as $opener) {
if (isset($tokens[$opener]['parenthesis_owner']) === false) {
continue;
}

$owner = $tokens[$opener]['parenthesis_owner'];
if ($tokens[$owner]['code'] === T_CATCH) {
return true;
}
}

return false;
}
}
40 changes: 40 additions & 0 deletions CakePHP/Tests/Operators/OperatorSpacingUnitTest.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace CakePHP\Tests\Operators;

class OperatorSpacing
{
public function test(): void
{
try {
foo();
} catch (FirstException|SecondException $exception) {
bar();
}

try {
foo();
} catch (FirstException | SecondException $exception) {
bar();
}

try {
foo();
} catch (FirstException&SecondException $exception) {
bar();
}

try {
foo();
} catch (FirstException & SecondException $exception) {
bar();
}

$a = 1|2;
$b = 1 |2;
$c = 1| 2;
$d = 1 & 2;
$e = 1&2;
$f = 1 &2;
}
}
40 changes: 40 additions & 0 deletions CakePHP/Tests/Operators/OperatorSpacingUnitTest.inc.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace CakePHP\Tests\Operators;

class OperatorSpacing
{
public function test(): void
{
try {
foo();
} catch (FirstException|SecondException $exception) {
bar();
}

try {
foo();
} catch (FirstException|SecondException $exception) {
bar();
}

try {
foo();
} catch (FirstException&SecondException $exception) {
bar();
}

try {
foo();
} catch (FirstException&SecondException $exception) {
bar();
}

$a = 1 | 2;
$b = 1 | 2;
$c = 1 | 2;
$d = 1 & 2;
$e = 1 & 2;
$f = 1 & 2;
}
}
32 changes: 32 additions & 0 deletions CakePHP/Tests/Operators/OperatorSpacingUnitTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace CakePHP\Tests\Operators;

use PHP_CodeSniffer\Tests\Standards\AbstractSniffTestCase;

class OperatorSpacingUnitTest extends AbstractSniffTestCase
{
/**
* @inheritDoc
*/
public function getErrorList()
{
return [
17 => 2,
29 => 2,
33 => 2,
34 => 1,
35 => 1,
37 => 2,
38 => 1,
];
}

/**
* @inheritDoc
*/
public function getWarningList()
{
return [];
}
}
5 changes: 5 additions & 0 deletions CakePHP/ruleset.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
<exclude name="PSR12.Files.FileHeader.SpacingAfterDocblockBlock"/>
<exclude name="PSR12.Files.FileHeader.IncorrectOrder"/>
<!--
We use our own CakePHP.Operators.OperatorSpacing sniff which ignores union/intersection
type separators in catch statements.
-->
<exclude name="PSR12.Operators.OperatorSpacing"/>
<!--
We use our own CakePHP.NamingConventions.ValidFunctionName sniff which allows
Entity accessor/mutator pattern (_getField, _setField) while enforcing PSR naming elsewhere.
-->
Expand Down
6 changes: 3 additions & 3 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

The CakePHP standard contains 157 sniffs

CakePHP (19 sniffs)
CakePHP (20 sniffs)
-------------------
- CakePHP.Classes.ReturnTypeHint
- CakePHP.Commenting.DocBlockAlignment
Expand All @@ -16,6 +16,7 @@ CakePHP (19 sniffs)
- CakePHP.NamingConventions.ValidEnumName
- CakePHP.NamingConventions.ValidFunctionName
- CakePHP.NamingConventions.ValidTraitName
- CakePHP.Operators.OperatorSpacing
- CakePHP.PHP.DisallowShortOpenTag
- CakePHP.PHP.SingleQuote
- CakePHP.WhiteSpace.EmptyLines
Expand Down Expand Up @@ -75,7 +76,7 @@ PSR2 (9 sniffs)
- PSR2.Methods.FunctionClosingBrace
- PSR2.Methods.MethodDeclaration

PSR12 (17 sniffs)
PSR12 (16 sniffs)
-----------------
- PSR12.Classes.AnonClassDeclaration
- PSR12.Classes.ClassInstantiation
Expand All @@ -91,7 +92,6 @@ PSR12 (17 sniffs)
- PSR12.Functions.ReturnTypeDeclaration
- PSR12.Keywords.ShortFormTypeKeywords
- PSR12.Namespaces.CompoundNamespaceDepth
- PSR12.Operators.OperatorSpacing
- PSR12.Properties.ConstantVisibility
- PSR12.Traits.UseDeclaration

Expand Down
Loading