more updates yay

This commit is contained in:
Wyatt Miller
2018-05-21 12:29:14 -04:00
parent 168f2f2a54
commit 2a39739af0
1105 changed files with 115947 additions and 34 deletions

View File

@ -0,0 +1,66 @@
<?php
/**
* A test class for running all PHP_CodeSniffer unit tests.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests;
use PHP_CodeSniffer\Tests\TestSuite;
use PHPUnit\TextUI\TestRunner;
if (is_file(__DIR__.'/../autoload.php') === true) {
include_once 'Core/AllTests.php';
include_once 'Standards/AllSniffs.php';
} else {
include_once 'CodeSniffer/Core/AllTests.php';
include_once 'CodeSniffer/Standards/AllSniffs.php';
}
// PHPUnit 7 made the TestSuite run() method incompatible with
// older PHPUnit versions due to return type hints, so maintain
// two different suite objects.
$phpunit7 = false;
if (class_exists('\PHPUnit\Runner\Version') === true) {
$version = \PHPUnit\Runner\Version::id();
if ($version[0] === '7') {
$phpunit7 = true;
}
}
if ($phpunit7 === true) {
include_once 'TestSuite7.php';
} else {
include_once 'TestSuite.php';
}
class PHP_CodeSniffer_AllTests
{
/**
* Add all PHP_CodeSniffer test suites into a single test suite.
*
* @return \PHPUnit\Framework\TestSuite
*/
public static function suite()
{
$GLOBALS['PHP_CODESNIFFER_STANDARD_DIRS'] = [];
$GLOBALS['PHP_CODESNIFFER_TEST_DIRS'] = [];
// Use a special PHP_CodeSniffer test suite so that we can
// unset our autoload function after the run.
$suite = new TestSuite('PHP CodeSniffer');
$suite->addTest(Core\AllTests::suite());
$suite->addTest(Standards\AllSniffs::suite());
return $suite;
}//end suite()
}//end class

View File

@ -0,0 +1,57 @@
<?php
/**
* A test class for testing the core.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests\Core;
use PHPUnit\TextUI\TestRunner;
use PHPUnit\Framework\TestSuite;
require_once 'IsCamelCapsTest.php';
require_once 'ErrorSuppressionTest.php';
require_once 'File/GetMethodParametersTest.php';
require_once 'File/FindExtendedClassNameTest.php';
require_once 'File/FindImplementedInterfaceNamesTest.php';
require_once 'File/IsReferenceTest.php';
class AllTests
{
/**
* Prepare the test runner.
*
* @return void
*/
public static function main()
{
TestRunner::run(self::suite());
}//end main()
/**
* Add all core unit tests into a test suite.
*
* @return \PHPUnit\Framework\TestSuite
*/
public static function suite()
{
$suite = new TestSuite('PHP CodeSniffer Core');
$suite->addTestSuite('PHP_CodeSniffer\Tests\Core\IsCamelCapsTest');
$suite->addTestSuite('PHP_CodeSniffer\Tests\Core\ErrorSuppressionTest');
$suite->addTestSuite('PHP_CodeSniffer\Tests\Core\File\GetMethodParametersTest');
$suite->addTestSuite('PHP_CodeSniffer\Tests\Core\File\FindExtendedClassNameTest');
$suite->addTestSuite('PHP_CodeSniffer\Tests\Core\File\FindImplementedInterfaceNamesTest');
$suite->addTestSuite('PHP_CodeSniffer\Tests\Core\File\IsReferenceTest');
return $suite;
}//end suite()
}//end class

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,24 @@
<?php
/* @codingStandardsIgnoreFile */
namespace PHP_CodeSniffer\Tests\Core\File;
class testFECNClass {}
/* testExtendedClass */
class testFECNExtendedClass extends testFECNClass {}
/* testNamespacedClass */
class testFECNNamespacedClass extends \PHP_CodeSniffer\Tests\Core\File\testFECNClass {}
/* testNonExtendedClass */
class testFECNNonExtendedClass {}
/* testInterface */
interface testFECNInterface {}
/* testInterfaceThatExtendsInterface */
interface testInterfaceThatExtendsInterface extends testFECNInterface{}
/* testInterfaceThatExtendsFQCNInterface */
interface testInterfaceThatExtendsFQCNInterface extends \PHP_CodeSniffer\Tests\Core\File\testFECNInterface{}

View File

@ -0,0 +1,194 @@
<?php
/**
* Tests for the \PHP_CodeSniffer\Files\File:findExtendedClassName method.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests\Core\File;
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Ruleset;
use PHP_CodeSniffer\Files\DummyFile;
use PHPUnit\Framework\TestCase;
class FindExtendedClassNameTest extends TestCase
{
/**
* The PHP_CodeSniffer_File object containing parsed contents of the test case file.
*
* @var \PHP_CodeSniffer\Files\File
*/
private $phpcsFile;
/**
* Initialize & tokenize \PHP_CodeSniffer\Files\File with code from the test case file.
*
* Methods used for these tests can be found in a test case file in the same
* directory and with the same name, using the .inc extension.
*
* @return void
*/
public function setUp()
{
$config = new Config();
$config->standards = ['Generic'];
$ruleset = new Ruleset($config);
$pathToTestFile = dirname(__FILE__).'/'.basename(__FILE__, '.php').'.inc';
$this->phpcsFile = new DummyFile(file_get_contents($pathToTestFile), $ruleset, $config);
$this->phpcsFile->process();
}//end setUp()
/**
* Clean up after finished test.
*
* @return void
*/
public function tearDown()
{
unset($this->phpcsFile);
}//end tearDown()
/**
* Test a class that extends another.
*
* @return void
*/
public function testExtendedClass()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testExtendedClass */'
);
$found = $this->phpcsFile->findExtendedClassName(($class + 2));
$this->assertSame('testFECNClass', $found);
}//end testExtendedClass()
/**
* Test a class that extends another, using namespaces.
*
* @return void
*/
public function testNamespacedClass()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testNamespacedClass */'
);
$found = $this->phpcsFile->findExtendedClassName(($class + 2));
$this->assertSame('\PHP_CodeSniffer\Tests\Core\File\testFECNClass', $found);
}//end testNamespacedClass()
/**
* Test a class that doesn't extend another.
*
* @return void
*/
public function testNonExtendedClass()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testNonExtendedClass */'
);
$found = $this->phpcsFile->findExtendedClassName(($class + 2));
$this->assertFalse($found);
}//end testNonExtendedClass()
/**
* Test an interface.
*
* @return void
*/
public function testInterface()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testInterface */'
);
$found = $this->phpcsFile->findExtendedClassName(($class + 2));
$this->assertFalse($found);
}//end testInterface()
/**
* Test an interface that extends another.
*
* @return void
*/
public function testExtendedInterface()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testInterfaceThatExtendsInterface */'
);
$found = $this->phpcsFile->findExtendedClassName(($class + 2));
$this->assertSame('testFECNInterface', $found);
}//end testExtendedInterface()
/**
* Test an interface that extends another, using namespaces.
*
* @return void
*/
public function testExtendedNamespacedInterface()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testInterfaceThatExtendsFQCNInterface */'
);
$found = $this->phpcsFile->findExtendedClassName(($class + 2));
$this->assertSame('\PHP_CodeSniffer\Tests\Core\File\testFECNInterface', $found);
}//end testExtendedNamespacedInterface()
}//end class

View File

@ -0,0 +1,22 @@
<?php
/* @codingStandardsIgnoreFile */
namespace PHP_CodeSniffer\Tests\Core\File;
\PHP_CodeSniffer\Tests\Core\File\testFECNClass
interface testFIINInterface2 {}
/* testInterface */
interface testFIINInterface {}
/* testImplementedClass */
class testFIINImplementedClass implements testFIINInterface {}
/* testMultiImplementedClass */
class testFIINMultiImplementedClass implements testFIINInterface, testFIINInterface2 {}
/* testNamespacedClass */
class testFIINNamespacedClass implements \PHP_CodeSniffer\Tests\Core\File\testFIINInterface {}
/* testNonImplementedClass */
class testFIINNonImplementedClass {}

View File

@ -0,0 +1,172 @@
<?php
/**
* Tests for the \PHP_CodeSniffer\Files\File:findImplementedInterfaceNames method.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests\Core\File;
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Ruleset;
use PHP_CodeSniffer\Files\DummyFile;
use PHPUnit\Framework\TestCase;
class FindImplementedInterfaceNamesTest extends TestCase
{
/**
* The \PHP_CodeSniffer\Files\File object containing parsed contents of the test case file.
*
* @var \PHP_CodeSniffer\Files\File
*/
private $phpcsFile;
/**
* Initialize & tokenize \PHP_CodeSniffer\Files\File with code from the test case file.
*
* Methods used for these tests can be found in a test case file in the same
* directory and with the same name, using the .inc extension.
*
* @return void
*/
public function setUp()
{
$config = new Config();
$config->standards = ['Generic'];
$ruleset = new Ruleset($config);
$pathToTestFile = dirname(__FILE__).'/'.basename(__FILE__, '.php').'.inc';
$this->phpcsFile = new DummyFile(file_get_contents($pathToTestFile), $ruleset, $config);
$this->phpcsFile->process();
}//end setUp()
/**
* Clean up after finished test.
*
* @return void
*/
public function tearDown()
{
unset($this->phpcsFile);
}//end tearDown()
/**
* Test a class that implements a single interface.
*
* @return void
*/
public function testImplementedClass()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testImplementedClass */'
);
$found = $this->phpcsFile->findImplementedInterfaceNames(($class + 2));
$this->assertSame(['testFIINInterface'], $found);
}//end testImplementedClass()
/**
* Test a class that implements multiple interfaces.
*
* @return void
*/
public function testMultiImplementedClass()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testMultiImplementedClass */'
);
$found = $this->phpcsFile->findImplementedInterfaceNames(($class + 2));
$this->assertSame(['testFIINInterface', 'testFIINInterface2'], $found);
}//end testMultiImplementedClass()
/**
* Test a class that implements an interface, using namespaces.
*
* @return void
*/
public function testNamespacedClass()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testNamespacedClass */'
);
$found = $this->phpcsFile->findImplementedInterfaceNames(($class + 2));
$this->assertSame(['\PHP_CodeSniffer\Tests\Core\File\testFIINInterface'], $found);
}//end testNamespacedClass()
/**
* Test a class that doesn't implement an interface.
*
* @return void
*/
public function testNonImplementedClass()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testNonImplementedClass */'
);
$found = $this->phpcsFile->findImplementedInterfaceNames(($class + 2));
$this->assertFalse($found);
}//end testNonImplementedClass()
/**
* Test an interface.
*
* @return void
*/
public function testInterface()
{
$start = ($this->phpcsFile->numTokens - 1);
$class = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testInterface */'
);
$found = $this->phpcsFile->findImplementedInterfaceNames(($class + 2));
$this->assertFalse($found);
}//end testInterface()
}//end class

View File

@ -0,0 +1,30 @@
<?php
/* @codingStandardsIgnoreFile */
/* testPassByReference */
function passByReference(&$var) {}
/* testArrayHint */
function arrayHint(array $var) {}
/* testVariable */
function variable($var) {}
/* testSingleDefaultValue */
function defaultValue($var1=self::CONSTANT) {}
/* testDefaultValues */
function defaultValues($var1=1, $var2='value') {}
/* testTypeHint */
function typeHint(foo $var1, bar $var2) {}
class MyClass {
/* testSelfTypeHint */ function typeSelfHint(self $var) {}
}
/* testNullableTypeHint */
function nullableTypeHint(?int $var1, ?\bar $var2) {}
/* testBitwiseAndConstantExpressionDefaultValue */
function myFunction($a = 10 & 20) {}

View File

@ -0,0 +1,392 @@
<?php
/**
* Tests for the \PHP_CodeSniffer\Files\File:getMethodParameters method.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests\Core\File;
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Ruleset;
use PHP_CodeSniffer\Files\DummyFile;
use PHPUnit\Framework\TestCase;
class GetMethodParametersTest extends TestCase
{
/**
* The PHP_CodeSniffer_File object containing parsed contents of the test case file.
*
* @var \PHP_CodeSniffer\Files\File
*/
private $phpcsFile;
/**
* Initialize & tokenize PHP_CodeSniffer_File with code from the test case file.
*
* Methods used for these tests can be found in a test case file in the same
* directory and with the same name, using the .inc extension.
*
* @return void
*/
public function setUp()
{
$config = new Config();
$config->standards = ['Generic'];
$ruleset = new Ruleset($config);
$pathToTestFile = dirname(__FILE__).'/'.basename(__FILE__, '.php').'.inc';
$this->phpcsFile = new DummyFile(file_get_contents($pathToTestFile), $ruleset, $config);
$this->phpcsFile->process();
}//end setUp()
/**
* Clean up after finished test.
*
* @return void
*/
public function tearDown()
{
unset($this->phpcsFile);
}//end tearDown()
/**
* Verify pass-by-reference parsing.
*
* @return void
*/
public function testPassByReference()
{
$expected = [];
$expected[0] = [
'name' => '$var',
'content' => '&$var',
'pass_by_reference' => true,
'variable_length' => false,
'type_hint' => '',
'nullable_type' => false,
];
$start = ($this->phpcsFile->numTokens - 1);
$function = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testPassByReference */'
);
$found = $this->phpcsFile->getMethodParameters(($function + 2));
unset($found[0]['token']);
$this->assertSame($expected, $found);
}//end testPassByReference()
/**
* Verify array hint parsing.
*
* @return void
*/
public function testArrayHint()
{
$expected = [];
$expected[0] = [
'name' => '$var',
'content' => 'array $var',
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => 'array',
'nullable_type' => false,
];
$start = ($this->phpcsFile->numTokens - 1);
$function = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testArrayHint */'
);
$found = $this->phpcsFile->getMethodParameters(($function + 2));
unset($found[0]['token']);
$this->assertSame($expected, $found);
}//end testArrayHint()
/**
* Verify type hint parsing.
*
* @return void
*/
public function testTypeHint()
{
$expected = [];
$expected[0] = [
'name' => '$var1',
'content' => 'foo $var1',
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => 'foo',
'nullable_type' => false,
];
$expected[1] = [
'name' => '$var2',
'content' => 'bar $var2',
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => 'bar',
'nullable_type' => false,
];
$start = ($this->phpcsFile->numTokens - 1);
$function = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testTypeHint */'
);
$found = $this->phpcsFile->getMethodParameters(($function + 2));
unset($found[0]['token']);
unset($found[1]['token']);
$this->assertSame($expected, $found);
}//end testTypeHint()
/**
* Verify self type hint parsing.
*
* @return void
*/
public function testSelfTypeHint()
{
$expected = [];
$expected[0] = [
'name' => '$var',
'content' => 'self $var',
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => 'self',
'nullable_type' => false,
];
$start = ($this->phpcsFile->numTokens - 1);
$function = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testSelfTypeHint */'
);
$found = $this->phpcsFile->getMethodParameters(($function + 2));
unset($found[0]['token']);
$this->assertSame($expected, $found);
}//end testSelfTypeHint()
/**
* Verify nullable type hint parsing.
*
* @return void
*/
public function testNullableTypeHint()
{
$expected = [];
$expected[0] = [
'name' => '$var1',
'content' => '?int $var1',
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => '?int',
'nullable_type' => true,
];
$expected[1] = [
'name' => '$var2',
'content' => '?\bar $var2',
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => '?\bar',
'nullable_type' => true,
];
$start = ($this->phpcsFile->numTokens - 1);
$function = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testNullableTypeHint */'
);
$found = $this->phpcsFile->getMethodParameters(($function + 2));
unset($found[0]['token']);
unset($found[1]['token']);
$this->assertSame($expected, $found);
}//end testNullableTypeHint()
/**
* Verify variable.
*
* @return void
*/
public function testVariable()
{
$expected = [];
$expected[0] = [
'name' => '$var',
'content' => '$var',
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => '',
'nullable_type' => false,
];
$start = ($this->phpcsFile->numTokens - 1);
$function = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testVariable */'
);
$found = $this->phpcsFile->getMethodParameters(($function + 2));
unset($found[0]['token']);
$this->assertSame($expected, $found);
}//end testVariable()
/**
* Verify default value parsing with a single function param.
*
* @return void
*/
public function testSingleDefaultValue()
{
$expected = [];
$expected[0] = [
'name' => '$var1',
'content' => '$var1=self::CONSTANT',
'default' => 'self::CONSTANT',
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => '',
'nullable_type' => false,
];
$start = ($this->phpcsFile->numTokens - 1);
$function = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testSingleDefaultValue */'
);
$found = $this->phpcsFile->getMethodParameters(($function + 2));
unset($found[0]['token']);
$this->assertSame($expected, $found);
}//end testSingleDefaultValue()
/**
* Verify default value parsing.
*
* @return void
*/
public function testDefaultValues()
{
$expected = [];
$expected[0] = [
'name' => '$var1',
'content' => '$var1=1',
'default' => '1',
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => '',
'nullable_type' => false,
];
$expected[1] = [
'name' => '$var2',
'content' => "\$var2='value'",
'default' => "'value'",
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => '',
'nullable_type' => false,
];
$start = ($this->phpcsFile->numTokens - 1);
$function = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testDefaultValues */'
);
$found = $this->phpcsFile->getMethodParameters(($function + 2));
unset($found[0]['token']);
unset($found[1]['token']);
$this->assertSame($expected, $found);
}//end testDefaultValues()
/**
* Verify "bitwise and" in default value !== pass-by-reference.
*
* @return void
*/
public function testBitwiseAndConstantExpressionDefaultValue()
{
$expected = [];
$expected[0] = [
'name' => '$a',
'content' => '$a = 10 & 20',
'default' => '10 & 20',
'pass_by_reference' => false,
'variable_length' => false,
'type_hint' => '',
'nullable_type' => false,
];
$start = ($this->phpcsFile->numTokens - 1);
$function = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
'/* testBitwiseAndConstantExpressionDefaultValue */'
);
$found = $this->phpcsFile->getMethodParameters(($function + 2));
unset($found[0]['token']);
$this->assertSame($expected, $found);
}//end testBitwiseAndConstantExpressionDefaultValue()
}//end class

View File

@ -0,0 +1,139 @@
<?php
/* @codingStandardsIgnoreFile */
namespace PHP_CodeSniffer\Tests\Core\File;
/* bitwiseAndA */
error_reporting( E_NOTICE & E_STRICT );
/* bitwiseAndB */
$a = [ $something & $somethingElse ];
/* bitwiseAndC */
$a = [ $first, $something & self::$somethingElse ];
/* bitwiseAndD */
$a = array $first, $something & $somethingElse );
/* bitwiseAndE */
$a = [ 'a' => $first, 'b' => $something & $somethingElse ];
/* bitwiseAndF */
$a = array( 'a' => $first, 'b' => $something & \MyClass::$somethingElse );
/* bitwiseAndG */
$a = $something & $somethingElse;
/* bitwiseAndH */
function myFunction($a = 10 & 20) {}
/* bitwiseAndI */
$closure = function ($a = MY_CONSTANT & parent::OTHER_CONSTANT) {};
/* functionReturnByReference */
function &myFunction() {}
/* functionPassByReferenceA */
function myFunction( &$a ) {}
/* functionPassByReferenceB */
function myFunction( $a, &$b ) {}
/* functionPassByReferenceC */
$closure = function ( &$a ) {};
/* functionPassByReferenceD */
$closure = function ( $a, &$b ) {};
/* functionPassByReferenceE */
function myFunction(array &$one) {}
/* functionPassByReferenceF */
$closure = function (\MyClass &$one) {};
/* functionPassByReferenceG */
$closure = function myFunc($param, &...$moreParams) {};
/* foreachValueByReference */
foreach( $array as $key => &$value ) {}
/* foreachKeyByReference */
foreach( $array as &$key => $value ) {}
/* arrayValueByReferenceA */
$a = [ 'a' => &$something ];
/* arrayValueByReferenceB */
$a = [ 'a' => $something, 'b' => &$somethingElse ];
/* arrayValueByReferenceC */
$a = [ &$something ];
/* arrayValueByReferenceD */
$a = [ $something, &$somethingElse ];
/* arrayValueByReferenceE */
$a = array( 'a' => &$something );
/* arrayValueByReferenceF */
$a = array( 'a' => $something, 'b' => &$somethingElse );
/* arrayValueByReferenceG */
$a = array( &$something );
/* arrayValueByReferenceH */
$a = array( $something, &$somethingElse );
/* assignByReferenceA */
$b = &$something;
/* assignByReferenceB */
$b =& $something;
/* assignByReferenceC */
$b .= &$something;
/* assignByReferenceD */
$myValue = &$obj->getValue();
/* assignByReferenceE */
$collection = &collector();
/* passByReferenceA */
functionCall(&$something, $somethingElse);
/* passByReferenceB */
functionCall($something, &$somethingElse);
/* passByReferenceC */
functionCall($something, &$this->somethingElse);
/* passByReferenceD */
functionCall($something, &self::$somethingElse);
/* passByReferenceE */
functionCall($something, &parent::$somethingElse);
/* passByReferenceF */
functionCall($something, &static::$somethingElse);
/* passByReferenceG */
functionCall($something, &SomeClass::$somethingElse);
/* passByReferenceH */
functionCall(&\SomeClass::$somethingElse);
/* passByReferenceI */
functionCall($something, &\SomeNS\SomeClass::$somethingElse);
/* passByReferenceJ */
functionCall($something, &namespace\SomeClass::$somethingElse);
/* newByReferenceA */
$foobar2 = &new Foobar();
/* newByReferenceB */
functionCall( $something , &new Foobar() );
/* useByReference */
$closure = function() use (&$var){};

View File

@ -0,0 +1,285 @@
<?php
/**
* Tests for the \PHP_CodeSniffer\Files\File:isReference method.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests\Core\File;
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Ruleset;
use PHP_CodeSniffer\Files\DummyFile;
use PHPUnit\Framework\TestCase;
class IsReferenceTest extends TestCase
{
/**
* The PHP_CodeSniffer_File object containing parsed contents of the test case file.
*
* @var \PHP_CodeSniffer\Files\File
*/
private $phpcsFile;
/**
* Initialize & tokenize \PHP_CodeSniffer\Files\File with code from the test case file.
*
* Methods used for these tests can be found in a test case file in the same
* directory and with the same name, using the .inc extension.
*
* @return void
*/
public function setUp()
{
$config = new Config();
$config->standards = ['Generic'];
$ruleset = new Ruleset($config);
$pathToTestFile = dirname(__FILE__).'/'.basename(__FILE__, '.php').'.inc';
$this->phpcsFile = new DummyFile(file_get_contents($pathToTestFile), $ruleset, $config);
$this->phpcsFile->process();
}//end setUp()
/**
* Clean up after finished test.
*
* @return void
*/
public function tearDown()
{
unset($this->phpcsFile);
}//end tearDown()
/**
* Test a class that extends another.
*
* @param string $identifier Comment which preceeds the test case.
* @param bool $expected Expected function output.
*
* @dataProvider dataIsReference
*
* @return void
*/
public function testIsReference($identifier, $expected)
{
$start = ($this->phpcsFile->numTokens - 1);
$delim = $this->phpcsFile->findPrevious(
T_COMMENT,
$start,
null,
false,
$identifier
);
$bitwiseAnd = $this->phpcsFile->findNext(T_BITWISE_AND, ($delim + 1));
$result = $this->phpcsFile->isReference($bitwiseAnd);
$this->assertSame($expected, $result);
}//end testIsReference()
/**
* Data provider for the IsReference test.
*
* @see testIsReference()
*
* @return array
*/
public function dataIsReference()
{
return [
[
'/* bitwiseAndA */',
false,
],
[
'/* bitwiseAndB */',
false,
],
[
'/* bitwiseAndC */',
false,
],
[
'/* bitwiseAndD */',
false,
],
[
'/* bitwiseAndE */',
false,
],
[
'/* bitwiseAndF */',
false,
],
[
'/* bitwiseAndG */',
false,
],
[
'/* bitwiseAndH */',
false,
],
[
'/* bitwiseAndI */',
false,
],
[
'/* functionReturnByReference */',
true,
],
[
'/* functionPassByReferenceA */',
true,
],
[
'/* functionPassByReferenceB */',
true,
],
[
'/* functionPassByReferenceC */',
true,
],
[
'/* functionPassByReferenceD */',
true,
],
[
'/* functionPassByReferenceE */',
true,
],
[
'/* functionPassByReferenceF */',
true,
],
[
'/* functionPassByReferenceG */',
true,
],
[
'/* foreachValueByReference */',
true,
],
[
'/* foreachKeyByReference */',
true,
],
[
'/* arrayValueByReferenceA */',
true,
],
[
'/* arrayValueByReferenceB */',
true,
],
[
'/* arrayValueByReferenceC */',
true,
],
[
'/* arrayValueByReferenceD */',
true,
],
[
'/* arrayValueByReferenceE */',
true,
],
[
'/* arrayValueByReferenceF */',
true,
],
[
'/* arrayValueByReferenceG */',
true,
],
[
'/* arrayValueByReferenceH */',
true,
],
[
'/* assignByReferenceA */',
true,
],
[
'/* assignByReferenceB */',
true,
],
[
'/* assignByReferenceC */',
true,
],
[
'/* assignByReferenceD */',
true,
],
[
'/* assignByReferenceE */',
true,
],
[
'/* passByReferenceA */',
true,
],
[
'/* passByReferenceB */',
true,
],
[
'/* passByReferenceC */',
true,
],
[
'/* passByReferenceD */',
true,
],
[
'/* passByReferenceE */',
true,
],
[
'/* passByReferenceF */',
true,
],
[
'/* passByReferenceG */',
true,
],
[
'/* passByReferenceH */',
true,
],
[
'/* passByReferenceI */',
true,
],
[
'/* passByReferenceJ */',
true,
],
[
'/* newByReferenceA */',
true,
],
[
'/* newByReferenceB */',
true,
],
[
'/* useByReference */',
true,
],
];
}//end dataIsReference()
}//end class

View File

@ -0,0 +1,135 @@
<?php
/**
* Tests for the \PHP_CodeSniffer\Util\Common::isCamelCaps method.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests\Core;
use PHP_CodeSniffer\Util\Common;
use PHPUnit\Framework\TestCase;
class IsCamelCapsTest extends TestCase
{
/**
* Test valid public function/method names.
*
* @return void
*/
public function testValidNotClassFormatPublic()
{
$this->assertTrue(Common::isCamelCaps('thisIsCamelCaps', false, true, true));
$this->assertTrue(Common::isCamelCaps('thisISCamelCaps', false, true, false));
}//end testValidNotClassFormatPublic()
/**
* Test invalid public function/method names.
*
* @return void
*/
public function testInvalidNotClassFormatPublic()
{
$this->assertFalse(Common::isCamelCaps('_thisIsCamelCaps', false, true, true));
$this->assertFalse(Common::isCamelCaps('thisISCamelCaps', false, true, true));
$this->assertFalse(Common::isCamelCaps('ThisIsCamelCaps', false, true, true));
$this->assertFalse(Common::isCamelCaps('3thisIsCamelCaps', false, true, true));
$this->assertFalse(Common::isCamelCaps('*thisIsCamelCaps', false, true, true));
$this->assertFalse(Common::isCamelCaps('-thisIsCamelCaps', false, true, true));
$this->assertFalse(Common::isCamelCaps('this*IsCamelCaps', false, true, true));
$this->assertFalse(Common::isCamelCaps('this-IsCamelCaps', false, true, true));
$this->assertFalse(Common::isCamelCaps('this_IsCamelCaps', false, true, true));
$this->assertFalse(Common::isCamelCaps('this_is_camel_caps', false, true, true));
}//end testInvalidNotClassFormatPublic()
/**
* Test valid private method names.
*
* @return void
*/
public function testValidNotClassFormatPrivate()
{
$this->assertTrue(Common::isCamelCaps('_thisIsCamelCaps', false, false, true));
$this->assertTrue(Common::isCamelCaps('_thisISCamelCaps', false, false, false));
$this->assertTrue(Common::isCamelCaps('_i18N', false, false, true));
$this->assertTrue(Common::isCamelCaps('_i18n', false, false, true));
}//end testValidNotClassFormatPrivate()
/**
* Test invalid private method names.
*
* @return void
*/
public function testInvalidNotClassFormatPrivate()
{
$this->assertFalse(Common::isCamelCaps('thisIsCamelCaps', false, false, true));
$this->assertFalse(Common::isCamelCaps('_thisISCamelCaps', false, false, true));
$this->assertFalse(Common::isCamelCaps('_ThisIsCamelCaps', false, false, true));
$this->assertFalse(Common::isCamelCaps('__thisIsCamelCaps', false, false, true));
$this->assertFalse(Common::isCamelCaps('__thisISCamelCaps', false, false, false));
$this->assertFalse(Common::isCamelCaps('3thisIsCamelCaps', false, false, true));
$this->assertFalse(Common::isCamelCaps('*thisIsCamelCaps', false, false, true));
$this->assertFalse(Common::isCamelCaps('-thisIsCamelCaps', false, false, true));
$this->assertFalse(Common::isCamelCaps('_this_is_camel_caps', false, false, true));
}//end testInvalidNotClassFormatPrivate()
/**
* Test valid class names.
*
* @return void
*/
public function testValidClassFormatPublic()
{
$this->assertTrue(Common::isCamelCaps('ThisIsCamelCaps', true, true, true));
$this->assertTrue(Common::isCamelCaps('ThisISCamelCaps', true, true, false));
$this->assertTrue(Common::isCamelCaps('This3IsCamelCaps', true, true, false));
}//end testValidClassFormatPublic()
/**
* Test invalid class names.
*
* @return void
*/
public function testInvalidClassFormat()
{
$this->assertFalse(Common::isCamelCaps('thisIsCamelCaps', true));
$this->assertFalse(Common::isCamelCaps('This-IsCamelCaps', true));
$this->assertFalse(Common::isCamelCaps('This_Is_Camel_Caps', true));
}//end testInvalidClassFormat()
/**
* Test invalid class names with the private flag set.
*
* Note that the private flag is ignored if the class format
* flag is set, so these names are all invalid.
*
* @return void
*/
public function testInvalidClassFormatPrivate()
{
$this->assertFalse(Common::isCamelCaps('_ThisIsCamelCaps', true, true));
$this->assertFalse(Common::isCamelCaps('_ThisIsCamelCaps', true, false));
}//end testInvalidClassFormatPrivate()
}//end class

View File

@ -0,0 +1,449 @@
<?php
/**
* An abstract class that all sniff unit tests must extend.
*
* A sniff unit test checks a .inc file for expected violations of a single
* coding standard. Expected errors and warnings that are not found, or
* warnings and errors that are not expected, are considered test failures.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests\Standards;
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Exceptions\RuntimeException;
use PHP_CodeSniffer\Ruleset;
use PHP_CodeSniffer\Files\LocalFile;
use PHP_CodeSniffer\Util\Common;
use PHPUnit\Framework\TestCase;
abstract class AbstractSniffUnitTest extends TestCase
{
/**
* Enable or disable the backup and restoration of the $GLOBALS array.
* Overwrite this attribute in a child class of TestCase.
* Setting this attribute in setUp() has no effect!
*
* @var boolean
*/
protected $backupGlobals = false;
/**
* The path to the standard's main directory.
*
* @var string
*/
public $standardsDir = null;
/**
* The path to the standard's test directory.
*
* @var string
*/
public $testsDir = null;
/**
* Sets up this unit test.
*
* @return void
*/
protected function setUp()
{
$class = get_class($this);
$this->standardsDir = $GLOBALS['PHP_CODESNIFFER_STANDARD_DIRS'][$class];
$this->testsDir = $GLOBALS['PHP_CODESNIFFER_TEST_DIRS'][$class];
}//end setUp()
/**
* Get a list of all test files to check.
*
* These will have the same base as the sniff name but different extensions.
* We ignore the .php file as it is the class.
*
* @param string $testFileBase The base path that the unit tests files will have.
*
* @return string[]
*/
protected function getTestFiles($testFileBase)
{
$testFiles = [];
$dir = substr($testFileBase, 0, strrpos($testFileBase, DIRECTORY_SEPARATOR));
$di = new \DirectoryIterator($dir);
foreach ($di as $file) {
$path = $file->getPathname();
if (substr($path, 0, strlen($testFileBase)) === $testFileBase) {
if ($path !== $testFileBase.'php' && substr($path, -5) !== 'fixed') {
$testFiles[] = $path;
}
}
}
// Put them in order.
sort($testFiles);
return $testFiles;
}//end getTestFiles()
/**
* Should this test be skipped for some reason.
*
* @return boolean
*/
protected function shouldSkipTest()
{
return false;
}//end shouldSkipTest()
/**
* Tests the extending classes Sniff class.
*
* @return void
* @throws \PHPUnit\Framework\Exception
*/
final public function testSniff()
{
// Skip this test if we can't run in this environment.
if ($this->shouldSkipTest() === true) {
$this->markTestSkipped();
}
$sniffCode = Common::getSniffCode(get_class($this));
list($standardName, $categoryName, $sniffName) = explode('.', $sniffCode);
$testFileBase = $this->testsDir.$categoryName.DIRECTORY_SEPARATOR.$sniffName.'UnitTest.';
// Get a list of all test files to check.
$testFiles = $this->getTestFiles($testFileBase);
if (isset($GLOBALS['PHP_CODESNIFFER_CONFIG']) === true) {
$config = $GLOBALS['PHP_CODESNIFFER_CONFIG'];
} else {
$config = new Config();
$config->cache = false;
$GLOBALS['PHP_CODESNIFFER_CONFIG'] = $config;
}
$config->standards = [$standardName];
$config->sniffs = [$sniffCode];
$config->ignored = [];
if (isset($GLOBALS['PHP_CODESNIFFER_RULESETS']) === false) {
$GLOBALS['PHP_CODESNIFFER_RULESETS'] = [];
}
if (isset($GLOBALS['PHP_CODESNIFFER_RULESETS'][$standardName]) === false) {
$ruleset = new Ruleset($config);
$GLOBALS['PHP_CODESNIFFER_RULESETS'][$standardName] = $ruleset;
}
$ruleset = $GLOBALS['PHP_CODESNIFFER_RULESETS'][$standardName];
$sniffFile = $this->standardsDir.DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR.$categoryName.DIRECTORY_SEPARATOR.$sniffName.'Sniff.php';
$sniffClassName = substr(get_class($this), 0, -8).'Sniff';
$sniffClassName = str_replace('\Tests\\', '\Sniffs\\', $sniffClassName);
$sniffClassName = Common::cleanSniffClass($sniffClassName);
$restrictions = [strtolower($sniffClassName) => true];
$ruleset->registerSniffs([$sniffFile], $restrictions, []);
$ruleset->populateTokenListeners();
$failureMessages = [];
foreach ($testFiles as $testFile) {
$filename = basename($testFile);
$oldConfig = $config->getSettings();
try {
$this->setCliValues($filename, $config);
$phpcsFile = new LocalFile($testFile, $ruleset, $config);
$phpcsFile->process();
} catch (RuntimeException $e) {
$this->fail('An unexpected exception has been caught: '.$e->getMessage());
}
$failures = $this->generateFailureMessages($phpcsFile);
$failureMessages = array_merge($failureMessages, $failures);
if ($phpcsFile->getFixableCount() > 0) {
// Attempt to fix the errors.
$phpcsFile->fixer->fixFile();
$fixable = $phpcsFile->getFixableCount();
if ($fixable > 0) {
$failureMessages[] = "Failed to fix $fixable fixable violations in $filename";
}
// Check for a .fixed file to check for accuracy of fixes.
$fixedFile = $testFile.'.fixed';
if (file_exists($fixedFile) === true) {
$diff = $phpcsFile->fixer->generateDiff($fixedFile);
if (trim($diff) !== '') {
$filename = basename($testFile);
$fixedFilename = basename($fixedFile);
$failureMessages[] = "Fixed version of $filename does not match expected version in $fixedFilename; the diff is\n$diff";
}
}
}
// Restore the config.
$config->setSettings($oldConfig);
}//end foreach
if (empty($failureMessages) === false) {
$this->fail(implode(PHP_EOL, $failureMessages));
}
}//end testSniff()
/**
* Generate a list of test failures for a given sniffed file.
*
* @param \PHP_CodeSniffer\Files\LocalFile $file The file being tested.
*
* @return array
* @throws \PHP_CodeSniffer\Exceptions\RuntimeException
*/
public function generateFailureMessages(LocalFile $file)
{
$testFile = $file->getFilename();
$foundErrors = $file->getErrors();
$foundWarnings = $file->getWarnings();
$expectedErrors = $this->getErrorList(basename($testFile));
$expectedWarnings = $this->getWarningList(basename($testFile));
if (is_array($expectedErrors) === false) {
throw new RuntimeException('getErrorList() must return an array');
}
if (is_array($expectedWarnings) === false) {
throw new RuntimeException('getWarningList() must return an array');
}
/*
We merge errors and warnings together to make it easier
to iterate over them and produce the errors string. In this way,
we can report on errors and warnings in the same line even though
it's not really structured to allow that.
*/
$allProblems = [];
$failureMessages = [];
foreach ($foundErrors as $line => $lineErrors) {
foreach ($lineErrors as $column => $errors) {
if (isset($allProblems[$line]) === false) {
$allProblems[$line] = [
'expected_errors' => 0,
'expected_warnings' => 0,
'found_errors' => [],
'found_warnings' => [],
];
}
$foundErrorsTemp = [];
foreach ($allProblems[$line]['found_errors'] as $foundError) {
$foundErrorsTemp[] = $foundError;
}
$errorsTemp = [];
foreach ($errors as $foundError) {
$errorsTemp[] = $foundError['message'].' ('.$foundError['source'].')';
$source = $foundError['source'];
if (in_array($source, $GLOBALS['PHP_CODESNIFFER_SNIFF_CODES']) === false) {
$GLOBALS['PHP_CODESNIFFER_SNIFF_CODES'][] = $source;
}
if ($foundError['fixable'] === true
&& in_array($source, $GLOBALS['PHP_CODESNIFFER_FIXABLE_CODES']) === false
) {
$GLOBALS['PHP_CODESNIFFER_FIXABLE_CODES'][] = $source;
}
}
$allProblems[$line]['found_errors'] = array_merge($foundErrorsTemp, $errorsTemp);
}//end foreach
if (isset($expectedErrors[$line]) === true) {
$allProblems[$line]['expected_errors'] = $expectedErrors[$line];
} else {
$allProblems[$line]['expected_errors'] = 0;
}
unset($expectedErrors[$line]);
}//end foreach
foreach ($expectedErrors as $line => $numErrors) {
if (isset($allProblems[$line]) === false) {
$allProblems[$line] = [
'expected_errors' => 0,
'expected_warnings' => 0,
'found_errors' => [],
'found_warnings' => [],
];
}
$allProblems[$line]['expected_errors'] = $numErrors;
}
foreach ($foundWarnings as $line => $lineWarnings) {
foreach ($lineWarnings as $column => $warnings) {
if (isset($allProblems[$line]) === false) {
$allProblems[$line] = [
'expected_errors' => 0,
'expected_warnings' => 0,
'found_errors' => [],
'found_warnings' => [],
];
}
$foundWarningsTemp = [];
foreach ($allProblems[$line]['found_warnings'] as $foundWarning) {
$foundWarningsTemp[] = $foundWarning;
}
$warningsTemp = [];
foreach ($warnings as $warning) {
$warningsTemp[] = $warning['message'].' ('.$warning['source'].')';
}
$allProblems[$line]['found_warnings'] = array_merge($foundWarningsTemp, $warningsTemp);
}//end foreach
if (isset($expectedWarnings[$line]) === true) {
$allProblems[$line]['expected_warnings'] = $expectedWarnings[$line];
} else {
$allProblems[$line]['expected_warnings'] = 0;
}
unset($expectedWarnings[$line]);
}//end foreach
foreach ($expectedWarnings as $line => $numWarnings) {
if (isset($allProblems[$line]) === false) {
$allProblems[$line] = [
'expected_errors' => 0,
'expected_warnings' => 0,
'found_errors' => [],
'found_warnings' => [],
];
}
$allProblems[$line]['expected_warnings'] = $numWarnings;
}
// Order the messages by line number.
ksort($allProblems);
foreach ($allProblems as $line => $problems) {
$numErrors = count($problems['found_errors']);
$numWarnings = count($problems['found_warnings']);
$expectedErrors = $problems['expected_errors'];
$expectedWarnings = $problems['expected_warnings'];
$errors = '';
$foundString = '';
if ($expectedErrors !== $numErrors || $expectedWarnings !== $numWarnings) {
$lineMessage = "[LINE $line]";
$expectedMessage = 'Expected ';
$foundMessage = 'in '.basename($testFile).' but found ';
if ($expectedErrors !== $numErrors) {
$expectedMessage .= "$expectedErrors error(s)";
$foundMessage .= "$numErrors error(s)";
if ($numErrors !== 0) {
$foundString .= 'error(s)';
$errors .= implode(PHP_EOL.' -> ', $problems['found_errors']);
}
if ($expectedWarnings !== $numWarnings) {
$expectedMessage .= ' and ';
$foundMessage .= ' and ';
if ($numWarnings !== 0) {
if ($foundString !== '') {
$foundString .= ' and ';
}
}
}
}
if ($expectedWarnings !== $numWarnings) {
$expectedMessage .= "$expectedWarnings warning(s)";
$foundMessage .= "$numWarnings warning(s)";
if ($numWarnings !== 0) {
$foundString .= 'warning(s)';
if (empty($errors) === false) {
$errors .= PHP_EOL.' -> ';
}
$errors .= implode(PHP_EOL.' -> ', $problems['found_warnings']);
}
}
$fullMessage = "$lineMessage $expectedMessage $foundMessage.";
if ($errors !== '') {
$fullMessage .= " The $foundString found were:".PHP_EOL." -> $errors";
}
$failureMessages[] = $fullMessage;
}//end if
}//end foreach
return $failureMessages;
}//end generateFailureMessages()
/**
* Get a list of CLI values to set before the file is tested.
*
* @param string $filename The name of the file being tested.
* @param \PHP_CodeSniffer\Config $config The config data for the run.
*
* @return void
*/
public function setCliValues($filename, $config)
{
return;
}//end setCliValues()
/**
* Returns the lines where errors should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of errors that should occur on that line.
*
* @return array<int, int>
*/
abstract protected function getErrorList();
/**
* Returns the lines where warnings should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of warnings that should occur on that line.
*
* @return array<int, int>
*/
abstract protected function getWarningList();
}//end class

View File

@ -0,0 +1,110 @@
<?php
/**
* A test class for testing all sniffs for installed standards.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests\Standards;
use PHP_CodeSniffer\Util\Standards;
use PHP_CodeSniffer\Autoload;
use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;
use PHPUnit\TextUI\TestRunner;
use PHPUnit\Framework\TestSuite;
class AllSniffs
{
/**
* Prepare the test runner.
*
* @return void
*/
public static function main()
{
TestRunner::run(self::suite());
}//end main()
/**
* Add all sniff unit tests into a test suite.
*
* Sniff unit tests are found by recursing through the 'Tests' directory
* of each installed coding standard.
*
* @return \PHPUnit\Framework\TestSuite
*/
public static function suite()
{
$GLOBALS['PHP_CODESNIFFER_SNIFF_CODES'] = [];
$GLOBALS['PHP_CODESNIFFER_FIXABLE_CODES'] = [];
$suite = new TestSuite('PHP CodeSniffer Standards');
$isInstalled = !is_file(__DIR__.'/../../autoload.php');
// Optionally allow for ignoring the tests for one or more standards.
$ignoreTestsForStandards = getenv('PHPCS_IGNORE_TESTS');
if ($ignoreTestsForStandards === false) {
$ignoreTestsForStandards = [];
} else {
$ignoreTestsForStandards = explode(',', $ignoreTestsForStandards);
}
$installedStandards = Standards::getInstalledStandardDetails(true);
foreach ($installedStandards as $standard => $details) {
Autoload::addSearchPath($details['path'], $details['namespace']);
// If the test is running PEAR installed, the built-in standards
// are split into different directories; one for the sniffs and
// a different file system location for tests.
if ($isInstalled === true && is_dir(dirname($details['path']).DIRECTORY_SEPARATOR.'Generic') === true) {
$testPath = realpath(__DIR__.'/../../src/Standards/'.$standard);
} else {
$testPath = $details['path'];
}
if (in_array($standard, $ignoreTestsForStandards) === true) {
continue;
}
$testsDir = $testPath.DIRECTORY_SEPARATOR.'Tests'.DIRECTORY_SEPARATOR;
if (is_dir($testsDir) === false) {
// No tests for this standard.
continue;
}
$di = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($testsDir));
foreach ($di as $file) {
// Skip hidden files.
if (substr($file->getFilename(), 0, 1) === '.') {
continue;
}
// Tests must have the extension 'php'.
$parts = explode('.', $file);
$ext = array_pop($parts);
if ($ext !== 'php') {
continue;
}
$className = Autoload::loadFile($file->getPathname());
$GLOBALS['PHP_CODESNIFFER_STANDARD_DIRS'][$className] = $details['path'];
$GLOBALS['PHP_CODESNIFFER_TEST_DIRS'][$className] = $testsDir;
$suite->addTestSuite($className);
}
}//end foreach
return $suite;
}//end suite()
}//end class

View File

@ -0,0 +1,35 @@
<?php
/**
* A PHP_CodeSniffer specific test suite for PHPUnit.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests;
use PHPUnit\Framework\TestSuite as PHPUnit_TestSuite;
use PHPUnit\Framework\TestResult;
class TestSuite extends PHPUnit_TestSuite
{
/**
* Runs the tests and collects their result in a TestResult.
*
* @param \PHPUnit\Framework\TestResult $result A test result.
*
* @return \PHPUnit\Framework\TestResult
*/
public function run(TestResult $result=null)
{
$result = parent::run($result);
printPHPCodeSnifferTestOutput();
return $result;
}//end run()
}//end class

View File

@ -0,0 +1,35 @@
<?php
/**
* A PHP_CodeSniffer specific test suite for PHPUnit.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Tests;
use PHPUnit\Framework\TestSuite as PHPUnit_TestSuite;
use PHPUnit\Framework\TestResult;
class TestSuite extends PHPUnit_TestSuite
{
/**
* Runs the tests and collects their result in a TestResult.
*
* @param \PHPUnit\Framework\TestResult $result A test result.
*
* @return \PHPUnit\Framework\TestResult
*/
public function run(TestResult $result=null): TestResult
{
$result = parent::run($result);
printPHPCodeSnifferTestOutput();
return $result;
}//end run()
}//end class

View File

@ -0,0 +1,65 @@
<?php
/**
* Bootstrap file for PHP_CodeSniffer unit tests.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2017 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
if (defined('PHP_CODESNIFFER_IN_TESTS') === false) {
define('PHP_CODESNIFFER_IN_TESTS', true);
}
if (defined('PHP_CODESNIFFER_CBF') === false) {
define('PHP_CODESNIFFER_CBF', false);
}
if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
define('PHP_CODESNIFFER_VERBOSITY', 0);
}
if (is_file(__DIR__.'/../autoload.php') === true) {
include_once __DIR__.'/../autoload.php';
} else {
include_once 'PHP/CodeSniffer/autoload.php';
}
$tokens = new \PHP_CodeSniffer\Util\Tokens();
// Compatibility for PHPUnit < 6 and PHPUnit 6+.
if (class_exists('PHPUnit_Framework_TestSuite') === true && class_exists('PHPUnit\Framework\TestSuite') === false) {
class_alias('PHPUnit_Framework_TestSuite', 'PHPUnit'.'\Framework\TestSuite');
}
if (class_exists('PHPUnit_Framework_TestCase') === true && class_exists('PHPUnit\Framework\TestCase') === false) {
class_alias('PHPUnit_Framework_TestCase', 'PHPUnit'.'\Framework\TestCase');
}
if (class_exists('PHPUnit_TextUI_TestRunner') === true && class_exists('PHPUnit\TextUI\TestRunner') === false) {
class_alias('PHPUnit_TextUI_TestRunner', 'PHPUnit'.'\TextUI\TestRunner');
}
if (class_exists('PHPUnit_Framework_TestResult') === true && class_exists('PHPUnit\Framework\TestResult') === false) {
class_alias('PHPUnit_Framework_TestResult', 'PHPUnit'.'\Framework\TestResult');
}
/**
* A global util function to help print unit test fixing data.
*
* @return void
*/
function printPHPCodeSnifferTestOutput()
{
$codes = count($GLOBALS['PHP_CODESNIFFER_SNIFF_CODES']);
echo PHP_EOL.PHP_EOL;
echo "Tests generated $codes unique error codes";
if ($codes > 0) {
$fixes = count($GLOBALS['PHP_CODESNIFFER_FIXABLE_CODES']);
$percent = round(($fixes / $codes * 100), 2);
echo "; $fixes were fixable ($percent%)";
}
}//end printPHPCodeSnifferTestOutput()