repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Fixer/Semicolon/SpaceAfterSemicolonFixerTest.php
tests/Fixer/Semicolon/SpaceAfterSemicolonFixerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Fixer\Semicolon; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; /** * @internal * * @covers \PhpCsFixer\Fixer\Semicolon\SpaceAfterSemicolonFixer * * @extends AbstractFixerTestCase<\PhpCsFixer\Fixer\Semicolon\SpaceAfterSemicolonFixer> * * @phpstan-import-type _AutogeneratedInputConfiguration from \PhpCsFixer\Fixer\Semicolon\SpaceAfterSemicolonFixer * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SpaceAfterSemicolonFixerTest extends AbstractFixerTestCase { /** * @param _AutogeneratedInputConfiguration $configuration * * @dataProvider provideFixCases */ public function testFix(string $expected, ?string $input = null, array $configuration = []): void { $this->fixer->configure($configuration); $this->doTest($expected, $input); } /** * @return iterable<int, array{0: string, 1?: null|string, 2?: _AutogeneratedInputConfiguration}> */ public static function provideFixCases(): iterable { yield [ '<?php test1(); $a; // test ', ]; yield [ '<?php test2();', ]; yield [ '<?php test3(); ', ]; yield [ '<?php test4(); ', ]; yield [ '<?php test5(); // test ', ]; yield [ '<?php test6(); /* */ //', ]; yield [ '<?php test7a(); /* */', '<?php test7a();/* */', ]; yield [ '<?php test7b(); /* *//**/', '<?php test7b();/* *//**/', ]; yield [ '<?php test8(); $a = 4; ', '<?php test8(); $a = 4; ', ]; yield [ '<?php test9(); $b = 7; ', '<?php test9();$b = 7; ', ]; yield [ '<?php for (; ;) { } ', '<?php for (;;) { } ', ]; yield [ '<?php for (; ; ++$u1) { } ', '<?php for (;;++$u1) { } ', ]; yield [ '<?php for (; $u2 < 0;) { } ', '<?php for (;$u2 < 0;) { } ', ]; yield [ '<?php for (; $u3 < 3; ++$u3) { } ', '<?php for (;$u3 < 3;++$u3) { } ', ]; yield [ '<?php for ($u4 = 0; ;) { } ', '<?php for ($u4 = 0;;) { } ', ]; yield [ '<?php for ($u5 = 0; ; ++$u5) { } ', '<?php for ($u5 = 0;;++$u5) { } ', ]; yield [ '<?php for ($u6 = 0; $u6 < 6;) { } ', '<?php for ($u6 = 0;$u6 < 6;) { } ', ]; yield [ '<?php for ($u7 = 0; $u7 < 7; ++$u7) { } ', '<?php for ($u7 = 0;$u7 < 7;++$u7) { } ', ]; yield [ '<?php for (; ; ) { } ', '<?php for (; ; ) { } ', ]; yield [ '<?php for (; ; ++$u1) { } ', '<?php for (; ; ++$u1) { } ', ]; yield [ '<?php for (; $u2 < 0; ) { } ', '<?php for (; $u2 < 0; ) { } ', ]; yield [ '<?php for (; $u3 < 3; ++$u3) { } ', '<?php for (; $u3 < 3; ++$u3) { } ', ]; yield [ '<?php for ($ui4 = 0; ; ) { } ', '<?php for ($ui4 = 0; ; ) { } ', ]; yield [ '<?php for ($u5 = 0; ; ++$u5) { } ', '<?php for ($u5 = 0; ; ++$u5) { } ', ]; yield [ '<?php for ($u6 = 0; $u6 < 6; ) { } ', '<?php for ($u6 = 0; $u6 < 6; ) { } ', ]; yield [ '<?php for ($u7 = 0; $u7 < 7; ++$u7) { } ', '<?php for ($u7 = 0; $u7 < 7; ++$u7) { } ', ]; yield [ '<?php if ($a):?> 1 <?php endif; ?> <?php if ($b):?> 2 <?php endif; ?> <?php if ($c):?> 3 <?php endif; ?>', '<?php if ($a):?> 1 <?php endif;?> <?php if ($b):?> 2 <?php endif;?> <?php if ($c):?> 3 <?php endif;?>', ]; yield [ '<?php echo 1; ; ; ; ; ; ; ; ;', '<?php echo 1;;;;;;;;;', ]; yield [ '<?php test1(); $a; // test ', null, ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php test2();', null, ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php test3(); ', null, ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php test4(); ', null, ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php test5(); // test ', null, ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php test6(); /* */ //', null, ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php test7a(); /* */', '<?php test7a();/* */', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php test7b(); /* *//**/', '<?php test7b();/* *//**/', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php test8(); $a = 4; ', '<?php test8(); $a = 4; ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php test9(); $b = 7; ', '<?php test9();$b = 7; ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for (;;) { } ', '<?php for (; ;) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for (;; ++$u1) { } ', '<?php for (;;++$u1) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for (; $u2 < 0;) { } ', '<?php for (;$u2 < 0;) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for (; $u3 < 3; ++$u3) { } ', '<?php for (;$u3 < 3;++$u3) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for ($u4 = 0;;) { } ', '<?php for ($u4 = 0; ;) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for ($u5 = 0;; ++$u5) { } ', '<?php for ($u5 = 0;;++$u5) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for ($u6 = 0; $u6 < 6;) { } ', '<?php for ($u6 = 0;$u6 < 6;) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for ($u7 = 0; $u7 < 7; ++$u7) { } ', '<?php for ($u7 = 0;$u7 < 7;++$u7) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for (;;) { } ', '<?php for (; ; ) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for (;; ++$u1) { } ', '<?php for (; ; ++$u1) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for (; $u2 < 0;) { } ', '<?php for (; $u2 < 0; ) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for (; $u3 < 3; ++$u3) { } ', '<?php for (; $u3 < 3; ++$u3) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for ($ui4 = 0;;) { } ', '<?php for ($ui4 = 0; ; ) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for ($u5 = 0;; ++$u5) { } ', '<?php for ($u5 = 0; ; ++$u5) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for ($u6 = 0; $u6 < 6;) { } ', '<?php for ($u6 = 0; $u6 < 6; ) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for ($u7 = 0; $u7 < 7; ++$u7) { } ', '<?php for ($u7 = 0; $u7 < 7; ++$u7) { } ', ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for ( $u7 = 0; ; ++$u7 ) { } ', null, ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php for ( /* foo */ ; /* bar */ ; /* baz */ ) { }', null, ['remove_in_empty_for_expressions' => true], ]; yield [ '<?php __HALT_COMPILER(); ', ]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixerTest.php
tests/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Fixer\Semicolon; use PhpCsFixer\Fixer\Semicolon\MultilineWhitespaceBeforeSemicolonsFixer; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; use PhpCsFixer\WhitespacesFixerConfig; /** * @internal * * @covers \PhpCsFixer\Fixer\Semicolon\MultilineWhitespaceBeforeSemicolonsFixer * * @extends AbstractFixerTestCase<\PhpCsFixer\Fixer\Semicolon\MultilineWhitespaceBeforeSemicolonsFixer> * * @author John Kelly <wablam@gmail.com> * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * @author Egidijus Girčys <e.gircys@gmail.com> * * @phpstan-import-type _AutogeneratedInputConfiguration from \PhpCsFixer\Fixer\Semicolon\MultilineWhitespaceBeforeSemicolonsFixer * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class MultilineWhitespaceBeforeSemicolonsFixerTest extends AbstractFixerTestCase { /** * @param _AutogeneratedInputConfiguration $configuration * * @dataProvider provideFixCases */ public function testFix(string $expected, ?string $input = null, array $configuration = [], ?WhitespacesFixerConfig $whitespacesConfig = null): void { $this->fixer->configure($configuration); $this->fixer->setWhitespacesConfig($whitespacesConfig ?? new WhitespacesFixerConfig()); $this->doTest($expected, $input); } /** * @return iterable<array{0: string, 1?: null|string, 2?: _AutogeneratedInputConfiguration, 3?: WhitespacesFixerConfig}> */ public static function provideFixCases(): iterable { yield [ '<?php $foo->bar(); // test', '<?php $foo->bar() // test ;', ]; yield [ '<?php echo(1); // test', "<?php echo(1) // test\n;", ]; yield [ "<?php echo(1); // test\n", ]; yield [ '<?php $foo->bar(); # test', '<?php $foo->bar() # test ;', ]; yield [ '<?php $foo->bar();// test', '<?php $foo->bar()// test ;', ]; yield [ "<?php\n;", ]; yield [ '<?= $a; ?>', ]; yield [ '<?php $this ->setName(\'readme1\') ->setDescription(\'Generates the README\'); ', '<?php $this ->setName(\'readme1\') ->setDescription(\'Generates the README\') ; ', ]; yield [ '<?php $this ->setName(\'readme2\') ->setDescription(\'Generates the README\'); ', '<?php $this ->setName(\'readme2\') ->setDescription(\'Generates the README\') ; ', ]; yield [ '<?php echo "$this->foo(\'with param containing ;\') ;" ;', ]; yield [ '<?php $this->foo();', ]; yield [ '<?php $this->foo() ;', ]; yield [ '<?php $this->foo(\'with param containing ;\') ;', ]; yield [ '<?php $this->foo(\'with param containing ) ; \') ;', ]; yield [ '<?php $this->foo("with param containing ) ; ") ; ?>', ]; yield [ '<?php $this->foo("with semicolon in string) ; "); ?>', ]; yield [ '<?php $this ->example();', '<?php $this ->example() ;', ]; yield [ '<?php Foo::bar(); // test', '<?php Foo::bar() // test ;', ]; yield [ '<?php Foo::bar(); # test', '<?php Foo::bar() # test ;', ]; yield [ '<?php self ::setName(\'readme1\') ->setDescription(\'Generates the README\'); ', '<?php self ::setName(\'readme1\') ->setDescription(\'Generates the README\') ; ', ]; yield [ '<?php self ::setName(\'readme2\') ->setDescription(\'Generates the README\'); ', '<?php self ::setName(\'readme2\') ->setDescription(\'Generates the README\') ; ', ]; yield [ '<?php echo "self::foo(\'with param containing ;\') ;" ;', ]; yield [ '<?php self::foo();', ]; yield [ '<?php self::foo() ;', ]; yield [ '<?php self::foo(\'with param containing ;\') ;', ]; yield [ '<?php self::foo(\'with param containing ) ; \') ;', ]; yield [ '<?php self::foo("with param containing ) ; ") ; ?>', ]; yield [ '<?php self::foo("with semicolon in string) ; "); ?>', ]; yield [ '<?php self ::example();', '<?php self ::example() ;', ]; yield [ '<?php $seconds = $minutes * 60; // seconds in a minute', '<?php $seconds = $minutes * 60 // seconds in a minute ;', ]; yield [ '<?php $seconds = $minutes * (int) \'60\'; // seconds in a minute', '<?php $seconds = $minutes * (int) \'60\' // seconds in a minute ;', ]; yield [ '<?php $secondsPerMinute = 60; $seconds = $minutes * $secondsPerMinute; // seconds in a minute', '<?php $secondsPerMinute = 60; $seconds = $minutes * $secondsPerMinute // seconds in a minute ;', ]; yield [ '<?php $secondsPerMinute = 60; $seconds = $minutes * 60 * (int) true; // seconds in a minute', '<?php $secondsPerMinute = 60; $seconds = $minutes * 60 * (int) true // seconds in a minute ;', ]; yield [ '<?php echo(1); // test', "<?php echo(1) // test\r\n;", ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NO_MULTI_LINE], new WhitespacesFixerConfig("\t", "\r\n"), ]; yield [ '<?php $this ->method1() ->method2() ; ?>', '<?php $this ->method1() ->method2(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $this ->method1() ->method2() // comment ; ', '<?php $this ->method1() ->method2(); // comment ', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $service->method1() ->method2() ; $service->method3(); $this ->method1() ->method2() ;', '<?php $service->method1() ->method2() ; $service->method3(); $this ->method1() ->method2();', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $service ->method2() ; ?>', '<?php $service ->method2(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $service->method1() ->method2() ->method3() ->method4() ; ?>', '<?php $service->method1() ->method2() ->method3() ->method4(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $this->service->method1() ->method2([1, 2]) ->method3( "2", 2, [1, 2] ) ->method4() ; ?>', '<?php $this->service->method1() ->method2([1, 2]) ->method3( "2", 2, [1, 2] ) ->method4(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $service ->method1() ->method2() ->method3() ->method4() ; ?>', '<?php $service ->method1() ->method2() ->method3() ->method4(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $f = "g"; $service ->method1("a", true) ->method2(true, false) ->method3([1, 2, 3], ["a" => "b", "c" => 1, "d" => true]) ->method4(1, "a", $f) ; ?>', '<?php $f = "g"; $service ->method1("a", true) ->method2(true, false) ->method3([1, 2, 3], ["a" => "b", "c" => 1, "d" => true]) ->method4(1, "a", $f); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $f = "g"; $service ->method1("a", true) // this is a comment /* ->method2(true, false) */ ->method3([1, 2, 3], ["a" => "b", "c" => 1, "d" => true]) ->method4(1, "a", $f) /* this is a comment */ ; ?>', '<?php $f = "g"; $service ->method1("a", true) // this is a comment /* ->method2(true, false) */ ->method3([1, 2, 3], ["a" => "b", "c" => 1, "d" => true]) ->method4(1, "a", $f); /* this is a comment */ ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $service->method1(); $service->method2()->method3(); ?>', null, ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $service->method1() ; $service->method2()->method3() ; ?>', null, ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $service ->method2(function ($a) { $a->otherCall() ->a() ->b() ; }) ; ?>', '<?php $service ->method2(function ($a) { $a->otherCall() ->a() ->b() ; }); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $data = $service ->method2(function ($a) { $a->otherCall() ->a() ->b(array_merge([ 1 => 1, 2 => 2, ], $this->getOtherArray() )) ; }) ; ?>', '<?php $data = $service ->method2(function ($a) { $a->otherCall() ->a() ->b(array_merge([ 1 => 1, 2 => 2, ], $this->getOtherArray() )); }); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $service ->method1(null, null, [ null => null, 1 => $data->getId() > 0, ]) ->method2(4, Type::class) ; ', '<?php $service ->method1(null, null, [ null => null, 1 => $data->getId() > 0, ]) ->method2(4, Type::class); ', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $this ->method1() ->method2() ; ?>', '<?php $this ->method1() ->method2(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php self ::method1() ->method2() ; ?>', '<?php self ::method1() ->method2(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php self ::method1() ->method2() // comment ; ', '<?php self ::method1() ->method2(); // comment ', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php Service::method1() ->method2() ; Service::method3(); $this ->method1() ->method2() ;', '<?php Service::method1() ->method2() ; Service::method3(); $this ->method1() ->method2();', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php Service ::method2() ; ?>', '<?php Service ::method2(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php Service::method1() ->method2() ->method3() ->method4() ; ?>', '<?php Service::method1() ->method2() ->method3() ->method4(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php self::method1() ->method2([1, 2]) ->method3( "2", 2, [1, 2] ) ->method4() ; ?>', '<?php self::method1() ->method2([1, 2]) ->method3( "2", 2, [1, 2] ) ->method4(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php Service ::method1() ->method2() ->method3() ->method4() ; ?>', '<?php Service ::method1() ->method2() ->method3() ->method4(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $f = "g"; Service ::method1("a", true) ->method2(true, false) ->method3([1, 2, 3], ["a" => "b", "c" => 1, "d" => true]) ->method4(1, "a", $f) ; ?>', '<?php $f = "g"; Service ::method1("a", true) ->method2(true, false) ->method3([1, 2, 3], ["a" => "b", "c" => 1, "d" => true]) ->method4(1, "a", $f); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $f = "g"; Service ::method1("a", true) // this is a comment /* ->method2(true, false) */ ->method3([1, 2, 3], ["a" => "b", "c" => 1, "d" => true]) ->method4(1, "a", $f) /* this is a comment */ ; ?>', '<?php $f = "g"; Service ::method1("a", true) // this is a comment /* ->method2(true, false) */ ->method3([1, 2, 3], ["a" => "b", "c" => 1, "d" => true]) ->method4(1, "a", $f); /* this is a comment */ ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php Service::method1(); Service::method2()->method3(); ?>', null, ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php Service::method1() ; Service::method2()->method3() ; ?>', null, ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php Service ::method2(function ($a) { $a->otherCall() ->a() ->b() ; }) ; ?>', '<?php Service ::method2(function ($a) { $a->otherCall() ->a() ->b() ; }); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $data = Service ::method2(function () { Foo::otherCall() ->a() ->b(array_merge([ 1 => 1, 2 => 2, ], $this->getOtherArray() )) ; }) ; ?>', '<?php $data = Service ::method2(function () { Foo::otherCall() ->a() ->b(array_merge([ 1 => 1, 2 => 2, ], $this->getOtherArray() )); }); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php Service ::method1(null, null, [ null => null, 1 => $data->getId() > 0, ]) ->method2(4, Type::class) ; ', '<?php Service ::method1(null, null, [ null => null, 1 => $data->getId() > 0, ]) ->method2(4, Type::class); ', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php Service ::method1() ->method2() ; ?>', '<?php Service ::method1() ->method2(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php function foo($bar) { if ($bar === 1) { $baz ->bar() ; } return (new Foo($bar)) ->baz() ; } ?>', '<?php function foo($bar) { if ($bar === 1) { $baz ->bar(); } return (new Foo($bar)) ->baz(); } ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $foo = (new Foo($bar)) ->baz() ; function foo($bar) { $foo = (new Foo($bar)) ->baz() ; } ?>', '<?php $foo = (new Foo($bar)) ->baz(); function foo($bar) { $foo = (new Foo($bar)) ->baz(); } ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $object ->methodA() ->methodB() ; ', '<?php $object ->methodA() ->methodB(); ', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $object ->methodA() ->methodB() ; ', '<?php $object ->methodA() ->methodB(); ', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ "<?php\n\$this\n ->one()\n ->two(2, )\n;", "<?php\n\$this\n ->one()\n ->two(2, );", ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ "<?php\n\$this\n ->one(1, )\n ->two()\n;", "<?php\n\$this\n ->one(1, )\n ->two();", ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $foo->bar(); Service::method1() ->method2() ->method3()->method4() ; ?>', '<?php $foo->bar() ; Service::method1() ->method2() ->method3()->method4(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $foo->bar(); \Service::method1() ->method2() ->method3()->method4() ; ?>', '<?php $foo->bar() ; \Service::method1() ->method2() ->method3()->method4(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $foo->bar(); Ns\Service::method1() ->method2() ->method3()->method4() ; ?>', '<?php $foo->bar() ; Ns\Service::method1() ->method2() ->method3()->method4(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $foo->bar(); \Ns\Service::method1() ->method2() ->method3()->method4() ; ?>', '<?php $foo->bar() ; \Ns\Service::method1() ->method2() ->method3()->method4(); ?>', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $this ->setName(\'readme2\') ->setDescription(\'Generates the README\') ; ', '<?php $this ->setName(\'readme2\') ->setDescription(\'Generates the README\') ; ', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $this ->foo() ->{$bar ? \'bar\' : \'baz\'}() ; ', null, ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php foo("bar") ->method1() ->method2() ; ', '<?php foo("bar") ->method1() ->method2(); ', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $result = $arrayOfAwesomeObjects["most awesome object"] ->method1() ->method2() ; ', '<?php $result = $arrayOfAwesomeObjects["most awesome object"] ->method1() ->method2(); ', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php $foo; $bar = [ 1 => 2, 3 => $baz->method(), ]; ', null, ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ '<?php switch ($foo) { case 1: $bar ->baz() ; } ', '<?php switch ($foo) { case 1: $bar ->baz() ; } ', ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ <<<'PHP' <?php $x->foo() ->bar() ;$y = 42; PHP, <<<'PHP' <?php $x->foo() ->bar();$y = 42; PHP, ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], ]; yield [ "<?php\r\n\r\n \$this\r\n\t->method1()\r\n\t\t->method2()\r\n ;", "<?php\r\n\r\n \$this\r\n\t->method1()\r\n\t\t->method2();", ['strategy' => MultilineWhitespaceBeforeSemicolonsFixer::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], new WhitespacesFixerConfig("\t", "\r\n"), ]; yield [
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
true
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Fixer/Semicolon/SemicolonAfterInstructionFixerTest.php
tests/Fixer/Semicolon/SemicolonAfterInstructionFixerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Fixer\Semicolon; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; /** * @internal * * @covers \PhpCsFixer\Fixer\Semicolon\SemicolonAfterInstructionFixer * * @extends AbstractFixerTestCase<\PhpCsFixer\Fixer\Semicolon\SemicolonAfterInstructionFixer> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SemicolonAfterInstructionFixerTest extends AbstractFixerTestCase { /** * @dataProvider provideFixCases */ public function testFix(string $expected, ?string $input = null): void { $this->doTest($expected, $input); } /** * @return iterable<array{0: string, 1?: string}> */ public static function provideFixCases(): iterable { yield 'comment' => [ '<?php $a++;//a ?>', '<?php $a++//a ?>', ]; yield 'comment II' => [ '<?php $b++; /**/ ?>', '<?php $b++ /**/ ?>', ]; yield 'no space' => [ '<?php $b++;?>', '<?php $b++?>', ]; yield [ '<?php echo 123; ?>', '<?php echo 123 ?>', ]; yield [ "<?php echo 123;\n\t?>", "<?php echo 123\n\t?>", ]; yield ['<?php ?>']; yield ['<?php ; ?>']; yield ['<?php if($a){}']; yield ['<?php while($a > $b){}']; yield [ '<?php if ($a == 5): ?> A is equal to 5 <?php endif; ?> <?php switch ($foo): ?> <?php case 1: ?> ... <?php endswitch; ?>', '<?php if ($a == 5): ?> A is equal to 5 <?php endif; ?> <?php switch ($foo): ?> <?php case 1: ?> ... <?php endswitch ?>', ]; yield [ '<?php if ($a == 5) { ?> A is equal to 5 <?php } ?>', ]; yield 'open tag with echo' => [ "<?= '1_'; ?> <?php ?><?= 1; ?>", "<?= '1_' ?> <?php ?><?= 1; ?>", ]; } /** * @dataProvider provideFixPre80Cases * * @requires PHP <8.0 */ public function testFixPre80(string $expected, ?string $input = null): void { $this->doTest($expected, $input); } /** * @return iterable<int, array{string, string}> */ public static function provideFixPre80Cases(): iterable { yield [ '<?php $a = [1,2,3]; echo $a{1}; ?>', '<?php $a = [1,2,3]; echo $a{1} ?>', ]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixerTest.php
tests/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Fixer\NamespaceNotation; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; use PhpCsFixer\WhitespacesFixerConfig; /** * @internal * * @covers \PhpCsFixer\Fixer\NamespaceNotation\NoLeadingNamespaceWhitespaceFixer * * @extends AbstractFixerTestCase<\PhpCsFixer\Fixer\NamespaceNotation\NoLeadingNamespaceWhitespaceFixer> * * @author Bram Gotink <bram@gotink.me> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoLeadingNamespaceWhitespaceFixerTest extends AbstractFixerTestCase { /** * @dataProvider provideFixCases */ public function testFix(string $expected, ?string $input = null): void { $this->doTest($expected, $input); } /** * @return iterable<int, array{0: string, 1?: string}> */ public static function provideFixCases(): iterable { $manySpaces = []; for ($i = 1; $i <= 100; ++$i) { $manySpaces[] = 'namespace Test'.$i.';'; } // with newline yield ["<?php\nnamespace Test1;"]; yield ["<?php\n\nnamespace Test2;"]; yield [ "<?php\nnamespace Test3;", "<?php\n namespace Test3;", ]; // without newline yield ['<?php namespace Test4;']; yield [ '<?php namespace Test5;', '<?php namespace Test5;', ]; // multiple namespaces with newline yield [ '<?php namespace Test6a; namespace Test6b;', ]; yield [ '<?php namespace Test7a; /* abc */ namespace Test7b;', '<?php namespace Test7a; /* abc */namespace Test7b;', ]; yield [ '<?php namespace Test8a; namespace Test8b;', '<?php namespace Test8a; namespace Test8b;', ]; yield [ '<?php namespace Test9a; class Test {} namespace Test9b;', '<?php namespace Test9a; class Test {} namespace Test9b;', ]; yield [ '<?php namespace Test10a; use Exception; namespace Test10b;', '<?php namespace Test10a; use Exception; namespace Test10b;', ]; // multiple namespaces without newline yield ['<?php namespace Test11a; namespace Test11b;']; yield [ '<?php namespace Test12a; namespace Test12b;', '<?php namespace Test12a; namespace Test12b;', ]; yield [ '<?php namespace Test13a; namespace Test13b;', '<?php namespace Test13a; namespace Test13b;', ]; // namespaces without spaces in between yield [ '<?php namespace Test14a{} namespace Test14b{}', '<?php namespace Test14a{}namespace Test14b{}', ]; yield [ '<?php namespace Test15a; namespace Test15b;', '<?php namespace Test15a;namespace Test15b;', ]; yield [ '<?php '.implode("\n", $manySpaces), '<?php '.implode('', $manySpaces), ]; yield [ '<?php # namespace TestComment;', '<?php # namespace TestComment;', ]; } /** * @dataProvider provideWithWhitespacesConfigCases */ public function testWithWhitespacesConfig(string $expected, ?string $input = null): void { $this->fixer->setWhitespacesConfig(new WhitespacesFixerConfig("\t", "\r\n")); $this->doTest($expected, $input); } /** * @return iterable<int, array{string, string}> */ public static function provideWithWhitespacesConfigCases(): iterable { yield [ "<?php\r\nnamespace TestW1a{}\r\nnamespace TestW1b{}", "<?php\r\n namespace TestW1a{}\r\nnamespace TestW1b{}", ]; yield [ "<?php\r\nnamespace Test14a{}\r\nnamespace Test14b{}", "<?php\r\n namespace Test14a{}namespace Test14b{}", ]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Fixer/NamespaceNotation/CleanNamespaceFixerTest.php
tests/Fixer/NamespaceNotation/CleanNamespaceFixerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Fixer\NamespaceNotation; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; /** * @internal * * @covers \PhpCsFixer\Fixer\NamespaceNotation\CleanNamespaceFixer * * @extends AbstractFixerTestCase<\PhpCsFixer\Fixer\NamespaceNotation\CleanNamespaceFixer> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CleanNamespaceFixerTest extends AbstractFixerTestCase { /** * @requires PHP <8.0 * * @dataProvider provideFixCases */ public function testFix(string $expected, string $input): void { $this->doTest($expected, $input); } /** * @return iterable<int, array{string, string}> */ public static function provideFixCases(): iterable { yield [ '<?php use function FooLibrary\Bar\Baz\ClassA as Foo ?>', '<?php use function FooLibrary \ Bar \ Baz \ /* A */ ClassA as Foo ?>', ]; yield [ '<?php use function FooLibrary\Bar\Baz\ClassA as Foo;', '<?php use function FooLibrary \ Bar \ Baz \ /* A */ ClassA as Foo;', ]; yield [ '<?php namespace AT\B # foo 3 ;', '<?php namespace AT # foo 1 \ /** 2 */ B # foo 3 ;', ]; yield [ '<?php namespace AX\B;', '<?php namespace AX /* foo */ \ B;', ]; yield [ '<?php namespace A1\B\C ; // foo', '<?php namespace A1 \ B \ C ; // foo', ]; yield [ '<?php echo A\B();A\B();A\B();A\B();', '<?php echo A \ B();A \ B();A \ B();A \ B();', ]; yield [ '<?php namespace A\B ?>', '<?php namespace A \ B ?>', ]; yield [ '<?php echo /* */ x\y() ?>', '<?php echo /* */ x \ y() ?>', ]; yield [ '<?php namespace A\B\C\D;?>', '<?php namespace A\/* 1 */B/* 2 */\C/* 3 *//* 4 */\/* 5 */D;?>', ]; yield [ '<?php namespace A\B ?>', '<?php namespace A \/* 1 */ B ?>', ]; yield [ '<?php echo A\B(1, 2, 3) ?>', '<?php echo A \ /* 1 */ B(1, 2, 3) ?>', ]; yield [ '<?php namespace A\B\C\D\E /* 5.1 */{ } namespace B\B\C\D\E /* 5.2 */{ } namespace C\B\C\D\E /* 5.3 */{ } namespace D\B\C\D\E /* 5.4 */{ } namespace E\B\C\D\E /* 5.5 */{ } ', '<?php namespace A /* 1 */ \ B \ /** 2 */ C \ /* 3 */ D /* 4 */ \ E /* 5.1 */{ } namespace B /* 1 */ \ B \ /* 2 */ C \ /** 3 */ D /* 4 */ \ E /* 5.2 */{ } namespace C /* 1 */ \ B \ /* 2 */ C \ /* 3 */ D /** 4 */ \ E /* 5.3 */{ } namespace D /* 1 */ \ B \ /* 2 */ C \ /* 3 */ D /* 4 */ \ E /* 5.4 */{ } namespace E /* 1 */ \ B \ /* 2 */ C \ /* 3 */ D /* 4 */ \ E /* 5.5 */{ } ', ]; yield [ '<?php namespace A\B; try { foo(); } catch ( \ParseError\A\B $e) { } if ( !a instanceof \EventDispatcher\EventDispatcherInterface ) { foo(); } ', '<?php namespace A \ B; try { foo(); } catch ( \ ParseError\ A \ B $e) { } if ( !a instanceof \EventDispatcher\/* 1 */EventDispatcherInterface ) { foo(); } ', ]; yield [ '<?php use function Foo\iter\ { range, map, filter, apply, reduce, foo\operator }; class Foo { private function foo1(): \Exception\A /** 2 */ // trailing comment { } private function foo2(): \Exception // trailing comment { } }', '<?php use function Foo \ iter /* A */ \ { range, map, filter, apply, reduce, foo \ operator }; class Foo { private function foo1(): \Exception \ /* 1 */ A /** 2 */ // trailing comment { } private function foo2(): \Exception // trailing comment { } }', ]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixerTest.php
tests/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Fixer\NamespaceNotation; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; use PhpCsFixer\WhitespacesFixerConfig; /** * @internal * * @covers \PhpCsFixer\Fixer\NamespaceNotation\NoBlankLinesBeforeNamespaceFixer * * @extends AbstractFixerTestCase<\PhpCsFixer\Fixer\NamespaceNotation\NoBlankLinesBeforeNamespaceFixer> * * @author Graham Campbell <hello@gjcampbell.co.uk> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoBlankLinesBeforeNamespaceFixerTest extends AbstractFixerTestCase { /** * @dataProvider provideFixCases */ public function testFix(string $expected, ?string $input = null, ?WhitespacesFixerConfig $whitespacesConfig = null): void { $this->fixer->setWhitespacesConfig($whitespacesConfig ?? new WhitespacesFixerConfig()); $this->doTest($expected, $input); } /** * @return iterable<int, array{0: string, 1?: string, 2?: WhitespacesFixerConfig}> */ public static function provideFixCases(): iterable { yield ['<?php namespace Some\Name\Space;']; yield ["<?php\nnamespace X;"]; yield ["<?php\nnamespace X;", "<?php\n\n\n\nnamespace X;"]; yield ["<?php\r\nnamespace X;"]; yield ["<?php\nnamespace X;", "<?php\r\n\r\n\r\n\r\nnamespace X;"]; yield ["<?php\r\nnamespace X;", "<?php\r\n\r\n\r\n\r\nnamespace X;", new WhitespacesFixerConfig(' ', "\r\n")]; yield ["<?php\n\nnamespace\\Sub\\Foo::bar();"]; yield [ '<?php // Foo namespace Foo; ', '<?php // Foo '.' namespace Foo; ', ]; yield [ '<?php // Foo namespace Foo; ', '<?php // Foo '.' namespace Foo; ', ]; } public function testFixExampleWithComment(): void { $expected = <<<'EOF' <?php /* * This file is part of the PHP CS utility. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\Contrib; EOF; $input = <<<'EOF' <?php /* * This file is part of the PHP CS utility. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\Contrib; EOF; $this->doTest($expected, $input); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixerTest.php
tests/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Fixer\NamespaceNotation; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; use PhpCsFixer\WhitespacesFixerConfig; /** * @internal * * @covers \PhpCsFixer\Fixer\NamespaceNotation\SingleBlankLineBeforeNamespaceFixer * * @extends AbstractFixerTestCase<\PhpCsFixer\Fixer\NamespaceNotation\SingleBlankLineBeforeNamespaceFixer> * * @author Graham Campbell <hello@gjcampbell.co.uk> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SingleBlankLineBeforeNamespaceFixerTest extends AbstractFixerTestCase { /** * @dataProvider provideFixCases */ public function testFix(string $expected, ?string $input = null, ?WhitespacesFixerConfig $whitespacesConfig = null): void { $this->fixer->setWhitespacesConfig($whitespacesConfig ?? new WhitespacesFixerConfig()); $this->doTest($expected, $input); } /** * @return iterable<int, array{0: string, 1?: string, 2?: WhitespacesFixerConfig}> */ public static function provideFixCases(): iterable { yield ["<?php\n\nnamespace X;"]; yield ["<?php\n\nnamespace X;", "<?php\n\n\n\nnamespace X;"]; yield ["<?php\r\n\r\nnamespace X;"]; yield ["<?php\n\nnamespace X;", "<?php\r\n\r\n\r\n\r\nnamespace X;"]; yield ["<?php\n\nfoo();\nnamespace\\bar\\baz();"]; yield ["<?php\n\nnamespace X;", "<?php\nnamespace X;"]; yield ["<?php\n\nnamespace X;", '<?php namespace X;']; yield ["<?php\n\nnamespace X;", "<?php\t\nnamespace X;"]; yield ["<?php \n\nnamespace X;"]; yield ["<?php\r\n\r\nnamespace X;", '<?php namespace X;', new WhitespacesFixerConfig(' ', "\r\n")]; yield ["<?php\r\n\r\nnamespace X;", "<?php\nnamespace X;", new WhitespacesFixerConfig(' ', "\r\n")]; yield ["<?php\r\n\r\nnamespace X;", "<?php\n\n\n\nnamespace X;", new WhitespacesFixerConfig(' ', "\r\n")]; yield ["<?php\r\n\r\nnamespace X;", "<?php\r\n\n\nnamespace X;", new WhitespacesFixerConfig(' ', "\r\n")]; } public function testFixExampleWithCommentTooMuch(): void { $expected = <<<'EOF' <?php /* * This file is part of the PHP CS utility. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\Contrib; EOF; $input = <<<'EOF' <?php /* * This file is part of the PHP CS utility. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\Contrib; EOF; $this->doTest($expected, $input); } public function testFixExampleWithCommentTooLittle(): void { $expected = <<<'EOF' <?php /* * This file is part of the PHP CS utility. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\Contrib; EOF; $input = <<<'EOF' <?php /* * This file is part of the PHP CS utility. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\Contrib; EOF; $this->doTest($expected, $input); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixerTest.php
tests/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Fixer\NamespaceNotation; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; use PhpCsFixer\WhitespacesFixerConfig; /** * @internal * * @covers \PhpCsFixer\Fixer\NamespaceNotation\BlankLineAfterNamespaceFixer * * @extends AbstractFixerTestCase<\PhpCsFixer\Fixer\NamespaceNotation\BlankLineAfterNamespaceFixer> * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class BlankLineAfterNamespaceFixerTest extends AbstractFixerTestCase { /** * @dataProvider provideFixCases */ public function testFix(string $expected, ?string $input = null): void { $this->doTest($expected, $input); } /** * @return iterable<int, array{0: string, 1?: string}> */ public static function provideFixCases(): iterable { yield [ '<?php namespace A\B?> <?php for($i=0; $i<10; ++$i) {echo $i;}', ]; yield [ '<?php namespace A\B?>', ]; yield [ '<?php namespace A\B; class C {} ', '<?php namespace A\B; class C {} ', ]; yield [ '<?php namespace A\B; class C {} ', '<?php namespace A\B; class C {} ', ]; yield [ '<?php namespace A\B; class C {} ', '<?php namespace A\B; class C {} ', ]; yield [ '<?php namespace A\B; class C {} ', '<?php namespace A\B;class C {} ', ]; yield [ '<?php namespace A\B { class C { public $foo; private $bar; } } ', ]; yield [ "<?php\rnamespace A\\B; class C {}\r", "<?php\rnamespace A\\B;\r\r\r\r\r\rclass C {}\r", ]; yield [ '<?php namespace A\B; namespace\C\func(); foo(); ', ]; yield [ '<?php namespace Foo; ', '<?php namespace Foo; ', ]; yield [ '<?php namespace Foo; ', '<?php namespace Foo;', ]; yield [ '<?php namespace Foo; ?>', '<?php namespace Foo; ?>', ]; yield [ '<?php namespace Foo; class Bar {}', ]; yield [ '<?php namespace Foo; class Bar {}', '<?php namespace Foo; class Bar {}', ]; yield [ '<?php namespace My\NS; class X extends Y {}', ]; yield [ '<?php namespace My\NS; // comment class X extends Y {}', ]; yield [ '<?php namespace My\NS; /* comment */ class X extends Y {}', ]; yield [ '<?php namespace My\NS; /* comment 1 comment 2 */ class X extends Y {}', '<?php namespace My\NS; /* comment 1 comment 2 */ class X extends Y {}', ]; yield [ '<?php namespace My\NS; /** comment */ class X extends Y {}', ]; yield [ '<?php namespace My\NS; /** comment 1 comment 2 */ class X extends Y {}', '<?php namespace My\NS; /** comment 1 comment 2 */ class X extends Y {}', ]; } /** * @dataProvider provideWithWhitespacesConfigCases */ public function testWithWhitespacesConfig(string $expected, ?string $input = null): void { $this->fixer->setWhitespacesConfig(new WhitespacesFixerConfig("\t", "\r\n")); $this->doTest($expected, $input); } /** * @return iterable<int, array{string, string}> */ public static function provideWithWhitespacesConfigCases(): iterable { yield [ "<?php namespace A\\B;\r\n\r\nclass C {}", '<?php namespace A\B; class C {}', ]; yield [ "<?php namespace A\\B;\r\n\r\nclass C {}", "<?php namespace A\\B;\r\n\r\n\r\n\r\n\r\n\r\nclass C {}", ]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixerTest.php
tests/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Fixer\NamespaceNotation; use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; use PhpCsFixer\WhitespacesFixerConfig; /** * @internal * * @covers \PhpCsFixer\Fixer\NamespaceNotation\BlankLinesBeforeNamespaceFixer * * @extends AbstractFixerTestCase<\PhpCsFixer\Fixer\NamespaceNotation\BlankLinesBeforeNamespaceFixer> * * @author Greg Korba <greg@codito.dev> * * @phpstan-import-type _AutogeneratedInputConfiguration from \PhpCsFixer\Fixer\NamespaceNotation\BlankLinesBeforeNamespaceFixer * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class BlankLinesBeforeNamespaceFixerTest extends AbstractFixerTestCase { /** * @param _AutogeneratedInputConfiguration $configuration * * @dataProvider provideFixCases */ public function testFix( string $expected, ?string $input = null, ?array $configuration = [], ?WhitespacesFixerConfig $whitespacesConfig = null ): void { $this->fixer->configure($configuration); $this->fixer->setWhitespacesConfig($whitespacesConfig ?? new WhitespacesFixerConfig()); $this->doTest($expected, $input); } /** * @return iterable<string, array{0: string, 1?: null|string, 2?: _AutogeneratedInputConfiguration}> */ public static function provideFixCases(): iterable { yield 'multiple blank lines between namespace declaration and PHP opening tag' => [ "<?php\n\n\n\nnamespace X;", "<?php\nnamespace X;", ['min_line_breaks' => 4, 'max_line_breaks' => 4], ]; yield 'multiple blank lines between namespace declaration and comment' => [ "<?php\n/* Foo */\n\n\nnamespace X;", "<?php\n/* Foo */\nnamespace X;", ['min_line_breaks' => 3, 'max_line_breaks' => 3], ]; yield 'multiple blank lines within min and max line breaks range' => [ "<?php\n\n\n\nnamespace X;", null, ['min_line_breaks' => 3, 'max_line_breaks' => 5], ]; yield 'multiple blank lines with fewer line breaks than minimum' => [ "<?php\n\n\nnamespace X;", "<?php\n\nnamespace X;", ['min_line_breaks' => 3, 'max_line_breaks' => 5], ]; yield 'multiple blank lines with more line breaks than maximum' => [ "<?php\n\n\nnamespace X;", "<?php\n\n\n\n\nnamespace X;", ['min_line_breaks' => 1, 'max_line_breaks' => 3], ]; yield 'enforce namespace at the same line as opening tag' => [ '<?php namespace X;', "<?php\n\n\n\n\nnamespace X;", ['min_line_breaks' => 0, 'max_line_breaks' => 0], ]; yield 'no newline' => [ "<?php\n\nnamespace X;", '<?php namespace X;', ]; yield 'no newline with additional spaces' => [ "<?php\n\nnamespace X;", '<?php namespace X;', ]; } /** * @param array<string, mixed> $configuration * * @dataProvider provideInvalidConfigurationCases */ public function testInvalidConfiguration(array $configuration): void { $this->expectException(InvalidFixerConfigurationException::class); $this->fixer->configure($configuration); } /** * @return iterable<string, array{array<string, mixed>}> */ public static function provideInvalidConfigurationCases(): iterable { yield 'min not integer' => [['min_line_breaks' => true, 'max_line_breaks' => 2]]; yield 'max not integer' => [['min_line_breaks' => 1, 'max_line_breaks' => 'two and a half']]; yield 'min higher than max' => [['min_line_breaks' => 4, 'max_line_breaks' => 2]]; yield 'min lower than 0' => [['min_line_breaks' => -2, 'max_line_breaks' => 2]]; yield 'max lower than 0' => [['min_line_breaks' => -4, 'max_line_breaks' => -2]]; yield 'extra option' => [['min_line_breaks' => 1, 'max_line_breaks' => 3, 'average_line_breaks' => 2]]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Cache/CacheTest.php
tests/Cache/CacheTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Cache; use PhpCsFixer\Cache\Cache; use PhpCsFixer\Cache\CacheInterface; use PhpCsFixer\Cache\Signature; use PhpCsFixer\Cache\SignatureInterface; use PhpCsFixer\Config; use PhpCsFixer\Hasher; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\ToolInfo; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\Cache\Cache * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CacheTest extends TestCase { public function testIsFinal(): void { $reflection = new \ReflectionClass(Cache::class); self::assertTrue($reflection->isFinal()); } public function testImplementsCacheInterface(): void { $reflection = new \ReflectionClass(Cache::class); self::assertTrue($reflection->implementsInterface(CacheInterface::class)); } public function testConstructorSetsValues(): void { $signature = $this->createSignatureDouble(); $cache = new Cache($signature); self::assertSame($signature, $cache->getSignature()); } public function testDefaults(): void { $signature = $this->createSignatureDouble(); $cache = new Cache($signature); $file = 'test.php'; self::assertFalse($cache->has($file)); self::assertNull($cache->get($file)); } public function testCanSetAndGetValue(): void { $signature = $this->createSignatureDouble(); $cache = new Cache($signature); $file = 'test.php'; $hash = Hasher::calculate('hello'); $cache->set($file, $hash); self::assertTrue($cache->has($file)); self::assertSame($hash, $cache->get($file)); } public function testCanClearValue(): void { $signature = $this->createSignatureDouble(); $cache = new Cache($signature); $file = 'test.php'; $hash = Hasher::calculate('hello'); $cache->set($file, $hash); $cache->clear($file); self::assertNull($cache->get($file)); } public function testFromJsonThrowsInvalidArgumentExceptionIfJsonIsInvalid(): void { $this->expectException(\InvalidArgumentException::class); $json = '{"foo'; Cache::fromJson($json); } /** * @param array<string, mixed> $data * * @dataProvider provideFromJsonThrowsInvalidArgumentExceptionIfJsonIsMissingKeyCases */ public function testFromJsonThrowsInvalidArgumentExceptionIfJsonIsMissingKey(array $data): void { $this->expectException(\InvalidArgumentException::class); $json = json_encode($data, \JSON_THROW_ON_ERROR); Cache::fromJson($json); } /** * @return iterable<int, array{array<string, mixed>}> */ public static function provideFromJsonThrowsInvalidArgumentExceptionIfJsonIsMissingKeyCases(): iterable { $data = [ 'php' => '7.1.2', 'version' => '2.0', 'rules' => [ 'foo' => true, 'bar' => false, ], 'ruleCustomisationPolicyVersion' => '1.2.3', 'hashes' => [], ]; return array_map(static function (string $missingKey) use ($data): array { unset($data[$missingKey]); return [ $data, ]; }, array_keys($data)); } /** * @dataProvider provideCanConvertToAndFromJsonCases */ public function testCanConvertToAndFromJson(SignatureInterface $signature): void { $cache = new Cache($signature); $file = 'test.php'; $hash = Hasher::calculate('hello'); $cache->set($file, $hash); $cached = Cache::fromJson($cache->toJson()); self::assertTrue($cached->getSignature()->equals($signature)); self::assertTrue($cached->has($file)); self::assertSame($hash, $cached->get($file)); } /** * @return iterable<int, array{Signature}> */ public static function provideCanConvertToAndFromJsonCases(): iterable { $toolInfo = new ToolInfo(); $config = new Config(); yield [new Signature( \PHP_VERSION, '2.0', ' ', "\r\n", [ 'foo' => true, 'bar' => true, ], 'fooBar', )]; yield [new Signature( \PHP_VERSION, $toolInfo->getVersion(), $config->getIndent(), $config->getLineEnding(), [ // value encoded in ANSI, not UTF 'header_comment' => ['header' => 'Dariusz '.base64_decode('UnVtafFza2k=', true)], ], 'fooBar', )]; } public function testToJsonThrowsExceptionOnInvalid(): void { $signature = $this->createSignatureDouble(); $cache = new Cache($signature); $this->expectException( \UnexpectedValueException::class, ); $this->expectExceptionMessage( 'Cannot encode cache signature to JSON, error: "Malformed UTF-8 characters, possibly incorrectly encoded". If you have non-UTF8 chars in your signature, like in license for `header_comment`, consider enabling `ext-mbstring` or install `symfony/polyfill-mbstring`.', ); $cache->toJson(); } private function createSignatureDouble(): SignatureInterface { return new class implements SignatureInterface { public function getPhpVersion(): string { return '7.1.0'; } public function getFixerVersion(): string { return '2.2.0'; } public function getIndent(): string { return ' '; } public function getLineEnding(): string { return \PHP_EOL; } public function getRules(): array { return [ "\xB1\x31" => true, // invalid UTF8 sequence ]; } public function getRuleCustomisationPolicyVersion(): string { return 'Policy Version'; } public function equals(SignatureInterface $signature): bool { throw new \LogicException('Not implemented.'); } }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Cache/FileCacheManagerTest.php
tests/Cache/FileCacheManagerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Cache; use PhpCsFixer\Cache\CacheInterface; use PhpCsFixer\Cache\CacheManagerInterface; use PhpCsFixer\Cache\DirectoryInterface; use PhpCsFixer\Cache\FileCacheManager; use PhpCsFixer\Cache\FileHandlerInterface; use PhpCsFixer\Cache\SignatureInterface; use PhpCsFixer\Hasher; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\Cache\FileCacheManager * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FileCacheManagerTest extends TestCase { public function testIsFinal(): void { $reflection = new \ReflectionClass(FileCacheManager::class); self::assertTrue($reflection->isFinal()); } public function testImplementsCacheManagerInterface(): void { $reflection = new \ReflectionClass(FileCacheManager::class); self::assertTrue($reflection->implementsInterface(CacheManagerInterface::class)); } public function testCreatesCacheIfHandlerReturnedNoCache(): void { $signature = $this->createSignatureDouble(false); $handler = $this->createFileHandlerDouble(null); $manager = new FileCacheManager($handler, $signature); unset($manager); self::assertWriteCallCount(1, $handler); } public function testCreatesCacheIfCachedSignatureIsDifferent(): void { $cachedSignature = $this->createSignatureDouble(false); $signature = $this->createSignatureDouble(false); $cache = $this->createCacheDouble($cachedSignature); $handler = $this->createFileHandlerDouble($cache); $manager = new FileCacheManager($handler, $signature); unset($manager); self::assertWriteCallCount(1, $handler); } public function testUsesCacheIfCachedSignatureIsEqualAndNoFileWasUpdated(): void { $cachedSignature = $this->createSignatureDouble(true); $signature = $this->createSignatureDouble(true); $cache = $this->createCacheDouble($cachedSignature); $handler = $this->createFileHandlerDouble($cache); $manager = new FileCacheManager($handler, $signature); unset($manager); self::assertWriteCallCount(0, $handler); } public function testNeedFixingReturnsTrueIfCacheHasNoHash(): void { $cachedSignature = $this->createSignatureDouble(true); $signature = $this->createSignatureDouble(true); $cache = $this->createCacheDouble($cachedSignature); $handler = $this->createFileHandlerDouble($cache, $this->getFile()); $manager = new FileCacheManager($handler, $signature); self::assertTrue($manager->needFixing('hello.php', '<?php echo "Hello!"')); } public function testNeedFixingReturnsTrueIfCachedHashIsDifferent(): void { $file = 'hello.php'; $cachedSignature = $this->createSignatureDouble(true); $signature = $this->createSignatureDouble(true); $cache = $this->createCacheDouble($cachedSignature, [$file => Hasher::calculate('<?php echo "Hello, old world!";')]); $handler = $this->createFileHandlerDouble($cache, $this->getFile()); $manager = new FileCacheManager($handler, $signature); self::assertTrue($manager->needFixing($file, '<?php echo "Hello, new world!";')); } public function testNeedFixingReturnsFalseIfCachedHashIsIdentical(): void { $file = 'hello.php'; $fileContent = '<?php echo "Hello!"'; $cachedSignature = $this->createSignatureDouble(true); $signature = $this->createSignatureDouble(true); $cache = $this->createCacheDouble($cachedSignature, [$file => Hasher::calculate($fileContent)]); $handler = $this->createFileHandlerDouble($cache, $this->getFile()); $manager = new FileCacheManager($handler, $signature); self::assertFalse($manager->needFixing($file, $fileContent)); } public function testNeedFixingUsesRelativePathToFile(): void { $file = '/foo/bar/baz/src/hello.php'; $relativePathToFile = 'src/hello.php'; $directory = $this->createDirectoryDouble($relativePathToFile); $cachedSignature = $this->createSignatureDouble(true); $signature = $this->createSignatureDouble(true); $cache = $this->createCacheDouble($cachedSignature, [$relativePathToFile => Hasher::calculate('<?php echo "Old!"')]); $handler = $this->createFileHandlerDouble($cache, $this->getFile()); $manager = new FileCacheManager($handler, $signature, false, $directory); self::assertTrue($manager->needFixing($file, '<?php echo "New!"')); } public function testSetFileSetsHashOfFileContent(): void { $cacheFile = $this->getFile(); $file = 'hello.php'; $fileContent = '<?php echo "Hello!"'; $cachedSignature = $this->createSignatureDouble(true); $signature = $this->createSignatureDouble(true); $cache = $this->createCacheDouble($cachedSignature); $handler = $this->createFileHandlerDouble($cache, $cacheFile); $manager = new FileCacheManager($handler, $signature); self::assertFalse($cache->has($file)); $manager->setFile($file, $fileContent); unset($manager); self::assertTrue($cache->has($file)); self::assertSame(Hasher::calculate($fileContent), $cache->get($file)); self::assertWriteCallCount(1, $handler); } public function testSetFileSetsHashOfFileContentDuringDryRunIfCacheHasNoHash(): void { $isDryRun = true; $cacheFile = $this->getFile(); $file = 'hello.php'; $fileContent = '<?php echo "Hello!"'; $cachedSignature = $this->createSignatureDouble(true); $signature = $this->createSignatureDouble(true); $cache = $this->createCacheDouble($cachedSignature); $handler = $this->createFileHandlerDouble($cache, $cacheFile); self::assertFalse($cache->has($file)); $manager = new FileCacheManager($handler, $signature, $isDryRun); $manager->setFile($file, $fileContent); self::assertTrue($cache->has($file)); self::assertSame(Hasher::calculate($fileContent), $cache->get($file)); } public function testSetFileClearsHashDuringDryRunIfCachedHashIsDifferent(): void { $isDryRun = true; $cacheFile = $this->getFile(); $file = 'hello.php'; $fileContent = '<?php echo "Hello!"'; $previousFileContent = '<?php echo "Hello, world!"'; $cachedSignature = $this->createSignatureDouble(true); $signature = $this->createSignatureDouble(true); $cache = $this->createCacheDouble($cachedSignature, [$file => Hasher::calculate($previousFileContent)]); $handler = $this->createFileHandlerDouble($cache, $cacheFile); $manager = new FileCacheManager($handler, $signature, $isDryRun); $manager->setFile($file, $fileContent); self::assertFalse($cache->has($file)); } public function testSetFileUsesRelativePathToFile(): void { $cacheFile = $this->getFile(); $file = '/foo/bar/baz/src/hello.php'; $relativePathToFile = 'src/hello.php'; $fileContent = '<?php echo "Hello!"'; $directory = $this->createDirectoryDouble($relativePathToFile); $cachedSignature = $this->createSignatureDouble(true); $signature = $this->createSignatureDouble(true); $cache = $this->createCacheDouble($cachedSignature); $handler = $this->createFileHandlerDouble($cache, $cacheFile); $manager = new FileCacheManager($handler, $signature, false, $directory); $manager->setFile($file, $fileContent); self::assertTrue($cache->has($relativePathToFile)); self::assertSame(Hasher::calculate($fileContent), $cache->get($relativePathToFile)); } private static function assertWriteCallCount(int $writeCallCount, FileHandlerInterface $handler): void { self::assertSame( $writeCallCount, \Closure::bind( static fn ($handler): int => $handler->writeCallCount, null, \get_class($handler), )($handler), ); } private function getFile(): string { return __DIR__.'/../Fixtures/.php_cs.empty-cache'; } private function createDirectoryDouble(string $relativePath): DirectoryInterface { return new class($relativePath) implements DirectoryInterface { private string $relativePath; public function __construct(string $relativePath) { $this->relativePath = $relativePath; } public function getRelativePathTo(string $file): string { return $this->relativePath; } }; } private function createSignatureDouble(bool $isEqual): SignatureInterface { return new class($isEqual) implements SignatureInterface { private bool $isEqual; public function __construct(bool $isEqual) { $this->isEqual = $isEqual; } public function getPhpVersion(): string { throw new \LogicException('Not implemented.'); } public function getFixerVersion(): string { throw new \LogicException('Not implemented.'); } public function getIndent(): string { throw new \LogicException('Not implemented.'); } public function getLineEnding(): string { throw new \LogicException('Not implemented.'); } public function getRules(): array { throw new \LogicException('Not implemented.'); } public function getRuleCustomisationPolicyVersion(): string { throw new \LogicException('Not implemented.'); } public function equals(SignatureInterface $signature): bool { return $this->isEqual; } }; } /** * @param array<string, string> $fileMap */ private function createCacheDouble(SignatureInterface $signature, array $fileMap = []): CacheInterface { return new class($signature, $fileMap) implements CacheInterface { private SignatureInterface $signature; /** @var array<string, string> */ private array $fileMap; /** * @param array<string, string> $fileMap */ public function __construct(SignatureInterface $signature, array $fileMap) { $this->signature = $signature; $this->fileMap = $fileMap; } public function getSignature(): SignatureInterface { return $this->signature; } public function has(string $file): bool { return isset($this->fileMap[$file]); } public function get(string $file): string { \assert(\array_key_exists($file, $this->fileMap)); return $this->fileMap[$file]; } public function set(string $file, string $hash): void { $this->fileMap[$file] = $hash; } public function clear(string $file): void { unset($this->fileMap[$file]); } public function toJson(): string { throw new \LogicException('Not implemented.'); } }; } private function createFileHandlerDouble(?CacheInterface $cache, ?string $file = null, ?string $signature = null): FileHandlerInterface { return new class($cache, $file, $signature) implements FileHandlerInterface { private ?CacheInterface $cache; private ?string $file; private ?string $signature; private int $writeCallCount = 0; public function __construct(?CacheInterface $cache, ?string $file, ?string $signature) { $this->cache = $cache; $this->file = $file; $this->signature = $signature; } public function getFile(): string { return $this->file; } public function read(): ?CacheInterface { return $this->cache; } public function write(CacheInterface $cache): void { ++$this->writeCallCount; if (null !== $this->signature) { TestCase::assertSame($this->signature, $cache->getSignature()); } } }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Cache/FileHandlerTest.php
tests/Cache/FileHandlerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Cache; use PhpCsFixer\Cache\Cache; use PhpCsFixer\Cache\CacheInterface; use PhpCsFixer\Cache\FileHandler; use PhpCsFixer\Cache\Signature; use PhpCsFixer\Cache\SignatureInterface; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Filesystem\Exception\IOException; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\Cache\FileHandler * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FileHandlerTest extends TestCase { protected function tearDown(): void { parent::tearDown(); $file = $this->getFile(); if (file_exists($file)) { unlink($file); } } public function testConstructorSetsFile(): void { $file = $this->getFile(); $handler = new FileHandler($file); self::assertSame($file, $handler->getFile()); } public function testReadReturnsNullIfFileDoesNotExist(): void { $file = $this->getFile(); $handler = new FileHandler($file); self::assertNull($handler->read()); } public function testReadReturnsNullIfContentCanNotBeDeserialized(): void { $file = $this->getFile(); file_put_contents($file, 'hello'); $handler = new FileHandler($file); self::assertNull($handler->read()); } public function testReadReturnsCache(): void { $file = $this->getFile(); $signature = $this->createSignature(); $cache = new Cache($signature); file_put_contents($file, $cache->toJson()); $handler = new FileHandler($file); $cached = $handler->read(); self::assertInstanceOf(CacheInterface::class, $cached); self::assertTrue($cached->getSignature()->equals($signature)); } public function testWriteThrowsIOExceptionIfFileCanNotBeWritten(): void { $file = '/../"/out/of/range/cache.json'; // impossible path $this->expectException(IOException::class); $this->expectExceptionMessageMatches(\sprintf( '#^Directory of cache file "%s" does not exists and couldn\'t be created\.#', preg_quote($file, '#'), )); $cache = new Cache($this->createSignature()); $handler = new FileHandler($file); $handler->write($cache); } public function testWriteWritesCache(): void { $file = $this->getFile(); $cache = new Cache($this->createSignature()); $handler = new FileHandler($file); $handler->write($cache); self::assertFileExists($file); $actualCacheJson = file_get_contents($file); self::assertSame($cache->toJson(), $actualCacheJson); } public function testWriteCacheToDirectory(): void { $dir = __DIR__.'/../Fixtures/cache-file-handler'; $handler = new FileHandler($dir); $this->expectException(IOException::class); $this->expectExceptionMessageMatches(\sprintf( '#^%s$#', preg_quote('Cannot write cache file "'.realpath($dir).'" as the location exists as directory.', '#'), )); $handler->write(new Cache($this->createSignature())); } public function testWriteCacheToNonWriteableFile(): void { $file = __DIR__.'/../Fixtures/cache-file-handler/cache-file'; if (is_writable($file)) { self::markTestSkipped(\sprintf('File "%s" must be not writeable for this tests.', realpath($file))); } $handler = new FileHandler($file); $this->expectException(IOException::class); $this->expectExceptionMessageMatches(\sprintf( '#^%s$#', preg_quote('Cannot write to file "'.realpath($file).'" as it is not writable.', '#'), )); $handler->write(new Cache($this->createSignature())); } public function testWriteCacheFilePermissions(): void { $file = __DIR__.'/../Fixtures/cache-file-handler/rw_cache.test'; @unlink($file); self::assertFileDoesNotExist($file); $handler = new FileHandler($file); $handler->write(new Cache($this->createSignature())); self::assertFileExists($file); self::assertTrue(@is_file($file), \sprintf('Failed cache "%s" `is_file`.', $file)); self::assertTrue(@is_writable($file), \sprintf('Failed cache "%s" `is_writable`.', $file)); self::assertTrue(@is_readable($file), \sprintf('Failed cache "%s" `is_readable`.', $file)); @unlink($file); } public function testCachePathIsCreated(): void { $dir = __DIR__.'/../Fixtures/cache-file-handler/one/two/three'; $file = $dir.'/cache.json'; $cleanPath = static function () use ($dir, $file): void { @unlink($file); for ($i = 0; $i <= 2; ++$i) { @rmdir(0 === $i ? $dir : \dirname($dir, $i)); } }; $cleanPath(); self::assertDirectoryDoesNotExist($dir); self::assertFileDoesNotExist($file); $handler = new FileHandler($file); $handler->write(new Cache($this->createSignature())); self::assertDirectoryExists($dir); self::assertFileExists($file); $cleanPath(); } private function getFile(): string { return __DIR__.'/.php-cs-fixer.cache'; } private function createSignature(): SignatureInterface { return new Signature( \PHP_VERSION, '2.0', ' ', \PHP_EOL, ['foo' => true, 'bar' => false], 'baz', ); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Cache/SignatureTest.php
tests/Cache/SignatureTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Cache; use PhpCsFixer\Cache\Signature; use PhpCsFixer\Cache\SignatureInterface; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\Cache\Signature * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SignatureTest extends TestCase { public function testIsFinal(): void { $reflection = new \ReflectionClass(Signature::class); self::assertTrue($reflection->isFinal()); } public function testImplementsSignatureInterface(): void { $reflection = new \ReflectionClass(Signature::class); self::assertTrue($reflection->implementsInterface(SignatureInterface::class)); } public function testConstructorSetsValues(): void { $php = \PHP_VERSION; $version = '3.0'; $indent = ' '; $lineEnding = \PHP_EOL; $rules = ['foo' => true, 'bar' => false]; $ruleCustomisationPolicyVersion = '123'; $signature = new Signature($php, $version, $indent, $lineEnding, $rules, $ruleCustomisationPolicyVersion); self::assertSame($php, $signature->getPhpVersion()); self::assertSame($version, $signature->getFixerVersion()); self::assertSame($indent, $signature->getIndent()); self::assertSame($lineEnding, $signature->getLineEnding()); self::assertSame($rules, $signature->getRules()); self::assertSame($ruleCustomisationPolicyVersion, $signature->getRuleCustomisationPolicyVersion()); } /** * @dataProvider provideEqualsReturnsFalseIfValuesAreNotIdenticalCases */ public function testEqualsReturnsFalseIfValuesAreNotIdentical(Signature $signature, Signature $anotherSignature): void { self::assertFalse($signature->equals($anotherSignature)); } /** * @return iterable<string, array{Signature, Signature}> */ public static function provideEqualsReturnsFalseIfValuesAreNotIdenticalCases(): iterable { $php = \PHP_VERSION; $version = '2.0'; $indent = ' '; $lineEnding = "\n"; $rules = ['foo' => true, 'bar' => false]; $ruleCustomisationPolicyVersion = '1'; $base = new Signature($php, $version, $indent, $lineEnding, $rules, $ruleCustomisationPolicyVersion); yield 'php' => [ $base, new Signature('50400', $version, $indent, $lineEnding, $rules, $ruleCustomisationPolicyVersion), ]; yield 'version' => [ $base, new Signature($php, '2.12', $indent, $lineEnding, $rules, $ruleCustomisationPolicyVersion), ]; yield 'indent' => [ $base, new Signature($php, $version, "\t", $lineEnding, $rules, $ruleCustomisationPolicyVersion), ]; yield 'lineEnding' => [ $base, new Signature($php, $version, $indent, "\r\n", $rules, $ruleCustomisationPolicyVersion), ]; yield 'rules' => [ $base, new Signature($php, $version, $indent, $lineEnding, ['foo' => false], $ruleCustomisationPolicyVersion), ]; yield 'ruleCustomisationPolicyVersion' => [ $base, new Signature($php, $version, $indent, $lineEnding, $rules, '2'), ]; } public function testEqualsReturnsTrueIfValuesAreIdentical(): void { $php = \PHP_VERSION; $version = '2.0'; $indent = ' '; $lineEnding = \PHP_EOL; $rules = ['foo' => true, 'bar' => false]; $ruleCustomisationPolicyVersion = '1.2.3'; $signature = new Signature($php, $version, $indent, $lineEnding, $rules, $ruleCustomisationPolicyVersion); $anotherSignature = new Signature($php, $version, $indent, $lineEnding, $rules, $ruleCustomisationPolicyVersion); self::assertTrue($signature->equals($anotherSignature)); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Cache/NullCacheManagerTest.php
tests/Cache/NullCacheManagerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Cache; use PhpCsFixer\Cache\CacheManagerInterface; use PhpCsFixer\Cache\NullCacheManager; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\Cache\NullCacheManager * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NullCacheManagerTest extends TestCase { public function testIsFinal(): void { $reflection = new \ReflectionClass(NullCacheManager::class); self::assertTrue($reflection->isFinal()); } public function testImplementsCacheManagerInterface(): void { $reflection = new \ReflectionClass(NullCacheManager::class); self::assertTrue($reflection->implementsInterface(CacheManagerInterface::class)); } public function testNeedFixingReturnsTrue(): void { $manager = new NullCacheManager(); self::assertTrue($manager->needFixing('foo.php', 'bar')); $manager->setFile(__FILE__, 'XXX'); // no-op, should not raise an exception } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Cache/DirectoryTest.php
tests/Cache/DirectoryTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Cache; use PhpCsFixer\Cache\Directory; use PhpCsFixer\Cache\DirectoryInterface; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\Cache\Directory * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DirectoryTest extends TestCase { public function testIsFinal(): void { $reflection = new \ReflectionClass(Directory::class); self::assertTrue($reflection->isFinal()); } public function testImplementsDirectoryInterface(): void { $reflection = new \ReflectionClass(Directory::class); self::assertTrue($reflection->implementsInterface(DirectoryInterface::class)); } public function testGetRelativePathToReturnsFileIfAboveLevelOfDirectoryName(): void { $directoryName = __DIR__.\DIRECTORY_SEPARATOR.'foo'; $file = __DIR__.\DIRECTORY_SEPARATOR.'hello.php'; $directory = new Directory($directoryName); self::assertSame($file, $directory->getRelativePathTo($file)); } public function testGetRelativePathToReturnsRelativePathIfWithinDirectoryName(): void { $directoryName = __DIR__.\DIRECTORY_SEPARATOR.'foo'; $file = __DIR__.\DIRECTORY_SEPARATOR.'foo'.\DIRECTORY_SEPARATOR.'bar'.\DIRECTORY_SEPARATOR.'hello.php'; $directory = new Directory($directoryName); self::assertSame('bar'.\DIRECTORY_SEPARATOR.'hello.php', $directory->getRelativePathTo($file)); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/ApplicationTest.php
tests/Console/ApplicationTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Command\WorkerCommand; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\ToolInfo; use Symfony\Component\Console\Tester\ApplicationTester; /** * @internal * * @covers \PhpCsFixer\Console\Application * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ApplicationTest extends TestCase { public function testApplication(): void { $regex = '/^PHP CS Fixer <info>\d+.\d+.\d+(-DEV)?<\/info> <info>.+<\/info>' .' by <comment>Fabien Potencier<\/comment>, <comment>Dariusz Ruminski<\/comment> and <comment>contributors<\/comment>\.' ."\nPHP runtime: <info>\\d+.\\d+.\\d+(-dev|beta\\d+)?<\\/info>$/"; self::assertMatchesRegularExpression($regex, (new Application())->getLongVersion()); } public function testGetMajorVersion(): void { self::assertSame(3, Application::getMajorVersion()); } public function testWorkerExceptionsAreRenderedInMachineFriendlyWay(): void { $app = new Application(); $app->add(new WorkerCommand(new ToolInfo())); $app->setAutoExit(false); // see: https://symfony.com/doc/current/console.html#testing-commands $appTester = new ApplicationTester($app); $appTester->run(['worker']); self::assertStringContainsString( WorkerCommand::ERROR_PREFIX.'{"class":"PhpCsFixer\\\Runner\\\Parallel\\\ParallelisationException","message":"Missing parallelisation options"', $appTester->getDisplay(), ); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/ConfigurationResolverTest.php
tests/Console/ConfigurationResolverTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console; use PhpCsFixer\AbstractFixer; use PhpCsFixer\Cache\NullCacheManager; use PhpCsFixer\Config; use PhpCsFixer\ConfigInterface; use PhpCsFixer\ConfigurationException\InvalidConfigurationException; use PhpCsFixer\Console\Command\FixCommand; use PhpCsFixer\Console\ConfigurationResolver; use PhpCsFixer\Console\Output\Progress\ProgressOutputType; use PhpCsFixer\Console\Report\FixReport\CheckstyleReporter; use PhpCsFixer\Console\Report\FixReport\GitlabReporter; use PhpCsFixer\Console\Report\FixReport\JsonReporter; use PhpCsFixer\Console\Report\FixReport\TextReporter; use PhpCsFixer\Differ\NullDiffer; use PhpCsFixer\Differ\UnifiedDiffer; use PhpCsFixer\Finder; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ConfigurableFixerTrait; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\RuleSet\RuleSets; use PhpCsFixer\Runner\Parallel\ParallelConfig; use PhpCsFixer\Runner\Parallel\ParallelConfigFactory; use PhpCsFixer\Tests\Fixtures\ExternalRuleSet\ExampleRuleSet; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\ToolInfoInterface; use PhpCsFixer\Utils; use Symfony\Component\Console\Output\OutputInterface; /** * @author Katsuhiro Ogawa <ko.fivestar@gmail.com> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Console\ConfigurationResolver * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ConfigurationResolverTest extends TestCase { public function testResolveParallelConfig(): void { $parallelConfig = new ParallelConfig(); $config = (new Config())->setParallelConfig($parallelConfig); $resolver = $this->createConfigurationResolver([], $config); self::assertSame($parallelConfig, $resolver->getParallelConfig()); } public function testDefaultParallelConfigFallbacksToSequential(): void { $parallelConfig = $this->createConfigurationResolver([])->getParallelConfig(); $defaultParallelConfig = ParallelConfigFactory::sequential(); self::assertSame($defaultParallelConfig->getMaxProcesses(), $parallelConfig->getMaxProcesses()); self::assertSame($defaultParallelConfig->getFilesPerProcess(), $parallelConfig->getFilesPerProcess()); self::assertSame($defaultParallelConfig->getProcessTimeout(), $parallelConfig->getProcessTimeout()); } public function testCliSequentialOptionOverridesParallelConfig(): void { $config = (new Config())->setParallelConfig(new ParallelConfig(10)); $resolver = $this->createConfigurationResolver(['sequential' => true], $config); self::assertSame(1, $resolver->getParallelConfig()->getMaxProcesses()); } public function testSetOptionWithUndefinedOption(): void { $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessageMatches('/^Unknown option name: "foo"\.$/'); $this->createConfigurationResolver(['foo' => 'bar']); } public function testResolveProgressWithPositiveConfigAndPositiveOption(): void { $config = new Config(); $config->setHideProgress(true); $resolver = $this->createConfigurationResolver([ 'format' => 'txt', 'verbosity' => OutputInterface::VERBOSITY_VERBOSE, ], $config); self::assertSame('none', $resolver->getProgressType()); } public function testResolveProgressWithPositiveConfigAndNegativeOption(): void { $config = new Config(); $config->setHideProgress(true); $resolver = $this->createConfigurationResolver([ 'format' => 'txt', 'verbosity' => OutputInterface::VERBOSITY_NORMAL, ], $config); self::assertSame('none', $resolver->getProgressType()); } public function testResolveProgressWithNegativeConfigAndPositiveOption(): void { $config = new Config(); $config->setHideProgress(false); $resolver = $this->createConfigurationResolver([ 'format' => 'txt', 'verbosity' => OutputInterface::VERBOSITY_VERBOSE, ], $config); self::assertSame('bar', $resolver->getProgressType()); } public function testResolveProgressWithNegativeConfigAndNegativeOption(): void { $config = new Config(); $config->setHideProgress(false); $resolver = $this->createConfigurationResolver([ 'format' => 'txt', 'verbosity' => OutputInterface::VERBOSITY_NORMAL, ], $config); self::assertSame('bar', $resolver->getProgressType()); } /** * @dataProvider provideProgressTypeCases */ public function testResolveProgressWithPositiveConfigAndExplicitProgress(string $progressType): void { $config = new Config(); $config->setHideProgress(true); $resolver = $this->createConfigurationResolver([ 'format' => 'txt', 'verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'show-progress' => $progressType, ], $config); self::assertSame($progressType, $resolver->getProgressType()); } /** * @dataProvider provideProgressTypeCases */ public function testResolveProgressWithNegativeConfigAndExplicitProgress(string $progressType): void { $config = new Config(); $config->setHideProgress(false); $resolver = $this->createConfigurationResolver([ 'format' => 'txt', 'verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'show-progress' => $progressType, ], $config); self::assertSame($progressType, $resolver->getProgressType()); } /** * @return iterable<string, array{0: ProgressOutputType::*}> */ public static function provideProgressTypeCases(): iterable { foreach (ProgressOutputType::all() as $outputType) { yield $outputType => [$outputType]; } } public function testResolveProgressWithInvalidExplicitProgress(): void { $resolver = $this->createConfigurationResolver([ 'format' => 'txt', 'verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'show-progress' => 'foo', ]); $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('The progress type "foo" is not defined, supported are "bar", "dots" and "none".'); $resolver->getProgressType(); } public function testResolveConfigFileDefault(): void { $resolver = $this->createConfigurationResolver([]); self::assertNull($resolver->getConfigFile()); } public function testResolveConfigFileByPathOfFile(): void { $dir = __DIR__.'/../Fixtures/ConfigurationResolverConfigFile/case_1'; $resolver = $this->createConfigurationResolver(['path' => [$dir.\DIRECTORY_SEPARATOR.'foo.php']]); self::assertSame($dir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php', $resolver->getConfigFile()); self::assertInstanceOf(\Test1Config::class, $resolver->getConfig()); // @phpstan-ignore-line to avoid `Class Test1Config not found.` } public function testResolveConfigFileSpecified(): void { $file = __DIR__.'/../Fixtures/ConfigurationResolverConfigFile/case_4/my.php-cs-fixer.php'; $resolver = $this->createConfigurationResolver(['config' => $file]); self::assertSame($file, $resolver->getConfigFile()); self::assertInstanceOf(\Test4Config::class, $resolver->getConfig()); // @phpstan-ignore-line to avoid `Class Test4Config not found.` } /** * @dataProvider provideResolveConfigFileChooseFileCases * * @param class-string<ConfigInterface> $expectedClass */ public function testResolveConfigFileChooseFile(string $expectedFile, string $expectedClass, string $path, ?string $cwdPath = null): void { $resolver = $this->createConfigurationResolver( ['path' => [$path]], null, $cwdPath ?? '', ); self::assertSame($expectedFile, $resolver->getConfigFile()); self::assertInstanceOf($expectedClass, $resolver->getConfig()); } /** * @return iterable<int, array{0: string, 1: string, 2: string, 3?: string}> */ public static function provideResolveConfigFileChooseFileCases(): iterable { $dirBase = self::getFixtureDir(); yield [ $dirBase.'case_1'.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php', 'Test1Config', $dirBase.'case_1', ]; yield [ $dirBase.'case_2'.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php', 'Test2Config', $dirBase.'case_2', ]; yield [ $dirBase.'case_3'.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php', 'Test3Config', $dirBase.'case_3', ]; yield [ $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php', 'Test6Config', $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'subdir', $dirBase.'case_6', ]; yield [ $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php', 'Test6Config', $dirBase.'case_6'.\DIRECTORY_SEPARATOR.'subdir/empty_file.php', $dirBase.'case_6', ]; } public function testResolveConfigFileChooseFileWithInvalidFile(): void { $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessageMatches( '#^The config file: ".+[\/\\\]Fixtures[\/\\\]ConfigurationResolverConfigFile[\/\\\]case_5[\/\\\]\.php-cs-fixer\.dist\.php" does not return a "PhpCsFixer\\\ConfigInterface" instance\. Got: "string"\.$#', ); $dirBase = self::getFixtureDir(); $resolver = $this->createConfigurationResolver(['path' => [$dirBase.'case_5']]); $resolver->getConfig(); } public function testResolveConfigFileChooseFileWithInvalidFormat(): void { $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessageMatches('/^The format "xls" is not defined, supported are "checkstyle", "gitlab", "json", "junit", "txt" and "xml"\.$/'); $dirBase = self::getFixtureDir(); $resolver = $this->createConfigurationResolver(['path' => [$dirBase.'case_7']]); $resolver->getReporter(); } public function testResolveConfigFileChooseFileWithPathArrayWithoutConfig(): void { $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessageMatches('/^For multiple paths config parameter is required\.$/'); $dirBase = self::getFixtureDir(); $resolver = $this->createConfigurationResolver(['path' => [$dirBase.'case_1/.php-cs-fixer.dist.php', $dirBase.'case_1/foo.php']]); $resolver->getConfig(); } public function testResolveConfigFileChooseFileWithPathArrayAndConfig(): void { $dirBase = self::getFixtureDir(); $configFile = $dirBase.'case_1/.php-cs-fixer.dist.php'; $resolver = $this->createConfigurationResolver([ 'config' => $configFile, 'path' => [$configFile, $dirBase.'case_1/foo.php'], ]); self::assertSame($configFile, $resolver->getConfigFile()); } /** * @param array<int, string> $paths * @param array<int, string> $expectedPaths * * @dataProvider provideResolvePathCases */ public function testResolvePath(array $paths, string $cwd, array $expectedPaths): void { $resolver = $this->createConfigurationResolver( ['path' => $paths], null, $cwd, ); self::assertSame($expectedPaths, $resolver->getPath()); } /** * @return iterable<int, array{array<int, string>, string, array<int, string>}> */ public static function provideResolvePathCases(): iterable { yield [ ['Command'], __DIR__, [__DIR__.\DIRECTORY_SEPARATOR.'Command'], ]; yield [ [basename(__DIR__)], \dirname(__DIR__), [__DIR__], ]; yield [ [' Command'], __DIR__, [__DIR__.\DIRECTORY_SEPARATOR.'Command'], ]; yield [ ['Command '], __DIR__, [__DIR__.\DIRECTORY_SEPARATOR.'Command'], ]; } /** * @param list<string> $paths * * @dataProvider provideRejectInvalidPathCases */ public function testRejectInvalidPath(array $paths, string $expectedMessage): void { $resolver = $this->createConfigurationResolver( ['path' => $paths], null, \dirname(__DIR__), ); $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage($expectedMessage); $resolver->getPath(); } /** * @return iterable<int, array{list<string>, string}> */ public static function provideRejectInvalidPathCases(): iterable { yield [ [''], 'Invalid path: "".', ]; yield [ [__DIR__, ''], 'Invalid path: "".', ]; yield [ ['', __DIR__], 'Invalid path: "".', ]; yield [ [' '], 'Invalid path: " ".', ]; yield [ [__DIR__, ' '], 'Invalid path: " ".', ]; yield [ [' ', __DIR__], 'Invalid path: " ".', ]; } public function testResolvePathWithFileThatIsExcludedDirectlyOverridePathMode(): void { $config = new Config(); $finder = $config->getFinder(); \assert($finder instanceof Finder); // Config::getFinder() ensures only `iterable` $finder ->in(__DIR__.'/../Fixtures') ->notPath('dummy-file.php') ; $resolver = $this->createConfigurationResolver( ['path' => [__DIR__.'/../Fixtures/dummy-file.php']], $config, ); self::assertCount(1, $resolver->getFinder()); } public function testResolvePathWithFileThatIsExcludedDirectlyIntersectionPathMode(): void { $config = new Config(); $finder = $config->getFinder(); \assert($finder instanceof Finder); // Config::getFinder() ensures only `iterable` $finder ->in(__DIR__.'/../Fixtures') ->notPath('dummy-file.php') ; $resolver = $this->createConfigurationResolver([ 'path' => [__DIR__.'/../Fixtures/dummy-file.php'], 'path-mode' => 'intersection', ], $config); self::assertCount(0, $resolver->getFinder()); } public function testResolvePathWithFileThatIsExcludedByDirOverridePathMode(): void { $dir = __DIR__.'/..'; $config = new Config(); $finder = $config->getFinder(); \assert($finder instanceof Finder); // Config::getFinder() ensures only `iterable` $finder ->in($dir) ->exclude('Fixtures') ; $resolver = $this->createConfigurationResolver( ['path' => [__DIR__.'/../Fixtures/dummy-file.php']], $config, ); self::assertCount(1, $resolver->getFinder()); } public function testResolvePathWithFileThatIsExcludedByDirIntersectionPathMode(): void { $dir = __DIR__.'/..'; $config = new Config(); $finder = $config->getFinder(); \assert($finder instanceof Finder); // Config::getFinder() ensures only `iterable` $finder ->in($dir) ->exclude('Fixtures') ; $resolver = $this->createConfigurationResolver([ 'path-mode' => 'intersection', 'path' => [__DIR__.'/../Fixtures/dummy-file.php'], ], $config); self::assertCount(0, $resolver->getFinder()); } public function testResolvePathWithFileThatIsNotExcluded(): void { $dir = __DIR__; $config = new Config(); $finder = $config->getFinder(); \assert($finder instanceof Finder); // Config::getFinder() ensures only `iterable` $finder ->in($dir) ->notPath('foo-dummy-file.php') ; $resolver = $this->createConfigurationResolver( ['path' => [__DIR__.'/../Fixtures/dummy-file.php']], $config, ); self::assertCount(1, $resolver->getFinder()); } /** * @param \Exception|list<string> $expected * @param list<string> $path * * @dataProvider provideResolveIntersectionOfPathsCases */ public function testResolveIntersectionOfPaths($expected, ?Finder $configFinder, array $path, string $pathMode, ?string $configOption = null): void { if ($expected instanceof \Exception) { $this->expectException(\get_class($expected)); } if (null !== $configFinder) { $config = new Config(); $config->setFinder($configFinder); } else { $config = null; } $resolver = $this->createConfigurationResolver([ 'config' => $configOption, 'path' => $path, 'path-mode' => $pathMode, ], $config); $intersectionItems = array_map( static fn (\SplFileInfo $file): string => $file->getRealPath(), iterator_to_array($resolver->getFinder(), false), ); self::assertIsArray($expected); sort($expected); sort($intersectionItems); self::assertSame($expected, $intersectionItems); } /** * @return iterable<string, array{0: array<array-key, string>|\Exception, 1: null|Finder, 2: list<string>, 3: string, 4?: string}> */ public static function provideResolveIntersectionOfPathsCases(): iterable { $dir = __DIR__.'/../Fixtures/ConfigurationResolverPathsIntersection'; $cb = static fn (array $items): array => array_map( static fn (string $item): string => (string) realpath($dir.'/'.$item), $items, ); yield 'no path at all' => [ new \LogicException(), Finder::create(), [], 'override', ]; yield 'configured only by finder' => [ // don't override if the argument is empty $cb(['a1.php', 'a2.php', 'b/b1.php', 'b/b2.php', 'b_b/b_b1.php', 'c/c1.php', 'c/d/cd1.php', 'd/d1.php', 'd/d2.php', 'd/e/de1.php', 'd/f/df1.php']), Finder::create() ->in($dir), [], 'override', ]; yield 'configured only by argument' => [ $cb(['a1.php', 'a2.php', 'b/b1.php', 'b/b2.php', 'b_b/b_b1.php', 'c/c1.php', 'c/d/cd1.php', 'd/d1.php', 'd/d2.php', 'd/e/de1.php', 'd/f/df1.php']), Finder::create(), [$dir], 'override', ]; yield 'configured by finder, intersected with empty argument' => [ [], Finder::create() ->in($dir), [], 'intersection', ]; yield 'configured by finder, intersected with dir' => [ $cb(['c/c1.php', 'c/d/cd1.php']), Finder::create() ->in($dir), [$dir.'/c'], 'intersection', ]; yield 'configured by finder, intersected with file' => [ $cb(['c/c1.php']), Finder::create() ->in($dir), [$dir.'/c/c1.php'], 'intersection', ]; yield 'finder points to one dir while argument to another, not connected' => [ [], Finder::create() ->in($dir.'/b'), [$dir.'/c'], 'intersection', ]; yield 'finder with excluded dir, intersected with excluded file' => [ [], Finder::create() ->in($dir) ->exclude('c'), [$dir.'/c/d/cd1.php'], 'intersection', ]; yield 'finder with excluded dir, intersected with dir containing excluded one' => [ $cb(['c/c1.php']), Finder::create() ->in($dir) ->exclude('c/d'), [$dir.'/c'], 'intersection', ]; yield 'finder with excluded file, intersected with dir containing excluded one' => [ $cb(['c/d/cd1.php']), Finder::create() ->in($dir) ->notPath('c/c1.php'), [$dir.'/c'], 'intersection', ]; yield 'configured by finder, intersected with non-existing path' => [ new \LogicException(), Finder::create() ->in($dir), ['non_existing_dir'], 'intersection', ]; yield 'configured by config file, overridden by multiple files' => [ $cb(['d/d1.php', 'd/d2.php']), null, [$dir.'/d/d1.php', $dir.'/d/d2.php'], 'override', $dir.'/d/.php-cs-fixer.php', ]; yield 'configured by config file, intersected with multiple files' => [ $cb(['d/d1.php', 'd/d2.php']), null, [$dir.'/d/d1.php', $dir.'/d/d2.php'], 'intersection', $dir.'/d/.php-cs-fixer.php', ]; yield 'configured by config file, overridden by non-existing dir' => [ new \LogicException(), null, [$dir.'/d/fff'], 'override', $dir.'/d/.php-cs-fixer.php', ]; yield 'configured by config file, intersected with non-existing dir' => [ new \LogicException(), null, [$dir.'/d/fff'], 'intersection', $dir.'/d/.php-cs-fixer.php', ]; yield 'configured by config file, overridden by non-existing file' => [ new \LogicException(), null, [$dir.'/d/fff.php'], 'override', $dir.'/d/.php-cs-fixer.php', ]; yield 'configured by config file, intersected with non-existing file' => [ new \LogicException(), null, [$dir.'/d/fff.php'], 'intersection', $dir.'/d/.php-cs-fixer.php', ]; yield 'configured by config file, overridden by multiple files and dirs' => [ $cb(['d/d1.php', 'd/e/de1.php', 'd/f/df1.php']), null, [$dir.'/d/d1.php', $dir.'/d/e', $dir.'/d/f/'], 'override', $dir.'/d/.php-cs-fixer.php', ]; yield 'configured by config file, intersected with multiple files and dirs' => [ $cb(['d/d1.php', 'd/e/de1.php', 'd/f/df1.php']), null, [$dir.'/d/d1.php', $dir.'/d/e', $dir.'/d/f/'], 'intersection', $dir.'/d/.php-cs-fixer.php', ]; } /** * @param array<string, mixed> $options * * @dataProvider provideConfigFinderIsOverriddenCases */ public function testConfigFinderIsOverridden(array $options, bool $expectedResult): void { $resolver = $this->createConfigurationResolver($options); self::assertSame($expectedResult, $resolver->configFinderIsOverridden()); $resolver = $this->createConfigurationResolver($options); $resolver->getFinder(); self::assertSame($expectedResult, $resolver->configFinderIsOverridden()); } /** * @return iterable<int, array{array<string, mixed>, bool}> */ public static function provideConfigFinderIsOverriddenCases(): iterable { $root = __DIR__.'/../..'; yield [ [ 'config' => __DIR__.'/../Fixtures/.php-cs-fixer.vanilla.php', ], false, ]; yield [ [ 'config' => __DIR__.'/../Fixtures/.php-cs-fixer.vanilla.php', 'path' => [$root.'/src'], ], true, ]; yield [ [ 'config' => ConfigurationResolver::IGNORE_CONFIG_FILE, ], false, ]; yield [ [ 'config' => ConfigurationResolver::IGNORE_CONFIG_FILE, 'path' => [$root.'/src'], ], false, ]; yield [ [ 'config' => __DIR__.'/../Fixtures/.php-cs-fixer.vanilla.php', 'path' => [$root.'/src'], 'path-mode' => ConfigurationResolver::PATH_MODE_INTERSECTION, ], false, ]; // scenario when loaded config is not setting custom finder yield [ [ 'config' => $root.'/tests/Fixtures/ConfigurationResolverConfigFile/case_3/.php-cs-fixer.dist.php', 'path' => [$root.'/src'], ], false, ]; // scenario when loaded config contains not fully defined finder yield [ [ 'config' => $root.'/tests/Fixtures/ConfigurationResolverConfigFile/case_9/.php-cs-fixer.php', 'path' => [$root.'/src'], ], false, ]; } public function testResolveIsDryRunViaStdIn(): void { $resolver = $this->createConfigurationResolver([ 'dry-run' => false, 'path' => ['-'], ]); self::assertTrue($resolver->isDryRun()); } public function testResolveIsDryRunViaNegativeOption(): void { $resolver = $this->createConfigurationResolver(['dry-run' => false]); self::assertFalse($resolver->isDryRun()); } public function testResolveIsDryRunViaPositiveOption(): void { $resolver = $this->createConfigurationResolver(['dry-run' => true]); self::assertTrue($resolver->isDryRun()); } /** * @dataProvider provideResolveBooleanOptionCases */ public function testResolveUsingCacheWithConfigOption(bool $expected, bool $configValue, ?string $passed): void { $config = new Config(); $config->setUsingCache($configValue); $resolver = $this->createConfigurationResolver( ['using-cache' => $passed], $config, ); self::assertSame($expected, $resolver->getUsingCache()); } /** * @return iterable<int, array{bool, bool, null|string}> */ public static function provideResolveBooleanOptionCases(): iterable { yield [true, true, 'yes']; yield [true, false, 'yes']; yield [false, true, 'no']; yield [false, false, 'no']; yield [true, true, null]; yield [false, false, null]; } public function testResolveUsingCacheWithPositiveConfigAndNoOption(): void { $config = new Config(); $config->setUsingCache(true); $resolver = $this->createConfigurationResolver( [], $config, ); self::assertTrue($resolver->getUsingCache()); } public function testResolveUsingCacheWithNegativeConfigAndNoOption(): void { $config = new Config(); $config->setUsingCache(false); $resolver = $this->createConfigurationResolver( [], $config, ); self::assertFalse($resolver->getUsingCache()); } /** * @dataProvider provideResolveUsingCacheForRuntimesCases */ public function testResolveUsingCacheForRuntimes(bool $cacheAllowed, bool $installedWithComposer, bool $asPhar, bool $inDocker): void { $config = new Config(); $config->setUsingCache(true); $resolver = $this->createConfigurationResolver( [], $config, '', new class($installedWithComposer, $asPhar, $inDocker) implements ToolInfoInterface { private bool $installedWithComposer; private bool $asPhar; private bool $inDocker; public function __construct(bool $installedWithComposer, bool $asPhar, bool $inDocker) { $this->installedWithComposer = $installedWithComposer; $this->asPhar = $asPhar; $this->inDocker = $inDocker; } public function getComposerInstallationDetails(): array { throw new \BadMethodCallException(); } public function getComposerVersion(): string { throw new \BadMethodCallException(); } public function getVersion(): string { throw new \BadMethodCallException(); } public function isInstalledAsPhar(): bool { return $this->asPhar; } public function isInstalledByComposer(): bool { return $this->installedWithComposer; } public function isRunInsideDocker(): bool { return $this->inDocker; } public function getPharDownloadUri(string $version): string { throw new \BadMethodCallException(); } }, ); self::assertSame($cacheAllowed, $resolver->getUsingCache()); } /** * @return iterable<string, array{0: bool, 1: bool, 2: bool, 3: bool}> */ public static function provideResolveUsingCacheForRuntimesCases(): iterable { yield 'none of the allowed runtimes' => [false, false, false, false]; yield 'composer installation' => [true, true, false, false]; yield 'PHAR distribution' => [true, false, true, false]; yield 'Docker runtime' => [true, false, false, true]; } public function testResolveCacheFileWithoutConfigAndOption(): void { $config = new Config(); $default = $config->getCacheFile(); $resolver = $this->createConfigurationResolver( [], $config, ); self::assertSame($default, $resolver->getCacheFile()); } public function testResolveCacheFileWithConfig(): void { $cacheFile = 'foo/bar.baz'; $config = new Config(); $config ->setUsingCache(false) ->setCacheFile($cacheFile) ; $resolver = $this->createConfigurationResolver( [], $config, ); self::assertNull($resolver->getCacheFile()); $cacheManager = $resolver->getCacheManager(); self::assertInstanceOf(NullCacheManager::class, $cacheManager); self::assertFalse($resolver->getLinter()->isAsync()); } public function testResolveCacheFileWithOption(): void { $cacheFile = 'bar.baz'; $config = new Config(); $config->setCacheFile($cacheFile); $resolver = $this->createConfigurationResolver( ['cache-file' => $cacheFile], $config, ); self::assertSame($cacheFile, $resolver->getCacheFile()); } public function testResolveCacheFileWithConfigAndOption(): void { $configCacheFile = 'foo/bar.baz'; $optionCacheFile = 'bar.baz'; $config = new Config(); $config->setCacheFile($configCacheFile); $resolver = $this->createConfigurationResolver( ['cache-file' => $optionCacheFile], $config, ); self::assertSame($optionCacheFile, $resolver->getCacheFile()); } /**
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
true
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/WarningsDetectorTest.php
tests/Console/WarningsDetectorTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console; use PhpCsFixer\ComposerJsonReader; use PhpCsFixer\Console\WarningsDetector; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\ToolInfoInterface; /** * @author ntzm * * @internal * * @covers \PhpCsFixer\Console\WarningsDetector * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class WarningsDetectorTest extends TestCase { public function testDetectOldVendorNotInstalledByComposer(): void { $toolInfo = $this->createToolInfoDouble(false, 'not-installed-by-composer'); $warningsDetector = new WarningsDetector($toolInfo); $warningsDetector->detectOldVendor(); self::assertSame([], $warningsDetector->getWarnings()); } public function testDetectOldVendorNotLegacyPackage(): void { $toolInfo = $this->createToolInfoDouble(false, 'friendsofphp/php-cs-fixer'); $warningsDetector = new WarningsDetector($toolInfo); $warningsDetector->detectOldVendor(); self::assertSame([], $warningsDetector->getWarnings()); } public function testDetectOldVendorLegacyPackage(): void { $toolInfo = $this->createToolInfoDouble(true, 'fabpot/php-cs-fixer'); $warningsDetector = new WarningsDetector($toolInfo); $warningsDetector->detectOldVendor(); self::assertSame([ 'You are running PHP CS Fixer installed with old vendor `fabpot/php-cs-fixer`. Please update to `friendsofphp/php-cs-fixer`.', 'If you need help while solving warnings, ask at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/discussions/, we will help you!', ], $warningsDetector->getWarnings()); } /** * This test verifies that a warning is shown when running on a PHP version higher than the minimum required in composer.json. */ public function testDetectHigherPhpVersionWithHigherVersion(): void { // Extract the minimum PHP version from composer.json $composerJsonReader = ComposerJsonReader::createSingleton(); $minPhpVersion = $composerJsonReader->getPhp(); self::assertSame('7.4', $minPhpVersion, 'Expected minimum PHP version to be 7.4'); // Only run this test if we're actually running on a version higher than the minimum required $currentMajorMinor = \sprintf('%d.%d', \PHP_MAJOR_VERSION, \PHP_MINOR_VERSION); if (version_compare($currentMajorMinor, $minPhpVersion, '<=')) { self::markTestSkipped(\sprintf('This test requires running on PHP > %s', $minPhpVersion)); } $toolInfo = $this->createToolInfoDouble(false, 'not-installed-by-composer'); $warningsDetector = new WarningsDetector($toolInfo); $warningsDetector->detectHigherPhpVersion(); $warnings = $warningsDetector->getWarnings(); self::assertNotEmpty($warnings); self::assertStringStartsWith( \sprintf( 'You are running PHP CS Fixer on PHP %s, but the minimum PHP version supported by your project in composer.json is PHP %s', \PHP_VERSION, $minPhpVersion, ), $warnings[0], ); } /** * This test verifies that no warning is shown when running on a PHP version equal to or lower than the minimum required. * * @runInSeparateProcess */ public function testDetectHigherPhpVersionWithEqualOrLowerVersion(): void { $originalDir = getcwd(); if (false === $originalDir) { throw new \RuntimeException('Unable to determine current working directory'); } $tempDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'phpcsfixer_test_'.uniqid('', true); mkdir($tempDir); try { // Change to temp directory so ComposerJsonReader looks for composer.json there. // ComposerJsonReader reads from the current working directory, not a configurable path. chdir($tempDir); // Create a composer.json with PHP requirement equal to or higher than current version $currentMajorMinor = \sprintf('%d.%d', \PHP_MAJOR_VERSION, \PHP_MINOR_VERSION); file_put_contents('composer.json', json_encode([ 'name' => 'test/test', 'require' => [ 'php' => '^'.$currentMajorMinor, ], ])); $toolInfo = $this->createToolInfoDouble(false, 'not-installed-by-composer'); $warningsDetector = new WarningsDetector($toolInfo); $warningsDetector->detectHigherPhpVersion(); $warnings = $warningsDetector->getWarnings(); // No warning should be shown when running on the minimum required version or lower self::assertSame([], $warnings); } finally { chdir($originalDir); if (file_exists($tempDir.'/composer.json')) { unlink($tempDir.'/composer.json'); } rmdir($tempDir); } } /** * This test verifies that a warning is shown when composer.json cannot be read. * * @runInSeparateProcess */ public function testDetectHigherPhpVersionWithMissingComposerJson(): void { $originalDir = getcwd(); if (false === $originalDir) { throw new \RuntimeException('Unable to determine current working directory'); } $tempDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'phpcsfixer_test_'.uniqid('', true); mkdir($tempDir); try { // Change to temp directory so ComposerJsonReader looks for composer.json there. // ComposerJsonReader reads from the current working directory, not a configurable path. chdir($tempDir); $toolInfo = $this->createToolInfoDouble(false, 'not-installed-by-composer'); $warningsDetector = new WarningsDetector($toolInfo); $warningsDetector->detectHigherPhpVersion(); $warnings = $warningsDetector->getWarnings(); self::assertNotEmpty($warnings); self::assertStringContainsString('Unable to determine minimum PHP version supported by your project from composer.json:', $warnings[0]); } finally { chdir($originalDir); rmdir($tempDir); } } /** * This test verifies that a warning is shown when composer.json has no PHP requirement. * * @runInSeparateProcess */ public function testDetectHigherPhpVersionWithNoPhpRequirement(): void { $originalDir = getcwd(); if (false === $originalDir) { throw new \RuntimeException('Unable to determine current working directory'); } $tempDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'phpcsfixer_test_'.uniqid('', true); mkdir($tempDir); try { // Change to temp directory so ComposerJsonReader looks for composer.json there. // ComposerJsonReader reads from the current working directory, not a configurable path. chdir($tempDir); // Create a composer.json without PHP requirement file_put_contents('composer.json', json_encode([ 'name' => 'test/test', 'require' => [], ])); $toolInfo = $this->createToolInfoDouble(false, 'not-installed-by-composer'); $warningsDetector = new WarningsDetector($toolInfo); $warningsDetector->detectHigherPhpVersion(); $warnings = $warningsDetector->getWarnings(); self::assertNotEmpty($warnings); self::assertSame( 'No PHP version requirement found in composer.json. It is recommended to specify a minimum PHP version supported by your project.', $warnings[0], ); } finally { chdir($originalDir); if (file_exists($tempDir.'/composer.json')) { unlink($tempDir.'/composer.json'); } rmdir($tempDir); } } private function createToolInfoDouble(bool $isInstalledByComposer, string $packageName): ToolInfoInterface { $composerInstallationDetails = [ 'name' => $packageName, 'version' => '1.0.0', 'dist' => [], ]; return new class($isInstalledByComposer, $composerInstallationDetails) implements ToolInfoInterface { private bool $isInstalledByComposer; /** @var array{name: string, version: string, dist: array{reference?: string}} */ private array $composerInstallationDetails; /** * @param array{name: string, version: string, dist: array{reference?: string}} $composerInstallationDetails */ public function __construct(bool $isInstalledByComposer, array $composerInstallationDetails) { $this->isInstalledByComposer = $isInstalledByComposer; $this->composerInstallationDetails = $composerInstallationDetails; } public function getComposerInstallationDetails(): array { return $this->composerInstallationDetails; } public function getComposerVersion(): string { throw new \LogicException('Not implemented.'); } public function getVersion(): string { throw new \LogicException('Not implemented.'); } public function isInstalledAsPhar(): bool { throw new \LogicException('Not implemented.'); } public function isInstalledByComposer(): bool { return $this->isInstalledByComposer; } public function isRunInsideDocker(): bool { return false; } public function getPharDownloadUri(string $version): string { throw new \LogicException('Not implemented.'); } }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Output/ErrorOutputTest.php
tests/Console/Output/ErrorOutputTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Output; use PhpCsFixer\Console\Output\ErrorOutput; use PhpCsFixer\Error\Error; use PhpCsFixer\Linter\LintingException; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\StreamOutput; /** * @internal * * @covers \PhpCsFixer\Console\Output\ErrorOutput * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ErrorOutputTest extends TestCase { /** * @param OutputInterface::VERBOSITY_* $verbosityLevel * * @dataProvider provideErrorOutputCases */ public function testErrorOutput(Error $error, int $verbosityLevel, int $lineNumber, int $exceptionLineNumber, string $process): void { $source = $error->getSource(); $output = $this->createStreamOutput($verbosityLevel); $errorOutput = new ErrorOutput($output); $errorOutput->listErrors($process, [$error]); $displayed = $this->readFullStreamOutput($output); $startWith = \sprintf( ' Files that were not fixed due to errors reported during %s: 1) %s', $process, __FILE__, ); if ($verbosityLevel >= OutputInterface::VERBOSITY_VERY_VERBOSE) { $startWith .= \sprintf( ' '.' [%s] '.' %s (%d) '.' '.' ', \get_class($source), $source->getMessage(), $source->getCode(), ); } if ($verbosityLevel >= OutputInterface::VERBOSITY_DEBUG) { $startWith .= \sprintf( ' PhpCsFixer\Tests\Console\Output\ErrorOutputTest::getErrorAndLineNumber() in %s at line %d PhpCsFixer\Tests\Console\Output\ErrorOutputTest::provideErrorOutputCases() ', __FILE__, $lineNumber, ); } self::assertStringStartsWith($startWith, $displayed); } /** * @return iterable<int, array{Error, int, int, int, string}> */ public static function provideErrorOutputCases(): iterable { $lineNumber = __LINE__; [$exceptionLineNumber, $error] = self::getErrorAndLineNumber(); // note: keep call and __LINE__ separated with one line break ++$lineNumber; yield [$error, OutputInterface::VERBOSITY_NORMAL, $lineNumber, $exceptionLineNumber, 'VN']; yield [$error, OutputInterface::VERBOSITY_VERBOSE, $lineNumber, $exceptionLineNumber, 'VV']; yield [$error, OutputInterface::VERBOSITY_VERY_VERBOSE, $lineNumber, $exceptionLineNumber, 'VVV']; yield [$error, OutputInterface::VERBOSITY_DEBUG, $lineNumber, $exceptionLineNumber, 'DEBUG']; } public function testLintingExceptionOutputsAppliedFixersAndDiff(): void { $fixerName = uniqid('braces_'); $diffSpecificContext = uniqid('added_'); $diff = <<<EOT --- Original +++ New @@ @@ same line -deleted +{$diffSpecificContext} EOT; $lintError = new Error(Error::TYPE_LINT, __FILE__, new LintingException(), [$fixerName], $diff); $noDiffLintFixerName = uniqid('no_diff_'); $noDiffLintError = new Error(Error::TYPE_LINT, __FILE__, new LintingException(), [$noDiffLintFixerName]); $invalidErrorFixerName = uniqid('line_ending_'); $invalidDiff = uniqid('invalid_diff_'); $invalidError = new Error(Error::TYPE_INVALID, __FILE__, new LintingException(), [$invalidErrorFixerName], $invalidDiff); $output = $this->createStreamOutput(OutputInterface::VERBOSITY_VERY_VERBOSE); $errorOutput = new ErrorOutput($output); $errorOutput->listErrors(uniqid('process_'), [ $lintError, $noDiffLintError, $invalidError, ]); $displayed = $this->readFullStreamOutput($output); self::assertStringContainsString($fixerName, $displayed); self::assertStringContainsString($diffSpecificContext, $displayed); self::assertStringContainsString($noDiffLintFixerName, $displayed); self::assertStringNotContainsString($invalidErrorFixerName, $displayed); self::assertStringNotContainsString($invalidDiff, $displayed); } /** * @param OutputInterface::VERBOSITY_* $verbosityLevel */ private function createStreamOutput(int $verbosityLevel): StreamOutput { $steam = fopen('php://memory', 'w', false); \assert(\is_resource($steam)); $output = new StreamOutput($steam); $output->setDecorated(false); $output->setVerbosity($verbosityLevel); return $output; } private function readFullStreamOutput(StreamOutput $output): string { rewind($output->getStream()); $displayed = stream_get_contents($output->getStream()); \assert(\is_string($displayed)); // normalize line breaks, // as we output using SF `writeln` we are not sure what line ending has been used as it is // based on the platform/console/terminal used return str_replace(\PHP_EOL, "\n", $displayed); } /** * @return array{int, Error} */ private static function getErrorAndLineNumber(): array { $lineNumber = __LINE__; $exception = new \RuntimeException(// note: keep exception constructor and __LINE__ separated with one line break 'PHPUnit RT', 888, new \InvalidArgumentException('PHPUnit IAE'), ); return [$lineNumber + 1, new Error(Error::TYPE_EXCEPTION, __FILE__, $exception)]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Output/OutputContextTest.php
tests/Console/Output/OutputContextTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Output; use PhpCsFixer\Console\Output\OutputContext; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Console\Output\NullOutput; /** * @internal * * @covers \PhpCsFixer\Console\Output\OutputContext * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class OutputContextTest extends TestCase { public function testProvidedValuesAreAccessible(): void { $output = new NullOutput(); $width = 100; $filesCount = 10; $outputContext = new OutputContext($output, $width, $filesCount); self::assertSame($output, $outputContext->getOutput()); self::assertSame($width, $outputContext->getTerminalWidth()); self::assertSame($filesCount, $outputContext->getFilesCount()); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Output/Progress/PercentageBarOutputTest.php
tests/Console/Output/Progress/PercentageBarOutputTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Output\Progress; use PhpCsFixer\Console\Output\OutputContext; use PhpCsFixer\Console\Output\Progress\PercentageBarOutput; use PhpCsFixer\Runner\Event\FileProcessed; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Console\Output\BufferedOutput; /** * @internal * * @covers \PhpCsFixer\Console\Output\Progress\PercentageBarOutput * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PercentageBarOutputTest extends TestCase { /** * @param list<array{0: FileProcessed::STATUS_*, 1?: int}> $statuses * * @dataProvider providePercentageBarProgressOutputCases */ public function testPercentageBarProgressOutput(array $statuses, string $expectedOutput, int $width): void { $nbFiles = 0; $this->foreachStatus($statuses, static function () use (&$nbFiles): void { ++$nbFiles; }); $output = new BufferedOutput(); $processOutput = new PercentageBarOutput(new OutputContext($output, $width, $nbFiles)); $this->foreachStatus($statuses, static function (int $status) use ($processOutput): void { $processOutput->onFixerFileProcessed(new FileProcessed($status)); }); self::assertSame($expectedOutput, rtrim($output->fetch())); } /** * @return iterable<int, array{0: list<array{0: FileProcessed::STATUS_*, 1?: int}>, 1: string, 2: int}> */ public static function providePercentageBarProgressOutputCases(): iterable { yield [ [ [FileProcessed::STATUS_NO_CHANGES, 100], ], ' 0/100 [░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 0%'.\PHP_EOL .' 100/100 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%', 80, ]; } /** * @param list<array{0: FileProcessed::STATUS_*, 1?: int}> $statuses * @param \Closure(FileProcessed::STATUS_*): void $action */ private function foreachStatus(array $statuses, \Closure $action): void { foreach ($statuses as $status) { $multiplier = $status[1] ?? 1; $status = $status[0]; for ($i = 0; $i < $multiplier; ++$i) { $action($status); } } } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Output/Progress/NullOutputTest.php
tests/Console/Output/Progress/NullOutputTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Output\Progress; use PhpCsFixer\Console\Output\Progress\NullOutput; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\Console\Output\Progress\NullOutput * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NullOutputTest extends TestCase { /** * @doesNotPerformAssertions */ public function testNullOutput(): void { $output = new NullOutput(); $output->printLegend(); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Output/Progress/ProgressOutputFactoryTest.php
tests/Console/Output/Progress/ProgressOutputFactoryTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Output\Progress; use PhpCsFixer\Console\Output\OutputContext; use PhpCsFixer\Console\Output\Progress\DotsOutput; use PhpCsFixer\Console\Output\Progress\NullOutput; use PhpCsFixer\Console\Output\Progress\ProgressOutputFactory; use PhpCsFixer\Console\Output\Progress\ProgressOutputType; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Console\Output\NullOutput as SymfonyNullOutput; /** * @internal * * @covers \PhpCsFixer\Console\Output\Progress\ProgressOutputFactory * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ProgressOutputFactoryTest extends TestCase { /** * @dataProvider provideValidProcessOutputIsCreatedCases * * @param class-string<\Throwable> $expectedOutputClass */ public function testValidProcessOutputIsCreated( string $outputType, OutputContext $context, string $expectedOutputClass ): void { // @phpstan-ignore-next-line argument.type as we explicitly test non-valid $outputType self::assertInstanceOf($expectedOutputClass, (new ProgressOutputFactory())->create($outputType, $context)); } /** * @return iterable<string, array{string, OutputContext, string}> */ public static function provideValidProcessOutputIsCreatedCases(): iterable { $context = new OutputContext(new SymfonyNullOutput(), 100, 10); $nullContext = new OutputContext(null, 100, 10); yield 'none' => [ProgressOutputType::NONE, $context, NullOutput::class]; yield 'dots' => [ProgressOutputType::DOTS, $context, DotsOutput::class]; yield 'dots with null output' => [ProgressOutputType::DOTS, $nullContext, NullOutput::class]; yield 'unsupported type with null output' => ['boom', $nullContext, NullOutput::class]; } public function testExceptionIsThrownForUnsupportedProcessOutputType(): void { $this->expectException(\InvalidArgumentException::class); $outputContext = new OutputContext(new SymfonyNullOutput(), 100, 10); // @phpstan-ignore-next-line argument.type as we explicitly test non-valid $outputType (new ProgressOutputFactory())->create('boom', $outputContext); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Output/Progress/DotsOutputTest.php
tests/Console/Output/Progress/DotsOutputTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Output\Progress; use PhpCsFixer\Console\Output\OutputContext; use PhpCsFixer\Console\Output\Progress\DotsOutput; use PhpCsFixer\Runner\Event\FileProcessed; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Console\Output\BufferedOutput; /** * @internal * * @covers \PhpCsFixer\Console\Output\Progress\DotsOutput * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DotsOutputTest extends TestCase { /** * @param list<array{0: FileProcessed::STATUS_*, 1?: int}> $statuses * * @dataProvider provideDotsProgressOutputCases */ public function testDotsProgressOutput(array $statuses, string $expectedOutput, int $width): void { $nbFiles = 0; $this->foreachStatus($statuses, static function () use (&$nbFiles): void { ++$nbFiles; }); $output = new BufferedOutput(); $processOutput = new DotsOutput(new OutputContext($output, $width, $nbFiles)); $this->foreachStatus($statuses, static function (int $status) use ($processOutput): void { $processOutput->onFixerFileProcessed(new FileProcessed($status)); }); self::assertSame($expectedOutput, $output->fetch()); } /** * @return iterable<int, array{list<array{0: FileProcessed::STATUS_*, 1?: int}>, string, int}> */ public static function provideDotsProgressOutputCases(): iterable { yield [ [ [FileProcessed::STATUS_NO_CHANGES, 4], ], '.... 4 / 4 (100%)', 80, ]; yield [ [ [FileProcessed::STATUS_NO_CHANGES], [FileProcessed::STATUS_FIXED], [FileProcessed::STATUS_NO_CHANGES, 4], ], '.F.... 6 / 6 (100%)', 80, ]; yield [ [ [FileProcessed::STATUS_NO_CHANGES, 65], ], '................................................................. 65 / 65 (100%)', 80, ]; yield [ [ [FileProcessed::STATUS_NO_CHANGES, 66], ], '................................................................. 65 / 66 ( 98%)'.\PHP_EOL .'. 66 / 66 (100%)', 80, ]; yield [ [ [FileProcessed::STATUS_NO_CHANGES, 66], ], '......................... 25 / 66 ( 38%)'.\PHP_EOL .'......................... 50 / 66 ( 76%)'.\PHP_EOL .'................ 66 / 66 (100%)', 40, ]; yield [ [ [FileProcessed::STATUS_NO_CHANGES, 66], ], '.................................................................. 66 / 66 (100%)', 100, ]; yield [ [ [FileProcessed::STATUS_NO_CHANGES, 19], [FileProcessed::STATUS_EXCEPTION], [FileProcessed::STATUS_NO_CHANGES, 6], [FileProcessed::STATUS_LINT], [FileProcessed::STATUS_FIXED, 3], [FileProcessed::STATUS_NO_CHANGES, 50], [FileProcessed::STATUS_SKIPPED], [FileProcessed::STATUS_NO_CHANGES, 49], [FileProcessed::STATUS_INVALID], [FileProcessed::STATUS_NO_CHANGES], [FileProcessed::STATUS_INVALID], [FileProcessed::STATUS_NO_CHANGES, 40], [FileProcessed::STATUS_INVALID], [FileProcessed::STATUS_NO_CHANGES, 14], [FileProcessed::STATUS_NON_MONOLITHIC], ], '...................E......EFFF................................. 63 / 189 ( 33%)'.\PHP_EOL .'.................S............................................. 126 / 189 ( 67%)'.\PHP_EOL .'....I.I........................................I..............M 189 / 189 (100%)', 80, ]; yield [ [ [FileProcessed::STATUS_NO_CHANGES, 19], [FileProcessed::STATUS_EXCEPTION], [FileProcessed::STATUS_NO_CHANGES, 6], [FileProcessed::STATUS_LINT], [FileProcessed::STATUS_FIXED, 3], [FileProcessed::STATUS_NO_CHANGES, 50], [FileProcessed::STATUS_SKIPPED], [FileProcessed::STATUS_NO_CHANGES, 49], [FileProcessed::STATUS_INVALID], [FileProcessed::STATUS_NO_CHANGES], [FileProcessed::STATUS_INVALID], [FileProcessed::STATUS_NO_CHANGES, 40], [FileProcessed::STATUS_INVALID], [FileProcessed::STATUS_NO_CHANGES, 15], ], '...................E......EFFF..................................................S...................... 103 / 189 ( 54%)'.\PHP_EOL .'...........................I.I........................................I............... 189 / 189 (100%)', 120, ]; } public function testSerialize(): void { $processOutput = new DotsOutput(new OutputContext(new BufferedOutput(), 1, 1)); $this->expectException(\BadMethodCallException::class); $this->expectExceptionMessage('Cannot serialize '.DotsOutput::class); serialize($processOutput); } public function testUnserialize(): void { $this->expectException(\BadMethodCallException::class); $this->expectExceptionMessage('Cannot unserialize '.DotsOutput::class); unserialize(self::createSerializedStringOfClassName(DotsOutput::class)); } /** * @param list<array{0: FileProcessed::STATUS_*, 1?: int}> $statuses * @param \Closure(FileProcessed::STATUS_*): void $action */ private function foreachStatus(array $statuses, \Closure $action): void { foreach ($statuses as $status) { $multiplier = $status[1] ?? 1; $status = $status[0]; for ($i = 0; $i < $multiplier; ++$i) { $action($status); } } } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Output/Progress/ProgressOutputTypeTest.php
tests/Console/Output/Progress/ProgressOutputTypeTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Output\Progress; use PhpCsFixer\Console\Output\Progress\ProgressOutputType; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\Console\Output\Progress\ProgressOutputType * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ProgressOutputTypeTest extends TestCase { public function testAll(): void { $types = array_values((new \ReflectionClass(ProgressOutputType::class))->getConstants()); sort($types); self::assertSame($types, ProgressOutputType::all()); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Internal/ApplicationTest.php
tests/Console/Internal/ApplicationTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Internal; use PhpCsFixer\Console\Internal\Application; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\Console\Internal\Application * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ApplicationTest extends TestCase { public function testApplication(): void { $regex = '/^PHP CS Fixer - internal <info>\d+.\d+.\d+(-DEV)?<\/info> <info>.+<\/info>' .' by <comment>Fabien Potencier<\/comment>, <comment>Dariusz Ruminski<\/comment> and <comment>contributors<\/comment>\.' ."\nPHP runtime: <info>\\d+.\\d+.\\d+(-dev|beta\\d+)?<\\/info>$/"; self::assertMatchesRegularExpression($regex, (new Application())->getLongVersion()); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Internal/Command/ParseCommandTest.php
tests/Console/Internal/Command/ParseCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Internal\Command; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\Console\Internal\Command\ParseCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ParseCommandTest extends TestCase { public function testNotice(): void { self::markTestIncomplete('Tests is not implemented for this internal command, consider to support and implement it.'); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Internal/Command/DecodeIdCommandTest.php
tests/Console/Internal/Command/DecodeIdCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Internal\Command; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\Console\Internal\Command\DecodeIdCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DecodeIdCommandTest extends TestCase { public function testNotice(): void { self::markTestIncomplete('Tests is not implemented for this internal command, consider to support and implement it.'); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Internal/Command/DocumentationCommandTest.php
tests/Console/Internal/Command/DocumentationCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Internal\Command; use PhpCsFixer\Console\Internal\Application; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\Filesystem\Filesystem; /** * @internal * * @covers \PhpCsFixer\Console\Internal\Command\DocumentationCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DocumentationCommandTest extends TestCase { /** * @large * * @todo Find out the root cause of it being slower and hitting small test time limit */ public function testGeneratingDocumentation(): void { $application = new Application( $this->createFilesystemDouble(), ); $command = $application->find('documentation'); $commandTester = new CommandTester($command); $commandTester->execute( [ 'command' => $command->getName(), ], [ 'interactive' => false, 'decorated' => false, 'verbosity' => OutputInterface::VERBOSITY_DEBUG, ], ); self::assertStringContainsString( 'Docs updated.', $commandTester->getDisplay(), ); } private function createFilesystemDouble(): Filesystem { return new class extends Filesystem { public function dumpFile(string $filename, $content): void {} /** @phpstan-ignore-next-line */ public function remove($files): void {} }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/SelfUpdate/NewVersionCheckerTest.php
tests/Console/SelfUpdate/NewVersionCheckerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\SelfUpdate; use PhpCsFixer\Console\SelfUpdate\GithubClientInterface; use PhpCsFixer\Console\SelfUpdate\NewVersionChecker; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\Console\SelfUpdate\NewVersionChecker * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NewVersionCheckerTest extends TestCase { public function testGetLatestVersion(): void { $checker = new NewVersionChecker($this->createGithubClientDouble()); self::assertSame('v2.4.1', $checker->getLatestVersion()); } /** * @dataProvider provideGetLatestVersionOfMajorCases */ public function testGetLatestVersionOfMajor(int $majorVersion, ?string $expectedVersion): void { $checker = new NewVersionChecker($this->createGithubClientDouble()); self::assertSame($expectedVersion, $checker->getLatestVersionOfMajor($majorVersion)); } /** * @return iterable<int, array{int, null|string}> */ public static function provideGetLatestVersionOfMajorCases(): iterable { yield [1, 'v1.13.2']; yield [2, 'v2.4.1']; yield [4, null]; } /** * @dataProvider provideCompareVersionsCases */ public function testCompareVersions(string $versionA, string $versionB, int $expectedResult): void { $checker = new NewVersionChecker($this->createGithubClientDouble()); self::assertSame( $expectedResult, $checker->compareVersions($versionA, $versionB), ); self::assertSame( -$expectedResult, $checker->compareVersions($versionB, $versionA), ); } /** * @return iterable<int, array{string, string, int}> */ public static function provideCompareVersionsCases(): iterable { foreach ([ ['1.0.0-alpha', '1.0.0', -1], ['1.0.0-beta', '1.0.0', -1], ['1.0.0-RC', '1.0.0', -1], ['1.0.0', '1.0.0', 0], ['1.0.0', '1.0.1', -1], ['1.0.0', '1.1.0', -1], ['1.0.0', '2.0.0', -1], ] as $case) { // X.Y.Z vs. X.Y.Z yield $case; // vX.Y.Z vs. X.Y.Z $case[0] = 'v'.$case[0]; yield $case; // vX.Y.Z vs. vX.Y.Z $case[1] = 'v'.$case[1]; yield $case; // X.Y.Z vs. vX.Y.Z $case[0] = substr($case[0], 1); yield $case; } } private function createGithubClientDouble(): GithubClientInterface { return new class implements GithubClientInterface { public function getTags(): array { return [ 'v3.0.0-RC', 'v2.4.1', 'v2.4.0', 'v2.3.3', 'v2.3.2', 'v2.3.1', 'v2.3.0', 'v2.2.6', 'v2.2.5', 'v2.2.4', 'v2.2.3', 'v2.2.2', 'v2.2.1', 'v2.2.0', 'v2.1.3', 'v2.1.2', 'v2.1.1', 'v2.1.0', 'v2.0.1', 'v2.0.0', 'v2.0.0-beta', 'v2.0.0-alpha', 'v2.0.0-RC', 'v1.14.0-beta', 'v1.13.2', 'v1.13.1', 'v1.13.0', 'v1.12.4', 'v1.12.3', 'v1.12.2', 'v1.12.1', ]; } }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/SelfUpdate/GithubClientTest.php
tests/Console/SelfUpdate/GithubClientTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\SelfUpdate; use PhpCsFixer\Console\SelfUpdate\GithubClient; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\Console\SelfUpdate\GithubClient * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class GithubClientTest extends TestCase { public function testGettingTags(): void { $githubClient = new GithubClient(__DIR__.'/../../Fixtures/api_github_com_tags.json'); self::assertSame( [ 'v3.48.0', 'v3.47.1', 'v3.47.0', ], $githubClient->getTags(), ); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/ListSetsReport/ReportSummaryTest.php
tests/Console/Report/ListSetsReport/ReportSummaryTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\ListSetsReport; use PhpCsFixer\Console\Report\ListSetsReport\ReportSummary; use PhpCsFixer\RuleSet\Sets\PhpCsFixerSet; use PhpCsFixer\Tests\TestCase; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Console\Report\ListSetsReport\ReportSummary * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ReportSummaryTest extends TestCase { public function testReportSummary(): void { $sets = [ new PhpCsFixerSet(), ]; $reportSummary = new ReportSummary( $sets, ); self::assertSame($sets, $reportSummary->getSets()); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/ListSetsReport/JsonReporterTest.php
tests/Console/Report/ListSetsReport/JsonReporterTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\ListSetsReport; use PhpCsFixer\Console\Report\ListSetsReport\JsonReporter; use PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface; use PhpCsFixer\Tests\Test\Assert\AssertJsonSchemaTrait; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Console\Report\ListSetsReport\JsonReporter * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class JsonReporterTest extends AbstractReporterTestCase { use AssertJsonSchemaTrait; protected function createReporter(): ReporterInterface { return new JsonReporter(); } protected function getFormat(): string { return 'json'; } protected function assertFormat(string $expected, string $input): void { self::assertJsonSchema(__DIR__.'/../../../../doc/schemas/list-sets/schema.json', $input); self::assertJsonStringEqualsJsonString($expected, $input); } protected static function createSimpleReport(): string { return '{ "sets": { "@PhpCsFixer": { "description": "Rules recommended by ``PHP CS Fixer`` team, highly opinionated. Extends ``@PER-CS`` and ``@Symfony``.", "isRisky": false, "name": "@PhpCsFixer" }, "@Symfony:risky": { "description": "Rules that follow the official `Symfony Coding Standards <https://symfony.com/doc/current/contributing/code/standards.html>`_. Extends ``@PER-CS:risky``.", "isRisky": true, "name": "@Symfony:risky" } } }'; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/ListSetsReport/ReporterFactoryTest.php
tests/Console/Report/ListSetsReport/ReporterFactoryTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\ListSetsReport; use PhpCsFixer\Console\Report\ListSetsReport\ReporterFactory; use PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface; use PhpCsFixer\Console\Report\ListSetsReport\ReportSummary; use PhpCsFixer\Tests\TestCase; /** * @author Boris Gorbylev <ekho@ekho.name> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Console\Report\ListSetsReport\ReporterFactory * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ReporterFactoryTest extends TestCase { public function testInterfaceIsFluent(): void { $builder = new ReporterFactory(); $testInstance = $builder->registerBuiltInReporters(); self::assertSame($builder, $testInstance); $double = $this->createReporterDouble('r1'); $testInstance = $builder->registerReporter($double); self::assertSame($builder, $testInstance); } public function testRegisterBuiltInReports(): void { $builder = new ReporterFactory(); self::assertCount(0, $builder->getFormats()); $builder->registerBuiltInReporters(); self::assertSame( ['json', 'txt'], $builder->getFormats(), ); } public function testThatCanRegisterAndGetReports(): void { $builder = new ReporterFactory(); $r1 = $this->createReporterDouble('r1'); $r2 = $this->createReporterDouble('r2'); $r3 = $this->createReporterDouble('r3'); $builder->registerReporter($r1); $builder->registerReporter($r2); $builder->registerReporter($r3); self::assertSame($r1, $builder->getReporter('r1')); self::assertSame($r2, $builder->getReporter('r2')); self::assertSame($r3, $builder->getReporter('r3')); } public function testGetFormats(): void { $builder = new ReporterFactory(); $r1 = $this->createReporterDouble('r1'); $r2 = $this->createReporterDouble('r2'); $r3 = $this->createReporterDouble('r3'); $builder->registerReporter($r1); $builder->registerReporter($r2); $builder->registerReporter($r3); self::assertSame(['r1', 'r2', 'r3'], $builder->getFormats()); } public function testRegisterReportWithOccupiedFormat(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('Reporter for format "non_unique_name" is already registered.'); $factory = new ReporterFactory(); $r1 = $this->createReporterDouble('non_unique_name'); $r2 = $this->createReporterDouble('non_unique_name'); $factory->registerReporter($r1); $factory->registerReporter($r2); } public function testGetNonRegisteredReport(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('Reporter for format "non_registered_format" is not registered.'); $builder = new ReporterFactory(); $builder->getReporter('non_registered_format'); } private function createReporterDouble(string $format): ReporterInterface { return new class($format) implements ReporterInterface { private string $format; public function __construct(string $format) { $this->format = $format; } public function getFormat(): string { return $this->format; } public function generate(ReportSummary $reportSummary): string { throw new \LogicException('Not implemented.'); } }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/ListSetsReport/AbstractReporterTestCase.php
tests/Console/Report/ListSetsReport/AbstractReporterTestCase.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\ListSetsReport; use PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface; use PhpCsFixer\Console\Report\ListSetsReport\ReportSummary; use PhpCsFixer\RuleSet\Sets\PhpCsFixerSet; use PhpCsFixer\RuleSet\Sets\SymfonyRiskySet; use PhpCsFixer\Tests\TestCase; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractReporterTestCase extends TestCase { protected ?ReporterInterface $reporter = null; protected function setUp(): void { parent::setUp(); $this->reporter = $this->createReporter(); } protected function tearDown(): void { parent::tearDown(); $this->reporter = null; } final public function testGetFormat(): void { self::assertSame( $this->getFormat(), $this->reporter->getFormat(), ); } /** * @dataProvider provideGenerateCases */ final public function testGenerate(string $expectedReport, ReportSummary $reportSummary): void { $actualReport = $this->reporter->generate($reportSummary); $this->assertFormat($expectedReport, $actualReport); } /** * @return iterable<string, array{string, ReportSummary}> */ final public static function provideGenerateCases(): iterable { yield 'example' => [ static::createSimpleReport(), new ReportSummary([ new SymfonyRiskySet(), new PhpCsFixerSet(), ]), ]; } abstract protected function createReporter(): ReporterInterface; abstract protected function getFormat(): string; abstract protected function assertFormat(string $expected, string $input): void; abstract protected static function createSimpleReport(): string; }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/ListSetsReport/TextReporterTest.php
tests/Console/Report/ListSetsReport/TextReporterTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\ListSetsReport; use PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface; use PhpCsFixer\Console\Report\ListSetsReport\TextReporter; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Console\Report\ListSetsReport\TextReporter * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TextReporterTest extends AbstractReporterTestCase { protected function createReporter(): ReporterInterface { return new TextReporter(); } protected function getFormat(): string { return 'txt'; } protected function assertFormat(string $expected, string $input): void { self::assertSame($expected, $input); } protected static function createSimpleReport(): string { return str_replace("\n", \PHP_EOL, ' 1) @PhpCsFixer Rules recommended by ``PHP CS Fixer`` team, highly opinionated. Extends ``@PER-CS`` and ``@Symfony``. 2) @Symfony:risky Rules that follow the official `Symfony Coding Standards <https://symfony.com/doc/current/contributing/code/standards.html>`_. Extends ``@PER-CS:risky``. Set contains risky rules. '); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/FixReport/JunitReporterTest.php
tests/Console/Report/FixReport/JunitReporterTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\FixReport; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Report\FixReport\JunitReporter; use PhpCsFixer\Console\Report\FixReport\ReporterInterface; use PhpCsFixer\PhpunitConstraintXmlMatchesXsd\Constraint\XmlMatchesXsd; use Symfony\Component\Console\Formatter\OutputFormatter; /** * @author Boris Gorbylev <ekho@ekho.name> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Console\Report\FixReport\JunitReporter * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class JunitReporterTest extends AbstractReporterTestCase { /** * JUnit XML schema from Jenkins. * * @see https://github.com/jenkinsci/xunit-plugin/blob/master/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd */ private static ?string $xsd = null; public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); $content = file_get_contents(__DIR__.'/../../../../doc/schemas/fix/junit-10.xsd'); if (false === $content) { throw new \RuntimeException('Cannot read file.'); } self::$xsd = $content; } public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); self::$xsd = null; } protected function getFormat(): string { return 'junit'; } protected static function createNoErrorReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <testsuites> <testsuite name="PHP CS Fixer" tests="1" assertions="1" failures="0" errors="0"> <properties> <property name="about" value="{$about}"/> </properties> <testcase name="All OK" assertions="1"/> </testsuite> </testsuites> XML; } protected static function createSimpleReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <testsuites> <testsuite name="PHP CS Fixer" tests="1" assertions="1" failures="1" errors="0"> <properties> <property name="about" value="{$about}"/> </properties> <testcase name="someFile" file="someFile.php" assertions="1"> <failure type="code_style">Wrong code style Diff: --------------- --- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar(\$foo = 1, \$bar) + public function bar(\$foo, \$bar) { } }</failure> </testcase> </testsuite> </testsuites> XML; } protected static function createWithDiffReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <testsuites> <testsuite name="PHP CS Fixer" tests="1" assertions="1" failures="1" errors="0"> <properties> <property name="about" value="{$about}"/> </properties> <testcase name="someFile" file="someFile.php" assertions="1"> <failure type="code_style"><![CDATA[Wrong code style Diff: --------------- --- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar(\$foo = 1, \$bar) + public function bar(\$foo, \$bar) { } }]]></failure> </testcase> </testsuite> </testsuites> XML; } protected static function createWithAppliedFixersReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <testsuites> <testsuite name="PHP CS Fixer" tests="1" assertions="2" failures="2" errors="0"> <properties> <property name="about" value="{$about}"/> </properties> <testcase name="someFile" file="someFile.php" assertions="2"> <failure type="code_style">applied fixers: --------------- * some_fixer_name_here_1 * some_fixer_name_here_2</failure> </testcase> </testsuite> </testsuites> XML; } protected static function createWithTimeAndMemoryReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <testsuites> <testsuite name="PHP CS Fixer" tests="1" assertions="1" failures="1" errors="0" time="1.234"> <properties> <property name="about" value="{$about}"/> </properties> <testcase name="someFile" file="someFile.php" assertions="1"> <failure type="code_style">Wrong code style Diff: --------------- --- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar(\$foo = 1, \$bar) + public function bar(\$foo, \$bar) { } }</failure> </testcase> </testsuite> </testsuites> XML; } protected static function createComplexReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0"?> <testsuites> <testsuite assertions="3" errors="0" failures="3" name="PHP CS Fixer" tests="2" time="1.234"> <properties> <property name="about" value="{$about}"/> </properties> <testcase assertions="2" file="someFile.php" name="someFile"> <failure type="code_style">applied fixers: --------------- * some_fixer_name_here_1 * some_fixer_name_here_2 Diff: --------------- this text is a diff ;)</failure> </testcase> <testcase assertions="1" file="anotherFile.php" name="anotherFile"> <failure type="code_style">applied fixers: --------------- * another_fixer_name_here Diff: --------------- another diff here ;)</failure> </testcase> </testsuite> </testsuites> XML; } protected function assertFormat(string $expected, string $input): void { $formatter = new OutputFormatter(); $input = $formatter->format($input); self::assertThat($input, new XmlMatchesXsd(self::$xsd)); self::assertXmlStringEqualsXmlString($expected, $input); } protected function createReporter(): ReporterInterface { return new JunitReporter(); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/FixReport/ReportSummaryTest.php
tests/Console/Report/FixReport/ReportSummaryTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\FixReport; use PhpCsFixer\Console\Report\FixReport\ReportSummary; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\Console\Report\FixReport\ReportSummary * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ReportSummaryTest extends TestCase { public function testReportSummary(): void { $changed = [ 'someFile.php' => [ 'appliedFixers' => ['some_fixer_name_here'], 'diff' => 'this text is a diff ;)', ], ]; $filesCount = 10; $time = time(); $memory = 123_456_789; $addAppliedFixers = true; $isDryRun = true; $isDecoratedOutput = false; $reportSummary = new ReportSummary( $changed, $filesCount, $time, $memory, $addAppliedFixers, $isDryRun, $isDecoratedOutput, ); self::assertSame($changed, $reportSummary->getChanged()); self::assertSame($filesCount, $reportSummary->getFilesCount()); self::assertSame($time, $reportSummary->getTime()); self::assertSame($memory, $reportSummary->getMemory()); self::assertSame($addAppliedFixers, $reportSummary->shouldAddAppliedFixers()); self::assertSame($isDryRun, $reportSummary->isDryRun()); self::assertSame($isDecoratedOutput, $reportSummary->isDecoratedOutput()); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/FixReport/JsonReporterTest.php
tests/Console/Report/FixReport/JsonReporterTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\FixReport; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Report\FixReport\JsonReporter; use PhpCsFixer\Console\Report\FixReport\ReporterInterface; use PhpCsFixer\Tests\Test\Assert\AssertJsonSchemaTrait; /** * @author Boris Gorbylev <ekho@ekho.name> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Console\Report\FixReport\JsonReporter * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class JsonReporterTest extends AbstractReporterTestCase { use AssertJsonSchemaTrait; protected static function createSimpleReport(): string { $about = Application::getAbout(); $diff = <<<'DIFF' --- Original\n+++ New\n@@ -2,7 +2,7 @@\n\n class Foo\n {\n- public function bar($foo = 1, $bar)\n+ public function bar($foo, $bar)\n {\n }\n } DIFF; return <<<JSON { "about": "{$about}", "files": [ { "diff": "{$diff}", "name": "someFile.php" } ], "time": { "total": 0 }, "memory": 0 } JSON; } protected static function createWithDiffReport(): string { $about = Application::getAbout(); $diff = <<<'DIFF' --- Original\n+++ New\n@@ -2,7 +2,7 @@\n\n class Foo\n {\n- public function bar($foo = 1, $bar)\n+ public function bar($foo, $bar)\n {\n }\n } DIFF; return <<<JSON { "about": "{$about}", "files": [ { "name": "someFile.php", "diff": "{$diff}" } ], "time": { "total": 0 }, "memory": 0 } JSON; } protected static function createWithAppliedFixersReport(): string { $about = Application::getAbout(); return <<<JSON { "about": "{$about}", "files": [ { "name": "someFile.php", "appliedFixers":["some_fixer_name_here_1", "some_fixer_name_here_2"] } ], "time": { "total": 0 }, "memory": 0 } JSON; } protected static function createWithTimeAndMemoryReport(): string { $about = Application::getAbout(); $diff = <<<'DIFF' --- Original\n+++ New\n@@ -2,7 +2,7 @@\n\n class Foo\n {\n- public function bar($foo = 1, $bar)\n+ public function bar($foo, $bar)\n {\n }\n } DIFF; return <<<JSON { "about": "{$about}", "files": [ { "diff": "{$diff}", "name": "someFile.php" } ], "memory": 2.5, "time": { "total": 1.234 } } JSON; } protected static function createComplexReport(): string { $about = Application::getAbout(); return <<<JSON { "about": "{$about}", "files": [ { "name": "someFile.php", "appliedFixers":["some_fixer_name_here_1", "some_fixer_name_here_2"], "diff": "this text is a diff ;)" }, { "name": "anotherFile.php", "appliedFixers":["another_fixer_name_here"], "diff": "another diff here ;)" } ], "memory": 2.5, "time": { "total": 1.234 } } JSON; } protected function createReporter(): ReporterInterface { return new JsonReporter(); } protected function getFormat(): string { return 'json'; } protected static function createNoErrorReport(): string { $about = Application::getAbout(); return <<<JSON { "about": "{$about}", "files": [ ], "time": { "total": 0 }, "memory": 0 } JSON; } protected function assertFormat(string $expected, string $input): void { self::assertJsonSchema(__DIR__.'/../../../../doc/schemas/fix/schema.json', $input); self::assertJsonStringEqualsJsonString($expected, $input); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/FixReport/GitlabReporterTest.php
tests/Console/Report/FixReport/GitlabReporterTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\FixReport; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Report\FixReport\GitlabReporter; use PhpCsFixer\Console\Report\FixReport\ReporterInterface; use PhpCsFixer\Tests\Test\Assert\AssertJsonSchemaTrait; /** * @author Hans-Christian Otto <c.otto@suora.com> * * @internal * * @covers \PhpCsFixer\Console\Report\FixReport\GitlabReporter * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class GitlabReporterTest extends AbstractReporterTestCase { use AssertJsonSchemaTrait; protected function createReporter(): ReporterInterface { return new GitlabReporter(); } protected function getFormat(): string { return 'gitlab'; } protected static function createNoErrorReport(): string { return '[]'; } protected static function createSimpleReport(): string { $about = Application::getAbout(); return <<<JSON [{ "categories": ["Style"], "check_name": "PHP-CS-Fixer.some_fixer_name_here", "description": "PHP-CS-Fixer.some_fixer_name_here (custom rule)", "content": { "body": "{$about}\\nCheck performed with a custom rule." }, "fingerprint": "ad098ea6ea7a28dd85dfcdfc9e2bded0", "severity": "minor", "location": { "path": "someFile.php", "lines": { "begin": 5, "end": 9 } } }] JSON; } protected static function createWithDiffReport(): string { return self::createSimpleReport(); } protected static function createWithAppliedFixersReport(): string { $about = Application::getAbout(); return <<<JSON [{ "categories": ["Style"], "check_name": "PHP-CS-Fixer.some_fixer_name_here_1", "description": "PHP-CS-Fixer.some_fixer_name_here_1 (custom rule)", "content": { "body": "{$about}\\nCheck performed with a custom rule." }, "fingerprint": "b74e9385c8ae5b1f575c9c8226c7deff", "severity": "minor", "location": { "path": "someFile.php", "lines": { "begin": 0, "end": 0 } } },{ "categories": ["Style"], "check_name": "PHP-CS-Fixer.some_fixer_name_here_2", "description": "PHP-CS-Fixer.some_fixer_name_here_2 (custom rule)", "content": { "body": "{$about}\\nCheck performed with a custom rule." }, "fingerprint": "acad4672140c737a83c18d1474d84074", "severity": "minor", "location": { "path": "someFile.php", "lines": { "begin": 0, "end": 0 } } }] JSON; } protected static function createWithTimeAndMemoryReport(): string { return self::createSimpleReport(); } protected static function createComplexReport(): string { $about = Application::getAbout(); return <<<JSON [{ "categories": ["Style"], "check_name": "PHP-CS-Fixer.some_fixer_name_here_1", "description": "PHP-CS-Fixer.some_fixer_name_here_1 (custom rule)", "content": { "body": "{$about}\\nCheck performed with a custom rule." }, "fingerprint": "b74e9385c8ae5b1f575c9c8226c7deff", "severity": "minor", "location": { "path": "someFile.php", "lines": { "begin": 0, "end": 0 } } },{ "categories": ["Style"], "check_name": "PHP-CS-Fixer.some_fixer_name_here_2", "description": "PHP-CS-Fixer.some_fixer_name_here_2 (custom rule)", "content": { "body": "{$about}\\nCheck performed with a custom rule." }, "fingerprint": "acad4672140c737a83c18d1474d84074", "severity": "minor", "location": { "path": "someFile.php", "lines": { "begin": 0, "end": 0 } } },{ "categories": ["Style"], "check_name": "PHP-CS-Fixer.another_fixer_name_here", "description": "PHP-CS-Fixer.another_fixer_name_here (custom rule)", "content": { "body": "{$about}\\nCheck performed with a custom rule." }, "fingerprint": "30e86e533dac0f1b93bbc3a55c6908f8", "severity": "minor", "location": { "path": "anotherFile.php", "lines": { "begin": 0, "end": 0 } } }] JSON; } protected function assertFormat(string $expected, string $input): void { self::assertJsonSchema(__DIR__.'/../../../../doc/schemas/fix/codeclimate.json', $input); self::assertJsonStringEqualsJsonString($expected, $input); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/FixReport/ReporterFactoryTest.php
tests/Console/Report/FixReport/ReporterFactoryTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\FixReport; use PhpCsFixer\Console\Report\FixReport\ReporterFactory; use PhpCsFixer\Console\Report\FixReport\ReporterInterface; use PhpCsFixer\Console\Report\FixReport\ReportSummary; use PhpCsFixer\Tests\TestCase; /** * @author Boris Gorbylev <ekho@ekho.name> * * @internal * * @covers \PhpCsFixer\Console\Report\FixReport\ReporterFactory * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ReporterFactoryTest extends TestCase { public function testInterfaceIsFluent(): void { $builder = new ReporterFactory(); $testInstance = $builder->registerBuiltInReporters(); self::assertSame($builder, $testInstance); $double = $this->createReporterDouble('r1'); $testInstance = $builder->registerReporter($double); self::assertSame($builder, $testInstance); } public function testRegisterBuiltInReports(): void { $builder = new ReporterFactory(); self::assertCount(0, $builder->getFormats()); $builder->registerBuiltInReporters(); self::assertSame( ['checkstyle', 'gitlab', 'json', 'junit', 'txt', 'xml'], $builder->getFormats(), ); } public function testThatCanRegisterAndGetReports(): void { $builder = new ReporterFactory(); $r1 = $this->createReporterDouble('r1'); $r2 = $this->createReporterDouble('r2'); $r3 = $this->createReporterDouble('r3'); $builder->registerReporter($r1); $builder->registerReporter($r2); $builder->registerReporter($r3); self::assertSame($r1, $builder->getReporter('r1')); self::assertSame($r2, $builder->getReporter('r2')); self::assertSame($r3, $builder->getReporter('r3')); } public function testGetFormats(): void { $builder = new ReporterFactory(); $r1 = $this->createReporterDouble('r1'); $r2 = $this->createReporterDouble('r2'); $r3 = $this->createReporterDouble('r3'); $builder->registerReporter($r1); $builder->registerReporter($r2); $builder->registerReporter($r3); self::assertSame(['r1', 'r2', 'r3'], $builder->getFormats()); } public function testRegisterReportWithOccupiedFormat(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('Reporter for format "non_unique_name" is already registered.'); $factory = new ReporterFactory(); $r1 = $this->createReporterDouble('non_unique_name'); $r2 = $this->createReporterDouble('non_unique_name'); $factory->registerReporter($r1); $factory->registerReporter($r2); } public function testGetNonRegisteredReport(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessage('Reporter for format "non_registered_format" is not registered.'); $builder = new ReporterFactory(); $builder->getReporter('non_registered_format'); } private function createReporterDouble(string $format): ReporterInterface { return new class($format) implements ReporterInterface { private string $format; public function __construct(string $format) { $this->format = $format; } public function getFormat(): string { return $this->format; } public function generate(ReportSummary $reportSummary): string { throw new \LogicException('Not implemented.'); } }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/FixReport/CheckstyleReporterTest.php
tests/Console/Report/FixReport/CheckstyleReporterTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\FixReport; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Report\FixReport\CheckstyleReporter; use PhpCsFixer\Console\Report\FixReport\ReporterInterface; use PhpCsFixer\PhpunitConstraintXmlMatchesXsd\Constraint\XmlMatchesXsd; use Symfony\Component\Console\Formatter\OutputFormatter; /** * @author Kévin Gomez <contact@kevingomez.fr> * * @internal * * @covers \PhpCsFixer\Console\Report\FixReport\CheckstyleReporter * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CheckstyleReporterTest extends AbstractReporterTestCase { /** * "checkstyle" XML schema. */ private static ?string $xsd = null; public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); $content = file_get_contents(__DIR__.'/../../../../doc/schemas/fix/checkstyle.xsd'); if (false === $content) { throw new \RuntimeException('Cannot read file.'); } self::$xsd = $content; } public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); self::$xsd = null; } protected static function createNoErrorReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <checkstyle version="{$about}" /> XML; } protected static function createSimpleReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <checkstyle version="{$about}"> <file name="someFile.php"> <error severity="warning" source="PHP-CS-Fixer.some_fixer_name_here" message="Found violation(s) of type: some_fixer_name_here" /> </file> </checkstyle> XML; } protected static function createWithDiffReport(): string { $about = Application::getAbout(); // NOTE: checkstyle format does NOT include diffs return <<<XML <?xml version="1.0" encoding="UTF-8"?> <checkstyle version="{$about}"> <file name="someFile.php"> <error severity="warning" source="PHP-CS-Fixer.some_fixer_name_here" message="Found violation(s) of type: some_fixer_name_here" /> </file> </checkstyle> XML; } protected static function createWithAppliedFixersReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <checkstyle version="{$about}"> <file name="someFile.php"> <error severity="warning" source="PHP-CS-Fixer.some_fixer_name_here_1" message="Found violation(s) of type: some_fixer_name_here_1" /> <error severity="warning" source="PHP-CS-Fixer.some_fixer_name_here_2" message="Found violation(s) of type: some_fixer_name_here_2" /> </file> </checkstyle> XML; } protected static function createWithTimeAndMemoryReport(): string { $about = Application::getAbout(); // NOTE: checkstyle format does NOT include time or memory return <<<XML <?xml version="1.0" encoding="UTF-8"?> <checkstyle version="{$about}"> <file name="someFile.php"> <error severity="warning" source="PHP-CS-Fixer.some_fixer_name_here" message="Found violation(s) of type: some_fixer_name_here" /> </file> </checkstyle> XML; } protected static function createComplexReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <checkstyle version="{$about}"> <file name="someFile.php"> <error severity="warning" source="PHP-CS-Fixer.some_fixer_name_here_1" message="Found violation(s) of type: some_fixer_name_here_1" /> <error severity="warning" source="PHP-CS-Fixer.some_fixer_name_here_2" message="Found violation(s) of type: some_fixer_name_here_2" /> </file> <file name="anotherFile.php"> <error severity="warning" source="PHP-CS-Fixer.another_fixer_name_here" message="Found violation(s) of type: another_fixer_name_here" /> </file> </checkstyle> XML; } protected function createReporter(): ReporterInterface { return new CheckstyleReporter(); } protected function getFormat(): string { return 'checkstyle'; } protected function assertFormat(string $expected, string $input): void { $formatter = new OutputFormatter(); $input = $formatter->format($input); self::assertThat($input, new XmlMatchesXsd(self::$xsd)); self::assertXmlStringEqualsXmlString($expected, $input); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/FixReport/AbstractReporterTestCase.php
tests/Console/Report/FixReport/AbstractReporterTestCase.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\FixReport; use PhpCsFixer\Console\Report\FixReport\ReporterInterface; use PhpCsFixer\Console\Report\FixReport\ReportSummary; use PhpCsFixer\Tests\TestCase; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractReporterTestCase extends TestCase { protected ?ReporterInterface $reporter = null; protected function setUp(): void { parent::setUp(); $this->reporter = $this->createReporter(); } protected function tearDown(): void { parent::tearDown(); $this->reporter = null; } final public function testGetFormat(): void { self::assertSame( $this->getFormat(), $this->reporter->getFormat(), ); } /** * @dataProvider provideGenerateCases */ final public function testGenerate(string $expectedReport, ReportSummary $reportSummary): void { $actualReport = $this->reporter->generate($reportSummary); $this->assertFormat($expectedReport, $actualReport); } /** * @return iterable<string, array{string, ReportSummary}> */ final public static function provideGenerateCases(): iterable { yield 'no errors' => [ static::createNoErrorReport(), new ReportSummary( [], 10, 0, 0, false, false, false, ), ]; yield 'simple' => [ static::createSimpleReport(), new ReportSummary( [ 'someFile.php' => [ 'appliedFixers' => ['some_fixer_name_here'], 'diff' => '--- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar($foo = 1, $bar) + public function bar($foo, $bar) { } }', ], ], 10, 0, 0, false, false, false, ), ]; yield 'with diff' => [ static::createWithDiffReport(), new ReportSummary( [ 'someFile.php' => [ 'appliedFixers' => ['some_fixer_name_here'], 'diff' => '--- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar($foo = 1, $bar) + public function bar($foo, $bar) { } }', ], ], 10, 0, 0, false, false, false, ), ]; yield 'with applied fixers' => [ static::createWithAppliedFixersReport(), new ReportSummary( [ 'someFile.php' => [ 'appliedFixers' => ['some_fixer_name_here_1', 'some_fixer_name_here_2'], 'diff' => '', ], ], 10, 0, 0, true, false, false, ), ]; yield 'with time and memory' => [ static::createWithTimeAndMemoryReport(), new ReportSummary( [ 'someFile.php' => [ 'appliedFixers' => ['some_fixer_name_here'], 'diff' => '--- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar($foo = 1, $bar) + public function bar($foo, $bar) { } }', ], ], 10, 1_234, 2_621_440, // 2.5 * 1024 * 1024 false, false, false, ), ]; yield 'complex' => [ static::createComplexReport(), new ReportSummary( [ 'someFile.php' => [ 'appliedFixers' => ['some_fixer_name_here_1', 'some_fixer_name_here_2'], 'diff' => 'this text is a diff ;)', ], 'anotherFile.php' => [ 'appliedFixers' => ['another_fixer_name_here'], 'diff' => 'another diff here ;)', ], ], 10, 1_234, 2_621_440, // 2.5 * 1024 * 1024 true, true, true, ), ]; } abstract protected function createReporter(): ReporterInterface; abstract protected function getFormat(): string; abstract protected static function createNoErrorReport(): string; abstract protected static function createSimpleReport(): string; abstract protected static function createWithDiffReport(): string; abstract protected static function createWithAppliedFixersReport(): string; abstract protected static function createWithTimeAndMemoryReport(): string; abstract protected static function createComplexReport(): string; abstract protected function assertFormat(string $expected, string $input): void; }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/FixReport/XmlReporterTest.php
tests/Console/Report/FixReport/XmlReporterTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\FixReport; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Report\FixReport\ReporterInterface; use PhpCsFixer\Console\Report\FixReport\XmlReporter; use PhpCsFixer\PhpunitConstraintXmlMatchesXsd\Constraint\XmlMatchesXsd; use Symfony\Component\Console\Formatter\OutputFormatter; /** * @author Boris Gorbylev <ekho@ekho.name> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Console\Report\FixReport\XmlReporter * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class XmlReporterTest extends AbstractReporterTestCase { private static ?string $xsd = null; public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); $content = file_get_contents(__DIR__.'/../../../../doc/schemas/fix/xml.xsd'); if (false === $content) { throw new \RuntimeException('Cannot read file.'); } self::$xsd = $content; } public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); self::$xsd = null; } protected static function createNoErrorReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <report> <about value="{$about}"/> <files /> </report> XML; } protected static function createSimpleReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <report> <about value="{$about}"/> <files> <file id="1" name="someFile.php"> <diff>--- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar(\$foo = 1, \$bar) + public function bar(\$foo, \$bar) { } }</diff> </file> </files> </report> XML; } protected static function createWithDiffReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <report> <about value="{$about}"/> <files> <file id="1" name="someFile.php"> <diff>--- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar(\$foo = 1, \$bar) + public function bar(\$foo, \$bar) { } }</diff> </file> </files> </report> XML; } protected static function createWithAppliedFixersReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <report> <about value="{$about}"/> <files> <file id="1" name="someFile.php"> <applied_fixers> <applied_fixer name="some_fixer_name_here_1"/> <applied_fixer name="some_fixer_name_here_2"/> </applied_fixers> </file> </files> </report> XML; } protected static function createWithTimeAndMemoryReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <report> <about value="{$about}"/> <files> <file id="1" name="someFile.php"> <diff>--- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar(\$foo = 1, \$bar) + public function bar(\$foo, \$bar) { } }</diff> </file> </files> <time unit="s"> <total value="1.234"/> </time> <memory value="2.5" unit="MB"/> </report> XML; } protected static function createComplexReport(): string { $about = Application::getAbout(); return <<<XML <?xml version="1.0" encoding="UTF-8"?> <report> <about value="{$about}"/> <files> <file id="1" name="someFile.php"> <applied_fixers> <applied_fixer name="some_fixer_name_here_1"/> <applied_fixer name="some_fixer_name_here_2"/> </applied_fixers> <diff>this text is a diff ;)</diff> </file> <file id="2" name="anotherFile.php"> <applied_fixers> <applied_fixer name="another_fixer_name_here"/> </applied_fixers> <diff>another diff here ;)</diff> </file> </files> <time unit="s"> <total value="1.234"/> </time> <memory value="2.5" unit="MB"/> </report> XML; } protected function createReporter(): ReporterInterface { return new XmlReporter(); } protected function getFormat(): string { return 'xml'; } protected function assertFormat(string $expected, string $input): void { $formatter = new OutputFormatter(); $input = $formatter->format($input); self::assertThat($input, new XmlMatchesXsd(self::$xsd)); self::assertXmlStringEqualsXmlString($expected, $input); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Report/FixReport/TextReporterTest.php
tests/Console/Report/FixReport/TextReporterTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Report\FixReport; use PhpCsFixer\Console\Report\FixReport\ReporterInterface; use PhpCsFixer\Console\Report\FixReport\TextReporter; /** * @author Boris Gorbylev <ekho@ekho.name> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Console\Report\FixReport\TextReporter * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TextReporterTest extends AbstractReporterTestCase { protected static function createNoErrorReport(): string { return <<<'TEXT' TEXT; } protected static function createSimpleReport(): string { return str_replace( "\n", \PHP_EOL, <<<'TEXT' 1) someFile.php ---------- begin diff ---------- --- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar($foo = 1, $bar) + public function bar($foo, $bar) { } } ----------- end diff ----------- TEXT, ); } protected static function createWithDiffReport(): string { return str_replace( "\n", \PHP_EOL, <<<'TEXT' 1) someFile.php ---------- begin diff ---------- --- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar($foo = 1, $bar) + public function bar($foo, $bar) { } } ----------- end diff ----------- TEXT, ); } protected static function createWithAppliedFixersReport(): string { return str_replace( "\n", \PHP_EOL, <<<'TEXT' 1) someFile.php (some_fixer_name_here_1, some_fixer_name_here_2) TEXT, ); } protected static function createWithTimeAndMemoryReport(): string { return str_replace( "\n", \PHP_EOL, <<<'TEXT' 1) someFile.php ---------- begin diff ---------- --- Original +++ New @@ -2,7 +2,7 @@ class Foo { - public function bar($foo = 1, $bar) + public function bar($foo, $bar) { } } ----------- end diff ----------- Fixed 1 of 10 files in 1.234 seconds, 2.50 MB memory used TEXT, ); } protected static function createComplexReport(): string { return str_replace( "\n", \PHP_EOL, <<<'TEXT' 1) someFile.php (<comment>some_fixer_name_here_1, some_fixer_name_here_2</comment>) <comment> ---------- begin diff ----------</comment> this text is a diff ;) <comment> ----------- end diff -----------</comment> 2) anotherFile.php (<comment>another_fixer_name_here</comment>) <comment> ---------- begin diff ----------</comment> another diff here ;) <comment> ----------- end diff -----------</comment> Found 2 of 10 files that can be fixed in 1.234 seconds, 2.50 MB memory used TEXT, ); } protected function createReporter(): ReporterInterface { return new TextReporter(); } protected function getFormat(): string { return 'txt'; } protected function assertFormat(string $expected, string $input): void { self::assertSame($expected, $input); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Command/CheckCommandTest.php
tests/Console/Command/CheckCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Command; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Command\CheckCommand; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\ToolInfo; use Symfony\Component\Console\Exception\InvalidOptionException; use Symfony\Component\Console\Tester\CommandTester; /** * @internal * * @covers \PhpCsFixer\Console\Command\CheckCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CheckCommandTest extends TestCase { /** * This test ensures that `--dry-run` option is not available in `check` command, * because this command is a proxy for `fix` command which always set `--dry-run` during proxying, * so it does not make sense to provide this option again. */ public function testDryRunModeIsUnavailable(): void { $application = new Application(); $application->add(new CheckCommand(new ToolInfo())); $command = $application->find('check'); $commandTester = new CommandTester($command); $this->expectException(InvalidOptionException::class); $this->expectExceptionMessageMatches('/--dry-run/'); $commandTester->execute( [ 'command' => $command->getName(), '--dry-run' => true, ], ); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Command/SelfUpdateCommandTest.php
tests/Console/Command/SelfUpdateCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Command; use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStreamDirectory; use org\bovigo\vfs\vfsStreamException; use org\bovigo\vfs\vfsStreamWrapper; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Command\SelfUpdateCommand; use PhpCsFixer\Console\SelfUpdate\GithubClientInterface; use PhpCsFixer\Console\SelfUpdate\NewVersionChecker; use PhpCsFixer\Console\SelfUpdate\NewVersionCheckerInterface; use PhpCsFixer\PharCheckerInterface; use PhpCsFixer\Preg; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\ToolInfoInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Tester\CommandTester; /** * @internal * * @covers \PhpCsFixer\Console\Command\SelfUpdateCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SelfUpdateCommandTest extends TestCase { private ?vfsStreamDirectory $root = null; protected function setUp(): void { parent::setUp(); $this->root = vfsStream::setup(); file_put_contents($this->getToolPath(), 'Current PHP CS Fixer.'); file_put_contents($this->root->url().'/'.self::getNewMinorReleaseVersion().'.phar', 'New minor version of PHP CS Fixer.'); file_put_contents($this->root->url().'/'.self::getNewMajorReleaseVersion().'.phar', 'New major version of PHP CS Fixer.'); } protected function tearDown(): void { parent::tearDown(); $this->root = null; try { vfsStreamWrapper::unregister(); } catch (vfsStreamException $exception) { // ignored } } /** * @dataProvider provideCommandNameCases */ public function testCommandName(string $name): void { $command = new SelfUpdateCommand( $this->createNewVersionCheckerDouble(), $this->createToolInfoDouble(), $this->createPharCheckerDouble(), ); $application = new Application(); $application->add($command); self::assertSame($command, $application->find($name)); } /** * @return iterable<int, array{string}> */ public static function provideCommandNameCases(): iterable { yield ['self-update']; yield ['selfupdate']; } /** * @param array<string, bool|string> $input * * @dataProvider provideExecuteCases */ public function testExecute( string $latestVersion, ?string $latestMinorVersion, array $input, bool $decorated, string $expectedFileContents, string $expectedDisplay ): void { $versionChecker = $this->createNewVersionCheckerDouble($latestVersion, $latestMinorVersion); $command = new SelfUpdateCommand( $versionChecker, $this->createToolInfoDouble(), $this->createPharCheckerDouble(), ); $commandTester = $this->execute($command, $input, $decorated); self::assertSame($expectedFileContents, file_get_contents($this->getToolPath())); self::assertDisplay($expectedDisplay, $commandTester); self::assertSame(0, $commandTester->getStatusCode()); } /** * @return iterable<int, array{string, null|string, array<string, bool|string>, bool, string, string}> */ public static function provideExecuteCases(): iterable { $currentVersion = Application::VERSION; $minorRelease = self::getNewMinorReleaseVersion(); $majorRelease = self::getNewMajorReleaseVersion(); $major = self::getNewMajorVersion(); $currentContents = 'Current PHP CS Fixer.'; $minorContents = 'New minor version of PHP CS Fixer.'; $majorContents = 'New major version of PHP CS Fixer.'; $upToDateDisplay = "\033[32mPHP CS Fixer is already up-to-date.\033[39m\n"; $newMinorDisplay = "\033[32mPHP CS Fixer updated\033[39m (\033[33m{$currentVersion}\033[39m -> \033[33m{$minorRelease}\033[39m)\n"; $newMajorDisplay = "\033[32mPHP CS Fixer updated\033[39m (\033[33m{$currentVersion}\033[39m -> \033[33m{$majorRelease}\033[39m)\n"; $majorInfoNoMinorDisplay = <<<OUTPUT \033[32mA new major version of PHP CS Fixer is available\033[39m (\033[33m{$majorRelease}\033[39m) \033[32mBefore upgrading please read\033[39m https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/{$majorRelease}/UPGRADE-v{$major}.md \033[32mIf you are ready to upgrade run this command with\033[39m \033[33m-f\033[39m \033[32mChecking for new minor/patch version...\033[39m \033[32mNo minor update for PHP CS Fixer.\033[39m OUTPUT; $majorInfoNewMinorDisplay = <<<OUTPUT \033[32mA new major version of PHP CS Fixer is available\033[39m (\033[33m{$majorRelease}\033[39m) \033[32mBefore upgrading please read\033[39m https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/{$majorRelease}/UPGRADE-v{$major}.md \033[32mIf you are ready to upgrade run this command with\033[39m \033[33m-f\033[39m \033[32mChecking for new minor/patch version...\033[39m \033[32mPHP CS Fixer updated\033[39m (\033[33m{$currentVersion}\033[39m -> \033[33m{$minorRelease}\033[39m) OUTPUT; // no new version available yield [Application::VERSION, Application::VERSION, [], true, $currentContents, $upToDateDisplay]; yield [Application::VERSION, Application::VERSION, [], false, $currentContents, $upToDateDisplay]; yield [Application::VERSION, Application::VERSION, ['--force' => true], true, $currentContents, $upToDateDisplay]; yield [Application::VERSION, Application::VERSION, ['-f' => true], false, $currentContents, $upToDateDisplay]; // new minor version available yield [$minorRelease, $minorRelease, [], true, $minorContents, $newMinorDisplay]; yield [$minorRelease, $minorRelease, ['--force' => true], true, $minorContents, $newMinorDisplay]; yield [$minorRelease, $minorRelease, ['-f' => true], true, $minorContents, $newMinorDisplay]; yield [$minorRelease, $minorRelease, [], false, $minorContents, $newMinorDisplay]; yield [$minorRelease, $minorRelease, ['--force' => true], false, $minorContents, $newMinorDisplay]; yield [$minorRelease, $minorRelease, ['-f' => true], false, $minorContents, $newMinorDisplay]; // new major version available yield [$majorRelease, Application::VERSION, [], true, $currentContents, $majorInfoNoMinorDisplay]; yield [$majorRelease, Application::VERSION, [], false, $currentContents, $majorInfoNoMinorDisplay]; yield [$majorRelease, Application::VERSION, ['--force' => true], true, $majorContents, $newMajorDisplay]; yield [$majorRelease, Application::VERSION, ['-f' => true], false, $majorContents, $newMajorDisplay]; // new minor version and new major version available yield [$majorRelease, $minorRelease, [], true, $minorContents, $majorInfoNewMinorDisplay]; yield [$majorRelease, $minorRelease, [], false, $minorContents, $majorInfoNewMinorDisplay]; yield [$majorRelease, $minorRelease, ['--force' => true], true, $majorContents, $newMajorDisplay]; yield [$majorRelease, $minorRelease, ['-f' => true], false, $majorContents, $newMajorDisplay]; // weird/unexpected versions yield ['v0.1.0', 'v0.1.0', [], true, $currentContents, $upToDateDisplay]; yield ['v0.1.0', 'v0.1.0', [], false, $currentContents, $upToDateDisplay]; yield ['v0.1.0', 'v0.1.0', ['--force' => true], true, $currentContents, $upToDateDisplay]; yield ['v0.1.0', 'v0.1.0', ['-f' => true], false, $currentContents, $upToDateDisplay]; yield ['v0.1.0', null, [], true, $currentContents, $upToDateDisplay]; yield ['v0.1.0', null, [], false, $currentContents, $upToDateDisplay]; yield ['v0.1.0', null, ['--force' => true], true, $currentContents, $upToDateDisplay]; yield ['v0.1.0', null, ['-f' => true], false, $currentContents, $upToDateDisplay]; yield ['v0.1.0', Application::VERSION, [], true, $currentContents, $upToDateDisplay]; yield ['v0.1.0', Application::VERSION, [], false, $currentContents, $upToDateDisplay]; yield ['v0.1.0', Application::VERSION, ['--force' => true], true, $currentContents, $upToDateDisplay]; yield ['v0.1.0', Application::VERSION, ['-f' => true], false, $currentContents, $upToDateDisplay]; yield [Application::VERSION, 'v0.1.0', [], true, $currentContents, $upToDateDisplay]; yield [Application::VERSION, 'v0.1.0', [], false, $currentContents, $upToDateDisplay]; yield [Application::VERSION, 'v0.1.0', ['--force' => true], true, $currentContents, $upToDateDisplay]; yield [Application::VERSION, 'v0.1.0', ['-f' => true], false, $currentContents, $upToDateDisplay]; } /** * @param array<string, bool|string> $input * * @dataProvider provideExecuteWhenNotAbleToGetLatestVersionsCases */ public function testExecuteWhenNotAbleToGetLatestVersions( bool $latestMajorVersionSuccess, bool $latestMinorVersionSuccess, array $input, bool $decorated ): void { $versionChecker = $this->createNewVersionCheckerDouble( self::getNewMajorReleaseVersion(), self::getNewMinorReleaseVersion(), $latestMajorVersionSuccess, $latestMinorVersionSuccess, ); $command = new SelfUpdateCommand( $versionChecker, $this->createToolInfoDouble(), $this->createPharCheckerDouble(), ); $commandTester = $this->execute($command, $input, $decorated); self::assertDisplay( "\033[37;41mUnable to determine newest version: Foo.\033[39;49m\n", $commandTester, ); self::assertSame(1, $commandTester->getStatusCode()); } /** * @return iterable<int, array{bool, bool, array<string, bool|string>, bool}> */ public static function provideExecuteWhenNotAbleToGetLatestVersionsCases(): iterable { yield [false, false, [], true]; yield [false, false, ['--force' => true], true]; yield [false, false, ['-f' => true], true]; yield [false, false, [], false]; yield [false, false, ['--force' => true], false]; yield [false, false, ['-f' => true], false]; yield [true, false, [], true]; yield [true, false, ['--force' => true], true]; yield [true, false, ['-f' => true], true]; yield [true, false, [], false]; yield [true, false, ['--force' => true], false]; yield [true, false, ['-f' => true], false]; yield [false, true, [], true]; yield [false, true, ['--force' => true], true]; yield [false, true, ['-f' => true], true]; yield [false, true, [], false]; yield [false, true, ['--force' => true], false]; yield [false, true, ['-f' => true], false]; } /** * @param array<string, bool|string> $input * * @dataProvider provideExecuteWhenNotInstalledAsPharCases */ public function testExecuteWhenNotInstalledAsPhar(array $input, bool $decorated): void { $command = new SelfUpdateCommand( $this->createNewVersionCheckerDouble(), $this->createToolInfoDouble(false), $this->createPharCheckerDouble(), ); $commandTester = $this->execute($command, $input, $decorated); self::assertDisplay( "\033[37;41mSelf-update is available only for PHAR version.\033[39;49m\n", $commandTester, ); self::assertSame(1, $commandTester->getStatusCode()); } /** * @return iterable<int, array{array<string, bool|string>, bool}> */ public static function provideExecuteWhenNotInstalledAsPharCases(): iterable { yield [[], true]; yield [['--force' => true], true]; yield [['-f' => true], true]; yield [[], false]; yield [['--force' => true], false]; yield [['-f' => true], false]; } /** * @param array<string, bool|string> $input */ private function execute(Command $command, array $input, bool $decorated): CommandTester { $application = new Application(); $application->add($command); $input = ['command' => $command->getName()] + $input; $commandTester = new CommandTester($command); \assert(\array_key_exists('argv', $_SERVER)); $realPath = $_SERVER['argv'][0]; $_SERVER['argv'][0] = $this->getToolPath(); $commandTester->execute($input, ['decorated' => $decorated]); $_SERVER['argv'][0] = $realPath; return $commandTester; } private static function assertDisplay(string $expectedDisplay, CommandTester $commandTester): void { if (!$commandTester->getOutput()->isDecorated()) { $expectedDisplay = Preg::replace("/\033\\[(\\d+;)*\\d+m/", '', $expectedDisplay); } self::assertSame( $expectedDisplay, $commandTester->getDisplay(true), ); } private function createToolInfoDouble(bool $isInstalledAsPhar = true): ToolInfoInterface { return new class($this->root, $isInstalledAsPhar) implements ToolInfoInterface { private vfsStreamDirectory $directory; private bool $isInstalledAsPhar; public function __construct(vfsStreamDirectory $directory, bool $isInstalledAsPhar) { $this->directory = $directory; $this->isInstalledAsPhar = $isInstalledAsPhar; } public function getComposerInstallationDetails(): array { throw new \LogicException('Not implemented.'); } public function getComposerVersion(): string { throw new \LogicException('Not implemented.'); } public function getVersion(): string { throw new \LogicException('Not implemented.'); } public function isInstalledAsPhar(): bool { return $this->isInstalledAsPhar; } public function isInstalledByComposer(): bool { throw new \LogicException('Not implemented.'); } public function isRunInsideDocker(): bool { return false; } public function getPharDownloadUri(string $version): string { return \sprintf('%s/%s.phar', $this->directory->url(), $version); } }; } private function getToolPath(): string { return "{$this->root->url()}/php-cs-fixer"; } private static function getCurrentMajorVersion(): int { return (int) Preg::replace('/^v?(\d+).*$/', '$1', Application::VERSION); } private static function getNewMinorReleaseVersion(): string { return self::getCurrentMajorVersion().'.999.0'; } private static function getNewMajorVersion(): int { return self::getCurrentMajorVersion() + 1; } private static function getNewMajorReleaseVersion(): string { return self::getNewMajorVersion().'.0.0'; } private function createNewVersionCheckerDouble( string $latestVersion = Application::VERSION, ?string $latestMinorVersion = Application::VERSION, bool $latestMajorVersionSuccess = true, bool $latestMinorVersionSuccess = true ): NewVersionCheckerInterface { return new class($latestVersion, $latestMinorVersion, $latestMajorVersionSuccess, $latestMinorVersionSuccess) implements NewVersionCheckerInterface { private string $latestVersion; private ?string $latestMinorVersion; private bool $latestMajorVersionSuccess; private bool $latestMinorVersionSuccess; public function __construct( string $latestVersion, ?string $latestMinorVersion, bool $latestMajorVersionSuccess = true, bool $latestMinorVersionSuccess = true ) { $this->latestVersion = $latestVersion; $this->latestMinorVersion = $latestMinorVersion; $this->latestMajorVersionSuccess = $latestMajorVersionSuccess; $this->latestMinorVersionSuccess = $latestMinorVersionSuccess; } public function getLatestVersion(): string { if ($this->latestMajorVersionSuccess) { return $this->latestVersion; } throw new \RuntimeException('Foo.'); } public function getLatestVersionOfMajor(int $majorVersion): ?string { TestCase::assertSame((int) Preg::replace('/^v?(\d+).*$/', '$1', Application::VERSION), $majorVersion); if ($this->latestMinorVersionSuccess) { return $this->latestMinorVersion; } throw new \RuntimeException('Foo.'); } public function compareVersions(string $versionA, string $versionB): int { return (new NewVersionChecker( new class implements GithubClientInterface { public function getTags(): array { throw new \LogicException('Not implemented.'); } }, ))->compareVersions($versionA, $versionB); } }; } private function createPharCheckerDouble(): PharCheckerInterface { return new class implements PharCheckerInterface { public function checkFileValidity(string $filename): ?string { return null; } }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Command/WorkerCommandTest.php
tests/Console/Command/WorkerCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Command; use Clue\React\NDJson\Decoder; use Clue\React\NDJson\Encoder; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Command\FixCommand; use PhpCsFixer\Console\Command\WorkerCommand; use PhpCsFixer\Runner\Event\FileProcessed; use PhpCsFixer\Runner\Parallel\ParallelAction; use PhpCsFixer\Runner\Parallel\ParallelConfigFactory; use PhpCsFixer\Runner\Parallel\ParallelisationException; use PhpCsFixer\Runner\Parallel\ProcessFactory; use PhpCsFixer\Runner\Parallel\ProcessIdentifier; use PhpCsFixer\Runner\RunnerConfig; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\ToolInfo; use React\ChildProcess\Process; use React\EventLoop\StreamSelectLoop; use React\Socket\ConnectionInterface; use React\Socket\TcpServer; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tester\CommandTester; /** * @author Greg Korba <greg@codito.dev> * * @internal * * @covers \PhpCsFixer\Console\Command\WorkerCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class WorkerCommandTest extends TestCase { public function testMissingIdentifierCausesFailure(): void { self::expectException(ParallelisationException::class); self::expectExceptionMessage('Missing parallelisation options'); $this->doTestExecute(['--port' => 12_345]); } public function testMissingPortCausesFailure(): void { self::expectException(ParallelisationException::class); self::expectExceptionMessage('Missing parallelisation options'); $this->doTestExecute(['--identifier' => ProcessIdentifier::create()->toString()]); } public function testWorkerCantConnectToServerWhenExecutedDirectly(): void { $commandTester = $this->doTestExecute([ '--identifier' => ProcessIdentifier::create()->toString(), '--port' => 12_345, ]); self::assertStringContainsString( 'Connection refused', $commandTester->getErrorOutput(), ); } /** * This test is not executed on Windows because process pipes are not supported there, due to their blocking nature * on this particular OS. The cause of this lays in `react/child-process` component, but it's related only to tests, * as parallel runner works properly on Windows too. Feel free to fiddle with it and add testing support for Windows. * * @requires OS Linux|Darwin */ public function testWorkerCommunicatesWithTheServer(): void { $streamSelectLoop = new StreamSelectLoop(); $server = new TcpServer('127.0.0.1:0', $streamSelectLoop); $serverPort = parse_url($server->getAddress() ?? '', \PHP_URL_PORT); $processIdentifier = ProcessIdentifier::create(); $processFactory = new ProcessFactory(); $process = new Process(implode(' ', $processFactory->getCommandArgs( $serverPort, // @phpstan-ignore-line $processIdentifier, new ArrayInput( [ '--config' => __DIR__.'/../../Fixtures/.php-cs-fixer.parallel.php', ], (new FixCommand(new ToolInfo()))->getDefinition(), ), new RunnerConfig(true, false, ParallelConfigFactory::sequential()), ))); /** * @var array{ * identifier: string, * messages: list<array<string, mixed>>, * connected: bool, * chunkRequested: bool, * resultReported: bool * } $workerScope */ $workerScope = [ 'identifier' => $processIdentifier->toString(), 'messages' => [], 'connected' => false, 'chunkRequested' => false, 'resultReported' => false, ]; $server->on( 'connection', static function (ConnectionInterface $connection) use (&$workerScope): void { $decoder = new Decoder($connection, true, 512, \JSON_INVALID_UTF8_IGNORE); $encoder = new Encoder($connection, \JSON_INVALID_UTF8_IGNORE); $decoder->on( 'data', static function (array $data) use ($encoder, &$workerScope): void { $workerScope['messages'][] = $data; $ds = \DIRECTORY_SEPARATOR; \assert(\array_key_exists('action', $data)); if (ParallelAction::WORKER_HELLO === $data['action']) { $encoder->write(['action' => ParallelAction::RUNNER_REQUEST_ANALYSIS, 'files' => [ realpath(__DIR__.$ds.'..'.$ds.'..').$ds.'Fixtures'.$ds.'FixerTest'.$ds.'fix'.$ds.'somefile.php', ]]); return; } if (3 === \count($workerScope['messages'])) { $encoder->write(['action' => ParallelAction::RUNNER_THANK_YOU]); } }, ); }, ); $process->on('exit', static function () use ($streamSelectLoop): void { $streamSelectLoop->stop(); }); // Start worker in the async process, handle communication with server and wait for it to exit $process->start($streamSelectLoop); $streamSelectLoop->run(); self::assertSame(Command::SUCCESS, $process->getExitCode()); self::assertCount(3, $workerScope['messages']); self::assertArrayHasKey('action', $workerScope['messages'][0]); self::assertSame(ParallelAction::WORKER_HELLO, $workerScope['messages'][0]['action']); self::assertArrayHasKey('action', $workerScope['messages'][1]); self::assertSame(ParallelAction::WORKER_RESULT, $workerScope['messages'][1]['action']); self::assertArrayHasKey('status', $workerScope['messages'][1]); self::assertSame(FileProcessed::STATUS_FIXED, $workerScope['messages'][1]['status']); self::assertArrayHasKey('action', $workerScope['messages'][2]); self::assertSame(ParallelAction::WORKER_GET_FILE_CHUNK, $workerScope['messages'][2]['action']); $server->close(); } /** * @param array<string, mixed> $arguments */ private function doTestExecute(array $arguments): CommandTester { $application = new Application(); $application->add(new WorkerCommand(new ToolInfo())); $command = $application->find('worker'); $commandTester = new CommandTester($command); $commandTester->execute( array_merge( [ 'command' => $command->getName(), '--config' => __DIR__.'/../../Fixtures/.php-cs-fixer.parallel.php', ], $arguments, ), [ 'capture_stderr_separately' => true, 'interactive' => false, 'decorated' => false, 'verbosity' => OutputInterface::VERBOSITY_DEBUG, ], ); return $commandTester; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Command/ListSetsCommandTest.php
tests/Console/Command/ListSetsCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Command; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Command\ListSetsCommand; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Console\Tester\CommandTester; /** * @internal * * @covers \PhpCsFixer\Console\Command\ListSetsCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ListSetsCommandTest extends TestCase { public function testListWithTxtFormat(): void { $commandTester = $this->doTestExecute([ '--format' => 'txt', ]); $resultRaw = $commandTester->getDisplay(); $expectedResultStart = ' 1) @DoctrineAnnotation'.\PHP_EOL.' Rules covering ``Doctrine`` annotations'; self::assertStringStartsWith($expectedResultStart, $resultRaw); self::assertSame(0, $commandTester->getStatusCode()); } public function testListWithJsonFormat(): void { $commandTester = $this->doTestExecute([ '--format' => 'json', ]); $resultRaw = $commandTester->getDisplay(); self::assertJson($resultRaw); self::assertSame(0, $commandTester->getStatusCode()); } /** * @param array<string, bool|string> $arguments */ private function doTestExecute(array $arguments): CommandTester { $application = new Application(); $application->add(new ListSetsCommand()); $command = $application->find('list-sets'); $commandTester = new CommandTester($command); $commandTester->execute($arguments); return $commandTester; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Command/DescribeCommandTest.php
tests/Console/Command/DescribeCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Command; use PhpCsFixer\AbstractFixer; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Command\DescribeCommand; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\Fixer\FixerInterface; use PhpCsFixer\Fixer\Operator\BinaryOperatorSpacesFixer; use PhpCsFixer\FixerConfiguration\AliasedFixerOptionBuilder; use PhpCsFixer\FixerConfiguration\AllowedValueSubset; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\CodeSampleInterface; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\FixerDefinition\VersionSpecification; use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; use PhpCsFixer\FixerFactory; use PhpCsFixer\Tests\Fixtures\DescribeCommand\DescribeFixtureFixer; use PhpCsFixer\Tests\Fixtures\ExternalRuleSet\ExampleRuleSet; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tester\CommandTester; /** * @internal * * @group legacy * * @covers \PhpCsFixer\Console\Command\DescribeCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DescribeCommandTest extends TestCase { /** * @dataProvider provideExecuteOutputCases */ public function testExecuteOutput(string $expected, bool $expectedIsRegEx, bool $decorated, FixerInterface $fixer): void { if ($fixer instanceof DeprecatedFixerInterface) { $this->expectDeprecation(\sprintf('Rule "%s" is DEPRECATED and will be removed in the next major version 4.0. You should use "%s" instead.', $fixer->getName(), implode('", "', $fixer->getSuccessorsNames()))); } $actual = $this->execute($fixer->getName(), $decorated, $fixer)->getDisplay(true); if (true === $expectedIsRegEx) { self::assertMatchesRegularExpression($expected, $actual); } else { self::assertSame($expected, $actual); } } /** * @return iterable<string, array{string, bool, bool, FixerInterface}> */ public static function provideExecuteOutputCases(): iterable { yield 'rule is configurable, risky and deprecated' => [ "Description of the `Foo/bar` rule. Fixes stuff. Replaces bad stuff with good stuff. This rule is DEPRECATED and will be removed in the next major version 4.0 You should use `Foo/baz` instead. This rule is RISKY Can break stuff. Fixer is configurable using following options: * deprecated_option (bool): a deprecated option; defaults to false. DEPRECATED: use option `functions` instead. * functions (a subset of ['foo', 'test']): list of `function` names to fix; defaults to ['foo', 'test']; DEPRECATED alias: funcs Fixing examples: * Example #1. Fixing with the default configuration. ---------- begin diff ---------- --- Original +++ New @@ -1,1 +1,1 @@ -<?php echo 'bad stuff and bad thing'; +<?php echo 'good stuff and bad thing'; "." ----------- end diff ----------- * Example #2. Fixing with configuration: ['functions' => ['foo', 'bar']]. ---------- begin diff ---------- --- Original +++ New @@ -1,1 +1,1 @@ -<?php echo 'bad stuff and bad thing'; +<?php echo 'good stuff and good thing'; ".' ----------- end diff ----------- ', false, false, self::createConfigurableDeprecatedFixerDouble(), ]; yield 'rule is configurable, risky and deprecated [with decoration]' => [ "\033[34mDescription of the \033[39m\033[32m`Foo/bar`\033[39m\033[34m rule.\033[39m Fixes stuff. Replaces bad stuff with good stuff. \033[37;41mThis rule is DEPRECATED and will be removed in the next major version 4.0\033[39;49m You should use \033[32m`Foo/baz`\033[39m instead. \033[37;41mThis rule is RISKY\033[39;49m Can break stuff. Fixer is configurable using following options: * \033[32mdeprecated_option\033[39m (\033[33mbool\033[39m): a deprecated option; defaults to \e[33mfalse\e[39m. \033[37;41mDEPRECATED\033[39;49m: use option \e[32m`functions`\e[39m instead. * \033[32mfunctions\033[39m (a subset of \e[33m['foo', 'test']\e[39m): list of \033[32m`function`\033[39m names to fix; defaults to \033[33m['foo', 'test']\033[39m; \e[37;41mDEPRECATED\e[39;49m alias: \033[33mfuncs\033[39m Fixing examples: * Example #1. Fixing with the \033[33mdefault\033[39m configuration. \033[33m ---------- begin diff ----------\033[39m \033[31m--- Original\033[39m \033[32m+++ New\033[39m \033[36m@@ -1,1 +1,1 @@\033[39m \033[31m-<?php echo 'bad stuff and bad thing';\033[39m \033[32m+<?php echo 'good stuff and bad thing';\033[39m "." \033[33m ----------- end diff -----------\033[39m * Example #2. Fixing with configuration: \033[33m['functions' => ['foo', 'bar']]\033[39m. \033[33m ---------- begin diff ----------\033[39m \033[31m--- Original\033[39m \033[32m+++ New\033[39m \033[36m@@ -1,1 +1,1 @@\033[39m \033[31m-<?php echo 'bad stuff and bad thing';\033[39m \033[32m+<?php echo 'good stuff and good thing';\033[39m "." \033[33m ----------- end diff -----------\033[39m ", false, true, self::createConfigurableDeprecatedFixerDouble(), ]; yield 'rule without code samples' => [ 'Description of the `Foo/samples` rule. Summary of the rule. Description of the rule. Fixing examples are not available for this rule. ', false, false, self::createFixerWithSamplesDouble([]), ]; yield 'rule with code samples' => [ "Description of the `Foo/samples` rule. Summary of the rule. Description of the rule. Fixing examples: * Example #1. ---------- begin diff ---------- --- Original +++ New @@ -1,1 +1,1 @@ -<?php echo 'BEFORE'; +<?php echo 'AFTER'; "." ----------- end diff ----------- * Example #2. ---------- begin diff ---------- --- Original +++ New @@ -1,1 +1,1 @@ -<?php echo 'BEFORE'.'-B'; +<?php echo 'AFTER'.'-B'; ".' ----------- end diff ----------- ', false, false, self::createFixerWithSamplesDouble([ new CodeSample( "<?php echo 'BEFORE';".\PHP_EOL, ), new CodeSample( "<?php echo 'BEFORE'.'-B';".\PHP_EOL, ), ]), ]; yield 'rule with code samples (one with matching PHP version, one NOT)' => [ "Description of the `Foo/samples` rule. Summary of the rule. Description of the rule. Fixing examples: * Example #1. ---------- begin diff ---------- --- Original +++ New @@ -1,1 +1,1 @@ -<?php echo 'BEFORE'; +<?php echo 'AFTER'; ".' ----------- end diff ----------- ', false, false, self::createFixerWithSamplesDouble([ new CodeSample( "<?php echo 'BEFORE';".\PHP_EOL, ), new VersionSpecificCodeSample( "<?php echo 'BEFORE'.'-B';".\PHP_EOL, new VersionSpecification(20_00_00), ), ]), ]; yield 'rule with code samples (all with NOT matching PHP version)' => [ 'Description of the `Foo/samples` rule. Summary of the rule. Description of the rule. Fixing examples cannot be demonstrated on the current PHP version. ', false, false, self::createFixerWithSamplesDouble([ new VersionSpecificCodeSample( "<?php echo 'BEFORE';".\PHP_EOL, new VersionSpecification(20_00_00), ), new VersionSpecificCodeSample( "<?php echo 'BEFORE'.'-B';".\PHP_EOL, new VersionSpecification(20_00_00), ), ]), ]; yield 'rule that is part of ruleset' => [ '/^Description of the `binary_operator_spaces` rule. .* ----------- end diff ----------- '.preg_quote("The fixer is part of the following rule sets: * @PER *(deprecated)* with config: ['default' => 'at_least_single_space'] * @PER-CS with config: ['default' => 'at_least_single_space'] * @PER-CS1.0 *(deprecated)* with config: ['default' => 'at_least_single_space'] * @PER-CS1x0 with config: ['default' => 'at_least_single_space'] * @PER-CS2.0 *(deprecated)* with config: ['default' => 'at_least_single_space'] * @PER-CS2x0 with config: ['default' => 'at_least_single_space'] * @PER-CS3.0 *(deprecated)* with config: ['default' => 'at_least_single_space'] * @PER-CS3x0 with config: ['default' => 'at_least_single_space'] * @PSR12 with config: ['default' => 'at_least_single_space'] * @PhpCsFixer with default config * @Symfony with default config").' $/s', true, false, new BinaryOperatorSpacesFixer(), ]; } public function testExecuteStatusCode(): void { $this->expectDeprecation('Rule "Foo/bar" is DEPRECATED and will be removed in the next major version 4.0. You should use "Foo/baz" instead.'); self::assertSame(0, $this->execute('Foo/bar', false)->getStatusCode()); } public function testExecuteWithUnknownRuleName(): void { $application = new Application(); $application->add(new DescribeCommand(new FixerFactory())); $command = $application->find('describe'); $commandTester = new CommandTester($command); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessageMatches('#^Rule "Foo/bar" not found\.$#'); $commandTester->execute([ 'command' => $command->getName(), 'name' => 'Foo/bar', '--config' => __DIR__.'/../../Fixtures/.php-cs-fixer.vanilla.php', ]); } public function testExecuteWithUnknownSetName(): void { $application = new Application(); $application->add(new DescribeCommand(new FixerFactory())); $command = $application->find('describe'); $commandTester = new CommandTester($command); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessageMatches('#^Set "@NoSuchSet" not found\.$#'); $commandTester->execute([ 'command' => $command->getName(), 'name' => '@NoSuchSet', '--config' => __DIR__.'/../../Fixtures/.php-cs-fixer.vanilla.php', ]); } public function testExecuteWithoutName(): void { $application = new Application(); $application->add(new DescribeCommand(new FixerFactory())); $command = $application->find('describe'); $commandTester = new CommandTester($command); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Not enough arguments (missing: "name") when not running interactively.'); $commandTester->execute([ 'command' => $command->getName(), '--config' => __DIR__.'/../../Fixtures/.php-cs-fixer.vanilla.php', ], ['interactive' => false]); } public function testGetAlternativeSuggestion(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessageMatches('#^Rule "Foo2/bar" not found\. Did you mean "Foo/bar"\?$#'); $this->execute('Foo2/bar', false); } public function testFixerClassNameIsExposedWhenVerbose(): void { $fixer = new class implements FixerInterface { public function isCandidate(Tokens $tokens): bool { throw new \LogicException('Not implemented.'); } public function isRisky(): bool { return true; } public function fix(\SplFileInfo $file, Tokens $tokens): void { throw new \LogicException('Not implemented.'); } public function getDefinition(): FixerDefinition { return new FixerDefinition('Fixes stuff.', []); } public function getName(): string { return 'Foo/bar_baz'; } public function getPriority(): int { return 0; } public function supports(\SplFileInfo $file): bool { throw new \LogicException('Not implemented.'); } }; $fixerFactory = new FixerFactory(); $fixerFactory->registerFixer($fixer, true); $application = new Application(); $application->add(new DescribeCommand($fixerFactory)); $command = $application->find('describe'); $commandTester = new CommandTester($command); $commandTester->execute( [ 'command' => $command->getName(), 'name' => 'Foo/bar_baz', '--config' => __DIR__.'/../../Fixtures/.php-cs-fixer.vanilla.php', ], [ 'verbosity' => OutputInterface::VERBOSITY_VERBOSE, ], ); self::assertStringContainsString(str_replace("\0", '\\', \get_class($fixer)), $commandTester->getDisplay(true)); } public function testCommandDescribesCustomFixer(): void { $application = new Application(); $application->add(new DescribeCommand()); $command = $application->find('describe'); $commandTester = new CommandTester($command); $commandTester->execute([ 'command' => $command->getName(), 'name' => (new DescribeFixtureFixer())->getName(), '--config' => __DIR__.'/../../Fixtures/DescribeCommand/.php-cs-fixer.custom-rule.php', ]); $expected = "Description of the `Vendor/describe_fixture` rule. Fixture for describe command. Fixing examples: * Example #1. ---------- begin diff ---------- --- Original +++ New @@ -1,2 +1,2 @@ <?php -echo 'describe fixture'; +echo 'fixture for describe'; ".' ----------- end diff ----------- '; self::assertSame($expected, $commandTester->getDisplay(true)); self::assertSame(0, $commandTester->getStatusCode()); } public function testCommandDescribesCustomSet(): void { $application = new Application(); $application->add(new DescribeCommand()); $command = $application->find('describe'); $commandTester = new CommandTester($command); $commandTester->execute([ 'command' => $command->getName(), 'name' => (new ExampleRuleSet())->getName(), '--config' => __DIR__.'/../../Fixtures/DescribeCommand/.php-cs-fixer.custom-set.php', ]); $expected = "You may the '--expand' option to see nested sets expanded into nested rules. Description of the `@Vendor/RuleSet` set. Purpose of example rule set description. * align_multiline_comment configurable | Each line of multi-line DocComments must have an asterisk [PSR-5] and must be aligned with the first one. | Configuration: false "; self::assertSame($expected, $commandTester->getDisplay(true)); self::assertSame(0, $commandTester->getStatusCode()); } /** * @param list<CodeSampleInterface> $samples */ private static function createFixerWithSamplesDouble(array $samples): FixerInterface { return new class($samples) extends AbstractFixer { /** * @var list<CodeSampleInterface> */ private array $samples; /** * @param list<CodeSampleInterface> $samples */ public function __construct( array $samples ) { parent::__construct(); $this->samples = $samples; } public function getName(): string { return 'Foo/samples'; } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Summary of the rule.', $this->samples, 'Description of the rule.', null, ); } public function isCandidate(Tokens $tokens): bool { return true; } public function applyFix(\SplFileInfo $file, Tokens $tokens): void { $tokens[3] = new Token([ $tokens[3]->getId(), "'AFTER'", ]); } }; } private static function createConfigurableDeprecatedFixerDouble(): FixerInterface { return new class implements ConfigurableFixerInterface, DeprecatedFixerInterface { /** @var array<string, mixed> */ private array $configuration; public function configure(array $configuration): void { $this->configuration = $configuration; } public function getConfigurationDefinition(): FixerConfigurationResolver { $functionNames = ['foo', 'test']; return new FixerConfigurationResolver([ (new AliasedFixerOptionBuilder(new FixerOptionBuilder('functions', 'List of `function` names to fix.'), 'funcs')) ->setAllowedTypes(['string[]']) ->setAllowedValues([new AllowedValueSubset($functionNames)]) ->setDefault($functionNames) ->getOption(), (new FixerOptionBuilder('deprecated_option', 'A deprecated option.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->setDeprecationMessage('Use option `functions` instead.') ->getOption(), ]); } public function getSuccessorsNames(): array { return ['Foo/baz']; } public function isCandidate(Tokens $tokens): bool { throw new \LogicException('Not implemented.'); } public function isRisky(): bool { return true; } public function fix(\SplFileInfo $file, Tokens $tokens): void { $tokens[3] = new Token([ $tokens[3]->getId(), [] !== $this->configuration ? '\'good stuff and good thing\'' : '\'good stuff and bad thing\'', ]); } public function getDefinition(): FixerDefinition { return new FixerDefinition( 'Fixes stuff.', [ new CodeSample( "<?php echo 'bad stuff and bad thing';\n", ), new CodeSample( "<?php echo 'bad stuff and bad thing';\n", ['functions' => ['foo', 'bar']], ), ], 'Replaces bad stuff with good stuff.', 'Can break stuff.', ); } public function getName(): string { return 'Foo/bar'; } public function getPriority(): int { return 0; } public function supports(\SplFileInfo $file): bool { throw new \LogicException('Not implemented.'); } }; } private function execute(string $name, bool $decorated, ?FixerInterface $fixer = null): CommandTester { $fixer ??= self::createConfigurableDeprecatedFixerDouble(); $fixerClassName = \get_class($fixer); $isBuiltIn = str_starts_with($fixerClassName, 'PhpCsFixer') && !str_contains($fixerClassName, '@anon'); $fixerFactory = new FixerFactory(); $fixerFactory->registerFixer($fixer, !$isBuiltIn); $application = new Application(); $application->add(new DescribeCommand($fixerFactory)); $command = $application->find('describe'); $commandTester = new CommandTester($command); $commandTester->execute( [ 'command' => $command->getName(), 'name' => $name, '--config' => __DIR__.'/../../Fixtures/.php-cs-fixer.vanilla.php', ], [ 'decorated' => $decorated, ], ); return $commandTester; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Command/DescribeNameNotFoundExceptionTest.php
tests/Console/Command/DescribeNameNotFoundExceptionTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Command; use PhpCsFixer\Console\Command\DescribeNameNotFoundException; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\Console\Command\DescribeNameNotFoundException * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DescribeNameNotFoundExceptionTest extends TestCase { public function testConstructorSetsValues(): void { $name = 'Peter'; $type = 'weird'; $exception = new DescribeNameNotFoundException( $name, $type, ); self::assertSame($name, $exception->getName()); self::assertSame($type, $exception->getType()); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Command/FixCommandTest.php
tests/Console/Command/FixCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Command; use PhpCsFixer\ConfigInterface; use PhpCsFixer\ConfigurationException\InvalidConfigurationException; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Command\FixCommand; use PhpCsFixer\Console\ConfigurationResolver; use PhpCsFixer\Runner\Parallel\ParallelConfigFactory; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\ToolInfo; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tester\CommandTester; /** * @internal * * @covers \PhpCsFixer\Console\Command\FixCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FixCommandTest extends TestCase { public function testIntersectionPathMode(): void { $cmdTester = $this->doTestExecute([ '--path-mode' => 'intersection', '--show-progress' => 'none', '--config' => __DIR__.'/../../Fixtures/.php-cs-fixer.vanilla.php', ]); self::assertSame( Command::SUCCESS, $cmdTester->getStatusCode(), ); } public function testEmptyRulesValue(): void { $this->expectException( InvalidConfigurationException::class, ); $this->expectExceptionMessageMatches( '#^Empty rules value is not allowed\.$#', ); $this->doTestExecute( ['--rules' => ''], ); } public function testEmptyFormatValue(): void { $this->expectException(InvalidConfigurationException::class); $this->expectExceptionMessage('Expected "yes" or "no" for option "using-cache", got "not today".'); $cmdTester = $this->doTestExecute( [ '--using-cache' => 'not today', '--rules' => 'switch_case_semicolon_to_colon', ], ); $cmdTester->getStatusCode(); } /** * @covers \PhpCsFixer\Console\Command\WorkerCommand * @covers \PhpCsFixer\Runner\Runner::fixSequential */ public function testSequentialRun(): void { $pathToDistConfig = __DIR__.'/../../Fixtures/.php-cs-fixer.vanilla.php'; $configWithFixedParallelConfig = <<<PHP <?php \$config = require '{$pathToDistConfig}'; \$config->setRules(['header_comment' => ['header' => 'SEQUENTIAL!']]); \$config->setParallelConfig(\\PhpCsFixer\\Runner\\Parallel\\ParallelConfigFactory::sequential()); return \$config; PHP; $tmpFile = tempnam(sys_get_temp_dir(), 'php-cs-fixer-parallel-config-').'.php'; file_put_contents($tmpFile, $configWithFixedParallelConfig); $cmdTester = $this->doTestExecute( [ '--config' => $tmpFile, 'path' => [__DIR__], ], ); $availableMaxProcesses = ParallelConfigFactory::detect()->getMaxProcesses(); self::assertStringContainsString('Running analysis on 1 core sequentially.', $cmdTester->getDisplay()); if ($availableMaxProcesses > 1) { self::assertStringContainsString('You can enable parallel runner and speed up the analysis!', $cmdTester->getDisplay()); } self::assertStringContainsString('(header_comment)', $cmdTester->getDisplay()); self::assertSame(8, $cmdTester->getStatusCode()); } /** * There's no simple way to cover parallelisation with tests, because it involves a lot of hardcoded logic under the hood, * like opening server, communicating through sockets, etc. That's why we only test `fix` command with proper * parallel config, so runner utilises multi-processing internally. Expected outcome is information about utilising multiple CPUs. * * @covers \PhpCsFixer\Console\Command\WorkerCommand * @covers \PhpCsFixer\Runner\Runner::fixParallel */ public function testParallelRun(): void { $pathToDistConfig = __DIR__.'/../../Fixtures/.php-cs-fixer.vanilla.php'; $configWithFixedParallelConfig = <<<PHP <?php \$config = require '{$pathToDistConfig}'; \$config->setRules(['header_comment' => ['header' => 'PARALLEL!']]); \$config->setParallelConfig(new \\PhpCsFixer\\Runner\\Parallel\\ParallelConfig(2, 1, 300)); return \$config; PHP; $tmpFile = tempnam(sys_get_temp_dir(), 'php-cs-fixer-parallel-config-').'.php'; file_put_contents($tmpFile, $configWithFixedParallelConfig); $cmdTester = $this->doTestExecute( [ '--config' => $tmpFile, 'path' => [__DIR__], ], ); self::assertStringContainsString('Running analysis on 2 cores with 1 file per process.', $cmdTester->getDisplay()); self::assertStringContainsString('Parallel runner is an experimental feature and may be unstable, use it at your own risk. Feedback highly appreciated!', $cmdTester->getDisplay()); self::assertStringContainsString('(header_comment)', $cmdTester->getDisplay()); self::assertSame(8, $cmdTester->getStatusCode()); } /** * @large */ public function testUnsupportedVersionWarningRun(): void { if (version_compare(\PHP_VERSION, ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED.'.99', '<=')) { self::markTestSkipped('This test requires version of PHP higher than '.ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED); } $pathToDistConfig = __DIR__.'/../../Fixtures/.php-cs-fixer.vanilla.php'; $configWithFixedParallelConfig = <<<PHP <?php \$config = require '{$pathToDistConfig}'; \$config->setUnsupportedPhpVersionAllowed(true); return \$config; PHP; $tmpFile = tempnam(sys_get_temp_dir(), 'php-cs-fixer-parallel-config-').'.php'; file_put_contents($tmpFile, $configWithFixedParallelConfig); $cmdTester = $this->doTestExecute( [ '--config' => $tmpFile, 'path' => [__DIR__], ], ); self::assertStringContainsString('PHP CS Fixer currently supports PHP syntax only up to PHP '.ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED, $cmdTester->getDisplay()); self::assertStringContainsString('Execution may be unstable. You may experience code modified in a wrong way.', $cmdTester->getDisplay()); } public function testUnsupportedVersionErrorRun(): void { if (version_compare(\PHP_VERSION, ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED.'.99', '<=')) { self::markTestSkipped('This test requires version of PHP higher than '.ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED); } $pathToDistConfig = __DIR__.'/../../Fixtures/.php-cs-fixer.vanilla.php'; $configWithFixedParallelConfig = <<<PHP <?php \$config = require '{$pathToDistConfig}'; \$config->setUnsupportedPhpVersionAllowed(false); return \$config; PHP; $tmpFile = tempnam(sys_get_temp_dir(), 'php-cs-fixer-parallel-config-').'.php'; file_put_contents($tmpFile, $configWithFixedParallelConfig); $cmdTester = $this->doTestExecute( [ '--config' => $tmpFile, 'path' => [__DIR__], ], ); self::assertStringContainsString('PHP CS Fixer currently supports PHP syntax only up to PHP '.ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED, $cmdTester->getDisplay()); self::assertStringContainsString('Add `Config::setUnsupportedPhpVersionAllowed(true)` to allow executions on unsupported PHP versions.', $cmdTester->getDisplay()); self::assertSame(1, $cmdTester->getStatusCode()); } /** * @param array<string, mixed> $arguments */ private function doTestExecute(array $arguments): CommandTester { $application = new Application(); $application->add(new FixCommand(new ToolInfo())); $command = $application->find('fix'); $commandTester = new CommandTester($command); $commandTester->execute( array_merge( ['command' => $command->getName()], $this->getDefaultArguments(), $arguments, ), [ 'interactive' => false, 'decorated' => false, 'verbosity' => OutputInterface::VERBOSITY_DEBUG, ], ); return $commandTester; } /** * @return array<string, mixed> */ private function getDefaultArguments(): array { return [ 'path' => [__DIR__.'/../../Fixtures/dummy-file.php'], '--path-mode' => 'override', '--allow-risky' => 'yes', '--dry-run' => true, '--using-cache' => 'no', '--show-progress' => 'none', '--config' => ConfigurationResolver::IGNORE_CONFIG_FILE, ]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Command/FixCommandExitStatusCalculatorTest.php
tests/Console/Command/FixCommandExitStatusCalculatorTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Command; use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Console\Command\FixCommandExitStatusCalculator * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FixCommandExitStatusCalculatorTest extends TestCase { /** * @dataProvider provideCalculateCases */ public function testCalculate( int $expected, bool $isDryRun, bool $hasChangedFiles, bool $hasInvalidErrors, bool $hasExceptionErrors, bool $hasLintErrorsAfterFixing ): void { $calculator = new FixCommandExitStatusCalculator(); self::assertSame( $expected, $calculator->calculate( $isDryRun, $hasChangedFiles, $hasInvalidErrors, $hasExceptionErrors, $hasLintErrorsAfterFixing, ), ); } /** * @return iterable<int, array{int, bool, bool, bool, bool, bool}> */ public static function provideCalculateCases(): iterable { yield [0, true, false, false, false, false]; yield [0, false, false, false, false, false]; yield [8, true, true, false, false, false]; yield [0, false, true, false, false, false]; yield [4, true, false, true, false, false]; yield [0, false, false, true, false, false]; yield [12, true, true, true, false, false]; yield [0, false, true, true, false, false]; yield [76, true, true, true, true, false]; yield [64, false, false, false, false, true]; yield [64, false, false, false, true, false]; yield [64, false, false, false, true, true]; yield [8 | 64, true, true, false, true, true]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Command/HelpCommandTest.php
tests/Console/Command/HelpCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Command; use PhpCsFixer\Console\Command\HelpCommand; use PhpCsFixer\FixerConfiguration\FixerOption; use PhpCsFixer\FixerConfiguration\FixerOptionInterface; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\Console\Command\HelpCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class HelpCommandTest extends TestCase { /** * @param non-empty-list<string> $allowedValues * * @dataProvider provideGetDescriptionWithAllowedValuesCases */ public function testGetDescriptionWithAllowedValues(string $expected, string $description, array $allowedValues): void { self::assertSame($expected, HelpCommand::getDescriptionWithAllowedValues($description, $allowedValues)); } /** * @return iterable<int, array{string, string, non-empty-list<string>}> */ public static function provideGetDescriptionWithAllowedValuesCases(): iterable { yield [ 'Option description (can be `yes` or `no`).', 'Option description (%s).', ['yes', 'no'], ]; yield [ 'Option description (can be `txt`, `json` or `markdown`).', 'Option description (%s).', ['txt', 'json', 'markdown'], ]; } /** * @param null|mixed $expected * * @dataProvider provideGetDisplayableAllowedValuesCases */ public function testGetDisplayableAllowedValues($expected, FixerOptionInterface $input): void { self::assertSame($expected, HelpCommand::getDisplayableAllowedValues($input)); } /** * @return iterable<int, array{null|mixed, FixerOption}> */ public static function provideGetDisplayableAllowedValuesCases(): iterable { yield [null, new FixerOption('foo', 'bar', false, null, ['int'])]; yield [['A', 'B', 'x', 'z'], new FixerOption('foo', 'bar', false, null, ['string'], ['z', 'x', 'B', 'A'])]; yield [[0, 3, 9], new FixerOption('foo', 'bar', false, null, ['int'], [0, 3, 9, static fn () => true])]; yield [null, new FixerOption('foo', 'bar')]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Console/Command/ListFilesCommandTest.php
tests/Console/Command/ListFilesCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Console\Command; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Command\ListFilesCommand; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\ToolInfo; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Path; /** * @internal * * @covers \PhpCsFixer\Console\Command\ListFilesCommand * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ListFilesCommandTest extends TestCase { private static ?Filesystem $filesystem; public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); self::$filesystem = new Filesystem(); } public static function tearDownAfterClass(): void { self::$filesystem = null; parent::tearDownAfterClass(); } public function testListWithConfig(): void { $commandTester = $this->doTestExecute([ '--config' => __DIR__.'/../../Fixtures/ListFilesTest/.php-cs-fixer.php', ]); $expectedPath = './tests/Fixtures/ListFilesTest/needs-fixing/needs-fixing.php'; // make the test also work on Windows $expectedPath = str_replace('/', \DIRECTORY_SEPARATOR, $expectedPath); self::assertSame(0, $commandTester->getStatusCode()); self::assertSame(escapeshellarg($expectedPath).\PHP_EOL, $commandTester->getDisplay()); } /** * @requires OS Linux|Darwin * * Skip test on Windows as `getcwd()` includes the drive letter with a colon `:` which is illegal in filenames. */ public function testListFilesDoesNotCorruptListWithGetcwdInName(): void { try { $tmpDir = __DIR__.'/../../Fixtures/ListFilesTest/using-getcwd'; $tmpFile = $tmpDir.'/'.ltrim((string) getcwd(), '/').'-out.php'; self::$filesystem->dumpFile($tmpFile, '<?php function a() { }'); $tmpFile = realpath($tmpFile); self::assertIsString($tmpFile); self::assertFileExists($tmpFile); $commandTester = $this->doTestExecute([ '--config' => __DIR__.'/../../Fixtures/ListFilesTest/.php-cs-fixer.using-getcwd.php', ]); $expectedPath = str_replace('/', \DIRECTORY_SEPARATOR, './'.Path::makeRelative($tmpFile, (string) getcwd())); self::assertSame(0, $commandTester->getStatusCode()); self::assertSame(escapeshellarg($expectedPath).\PHP_EOL, $commandTester->getDisplay()); } finally { self::$filesystem->remove($tmpDir); } } /** * @param array<string, bool|string> $arguments */ private function doTestExecute(array $arguments): CommandTester { $application = new Application(); $application->add(new ListFilesCommand(new ToolInfo())); $command = $application->find('list-files'); $commandTester = new CommandTester($command); $commandTester->execute($arguments); return $commandTester; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Config/NullRuleCustomisationPolicyTest.php
tests/Config/NullRuleCustomisationPolicyTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Config; use PhpCsFixer\Config\NullRuleCustomisationPolicy; use PhpCsFixer\Config\RuleCustomisationPolicyInterface; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\Config\NullRuleCustomisationPolicy * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NullRuleCustomisationPolicyTest extends TestCase { public function testImplementsRuleCustomisationPolicyInterface(): void { $reflection = new \ReflectionClass(NullRuleCustomisationPolicy::class); self::assertTrue($reflection->implementsInterface(RuleCustomisationPolicyInterface::class)); } public function testValues(): void { $policy = new NullRuleCustomisationPolicy(); self::assertSame('null-policy', $policy->getPolicyVersionForCache()); self::assertSame([], $policy->getRuleCustomisers()); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/FixerDefinition/FixerDefinitionTest.php
tests/FixerDefinition/FixerDefinitionTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\FixerDefinition; use PhpCsFixer\FixerDefinition\CodeSampleInterface; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\FixerDefinition\FixerDefinition * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FixerDefinitionTest extends TestCase { public function testGetSummary(): void { $definition = new FixerDefinition('Foo', []); self::assertSame('Foo', $definition->getSummary()); } public function testGetCodeSamples(): void { $samples = [ $this->createCodeSampleDouble(), $this->createCodeSampleDouble(), ]; $definition = new FixerDefinition('', $samples); self::assertSame($samples, $definition->getCodeSamples()); } public function testGetDescription(): void { $definition = new FixerDefinition('', []); self::assertNull($definition->getDescription()); $definition = new FixerDefinition('', [], 'Foo'); self::assertSame('Foo', $definition->getDescription()); } public function testGetRiskyDescription(): void { $definition = new FixerDefinition('', []); self::assertNull($definition->getRiskyDescription()); $definition = new FixerDefinition('', [], null, 'Foo'); self::assertSame('Foo', $definition->getRiskyDescription()); } private function createCodeSampleDouble(): CodeSampleInterface { return new class implements CodeSampleInterface { public function getCode(): string { throw new \LogicException('Not implemented.'); } public function getConfiguration(): ?array { throw new \LogicException('Not implemented.'); } }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/FixerDefinition/FileSpecificCodeSampleTest.php
tests/FixerDefinition/FileSpecificCodeSampleTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\FixerDefinition; use PhpCsFixer\FixerDefinition\FileSpecificCodeSample; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\FixerDefinition\FileSpecificCodeSample * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FileSpecificCodeSampleTest extends TestCase { public function testDefaults(): void { $code = file_get_contents(__FILE__); self::assertIsString($code); $splFileInfo = new \SplFileInfo(__FILE__); $sample = new FileSpecificCodeSample( $code, $splFileInfo, ); self::assertSame($code, $sample->getCode()); self::assertSame($splFileInfo, $sample->getSplFileInfo()); self::assertNull($sample->getConfiguration()); } public function testConstructorSetsValues(): void { $code = file_get_contents(__FILE__); self::assertIsString($code); $splFileInfo = new \SplFileInfo(__FILE__); $configuration = [ 'foo' => 'bar', 'bar' => 'baz', ]; $sample = new FileSpecificCodeSample( $code, $splFileInfo, $configuration, ); self::assertSame($code, $sample->getCode()); self::assertSame($splFileInfo, $sample->getSplFileInfo()); self::assertSame($configuration, $sample->getConfiguration()); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/FixerDefinition/VersionSpecificCodeSampleTest.php
tests/FixerDefinition/VersionSpecificCodeSampleTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\FixerDefinition; use PhpCsFixer\FixerDefinition\VersionSpecificationInterface; use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\FixerDefinition\VersionSpecificCodeSample * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class VersionSpecificCodeSampleTest extends TestCase { public function testConstructorSetsValues(): void { $code = '<php echo $foo;'; $configuration = [ 'foo' => 'bar', ]; $codeSample = new VersionSpecificCodeSample( $code, $this->createVersionSpecificationDouble(), $configuration, ); self::assertSame($code, $codeSample->getCode()); self::assertSame($configuration, $codeSample->getConfiguration()); } public function testConfigurationDefaultsToNull(): void { $codeSample = new VersionSpecificCodeSample( '<php echo $foo;', $this->createVersionSpecificationDouble(), ); self::assertNull($codeSample->getConfiguration()); } /** * @dataProvider provideIsSuitableForUsesVersionSpecificationCases */ public function testIsSuitableForUsesVersionSpecification(int $version, bool $isSatisfied): void { $codeSample = new VersionSpecificCodeSample( '<php echo $foo;', $this->createVersionSpecificationDouble($isSatisfied), ); self::assertSame($isSatisfied, $codeSample->isSuitableFor($version)); } /** * @return iterable<string, array{int, bool}> */ public static function provideIsSuitableForUsesVersionSpecificationCases(): iterable { yield 'is-satisfied' => [100, true]; yield 'is-not-satisfied' => [100, false]; } private function createVersionSpecificationDouble(bool $isSatisfied = true): VersionSpecificationInterface { return new class($isSatisfied) implements VersionSpecificationInterface { private bool $isSatisfied; public function __construct(bool $isSatisfied) { $this->isSatisfied = $isSatisfied; } public function isSatisfiedBy(int $version): bool { return $this->isSatisfied; } }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/FixerDefinition/VersionSpecificationTest.php
tests/FixerDefinition/VersionSpecificationTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\FixerDefinition; use PhpCsFixer\FixerDefinition\VersionSpecification; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\FixerDefinition\VersionSpecification * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class VersionSpecificationTest extends TestCase { public function testConstructorRequiresEitherMinimumOrMaximum(): void { $this->expectException(\InvalidArgumentException::class); new VersionSpecification(); } /** * @dataProvider provideConstructorRejectsInvalidValuesCases * * @param null|int<1, max> $minimum * @param null|int<1, max> $maximum */ public function testConstructorRejectsInvalidValues(?int $minimum = null, ?int $maximum = null): void { $this->expectException(\InvalidArgumentException::class); new VersionSpecification( $minimum, $maximum, ); } /** * @return iterable<string, array{null|int, null|int}> */ public static function provideConstructorRejectsInvalidValuesCases(): iterable { yield 'minimum is negative' => [-1, null]; yield 'minimum is zero' => [0, null]; yield 'maximum is negative' => [null, -1]; yield 'maximum is zero' => [null, 0]; yield 'maximum less than minimum' => [32, 31]; } /** * @dataProvider provideIsSatisfiedByReturnsTrueCases * * @param null|int<1, max> $minimum * @param null|int<1, max> $maximum */ public function testIsSatisfiedByReturnsTrue(?int $minimum, ?int $maximum, int $actual): void { $versionSpecification = new VersionSpecification( $minimum, $maximum, ); self::assertTrue($versionSpecification->isSatisfiedBy($actual)); } /** * @return iterable<string, array{null|int, null|int, int}> */ public static function provideIsSatisfiedByReturnsTrueCases(): iterable { yield 'version-same-as-maximum' => [null, 100, 100]; yield 'version-same-as-minimum' => [200, null, 200]; yield 'version-between-minimum-and-maximum' => [299, 301, 300]; yield 'version-same-as-minimum-and-maximum' => [400, 400, 400]; } /** * @dataProvider provideIsSatisfiedByReturnsFalseCases * * @param null|int<1, max> $minimum * @param null|int<1, max> $maximum */ public function testIsSatisfiedByReturnsFalse(?int $minimum, ?int $maximum, int $actual): void { $versionSpecification = new VersionSpecification( $minimum, $maximum, ); self::assertFalse($versionSpecification->isSatisfiedBy($actual)); } /** * @return iterable<string, array{null|int, null|int, int}> */ public static function provideIsSatisfiedByReturnsFalseCases(): iterable { yield 'version-greater-than-maximum' => [null, 1_000, 1_001]; yield 'version-less-than-minimum' => [2_000, null, 1_999]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/FixerDefinition/CodeSampleTest.php
tests/FixerDefinition/CodeSampleTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\FixerDefinition; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\FixerDefinition\CodeSample * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CodeSampleTest extends TestCase { public function testConstructorSetsValues(): void { $code = '<php echo $foo;'; $configuration = [ 'foo' => 'bar', ]; $codeSample = new CodeSample( $code, $configuration, ); self::assertSame($code, $codeSample->getCode()); self::assertSame($configuration, $codeSample->getConfiguration()); } public function testConfigurationDefaultsToNull(): void { $codeSample = new CodeSample('<php echo $foo;'); self::assertNull($codeSample->getConfiguration()); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Differ/FullDifferTest.php
tests/Differ/FullDifferTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Differ; use PhpCsFixer\Differ\FullDiffer; /** * @internal * * @covers \PhpCsFixer\Differ\FullDiffer * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FullDifferTest extends AbstractDifferTestCase { public function testDiffReturnsDiff(): void { $diff = '--- Original +++ New @@ -1,10 +1,10 @@ <?php '.' function baz($options) { - if (!array_key_exists("foo", $options)) { + if (!\array_key_exists("foo", $options)) { throw new \InvalidArgumentException(); } '.' return json_encode($options); } '; $differ = new FullDiffer(); self::assertSame($diff, $differ->diff($this->oldCode(), $this->newCode())); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Differ/DiffConsoleFormatterTest.php
tests/Differ/DiffConsoleFormatterTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Differ; use PhpCsFixer\Differ\DiffConsoleFormatter; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Console\Formatter\OutputFormatter; /** * @internal * * @covers \PhpCsFixer\Differ\DiffConsoleFormatter * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DiffConsoleFormatterTest extends TestCase { /** * @dataProvider provideDiffConsoleFormatterCases */ public function testDiffConsoleFormatter(string $expected, bool $isDecoratedOutput, string $template, string $diff, string $lineTemplate): void { $diffFormatter = new DiffConsoleFormatter($isDecoratedOutput, $template); self::assertSame( str_replace(\PHP_EOL, "\n", $expected), str_replace(\PHP_EOL, "\n", $diffFormatter->format($diff, $lineTemplate)), ); } /** * @return iterable<int, array{string, bool, string, string, string}> */ public static function provideDiffConsoleFormatterCases(): iterable { yield [ \sprintf( '<comment> ---------- begin diff ----------</comment> '.' <fg=cyan>%s</fg=cyan> no change <fg=red>%s</fg=red> <fg=green>%s</fg=green> <fg=green>%s</fg=green> '.' <comment> ----------- end diff -----------</comment>', OutputFormatter::escape('@@ -12,51 +12,151 @@'), OutputFormatter::escape('-/**\\'), OutputFormatter::escape('+/*\\'), OutputFormatter::escape('+A'), ), true, \sprintf( '<comment> ---------- begin diff ----------</comment>%s%%s%s<comment> ----------- end diff -----------</comment>', \PHP_EOL, \PHP_EOL, ), ' @@ -12,51 +12,151 @@ no change -/**\ +/*\ +A ', ' %s', ]; yield [ '[start] | '.' | @@ -12,51 +12,151 @@ | no change | '.' | -/**\ | +/*\ | +A | '.' [end]', false, \sprintf('[start]%s%%s%s[end]', \PHP_EOL, \PHP_EOL), ' @@ -12,51 +12,151 @@ no change '.' -/**\ +/*\ +A ', '| %s', ]; yield [ (string) mb_convert_encoding("<fg=red>--- Original</fg=red>\n<fg=green>+ausgefüllt</fg=green>", 'ISO-8859-1'), true, '%s', (string) mb_convert_encoding("--- Original\n+ausgefüllt", 'ISO-8859-1'), '%s', ]; yield [ (string) mb_convert_encoding("<fg=red>--- Original</fg=red>\n<fg=green>+++ New</fg=green>\n<fg=cyan>@@ @@</fg=cyan>\n<fg=red>-ausgefüllt</fg=red>", 'ISO-8859-1'), true, '%s', (string) mb_convert_encoding("--- Original\n+++ New\n@@ @@\n-ausgefüllt", 'ISO-8859-1'), '%s', ]; yield [ (string) mb_convert_encoding("--- Original\n+++ New\n@@ @@\n-ausgefüllt", 'ISO-8859-1'), false, '%s', (string) mb_convert_encoding("--- Original\n+++ New\n@@ @@\n-ausgefüllt", 'ISO-8859-1'), '%s', ]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Differ/NullDifferTest.php
tests/Differ/NullDifferTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Differ; use PhpCsFixer\Differ\NullDiffer; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @covers \PhpCsFixer\Differ\NullDiffer * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NullDifferTest extends AbstractDifferTestCase { public function testDiffReturnsEmptyString(): void { $diff = ''; $differ = new NullDiffer(); self::assertSame($diff, $differ->diff($this->oldCode(), $this->newCode())); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Differ/AbstractDifferTestCase.php
tests/Differ/AbstractDifferTestCase.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Differ; use PhpCsFixer\Differ\DifferInterface; use PhpCsFixer\Preg; use PhpCsFixer\Tests\TestCase; /** * @author Andreas Möller <am@localheinz.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractDifferTestCase extends TestCase { final public function testIsDiffer(): void { $className = Preg::replace( '/Test$/', '', str_replace( 'PhpCsFixer\Tests\Differ\\', 'PhpCsFixer\Differ\\', static::class, ), ); $differ = new $className(); self::assertInstanceOf(DifferInterface::class, $differ); } final protected function oldCode(): string { return <<<'PHP' <?php function baz($options) { if (!array_key_exists("foo", $options)) { throw new \InvalidArgumentException(); } return json_encode($options); } PHP; } final protected function newCode(): string { return <<<'PHP' <?php function baz($options) { if (!\array_key_exists("foo", $options)) { throw new \InvalidArgumentException(); } return json_encode($options); } PHP; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/Differ/UnifiedDifferTest.php
tests/Differ/UnifiedDifferTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Differ; use PhpCsFixer\Differ\UnifiedDiffer; /** * @internal * * @covers \PhpCsFixer\Differ\UnifiedDiffer * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class UnifiedDifferTest extends AbstractDifferTestCase { public function testDiffReturnsDiff(): void { $differ = new UnifiedDiffer(); $file = __FILE__; $diff = '--- '.$file.' +++ '.$file.' @@ -2,7 +2,7 @@ '.' function baz($options) { - if (!array_key_exists("foo", $options)) { + if (!\array_key_exists("foo", $options)) { throw new \InvalidArgumentException(); } '.' '; self::assertSame($diff, $differ->diff($this->oldCode(), $this->newCode(), new \SplFileInfo($file))); } public function testDiffAddsQuotes(): void { $differ = new UnifiedDiffer(); self::assertSame( '--- "test test test.txt" +++ "test test test.txt" @@ -1 +1 @@ -a +b ', $differ->diff("a\n", "b\n", $this->createSplFileInfoDouble('/foo/bar/test test test.txt')), ); } public function testDiffWithoutFile(): void { $differ = new UnifiedDiffer(); self::assertSame( '--- Original +++ New @@ -1 +1 @@ -a \ No newline at end of file +b \ No newline at end of file ', $differ->diff('a', 'b'), ); } private function createSplFileInfoDouble(string $filename): \SplFileInfo { return new class($filename) extends \SplFileInfo { public function getRealPath(): string { return $this->getFilename(); } }; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/DuplicatedTestsTest.php
tests/AutoReview/DuplicatedTestsTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\Preg; use PhpCsFixer\Tests\TestCase; /** * @internal * * @coversNothing * * @group auto-review * @group covers-nothing * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DuplicatedTestsTest extends TestCase { /** * @dataProvider \PhpCsFixer\Tests\AutoReview\ProjectCodeTest::provideTestClassCases * * @param class-string $className */ public function testThatTestMethodsAreNotDuplicatedBasedOnContent(string $className): void { $alreadyFoundMethods = []; $duplicates = []; foreach (self::getMethodsForDuplicateCheck($className) as $method) { if (!str_starts_with($method->getName(), 'test')) { continue; } $startLine = (int) $method->getStartLine(); $length = (int) $method->getEndLine() - $startLine; if (3 === $length) { // open and closing brace are included - this checks for single line methods continue; } /** @var list<string> $source */ $source = file((string) $method->getFileName()); $candidateContent = implode('', \array_slice($source, $startLine, $length)); if (str_contains($candidateContent, '$this->doTest(')) { continue; } $foundInDuplicates = false; foreach ($alreadyFoundMethods as $methodKey => $methodContent) { if ($candidateContent === $methodContent) { $duplicates[] = \sprintf('%s is duplicate of %s', $methodKey, $method->getName()); $foundInDuplicates = true; } } if (!$foundInDuplicates) { $alreadyFoundMethods[$method->getName()] = $candidateContent; } } self::assertSame( [], $duplicates, \sprintf( "Duplicated methods found in %s:\n - %s", $className, implode("\n - ", $duplicates), ), ); } /** * @dataProvider \PhpCsFixer\Tests\AutoReview\ProjectCodeTest::provideTestClassCases * * @param class-string $className */ public function testThatTestMethodsAreNotDuplicatedBasedOnName(string $className): void { $alreadyFoundMethods = []; $duplicates = []; foreach (self::getMethodsForDuplicateCheck($className) as $method) { foreach ($alreadyFoundMethods as $alreadyFoundMethod) { if (!str_starts_with($method->getName(), $alreadyFoundMethod)) { continue; } $suffix = substr($method->getName(), \strlen($alreadyFoundMethod)); if (!Preg::match('/^\d{2,}/', $suffix)) { continue; } $duplicates[] = \sprintf( 'Method "%s" must be shorter, call "%s".', $method->getName(), $alreadyFoundMethod, ); } $alreadyFoundMethods[] = $method->getName(); } self::assertSame( [], $duplicates, \sprintf( "Duplicated methods found in %s:\n - %s", $className, implode("\n - ", $duplicates), ), ); } /** * @param class-string $className * * @return list<\ReflectionMethod> */ private static function getMethodsForDuplicateCheck(string $className): array { static $methodsForDuplicateCheckCache = []; if (!isset($methodsForDuplicateCheckCache[$className])) { $class = new \ReflectionClass($className); $methodsForDuplicateCheck = array_filter( $class->getMethods(\ReflectionMethod::IS_PUBLIC), static fn (\ReflectionMethod $method) => str_starts_with($method->getName(), 'test') && $method->getDeclaringClass()->getName() === $className /* * Why 4? * Open and closing brace are included, this checks for: * - single line methods * - single line methods with configs */ && 4 < (int) $method->getEndLine() - (int) $method->getStartLine(), ); usort( $methodsForDuplicateCheck, static fn (\ReflectionMethod $method1, \ReflectionMethod $method2) => $method1->getName() <=> $method2->getName(), ); $methodsForDuplicateCheckCache[$className] = $methodsForDuplicateCheck; } return $methodsForDuplicateCheckCache[$className]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/DescribeCommandTest.php
tests/AutoReview/DescribeCommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\Console\Application; use PhpCsFixer\Console\Command\DescribeCommand; use PhpCsFixer\Console\ConfigurationResolver; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\Fixer\Internal\ConfigurableFixerTemplateFixer; use PhpCsFixer\FixerFactory; use PhpCsFixer\RuleSet\RuleSets; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\Utils; use Symfony\Component\Console\Tester\CommandTester; /** * @internal * * @coversNothing * * @group legacy * @group auto-review * @group covers-nothing * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DescribeCommandTest extends TestCase { protected function tearDown(): void { parent::tearDown(); // Reset the global state of RuleSets::$customRuleSetDefinitions that was modified // when using `.php-cs-fixer.dist.php`, which registers custom rules/sets. // // @TODO: ideally, we don't have the global state but inject the state instead \Closure::bind( static fn () => RuleSets::$customRuleSetDefinitions = [], null, RuleSets::class, )(); } /** * @dataProvider provideDescribeCommandCases * * @param list<string> $successorsNames */ public function testDescribeCommand(string $fixerName, ?array $successorsNames, ?string $configFile = null): void { if (null !== $successorsNames) { $message = "Rule \"{$fixerName}\" is DEPRECATED and will be removed in the next major version 4.0. " .([] === $successorsNames ? 'No replacement available.' : \sprintf('You should use %s instead.', Utils::naturalLanguageJoin($successorsNames))); $this->expectDeprecation($message); } if ('ordered_imports' === $fixerName) { $this->expectDeprecation('[ordered_imports] Option "sort_algorithm:length" is deprecated and will be removed in version 4.0.'); } if ('nullable_type_declaration_for_default_null_value' === $fixerName) { $this->expectDeprecation('Option "use_nullable_type_declaration" for rule "nullable_type_declaration_for_default_null_value" is deprecated and will be removed in version 4.0. Behaviour will follow default one.'); } $command = new DescribeCommand(); $application = new Application(); $application->add($command); $commandTester = new CommandTester($command); $commandTester->execute([ 'command' => $command->getName(), 'name' => $fixerName, '--config' => $configFile ?? ConfigurationResolver::IGNORE_CONFIG_FILE, ]); self::assertSame(0, $commandTester->getStatusCode()); } /** * @return iterable<int, array{string, null|list<string>}> */ public static function provideDescribeCommandCases(): iterable { // internal rules yield [ (new ConfigurableFixerTemplateFixer())->getName(), null, __DIR__.'/../Fixtures/.php-cs-fixer.one-time-proxy.php', ]; $factory = new FixerFactory(); $factory->registerBuiltInFixers(); foreach ($factory->getFixers() as $fixer) { yield [ $fixer->getName(), $fixer instanceof DeprecatedFixerInterface ? $fixer->getSuccessorsNames() : null, ]; } } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/FixerFactoryTest.php
tests/AutoReview/FixerFactoryTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\Fixer\FixerInterface; use PhpCsFixer\FixerFactory; use PhpCsFixer\Preg; use PhpCsFixer\Tests\Test\IntegrationCaseFactory; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Finder\SplFileInfo; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @coversNothing * * @group auto-review * @group covers-nothing * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FixerFactoryTest extends TestCase { public function testFixersPriorityEdgeFixers(): void { $factory = new FixerFactory(); $factory->registerBuiltInFixers(); $fixers = $factory->getFixers(); foreach (self::getFixerWithFixedPosition() as $fixerName => $offset) { if ($offset < 0) { \assert(\array_key_exists(\count($fixers) + $offset, $fixers)); self::assertSame($fixerName, $fixers[\count($fixers) + $offset]->getName(), $fixerName); } else { \assert(\array_key_exists($offset, $fixers)); self::assertSame($fixerName, $fixers[$offset]->getName(), $fixerName); } } } public function testFixersPriority(): void { $fixers = self::getAllFixers(); $graphs = [ self::getFixersPriorityGraph(), self::getPhpDocFixersPriorityGraph(), ]; foreach ($graphs as $graph) { foreach ($graph as $fixerName => $edges) { \assert(\array_key_exists($fixerName, $fixers)); $first = $fixers[$fixerName]; foreach ($edges as $edge) { \assert(\array_key_exists($edge, $fixers)); $second = $fixers[$edge]; self::assertLessThan($first->getPriority(), $second->getPriority(), \sprintf('"%s" should have less priority than "%s"', $edge, $fixerName)); } } } } /** * @param list<string> $edges * * @dataProvider provideFixersPriorityCasesHaveIntegrationTestCases */ public function testFixersPriorityCasesHaveIntegrationTest(string $fixerName, array $edges): void { $forPerformanceEdgesOnly = [ 'function_to_constant' => [ 'native_function_casing' => true, ], 'no_unused_imports' => [ 'no_leading_import_slash' => true, ], 'no_useless_sprintf' => [ 'native_function_casing' => true, ], 'pow_to_exponentiation' => [ 'method_argument_space' => true, 'native_function_casing' => true, 'no_spaces_after_function_name' => true, 'no_spaces_inside_parenthesis' => true, 'spaces_inside_parentheses' => true, ], ]; $missingIntegrationsTests = []; foreach ($edges as $edge) { if (isset($forPerformanceEdgesOnly[$fixerName][$edge])) { continue; } $file = self::getIntegrationPriorityDirectory().$fixerName.','.$edge.'.test'; if (!is_file($file)) { $missingIntegrationsTests[] = $file; continue; } $file = realpath($file); self::assertIsString($file); $factory = new IntegrationCaseFactory(); $test = $factory->create(new SplFileInfo($file, './', __DIR__)); $rules = $test->getRuleset()->getRules(); $expected = [$fixerName, $edge]; $actual = array_keys($rules); sort($expected); sort($actual); self::assertSame( \sprintf('Integration of fixers: %s,%s.', $fixerName, $edge), $test->getTitle(), \sprintf('Please fix the title in "%s".', $file), ); self::assertCount(2, $rules, \sprintf('Only the two rules that are tested for priority should be in the ruleset of "%s".', $file)); foreach ($rules as $name => $config) { self::assertNotFalse($config, \sprintf('The rule "%s" in "%s" may not be disabled for the test.', $name, $file)); } self::assertSame($expected, $actual, \sprintf('The ruleset of "%s" must contain the rules for the priority test.', $file)); } self::assertCount(0, $missingIntegrationsTests, \sprintf("There shall be an integration test. How do you know that priority set up is good, if there is no integration test to check it?\nMissing:\n- %s", implode("\n- ", $missingIntegrationsTests))); } /** * @return iterable<string, array{string, list<string>}> */ public static function provideFixersPriorityCasesHaveIntegrationTestCases(): iterable { foreach (self::getFixersPriorityGraph() as $fixerName => $edges) { yield $fixerName => [$fixerName, $edges]; } } /** * @dataProvider providePriorityIntegrationTestFilesAreListedInPriorityGraphCases */ public function testPriorityIntegrationTestFilesAreListedInPriorityGraph(\SplFileInfo $file): void { $fileName = $file->getFilename(); self::assertTrue($file->isFile(), \sprintf('Expected only files in the priority integration test directory, got "%s".', $fileName)); self::assertFalse($file->isLink(), \sprintf('No (sym)links expected the priority integration test directory, got "%s".', $fileName)); self::assertTrue( Preg::match('#^([a-z][a-z0-9_]*),([a-z][a-z_]*)(?:_\d{1,3})?\.test(-(in|out)\.php)?$#', $fileName, $matches), \sprintf('File with unexpected name "%s" in the priority integration test directory.', $fileName), ); [, $fixerName1, $fixerName2] = $matches; $graph = self::getFixersPriorityGraph(); self::assertTrue( isset($graph[$fixerName1]) && \in_array($fixerName2, $graph[$fixerName1], true), \sprintf('Missing priority test entry for file "%s".', $fileName), ); } /** * @return iterable<int, array{\DirectoryIterator}> */ public static function providePriorityIntegrationTestFilesAreListedInPriorityGraphCases(): iterable { foreach (new \DirectoryIterator(self::getIntegrationPriorityDirectory()) as $candidate) { if (!$candidate->isDot()) { yield [clone $candidate]; } } } public function testFixersPriorityGraphIsSorted(): void { $previous = ''; foreach (self::getFixersPriorityGraph() as $fixerName => $edges) { self::assertLessThan(0, $previous <=> $fixerName, \sprintf('Not sorted "%s" "%s".', $previous, $fixerName)); $edgesSorted = $edges; sort($edgesSorted); self::assertSame($edgesSorted, $edges, \sprintf('Fixer "%s" edges are not sorted', $fixerName)); $previous = $fixerName; } } public function testFixersPriorityComment(): void { $fixersPhpDocIssues = []; $fixers = []; foreach (self::getAllFixers() as $name => $fixer) { $reflection = new \ReflectionObject($fixer); $fixers[$name] = ['reflection' => $reflection, 'short_classname' => $reflection->getShortName()]; } $mergedGraph = array_merge_recursive( self::getFixersPriorityGraph(), self::getPhpDocFixersPriorityGraph(), ); // expend $graph $graph = []; foreach ($mergedGraph as $fixerName => $edges) { if (!isset($graph[$fixerName]['before'])) { $graph[$fixerName] = ['before' => []]; } foreach ($mergedGraph as $candidateFixer => $candidateEdges) { if (\in_array($fixerName, $candidateEdges, true)) { $graph[$fixerName]['after'][$candidateFixer] = true; } } foreach ($edges as $edge) { if (!isset($graph[$edge]['after'])) { $graph[$edge] = ['after' => []]; } $graph[$edge]['after'][$fixerName] = true; $graph[$fixerName]['before'][$edge] = true; } } foreach ($graph as $fixerName => $edges) { \assert(\array_key_exists($fixerName, $fixers)); $expectedMessage = "/**\n * {@inheritdoc}\n *"; foreach ($edges as $label => $others) { if (\count($others) > 0) { $shortClassNames = []; foreach ($others as $other => $true) { \assert(\array_key_exists($other, $fixers)); $shortClassNames[$other] = $fixers[$other]['short_classname']; } sort($shortClassNames); $expectedMessage .= \sprintf("\n * Must run %s %s.", $label, implode(', ', $shortClassNames)); } } $expectedMessage .= "\n */"; $method = $fixers[$fixerName]['reflection']->getMethod('getPriority'); $phpDoc = $method->getDocComment(); if (false === $phpDoc) { $fixersPhpDocIssues[$fixerName] = \sprintf("PHPDoc for %s::getPriority is missing.\nExpected:\n%s", $fixers[$fixerName]['short_classname'], $expectedMessage); } elseif ($expectedMessage !== $phpDoc) { $fixersPhpDocIssues[$fixerName] = \sprintf("PHPDoc for %s::getPriority is not as expected.\nExpected:\n%s", $fixers[$fixerName]['short_classname'], $expectedMessage); } } if (0 === \count($fixersPhpDocIssues)) { $this->addToAssertionCount(1); } else { $message = \sprintf("There are %d priority PHPDoc issues found.\n", \count($fixersPhpDocIssues)); ksort($fixersPhpDocIssues); foreach ($fixersPhpDocIssues as $fixerName => $issue) { $message .= \sprintf("\n--------------------------------------------------\n[%s] %s", $fixerName, $issue); } self::fail($message); } } public function testFixerWithNoneDefaultPriorityIsTested(): void { $knownIssues = [ // should only shrink 'no_trailing_comma_in_singleline_function_call' => true, // had prio case but no longer, left prio the same for BC reasons, rule has been deprecated 'simple_to_complex_string_variable' => true, // had prio case but no longer, left prio the same for BC reasons 'visibility_required' => true, // deprecated, legacy name of `ModifierKeywordsFixer` ]; $factory = new FixerFactory(); $factory->registerBuiltInFixers(); $fixers = $factory->getFixers(); $fixerNamesWithTests = array_map(static fn () => true, self::getFixerWithFixedPosition()); foreach ([ self::getFixersPriorityGraph(), self::getPhpDocFixersPriorityGraph(), ] as $set) { foreach ($set as $fixerName => $edges) { $fixerNamesWithTests[$fixerName] = true; foreach ($edges as $edge) { $fixerNamesWithTests[$edge] = true; } } } $missing = []; foreach ($fixers as $fixer) { $fixerName = $fixer->getName(); if (0 !== $fixer->getPriority() && !isset($fixerNamesWithTests[$fixerName])) { $missing[$fixerName] = true; } } foreach ($knownIssues as $knownIssue => $true) { if (isset($missing[$knownIssue])) { unset($missing[$knownIssue]); } else { self::fail(\sprintf('No longer found known issue "%s", please update the set.', $knownIssue)); } } self::assertEmpty($missing, 'Fixers with non-default priority and yet without priority unit tests [vide "getFixersPriorityGraph()" and "getPhpDocFixersPriorityGraph()"]: "'.implode('", "', array_keys($missing)).'."'); } /** * @return array<string, list<string>> */ private static function getFixersPriorityGraph(): array { return [ 'align_multiline_comment' => [ 'phpdoc_trim_consecutive_blank_line_separation', ], 'array_indentation' => [ 'align_multiline_comment', 'binary_operator_spaces', ], 'array_syntax' => [ 'binary_operator_spaces', 'single_space_after_construct', 'single_space_around_construct', 'ternary_operator_spaces', ], 'assign_null_coalescing_to_coalesce_equal' => [ 'binary_operator_spaces', 'no_whitespace_in_blank_line', ], 'backtick_to_shell_exec' => [ 'explicit_string_variable', 'native_function_invocation', 'single_quote', ], 'blank_line_after_opening_tag' => [ 'blank_lines_before_namespace', 'no_blank_lines_before_namespace', ], 'braces' => [ 'heredoc_indentation', ], 'braces_position' => [ 'single_line_empty_body', 'statement_indentation', ], 'class_attributes_separation' => [ 'braces', 'indentation_type', 'no_extra_blank_lines', 'statement_indentation', ], 'class_definition' => [ 'braces', 'single_line_empty_body', ], 'class_keyword' => [ 'fully_qualified_strict_types', ], 'class_keyword_remove' => [ 'no_unused_imports', ], 'clean_namespace' => [ 'php_unit_data_provider_return_type', ], 'combine_consecutive_issets' => [ 'multiline_whitespace_before_semicolons', 'no_singleline_whitespace_before_semicolons', 'no_spaces_inside_parenthesis', 'no_trailing_whitespace', 'no_whitespace_in_blank_line', 'spaces_inside_parentheses', ], 'combine_consecutive_unsets' => [ 'no_extra_blank_lines', 'no_trailing_whitespace', 'no_whitespace_in_blank_line', 'space_after_semicolon', ], 'combine_nested_dirname' => [ 'method_argument_space', 'no_spaces_inside_parenthesis', 'spaces_inside_parentheses', ], 'control_structure_braces' => [ 'braces_position', 'control_structure_continuation_position', 'curly_braces_position', 'no_multiple_statements_per_line', ], 'curly_braces_position' => [ 'single_line_empty_body', 'statement_indentation', ], 'declare_strict_types' => [ 'blank_line_after_opening_tag', 'declare_equal_normalize', 'header_comment', ], 'dir_constant' => [ 'combine_nested_dirname', ], 'doctrine_annotation_array_assignment' => [ 'doctrine_annotation_spaces', ], 'echo_tag_syntax' => [ 'no_mixed_echo_print', ], 'empty_loop_body' => [ 'braces', 'no_extra_blank_lines', 'no_trailing_whitespace', ], 'empty_loop_condition' => [ 'no_extra_blank_lines', 'no_trailing_whitespace', ], 'escape_implicit_backslashes' => [ 'heredoc_to_nowdoc', 'single_quote', ], 'explicit_string_variable' => [ 'no_useless_concat_operator', ], 'final_class' => [ 'protected_to_private', 'self_static_accessor', ], 'final_internal_class' => [ 'protected_to_private', 'self_static_accessor', ], 'fully_qualified_strict_types' => [ 'no_superfluous_phpdoc_tags', 'ordered_attributes', 'ordered_imports', 'ordered_interfaces', 'statement_indentation', ], 'function_declaration' => [ 'method_argument_space', ], 'function_to_constant' => [ 'native_constant_invocation', 'native_function_casing', 'no_extra_blank_lines', 'no_singleline_whitespace_before_semicolons', 'no_trailing_whitespace', 'no_whitespace_in_blank_line', 'self_static_accessor', ], 'general_phpdoc_annotation_remove' => [ 'no_empty_phpdoc', 'phpdoc_line_span', 'phpdoc_separation', 'phpdoc_trim', ], 'general_phpdoc_tag_rename' => [ 'phpdoc_add_missing_param_annotation', ], 'get_class_to_class_keyword' => [ 'multiline_whitespace_before_semicolons', ], 'global_namespace_import' => [ 'no_unused_imports', 'ordered_imports', 'statement_indentation', ], 'header_comment' => [ 'blank_lines_before_namespace', 'single_blank_line_before_namespace', 'single_line_comment_style', ], 'implode_call' => [ 'method_argument_space', ], 'increment_style' => [ 'no_spaces_inside_parenthesis', 'spaces_inside_parentheses', ], 'indentation_type' => [ 'phpdoc_indent', ], 'is_null' => [ 'yoda_style', ], 'lambda_not_used_import' => [ 'method_argument_space', 'no_spaces_inside_parenthesis', 'spaces_inside_parentheses', ], 'list_syntax' => [ 'binary_operator_spaces', 'ternary_operator_spaces', ], 'long_to_shorthand_operator' => [ 'binary_operator_spaces', 'no_extra_blank_lines', 'no_singleline_whitespace_before_semicolons', 'standardize_increment', ], 'mb_str_functions' => [ 'native_function_invocation', ], 'method_argument_space' => [ 'array_indentation', 'statement_indentation', ], 'modernize_strpos' => [ 'binary_operator_spaces', 'no_extra_blank_lines', 'no_spaces_inside_parenthesis', 'no_trailing_whitespace', 'not_operator_with_space', 'not_operator_with_successor_space', 'php_unit_dedicate_assert', 'single_space_after_construct', 'single_space_around_construct', 'spaces_inside_parentheses', ], 'modernize_types_casting' => [ 'no_unneeded_control_parentheses', ], 'modifier_keywords' => [ 'class_attributes_separation', ], 'multiline_promoted_properties' => [ 'braces_position', 'trailing_comma_in_multiline', ], 'multiline_string_to_heredoc' => [ 'escape_implicit_backslashes', 'heredoc_indentation', 'string_implicit_backslashes', ], 'multiline_whitespace_before_semicolons' => [ 'space_after_semicolon', ], 'native_constant_invocation' => [ 'global_namespace_import', ], 'native_function_invocation' => [ 'global_namespace_import', ], 'new_with_braces' => [ 'class_definition', ], 'new_with_parentheses' => [ 'class_definition', 'new_expression_parentheses', ], 'no_alias_functions' => [ 'implode_call', 'php_unit_dedicate_assert', ], 'no_alternative_syntax' => [ 'braces', 'elseif', 'no_superfluous_elseif', 'no_unneeded_control_parentheses', 'no_useless_else', 'switch_continue_to_break', ], 'no_binary_string' => [ 'no_useless_concat_operator', 'php_unit_dedicate_assert_internal_type', 'regular_callable_call', 'set_type_to_cast', ], 'no_blank_lines_after_phpdoc' => [ 'header_comment', ], 'no_empty_comment' => [ 'no_extra_blank_lines', 'no_trailing_whitespace', 'no_whitespace_in_blank_line', ], 'no_empty_phpdoc' => [ 'no_extra_blank_lines', 'no_trailing_whitespace', ], 'no_empty_statement' => [ 'braces', 'combine_consecutive_unsets', 'empty_loop_body', 'multiline_whitespace_before_semicolons', 'no_extra_blank_lines', 'no_multiple_statements_per_line', 'no_singleline_whitespace_before_semicolons', 'no_trailing_whitespace', 'no_useless_else', 'no_useless_return', 'no_whitespace_in_blank_line', 'return_assignment', 'space_after_semicolon', 'switch_case_semicolon_to_colon', ], 'no_extra_blank_lines' => [ 'blank_line_before_statement', ], 'no_leading_import_slash' => [ 'ordered_imports', ], 'no_multiline_whitespace_around_double_arrow' => [ 'binary_operator_spaces', 'method_argument_space', ], 'no_multiple_statements_per_line' => [ 'braces_position', 'curly_braces_position', ], 'no_php4_constructor' => [ 'ordered_class_elements', ], 'no_short_bool_cast' => [ 'cast_spaces', ], 'no_space_around_double_colon' => [ 'method_chaining_indentation', ], 'no_spaces_after_function_name' => [ 'function_to_constant', 'get_class_to_class_keyword', ], 'no_spaces_inside_parenthesis' => [ 'function_to_constant', 'get_class_to_class_keyword', 'string_length_to_empty', ], 'no_superfluous_elseif' => [ 'simplified_if_return', ], 'no_superfluous_phpdoc_tags' => [ 'no_empty_phpdoc', 'void_return', ], 'no_unneeded_braces' => [ 'no_useless_else', 'no_useless_return', 'return_assignment', 'simplified_if_return', ], 'no_unneeded_control_parentheses' => [ 'concat_space', 'new_expression_parentheses', 'no_trailing_whitespace', ], 'no_unneeded_curly_braces' => [ 'no_useless_else', 'no_useless_return', 'return_assignment', 'simplified_if_return', ], 'no_unneeded_import_alias' => [ 'no_singleline_whitespace_before_semicolons', ], 'no_unset_cast' => [ 'binary_operator_spaces', ], 'no_unset_on_property' => [ 'combine_consecutive_unsets', ], 'no_unused_imports' => [ 'blank_line_after_namespace', 'no_extra_blank_lines', 'no_leading_import_slash', 'single_line_after_imports', ], 'no_useless_concat_operator' => [ 'date_time_create_from_format_call', 'ereg_to_preg', 'php_unit_dedicate_assert_internal_type', 'regular_callable_call', 'set_type_to_cast', ], 'no_useless_else' => [ 'blank_line_before_statement', 'braces', 'combine_consecutive_unsets', 'no_break_comment', 'no_extra_blank_lines', 'no_trailing_whitespace', 'no_useless_return', 'no_whitespace_in_blank_line', 'simplified_if_return', 'statement_indentation', ], 'no_useless_printf' => [ 'echo_tag_syntax', 'no_extra_blank_lines', 'no_mixed_echo_print', ], 'no_useless_return' => [ 'blank_line_before_statement', 'no_extra_blank_lines', 'no_whitespace_in_blank_line', 'single_line_comment_style', 'single_line_empty_body', ], 'no_useless_sprintf' => [ 'method_argument_space', 'native_function_casing', 'no_empty_statement', 'no_extra_blank_lines', 'no_spaces_inside_parenthesis', 'spaces_inside_parentheses', ], 'nullable_type_declaration' => [ 'ordered_types', 'types_spaces', ], 'nullable_type_declaration_for_default_null_value' => [ 'no_unreachable_default_argument_value', 'nullable_type_declaration', 'ordered_types', ], 'ordered_class_elements' => [ 'class_attributes_separation', 'no_blank_lines_after_class_opening', 'php_unit_data_provider_method_order', 'space_after_semicolon', ], 'ordered_imports' => [ 'blank_line_between_import_groups', ], 'ordered_types' => [ 'types_spaces', ], 'php_unit_attributes' => [ 'fully_qualified_strict_types', 'no_empty_phpdoc', 'phpdoc_separation', 'phpdoc_trim', 'phpdoc_trim_consecutive_blank_line_separation', ], 'php_unit_construct' => [ 'php_unit_dedicate_assert', ], 'php_unit_data_provider_method_order' => [ 'class_attributes_separation', 'no_blank_lines_after_class_opening', ], 'php_unit_data_provider_return_type' => [ 'return_to_yield_from', 'return_type_declaration', ], 'php_unit_dedicate_assert' => [ 'no_unused_imports', 'php_unit_assert_new_names', 'php_unit_dedicate_assert_internal_type', ], 'php_unit_fqcn_annotation' => [ 'no_unused_imports', 'phpdoc_order_by_value', ], 'php_unit_internal_class' => [ 'final_internal_class', 'phpdoc_separation', ], 'php_unit_namespaced' => [ 'no_unneeded_import_alias', ], 'php_unit_no_expectation_annotation' => [ 'no_empty_phpdoc', 'php_unit_expectation', ], 'php_unit_size_class' => [ 'php_unit_attributes', 'phpdoc_separation', ], 'php_unit_test_annotation' => [ 'no_empty_phpdoc', 'php_unit_method_casing', 'phpdoc_trim', ], 'php_unit_test_case_static_method_calls' => [ 'self_static_accessor', ], 'php_unit_test_class_requires_covers' => [ 'php_unit_attributes', 'phpdoc_separation', ], 'phpdoc_add_missing_param_annotation' => [ 'no_empty_phpdoc', 'no_superfluous_phpdoc_tags', 'phpdoc_align', 'phpdoc_order', ], 'phpdoc_array_type' => [ 'phpdoc_list_type', 'phpdoc_types_order', ], 'phpdoc_line_span' => [ 'no_superfluous_phpdoc_tags', ], 'phpdoc_list_type' => [ 'phpdoc_types_order', ], 'phpdoc_no_access' => [ 'no_empty_phpdoc', 'phpdoc_separation', 'phpdoc_trim', ], 'phpdoc_no_alias_tag' => [ 'phpdoc_add_missing_param_annotation', 'phpdoc_single_line_var_spacing', ], 'phpdoc_no_empty_return' => [ 'no_empty_phpdoc', 'phpdoc_separation', 'phpdoc_trim', ], 'phpdoc_no_package' => [ 'no_empty_phpdoc', 'phpdoc_separation', 'phpdoc_trim', ], 'phpdoc_no_useless_inheritdoc' => [ 'no_empty_phpdoc', 'no_trailing_whitespace_in_comment', ], 'phpdoc_order' => [ 'phpdoc_separation', 'phpdoc_trim', ], 'phpdoc_readonly_class_comment_to_keyword' => [ 'no_empty_phpdoc', 'no_extra_blank_lines', 'phpdoc_align', ], 'phpdoc_return_self_reference' => [ 'no_superfluous_phpdoc_tags', ], 'phpdoc_scalar' => [ 'phpdoc_to_return_type', ], 'phpdoc_to_comment' => [ 'no_empty_comment', 'phpdoc_no_useless_inheritdoc', 'single_line_comment_spacing', 'single_line_comment_style', ], 'phpdoc_to_param_type' => [ 'no_superfluous_phpdoc_tags', ], 'phpdoc_to_property_type' => [ 'fully_qualified_strict_types', 'no_superfluous_phpdoc_tags', ], 'phpdoc_to_return_type' => [ 'fully_qualified_strict_types', 'no_superfluous_phpdoc_tags', 'return_to_yield_from', 'return_type_declaration', ], 'phpdoc_types' => [ 'phpdoc_to_return_type', ], 'pow_to_exponentiation' => [ 'binary_operator_spaces', 'method_argument_space', 'native_function_casing', 'no_spaces_after_function_name', 'no_spaces_inside_parenthesis', 'spaces_inside_parentheses', ], 'protected_to_private' => [ 'ordered_class_elements', 'static_private_method', ],
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
true
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/BinEntryFileTest.php
tests/AutoReview/BinEntryFileTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\Tests\TestCase; /** * @author Victor Bocharsky <bocharsky.bw@gmail.com> * * @internal * * @coversNothing * * @group auto-review * @group covers-nothing * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class BinEntryFileTest extends TestCase { public function testSupportedPhpVersions(): void { $phpVersionIdLines = []; $file = new \SplFileObject(__DIR__.'/../../php-cs-fixer'); while (!$file->eof()) { $line = $file->fgets(); if (str_contains($line, 'PHP_VERSION_ID')) { $phpVersionIdLines[] = $line; } } // Unset the file to call __destruct(), closing the file handle. $file = null; self::assertEqualsCanonicalizing([ ' if (\PHP_VERSION_ID === (int) \'80000\') { // TODO use 8_00_00 once only PHP 7.4+ is supported by this entry file'."\n", ' if (\PHP_VERSION_ID < (int) \'70400\') {'."\n", ], $phpVersionIdLines, 'Seems supported PHP versions changed in "./php-cs-fixer" - edit the README.md (and this test file) to match them!'); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/CiConfigurationTest.php
tests/AutoReview/CiConfigurationTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\ConfigInterface; use PhpCsFixer\Preg; use PhpCsFixer\Tests\Test\CiReader; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\Tokenizer\Tokens; use PHPUnit\Framework\Constraint\TraversableContainsIdentical; use Symfony\Component\Yaml\Yaml; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @coversNothing * * @group auto-review * @group covers-nothing * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CiConfigurationTest extends TestCase { public function testThatPhpVersionEnvsAreSetProperly(): void { self::assertSame( [ 'PHP_MAX' => $this->getMaxPhpVersionFromEntryFile(), 'PHP_MIN' => $this->getMinPhpVersionFromEntryFile(), ], CiReader::getGitHubCiEnvs(), ); } public function testTestJobsRunOnEachPhp(): void { $supportedMinPhp = (float) $this->getMinPhpVersionFromEntryFile(); $supportedMaxPhp = (float) $this->getMaxPhpVersionFromEntryFile(); $supportedVersions = self::generateMinorVersionsRange($supportedMinPhp, $supportedMaxPhp); self::assertTrue(\count($supportedVersions) > 0); $ciVersions = CiReader::getAllPhpBuildsUsedByCiForTests(); self::assertNotEmpty($ciVersions); self::assertSupportedPhpVersionsAreCoveredByCiJobs($supportedVersions, $ciVersions); self::assertUpcomingPhpVersionIsCoveredByCiJob(end($supportedVersions), $ciVersions); self::assertSupportedPhpVersionsAreCoveredByCiJobs($supportedVersions, $this->getPhpVersionsUsedForBuildingOfficialImages()); self::assertSupportedPhpVersionsAreCoveredByCiJobs($supportedVersions, $this->getPhpVersionsUsedForBuildingLocalImages()); self::assertPhpCompatibilityRangeIsValid($supportedMinPhp, $supportedMaxPhp); } public function testDeploymentJobRunOnLatestStablePhpThatIsSupportedByTool(): void { $ciVersionsForDeployment = CiReader::getPhpVersionUsedByCiForDeployments(); $ciVersions = CiReader::getAllPhpVersionsUsedByCiForTests(); $expectedPhp = $this->getMaxPhpVersionFromEntryFile(); if (\in_array($expectedPhp.'snapshot', $ciVersions, true)) { // last version of used PHP is snapshot. we should test against previous one, that is stable $expectedPhp = (string) ((float) $expectedPhp - 0.1); } if (str_starts_with($ciVersionsForDeployment, '$')) { self::assertSame('${{ needs.setup.outputs.PHP_MAX }}', $ciVersionsForDeployment); } else { self::assertTrue( version_compare($expectedPhp, $ciVersionsForDeployment, 'eq'), \sprintf('Expects %s to be %s', $ciVersionsForDeployment, $expectedPhp), ); } } public function testDockerCIBuildsComposeServices(): void { $compose = Yaml::parseFile(__DIR__.'/../../compose.yaml'); $composeServices = array_keys($compose['services']); sort($composeServices); $ci = Yaml::parseFile(__DIR__.'/../../.github/workflows/docker.yml'); $ciServices = array_map( static fn ($item) => $item['docker-service'], $ci['jobs']['docker-compose-build']['strategy']['matrix']['include'], ); sort($ciServices); self::assertSame($composeServices, $ciServices); } public static function testThatAlpineVersionsAreInSync(): void { $yaml = Yaml::parseFile(__DIR__.'/../../.github/workflows/release.yml'); $releaseMap = []; foreach ($yaml['jobs']['docker-images']['strategy']['matrix']['include'] as $item) { $releaseMap[$item['php-version']] = $item['alpine-version']; } $yaml = Yaml::parseFile(__DIR__.'/../../compose.yaml'); $dockerMap = []; foreach ($yaml['services'] as $item) { if (isset($item['build']['args']['PHP_VERSION'], $item['build']['args']['ALPINE_VERSION'])) { // @TODO uncomment and adjust me when new development PHP version is added // // PHP 8.x at this point is only allowed for local development and is not a part of Docker releases // if (str_starts_with($item['build']['args']['PHP_VERSION'], '8.x')) { // continue; // } $dockerMap[$item['build']['args']['PHP_VERSION']] = $item['build']['args']['ALPINE_VERSION']; } } self::assertSame($dockerMap, $releaseMap, 'Expects release.yml and compose.yaml to use same Alpine versions for same PHP versions.'); Preg::matchAll( '/(?:ALPINE_VERSION=|alpine:)(\d+\.\d+)/', (string) file_get_contents(__DIR__.'/../../Dockerfile'), $dockerVersions, ); $dockerVersions = $dockerVersions[1]; self::assertCount(2, $dockerVersions); self::assertSame($dockerVersions[0], $dockerVersions[1], 'Expects both Alpine versions in Dockerfile to be the same.'); natsort($dockerMap); $alpineHighestVersion = end($dockerMap); self::assertSame($alpineHighestVersion, $dockerVersions[0], 'Expects Alpine version used in Dockerfile to be highest Alpine version used in compose.yaml.'); } /** * @return list<numeric-string> */ private static function generateMinorVersionsRange(float $from, float $to): array { $range = []; $lastMinorVersions = [7.4]; $version = $from; while ($version <= $to) { $range[] = \sprintf('%.1f', $version); if (\in_array($version, $lastMinorVersions, true)) { $version = ceil($version); } else { $version += 0.1; } } return $range; } private static function ensureTraversableContainsIdenticalIsAvailable(): void { if (!class_exists(TraversableContainsIdentical::class)) { self::markTestSkipped('TraversableContainsIdentical not available.'); } } /** * @param numeric-string $lastSupportedVersion * @param list<string> $ciVersions */ private static function assertUpcomingPhpVersionIsCoveredByCiJob(string $lastSupportedVersion, array $ciVersions): void { self::ensureTraversableContainsIdenticalIsAvailable(); self::assertThat($ciVersions, self::logicalOr( // if `$lastsupportedVersion` is already a snapshot version new TraversableContainsIdentical(\sprintf('%.1fsnapshot', $lastSupportedVersion)), // if `$lastsupportedVersion` is not snapshot version, expect CI to run snapshot of next PHP version new TraversableContainsIdentical('nightly'), new TraversableContainsIdentical(\sprintf('%.1fsnapshot', $lastSupportedVersion + 0.1)), // GitHub CI uses just versions, without suffix, e.g. 8.1 for 8.1snapshot as of writing new TraversableContainsIdentical(\sprintf('%.1f', $lastSupportedVersion + 0.1)), new TraversableContainsIdentical(\sprintf('%.1f', floor($lastSupportedVersion + 1.0))), )); } /** * @param list<numeric-string> $supportedVersions * @param array<array-key, string> $ciVersions */ private static function assertSupportedPhpVersionsAreCoveredByCiJobs(array $supportedVersions, array $ciVersions): void { $lastSupportedVersion = array_pop($supportedVersions); foreach ($supportedVersions as $expectedVersion) { self::assertContains($expectedVersion, $ciVersions); } self::ensureTraversableContainsIdenticalIsAvailable(); self::assertThat($ciVersions, self::logicalOr( new TraversableContainsIdentical($lastSupportedVersion), new TraversableContainsIdentical(\sprintf('%.1fsnapshot', $lastSupportedVersion)), )); } private static function assertPhpCompatibilityRangeIsValid(float $supportedMinPhp, float $supportedMaxPhp): void { $matchResult = Preg::match( '/<config name="testVersion" value="(?<min>\d+\.\d+)-(?<max>\d+\.\d+)"\/>/', (string) file_get_contents(__DIR__.'/../../dev-tools/php-compatibility/phpcs-php-compatibility.xml'), $capture, ); if (!$matchResult) { throw new \LogicException('Can\'t parse PHP version range for verifying compatibility.'); } self::assertSame($supportedMinPhp, (float) $capture['min']); self::assertSame($supportedMaxPhp, (float) $capture['max']); } private function convertPhpVerIdToNiceVer(string $verId): string { $matchResult = Preg::match('/^(?<major>\d{1,2})_?(?<minor>\d{2})_?(?<patch>\d{2})$/', $verId, $capture); if (!$matchResult) { throw new \LogicException(\sprintf('Can\'t parse version "%s" id.', $verId)); } return \sprintf('%d.%d', $capture['major'], $capture['minor']); } private function getMaxPhpVersionFromEntryFile(): string { return ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED; } private function getMinPhpVersionFromEntryFile(): string { $tokens = Tokens::fromCode((string) file_get_contents(__DIR__.'/../../php-cs-fixer')); $sequence = $tokens->findSequence([ [\T_STRING, 'PHP_VERSION_ID'], '<', [\T_INT_CAST], [\T_CONSTANT_ENCAPSED_STRING], ]); if (null === $sequence) { throw new \LogicException("Can't find version - perhaps entry file was modified?"); } $phpVerId = trim(end($sequence)->getContent(), '\''); return $this->convertPhpVerIdToNiceVer($phpVerId); } /** * @return array<array-key, string> */ private function getPhpVersionsUsedForBuildingOfficialImages(): array { $yaml = Yaml::parseFile(__DIR__.'/../../.github/workflows/release.yml'); return array_map( static fn ($item) => $item['php-version'], $yaml['jobs']['docker-images']['strategy']['matrix']['include'], ); } /** * @return array<array-key, string> */ private function getPhpVersionsUsedForBuildingLocalImages(): array { $yaml = Yaml::parseFile(__DIR__.'/../../.github/workflows/docker.yml'); return array_map( static fn ($item) => substr($item, 4), array_filter( array_map( static fn ($item) => $item['docker-service'], $yaml['jobs']['docker-compose-build']['strategy']['matrix']['include'], ), static fn ($item) => str_starts_with($item, 'php-'), ), ); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/TransformerTest.php
tests/AutoReview/TransformerTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\Tokenizer\TransformerInterface; use PhpCsFixer\Tokenizer\Transformers; /** * @author Dave van der Brugge <dmvdbrugge@gmail.com> * * @internal * * @coversNothing * * @group auto-review * @group covers-nothing * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TransformerTest extends TestCase { /** * @dataProvider provideTransformerPriorityCases */ public function testTransformerPriority(TransformerInterface $first, TransformerInterface $second): void { self::assertLessThan( $first->getPriority(), $second->getPriority(), \sprintf('"%s" should have less priority than "%s"', \get_class($second), \get_class($first)), ); } /** * @return iterable<int, array{TransformerInterface, TransformerInterface}> */ public static function provideTransformerPriorityCases(): iterable { $transformers = []; foreach (self::provideTransformerPriorityIsListedCases() as [$transformer]) { $transformers[$transformer->getName()] = $transformer; } \assert(\array_key_exists('array_typehint', $transformers)); \assert(\array_key_exists('attribute', $transformers)); \assert(\array_key_exists('brace', $transformers)); \assert(\array_key_exists('brace_class_instantiation', $transformers)); \assert(\array_key_exists('disjunctive_normal_form_type_parenthesis', $transformers)); \assert(\array_key_exists('import', $transformers)); \assert(\array_key_exists('name_qualified', $transformers)); \assert(\array_key_exists('named_argument', $transformers)); \assert(\array_key_exists('namespace_operator', $transformers)); \assert(\array_key_exists('nullable_type', $transformers)); \assert(\array_key_exists('return_ref', $transformers)); \assert(\array_key_exists('square_brace', $transformers)); \assert(\array_key_exists('type_alternation', $transformers)); \assert(\array_key_exists('type_colon', $transformers)); \assert(\array_key_exists('type_intersection', $transformers)); \assert(\array_key_exists('use', $transformers)); yield [$transformers['attribute'], $transformers['brace']]; yield [$transformers['attribute'], $transformers['square_brace']]; yield [$transformers['brace'], $transformers['brace_class_instantiation']]; yield [$transformers['brace'], $transformers['import']]; yield [$transformers['brace'], $transformers['use']]; yield [$transformers['name_qualified'], $transformers['namespace_operator']]; yield [$transformers['return_ref'], $transformers['import']]; yield [$transformers['return_ref'], $transformers['type_colon']]; yield [$transformers['square_brace'], $transformers['brace_class_instantiation']]; yield [$transformers['type_colon'], $transformers['named_argument']]; yield [$transformers['type_colon'], $transformers['nullable_type']]; yield [$transformers['array_typehint'], $transformers['type_alternation']]; yield [$transformers['type_colon'], $transformers['type_alternation']]; yield [$transformers['array_typehint'], $transformers['type_intersection']]; yield [$transformers['type_colon'], $transformers['type_intersection']]; yield [$transformers['type_alternation'], $transformers['disjunctive_normal_form_type_parenthesis']]; yield [$transformers['use'], $transformers['type_colon']]; } /** * @dataProvider provideTransformerPriorityIsListedCases */ public function testTransformerPriorityIsListed(TransformerInterface $transformer): void { $priority = $transformer->getPriority(); if (0 === $priority) { $this->expectNotToPerformAssertions(); return; } $name = $transformer->getName(); foreach (self::provideTransformerPriorityCases() as $pair) { [$first, $second] = $pair; if ($name === $first->getName() || $name === $second->getName()) { $this->addToAssertionCount(1); return; } } self::fail(\sprintf('Transformer "%s" has priority %d but is not in priority test list.', $name, $priority)); } /** * @return iterable<int, array{TransformerInterface}> */ public static function provideTransformerPriorityIsListedCases(): iterable { static $transformersArray = null; if (null === $transformersArray) { $transformersArray = []; foreach (\Closure::bind(static fn (Transformers $transformers): iterable => $transformers->findBuiltInTransformers(), null, Transformers::class)(Transformers::createSingleton()) as $transformer) { $transformersArray[] = [$transformer]; } } return $transformersArray; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/CommandTest.php
tests/AutoReview/CommandTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\Console\Application; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Console\Command\Command; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @coversNothing * * @group auto-review * @group covers-nothing * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CommandTest extends TestCase { /** * @dataProvider provideCommandHasNameConstCases */ public function testCommandHasNameConst(Command $command): void { self::assertNotNull($command::getDefaultName()); } /** * @return iterable<int, array{Command}> */ public static function provideCommandHasNameConstCases(): iterable { $application = new Application(); $commands = $application->all(); $names = array_filter( array_keys($commands), // @phpstan-ignore-next-line offsetAccess.notFound is not an alias and is our command static fn (string $name): bool => !\in_array($name, $commands[$name]->getAliases(), true) && str_starts_with(\get_class($commands[$name]), 'PhpCsFixer\\'), ); // @phpstan-ignore-next-line offsetAccess.notFound return array_map(static fn (string $name): array => [$commands[$name]], $names); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/ComposerFileTest.php
tests/AutoReview/ComposerFileTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\Tests\TestCase; /** * @internal * * @coversNothing * * @group covers-nothing * @group auto-review * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ComposerFileTest extends TestCase { public function testScriptsHaveDescriptions(): void { $composerJson = self::readComposerJson(); self::assertArrayHasKey('scripts', $composerJson); self::assertArrayHasKey('scripts-descriptions', $composerJson); $scripts = array_keys($composerJson['scripts']); $descriptions = array_keys($composerJson['scripts-descriptions']); self::assertSame([], array_diff($scripts, $descriptions), 'There should be no scripts with missing description.'); self::assertSame([], array_diff($descriptions, $scripts), 'There should be no superfluous description for not defined scripts.'); } public function testScriptsAliasesDescriptionsFollowThePattern(): void { $composerJson = self::readComposerJson(); self::assertArrayHasKey('scripts', $composerJson); self::assertArrayHasKey('scripts-descriptions', $composerJson); $scripts = array_keys($composerJson['scripts']); $aliases = array_reduce( $scripts, // @phpstan-ignore-next-line argument.type static function (array $carry, string $script) use ($composerJson): array { $code = $composerJson['scripts'][$script]; if (\is_string($code) && '@' === $code[0]) { $potentialAlias = substr($code, 1); if (isset($composerJson['scripts'][$potentialAlias])) { $carry[$script] = $potentialAlias; } } return $carry; }, [], ); foreach ($aliases as $code => $alias) { self::assertSame( "Alias for '{$alias}'", $composerJson['scripts-descriptions'][$code], "Script description for '{$code}' alias should be following the pattern.", ); } } /** * @return array<string, mixed> */ private static function readComposerJson(): array { $composerJsonContent = (string) file_get_contents(__DIR__.'/../../composer.json'); return json_decode($composerJsonContent, true, 512, \JSON_THROW_ON_ERROR); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/ProjectFixerConfigurationTest.php
tests/AutoReview/ProjectFixerConfigurationTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\Config; use PhpCsFixer\Console\ConfigurationResolver; use PhpCsFixer\Fixer\InternalFixerInterface; use PhpCsFixer\RuleSet\RuleSets; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\ToolInfo; /** * @internal * * @coversNothing * * @group auto-review * @group covers-nothing * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ProjectFixerConfigurationTest extends TestCase { protected function tearDown(): void { parent::tearDown(); // Reset the global state of RuleSets::$customRuleSetDefinitions that was modified // when using `.php-cs-fixer.dist.php`, which registers custom rules/sets. // // @TODO: ideally, we don't have the global state but inject the state instead \Closure::bind( static fn () => RuleSets::$customRuleSetDefinitions = [], null, RuleSets::class, )(); } public function testCreate(): void { $config = $this->loadConfig(); self::assertContainsOnlyInstancesOf(InternalFixerInterface::class, $config->getCustomFixers()); self::assertNotEmpty($config->getRules()); // call so the fixers get configured to reveal issue (like deprecated configuration used etc.) $resolver = new ConfigurationResolver( $config, [], __DIR__, new ToolInfo(), ); $resolver->getFixers(); } public function testRuleDefinedAlpha(): void { $rules = $rulesSorted = array_keys($this->loadConfig()->getRules()); natcasesort($rulesSorted); self::assertSame($rulesSorted, $rules, 'Please sort the "rules" in `.php-cs-fixer.dist.php` of this project.'); } private function loadConfig(): Config { return require __DIR__.'/../Fixtures/.php-cs-fixer.one-time-proxy.php'; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/DocumentationTest.php
tests/AutoReview/DocumentationTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\Console\Report\FixReport\ReporterFactory; use PhpCsFixer\Documentation\DocumentationLocator; use PhpCsFixer\Documentation\FixerDocumentGenerator; use PhpCsFixer\Documentation\RuleSetDocumentationGenerator; use PhpCsFixer\Fixer\FixerInterface; use PhpCsFixer\FixerFactory; use PhpCsFixer\Preg; use PhpCsFixer\RuleSet\RuleSets; use PhpCsFixer\Tests\TestCase; use Symfony\Component\Finder\Finder; /** * @internal * * @coversNothing * * @group legacy * @group auto-review * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DocumentationTest extends TestCase { /** * @dataProvider provideFixerDocumentationFileIsUpToDateCases */ public function testFixerDocumentationFileIsUpToDate(FixerInterface $fixer): void { if ('ordered_imports' === $fixer->getName()) { $this->expectDeprecation('[ordered_imports] Option "sort_algorithm:length" is deprecated and will be removed in version 4.0.'); } if ('nullable_type_declaration_for_default_null_value' === $fixer->getName()) { $this->expectDeprecation('Option "use_nullable_type_declaration" for rule "nullable_type_declaration_for_default_null_value" is deprecated and will be removed in version 4.0. Behaviour will follow default one.'); } $locator = new DocumentationLocator(); $generator = new FixerDocumentGenerator($locator); $path = $locator->getFixerDocumentationFilePath($fixer); self::assertFileExists($path); $expected = $generator->generateFixerDocumentation($fixer); $actual = file_get_contents($path); self::assertIsString($actual); $expected = Preg::replaceCallback( '/ # an example (?<before> Example\ \#\d\n ~+\n \n (?:\*Default\*\ configuration\.\n\n)? (?:With\ configuration:.*?\n\n)? ) # with a diff that could not be generated \.\.\ error::\n \ \ \ Cannot\ generate\ diff\ for\ code\ sample\ \#\d\ of\ rule\ .+?:\n \ \ \ the\ sample\ is\ not\ suitable\ for\ current\ version\ of\ PHP\ \(.+?\).\n # followed by another title or end of file (?<after> \n [^ \n].*? \n |$ ) /x', static function (array $matches) use ($actual): string { /** @var array{before: string, after: string} $matches */ $before = preg_quote($matches['before'], '/'); $after = preg_quote($matches['after'], '/'); $replacement = '[UNAVAILABLE EXAMPLE DIFF]'; if (Preg::match("/{$before}(\\.\\. code-block:: diff.*?){$after}/s", $actual, $actualMatches)) { \assert(\array_key_exists(1, $actualMatches)); $replacement = $actualMatches[1]; } return $matches['before'].$replacement.$matches['after']; }, $expected, ); self::assertSame($expected, $actual); } /** * @return iterable<string, array{FixerInterface}> */ public static function provideFixerDocumentationFileIsUpToDateCases(): iterable { foreach (self::getFixers() as $fixer) { yield $fixer->getName() => [$fixer]; } } public function testFixersDocumentationIndexFileIsUpToDate(): void { $locator = new DocumentationLocator(); $generator = new FixerDocumentGenerator($locator); self::assertFileEqualsString( $generator->generateFixersDocumentationIndex(self::getFixers()), $locator->getFixersDocumentationIndexFilePath(), ); } public function testFixersDocumentationDirectoryHasNoExtraFiles(): void { $generator = new DocumentationLocator(); self::assertCount( \count(self::getFixers()) + 1, (new Finder())->files()->in($generator->getFixersDocumentationDirectoryPath()), ); } public function testRuleSetsDocumentationIsUpToDate(): void { $locator = new DocumentationLocator(); $generator = new RuleSetDocumentationGenerator($locator); $fixers = self::getFixers(); $paths = []; foreach (RuleSets::getBuiltInSetDefinitions() as $name => $definition) { $path = $locator->getRuleSetsDocumentationFilePath($name); $paths[$path] = $definition; self::assertFileEqualsString( $generator->generateRuleSetsDocumentation($definition, $fixers), $path, \sprintf('RuleSet documentation is generated (please see CONTRIBUTING.md), file "%s".', $path), ); } $indexFilePath = $locator->getRuleSetsDocumentationIndexFilePath(); self::assertFileEqualsString( $generator->generateRuleSetsDocumentationIndex($paths), $indexFilePath, \sprintf('RuleSet documentation is generated (please CONTRIBUTING.md), file "%s".', $indexFilePath), ); } public function testRuleSetsDocumentationDirectoryHasNoExtraFiles(): void { $generator = new DocumentationLocator(); self::assertCount( \count(RuleSets::getBuiltInSetDefinitions()) + 1, (new Finder())->files()->in($generator->getRuleSetsDocumentationDirectoryPath()), ); } public function testInstallationDocHasCorrectMinimumVersion(): void { $composerJsonContent = (string) file_get_contents(__DIR__.'/../../composer.json'); $composerJson = json_decode($composerJsonContent, true, 512, \JSON_THROW_ON_ERROR); $phpVersion = $composerJson['require']['php']; $minimumVersion = ltrim(substr($phpVersion, 0, (int) strpos($phpVersion, ' ')), '^'); $minimumVersionInformation = \sprintf('PHP needs to be a minimum version of PHP %s.', $minimumVersion); $installationDocPath = realpath(__DIR__.'/../../doc/installation.rst'); self::assertIsString($installationDocPath); self::assertStringContainsString( $minimumVersionInformation, (string) file_get_contents($installationDocPath), \sprintf('Files %s needs to contain information "%s"', $installationDocPath, $minimumVersionInformation), ); } public function testCiIntegrationSampleMatches(): void { $locator = new DocumentationLocator(); $usage = $locator->getUsageFilePath(); self::assertFileExists($usage); $usage = file_get_contents($usage); self::assertIsString($usage); $expectedCiIntegrationContent = file_get_contents(__DIR__.'/../../doc/examples/ci-integration.sh'); self::assertIsString($expectedCiIntegrationContent); $expectedCiIntegrationContent = trim(str_replace(['#!/bin/sh', 'set -eu'], ['', ''], $expectedCiIntegrationContent)); $expectedCiIntegrationContent = ' '.implode("\n ", explode("\n", $expectedCiIntegrationContent)); self::assertStringContainsString($expectedCiIntegrationContent, $usage); } public function testAllReportFormatsAreInUsageDoc(): void { $locator = new DocumentationLocator(); $usage = $locator->getUsageFilePath(); self::assertFileExists($usage); $usage = file_get_contents($usage); self::assertIsString($usage); $reporterFactory = new ReporterFactory(); $reporterFactory->registerBuiltInReporters(); $formats = array_filter( $reporterFactory->getFormats(), static fn (string $format): bool => 'txt' !== $format, ); foreach ($formats as $format) { self::assertStringContainsString(\sprintf('* ``%s``', $format), $usage); } $lastFormat = array_pop($formats); $expectedContent = 'Supported formats are ``@auto`` (default one on v4+), ``txt`` (default one on v3), '; foreach ($formats as $format) { $expectedContent .= '``'.$format.'``, '; } $expectedContent = substr($expectedContent, 0, -2); $expectedContent .= ' and ``'.$lastFormat.'``.'; self::assertStringContainsString($expectedContent, $usage); } private static function assertFileEqualsString(string $expectedString, string $actualFilePath, string $message = ''): void { self::assertFileExists($actualFilePath, $message); self::assertSame($expectedString, file_get_contents($actualFilePath), $message); } /** * @return list<FixerInterface> */ private static function getFixers(): array { $fixerFactory = new FixerFactory(); $fixerFactory->registerBuiltInFixers(); return $fixerFactory->getFixers(); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/AutoReview/ProjectCodeTest.php
tests/AutoReview/ProjectCodeTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\AutoReview; use PhpCsFixer\AbstractFixer; use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; use PhpCsFixer\AbstractPhpdocTypesFixer; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\Console\Command\FixCommand; use PhpCsFixer\Console\Command\InitCommand; use PhpCsFixer\Console\Internal\Command\ParseCommand; use PhpCsFixer\DocBlock\Annotation; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\Documentation\DocumentationTag; use PhpCsFixer\Documentation\DocumentationTagGenerator; use PhpCsFixer\Fixer\AbstractPhpUnitFixer; use PhpCsFixer\Fixer\ConfigurableFixerTrait; use PhpCsFixer\Fixer\PhpUnit\PhpUnitNamespacedFixer; use PhpCsFixer\FixerConfiguration\AliasedFixerOptionBuilder; use PhpCsFixer\FixerFactory; use PhpCsFixer\Preg; use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; use PhpCsFixer\RuleSet\DeprecatedRuleSetDescriptionInterface; use PhpCsFixer\Runner\Parallel\ProcessUtils; use PhpCsFixer\Tests\Fixer\ClassNotation\ModifierKeywordsFixerTest; use PhpCsFixer\Tests\PregTest; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; use PhpCsFixer\Tests\Test\AbstractIntegrationTestCase; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\Tests\Tokenizer\CTTest; use PhpCsFixer\Tests\Tokenizer\FCTTest; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Tokenizer\TokensAnalyzer; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @coversNothing * * @group auto-review * @group covers-nothing * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ProjectCodeTest extends TestCase { /** * @var null|array<string, array{class-string<TestCase>}> */ private static ?array $testClassCases = null; /** * @var null|array<string, array{class-string}> */ private static ?array $srcClassCases = null; /** * @var null|array<string, array{class-string, string}> */ private static ?array $dataProviderMethodCases = null; /** * @var null|array<string, array{class-string, string}> */ private static ?array $phpUnitInheritedMethodsCases = null; /** * @var array<class-string, Tokens> */ private static array $tokensCache = []; public static function tearDownAfterClass(): void { self::$srcClassCases = null; self::$testClassCases = null; self::$tokensCache = []; parent::tearDownAfterClass(); } /** * @dataProvider provideThatSrcClassHaveTestClassCases */ public function testThatSrcClassHaveTestClass(string $className): void { \assert(class_exists($className)); // It is OK for deprecated ruleset to have no tests, as it would be only proxy to renamed ruleset. if (\in_array(DeprecatedRuleSetDefinitionInterface::class, class_implements($className), true)) { $this->expectNotToPerformAssertions(); return; } $testClassName = 'PhpCsFixer\Tests'.substr($className, 10).'Test'; $exceptions = [ InitCommand::class, DocumentationTag::class, DocumentationTagGenerator::class, ]; // we allow exceptions to _not_ follow the rule, // but when they are ready to start following it - we shall remove them from exceptions list if (\in_array($className, $exceptions, true)) { self::assertFalse(class_exists($testClassName)); return; } self::assertTrue(class_exists($testClassName), \sprintf('Expected test class "%s" for "%s" not found.', $testClassName, $className)); } /** * @return iterable<int, array{string}> */ public static function provideThatSrcClassHaveTestClassCases(): iterable { return array_map( static fn (string $item): array => [$item], array_filter( self::getSrcClasses(), static function (string $className): bool { $rc = new \ReflectionClass($className); return !$rc->isTrait() && !$rc->isAbstract() && !$rc->isInterface() && \count($rc->getMethods(\ReflectionMethod::IS_PUBLIC)) > 0; }, ), ); } /** * This test requires 8.2+, so it can properly detect readonly parent class. * * @dataProvider provideSrcClassCases * * @param class-string $className * * @requires PHP 8.2 */ public function testThatSrcClassesAreReadonlyWhenPossible(string $className): void { $rc = new \ReflectionClass($className); $rcProperties = $rc->getProperties(); if (0 === \count($rcProperties)) { $this->addToAssertionCount(1); return; // public properties present, no need for class to be readonly } if (\PHP_VERSION_ID >= 8_02_00) { if ($rc->isReadOnly()) { $this->addToAssertionCount(1); return; // Class is readonly, no need for further checks } $parentClass = $rc->getParentClass(); if (false !== $parentClass && !$parentClass->isReadOnly()) { $this->addToAssertionCount(1); return; // Parent class is _not_ readonly, child class cannot be readonly in such case } } $rc = new \ReflectionClass($className); $docComment = $rc->getDocComment(); $doc = new DocBlock(false !== $docComment ? $docComment : '/** */'); $readonly = \count($doc->getAnnotationsOfType('readonly')) > 0; $exceptions = [ AliasedFixerOptionBuilder::class, ]; // we allow exceptions to _not_ follow the rule, // but when they are ready to start following it - we shall remove them from exceptions list if (\in_array($className, $exceptions, true)) { self::assertFalse($readonly); return; } if ($readonly) { $this->addToAssertionCount(1); return; // already readonly } $tokens = $this->createTokensForClass($className); $constructorSequence = $tokens->findSequence([ [\T_FUNCTION], [\T_STRING, '__construct'], '(', ]); if (null !== $constructorSequence) { $tokens = clone $tokens; $openIndex = $tokens->getNextTokenOfKind(array_key_last($constructorSequence), ['{']); $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openIndex); $tokens->overrideRange($openIndex + 1, $closeIndex - 1, []); } $tokensContent = $tokens->generateCode(); $propertyNames = array_map(static fn (\ReflectionProperty $item) => $item->getName(), $rcProperties); $overrideFound = Preg::match( '/(?:self::\$|static::\$|\$this->)(?:'.implode('|', $propertyNames).')(?:\[[^=]*\])?\s*(?:=|(?:\?\?=))/', $tokensContent, ); if ($overrideFound) { $this->addToAssertionCount(1); return; // properties are mutable during lifecycle of instance, class is not readonly } self::fail( \sprintf('The class "%s" should have readonly annotation.', $className), ); } /** * @dataProvider provideThatSrcClassesNotAbuseInterfacesCases * * @param class-string $className */ public function testThatSrcClassesNotAbuseInterfaces(string $className): void { $rc = new \ReflectionClass($className); $allowedMethods = array_map( fn (\ReflectionClass $interface): array => $this->getPublicMethodNames($interface), $rc->getInterfaces(), ); if (\count($allowedMethods) > 0) { $allowedMethods = array_unique(array_merge(...array_values($allowedMethods))); } $allowedMethods[] = '__construct'; $allowedMethods[] = '__destruct'; $allowedMethods[] = '__wakeup'; $exceptionMethods = [ 'configure', // due to AbstractFixer::configure 'getConfigurationDefinition', // due to AbstractFixer::getConfigurationDefinition 'getDefaultConfiguration', // due to AbstractFixer::getDefaultConfiguration 'setWhitespacesConfig', // due to AbstractFixer::setWhitespacesConfig 'createConfigurationDefinition', // due to AbstractProxyFixer calling `createConfigurationDefinition` of proxied rule ]; $definedMethods = $this->getPublicMethodNames($rc); $extraMethods = array_diff( $definedMethods, $allowedMethods, $exceptionMethods, ); sort($extraMethods); self::assertEmpty( $extraMethods, \sprintf( "Class '%s' should not have public methods that are not part of implemented interfaces.\nViolations:\n%s", $className, implode("\n", array_map(static fn (string $item): string => " * {$item}", $extraMethods)), ), ); } /** * @return iterable<int, array{string}> */ public static function provideThatSrcClassesNotAbuseInterfacesCases(): iterable { return array_map( static fn (string $item): array => [$item], array_filter(self::getSrcClasses(), static function (string $className): bool { $rc = new \ReflectionClass($className); $doc = false !== $rc->getDocComment() ? new DocBlock($rc->getDocComment()) : null; if ( $rc->isInterface() || (null !== $doc && \count($doc->getAnnotationsOfType('internal')) > 0) || \in_array($className, [ \PhpCsFixer\Finder::class, AbstractFixerTestCase::class, AbstractIntegrationTestCase::class, Tokens::class, ], true) ) { return false; } $interfaces = $rc->getInterfaces(); $interfacesCount = \count($interfaces); if (0 === $interfacesCount) { return false; } if (1 === $interfacesCount) { $interface = reset($interfaces); if (\Stringable::class === $interface->getName()) { return false; } } return true; }), ); } /** * @dataProvider provideSrcClassCases * * @param class-string $className */ public function testThatSrcClassesNotExposeProperties(string $className): void { if (\in_array($className, [ DocumentationTag::class, // @TODO: change test to allow public readonly properties ], true)) { self::markTestIncomplete('This test does not know yet how to handle immutable Value Objects with read-only public properties.'); } $rc = new \ReflectionClass($className); self::assertEmpty( $rc->getProperties(\ReflectionProperty::IS_PUBLIC), \sprintf('Class \'%s\' should not have public properties.', $className), ); if ($rc->isFinal()) { return; } $allowedProps = []; $definedProps = $rc->getProperties(\ReflectionProperty::IS_PROTECTED); if (false !== $rc->getParentClass()) { $allowedProps = $rc->getParentClass()->getProperties(\ReflectionProperty::IS_PROTECTED); } $allowedProps = array_map(static fn (\ReflectionProperty $item): string => $item->getName(), $allowedProps); $definedProps = array_map(static fn (\ReflectionProperty $item): string => $item->getName(), $definedProps); $exceptionPropsPerClass = [ AbstractFixer::class => ['configuration', 'configurationDefinition', 'whitespacesConfig'], AbstractPhpdocToTypeDeclarationFixer::class => ['configuration'], AbstractPhpdocTypesFixer::class => ['tags'], AbstractProxyFixer::class => ['proxyFixers'], ConfigurableFixerTrait::class => ['configuration'], FixCommand::class => ['defaultDescription', 'defaultName'], // @TODO: PHP 8.0+, remove properties and test when PHP 8+ is required ]; $extraProps = array_diff( $definedProps, $allowedProps, $exceptionPropsPerClass[$className] ?? [], ); sort($extraProps); self::assertEmpty( $extraProps, \sprintf( "Class '%s' should not have protected properties.\nViolations:\n%s", $className, implode("\n", array_map(static fn (string $item): string => " * {$item}", $extraProps)), ), ); } /** * @dataProvider provideTestClassCases */ public function testThatTestClassExtendsPhpCsFixerTestCaseClass(string $className): void { self::assertTrue(is_subclass_of($className, TestCase::class), \sprintf('Expected test class "%s" to be a subclass of "%s".', $className, TestCase::class)); } /** * @dataProvider provideTestClassCases * * @param class-string<TestCase> $testClassName */ public function testThatTestClassesAreTraitOrAbstractOrFinal(string $testClassName): void { $rc = new \ReflectionClass($testClassName); $exceptionClasses = [ // @TODO 4.0 remove while removing legacy `VisibilityRequiredFixer` ModifierKeywordsFixerTest::class, ]; self::assertTrue( $rc->isTrait() || $rc->isAbstract() || $rc->isFinal() || \in_array($testClassName, $exceptionClasses, true), \sprintf('Test class %s should be trait, abstract or final.', $testClassName), ); } /** * @dataProvider provideTestClassCases * * @param class-string<TestCase> $testClassName */ public function testThatTestClassesAreInternal(string $testClassName): void { $rc = new \ReflectionClass($testClassName); $doc = new DocBlock((string) $rc->getDocComment()); self::assertNotEmpty( $doc->getAnnotationsOfType('internal'), \sprintf('Test class %s should have internal annotation.', $testClassName), ); } /** * @dataProvider provideTestClassCases * * @param class-string<TestCase> $testClassName */ public function testThatTestClassesPublicMethodsAreCorrectlyNamed(string $testClassName): void { $reflectionClass = new \ReflectionClass($testClassName); $publicMethods = array_filter( $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC), static fn (\ReflectionMethod $reflectionMethod): bool => $reflectionMethod->getDeclaringClass()->getName() === $reflectionClass->getName(), ); if ([] === $publicMethods) { $this->expectNotToPerformAssertions(); // no methods to test, all good! return; } foreach ($publicMethods as $method) { self::assertMatchesRegularExpression( '/^(test|expect|provide|setUpBeforeClass$|tearDownAfterClass$|__construct$)/', $method->getName(), \sprintf('Public method "%s::%s" is not properly named.', $reflectionClass->getName(), $method->getName()), ); } } /** * @dataProvider provideDataProviderMethodCases * * @param class-string<TestCase> $testClassName */ public function testThatTestDataProvidersAreUsed(string $testClassName, string $dataProviderName): void { $usedDataProviderMethodNames = []; foreach ($this->getUsedDataProviderMethodNames($testClassName) as $providerName) { $usedDataProviderMethodNames[] = $providerName; } self::assertContains( $dataProviderName, $usedDataProviderMethodNames, \sprintf('Data provider "%s::%s" is not used.', $testClassName, $dataProviderName), ); } /** * @dataProvider provideDataProviderMethodCases */ public function testThatTestDataProvidersAreCorrectlyNamed(string $testClassName, string $dataProviderName): void { self::assertMatchesRegularExpression('/^provide[A-Z]\S+Cases$/', $dataProviderName, \sprintf( 'Data provider "%s::%s" is not correctly named.', $testClassName, $dataProviderName, )); } /** * @dataProvider provideTestClassCases * * @param class-string<TestCase> $testClassName */ public function testThatTestClassCoversAreCorrect(string $testClassName): void { $reflectionClass = new \ReflectionClass($testClassName); if ($reflectionClass->isAbstract() || $reflectionClass->isInterface()) { $this->expectNotToPerformAssertions(); return; } $doc = $reflectionClass->getDocComment(); self::assertNotFalse($doc); if (Preg::match('/@coversNothing/', $doc)) { return; } $covers = Preg::matchAll('/@covers (\S*)/', $doc, $matches); self::assertGreaterThanOrEqual(1, $covers, \sprintf('Missing @covers in PHPDoc of test class "%s".', $testClassName)); array_shift($matches); /** @var class-string $class */ $class = '\\'.str_replace('PhpCsFixer\Tests\\', 'PhpCsFixer\\', substr($testClassName, 0, -4)); $parentClass = (new \ReflectionClass($class))->getParentClass(); $parentClassName = false === $parentClass ? null : '\\'.$parentClass->getName(); foreach ($matches as $match) { $classMatch = array_shift($match); self::assertTrue( $classMatch === $class || $parentClassName === $classMatch, \sprintf('Unexpected @covers "%s" for "%s".', $classMatch, $testClassName), ); } } /** * @dataProvider provideSrcClassCases * @dataProvider provideTestClassCases * * @param class-string $className */ public function testThereIsNoUsageOfDefined(string $className): void { if (\in_array($className, [ CTTest::class, FCTTest::class, ParseCommand::class, ], true)) { $this->expectNotToPerformAssertions(); return; } self::assertNotContains( 'defined', $this->extractFunctionNamesCalledInClass($className), \sprintf('Class %s must not use "defined()", use "%s" to use newly introduced Token kinds.', $className, FCT::class), ); } /** * @dataProvider provideSrcClassCases * @dataProvider provideTestClassCases * * @param class-string $className */ public function testThereIsNoUsageOfExtract(string $className): void { $calledFunctions = $this->extractFunctionNamesCalledInClass($className); $message = \sprintf('Class %s must not use "extract()", explicitly extract only the keys that are needed - you never know what\'s else inside.', $className); self::assertNotContains('extract', $calledFunctions, $message); } /** * @dataProvider provideSrcClassCases * @dataProvider provideTestClassCases * * @param class-string $className */ public function testThereIsNoUsageOfJsonLastError(string $className): void { $calledFunctions = $this->extractFunctionNamesCalledInClass($className); $message = \sprintf('Class %s must not use "json_last_error()" nor "json_last_error_msg()", explicitly replace it to handle errors with "JSON_ERROR_NONE".', $className); self::assertNotContains('json_last_error', $calledFunctions, $message); self::assertNotContains('json_last_error_msg', $calledFunctions, $message); } /** * @dataProvider provideThereIsNoPregFunctionUsedDirectlyCases * * @param class-string $className */ public function testThereIsNoPregFunctionUsedDirectly(string $className): void { if (\in_array($className, [ ProcessUtils::class, // code copied from Symfony, we do not want to make custom adjustments there ], true)) { $this->expectNotToPerformAssertions(); return; } $calledFunctions = $this->extractFunctionNamesCalledInClass($className); $message = \sprintf('Class %s must not use preg_*, it shall use Preg::* instead.', $className); self::assertNotContains('preg_filter', $calledFunctions, $message); self::assertNotContains('preg_grep', $calledFunctions, $message); self::assertNotContains('preg_match', $calledFunctions, $message); self::assertNotContains('preg_match_all', $calledFunctions, $message); self::assertNotContains('preg_replace', $calledFunctions, $message); self::assertNotContains('preg_replace_callback', $calledFunctions, $message); self::assertNotContains('preg_split', $calledFunctions, $message); } /** * @return iterable<string, array{string}> */ public static function provideThereIsNoPregFunctionUsedDirectlyCases(): iterable { foreach (self::getSrcClasses() as $className) { if (Preg::class === $className) { continue; } yield $className => [$className]; } foreach (self::getTestsDirectoryClasses('*.php') as $className) { if (PregTest::class === $className) { continue; } yield $className => [$className]; } } /** * @dataProvider provideTestClassCases * * @param class-string $className */ public function testThereIsNoUsageOfSetAccessible(string $className): void { $calledFunctions = $this->extractFunctionNamesCalledInClass($className); $message = \sprintf('Class %s must not use "setAccessible()", use "Closure::bind()" instead.', $className); self::assertNotContains('setAccessible', $calledFunctions, $message); } /** * @dataProvider provideTestClassCases * * @param class-string<TestCase> $className */ public function testNoPHPUnitMockUsed(string $className): void { $calledFunctions = $this->extractFunctionNamesCalledInClass($className); $message = \sprintf('Class %s must not use PHPUnit\'s mock, it shall use anonymous class instead.', $className); self::assertNotContains('getMockBuilder', $calledFunctions, $message); self::assertNotContains('createMock', $calledFunctions, $message); self::assertNotContains('createMockForIntersectionOfInterfaces', $calledFunctions, $message); self::assertNotContains('createPartialMock', $calledFunctions, $message); self::assertNotContains('createTestProxy', $calledFunctions, $message); self::assertNotContains('getMockForAbstractClass', $calledFunctions, $message); self::assertNotContains('getMockFromWsdl', $calledFunctions, $message); self::assertNotContains('getMockForTrait', $calledFunctions, $message); self::assertNotContains('getMockClass', $calledFunctions, $message); self::assertNotContains('createConfiguredMock', $calledFunctions, $message); self::assertNotContains('getObjectForTrait', $calledFunctions, $message); } /** * @dataProvider provideTestClassCases * * @param class-string<TestCase> $testClassName */ public function testExpectedInputOrder(string $testClassName): void { $reflectionClass = new \ReflectionClass($testClassName); $publicMethods = array_filter( $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC), static fn (\ReflectionMethod $reflectionMethod): bool => $reflectionMethod->getDeclaringClass()->getName() === $reflectionClass->getName(), ); if ([] === $publicMethods) { $this->expectNotToPerformAssertions(); // no methods to test, all good! return; } foreach ($publicMethods as $method) { $parameters = $method->getParameters(); if (0 === \count($parameters)) { $this->addToAssertionCount(1); // not enough parameters to test, all good! continue; } $parameterNames = array_map( static fn (\ReflectionParameter $item): string => $item->getName(), $parameters, ); $parameterNamesToPosition = 0 === \count($parameterNames) ? [] : array_combine($parameterNames, range(0, \count($parameterNames) - 1)); if ( isset($parameterNamesToPosition['expected'], $parameterNamesToPosition['input']) ) { self::assertLessThan( $parameterNamesToPosition['input'], $parameterNamesToPosition['expected'], \sprintf('Public method "%s::%s" shall have parameter \'input\' after \'expected\'.', $reflectionClass->getName(), $method->getName()), ); } else { $this->addToAssertionCount(1); // not enough parameters to test, all good! } if ( $reflectionClass->isSubclassOf(AbstractFixerTestCase::class) && str_starts_with($method->getName(), 'testFix') ) { $expectedTestFixPotentialParamsOrder = ['expected', 'input', 'configuration', 'file', 'whitespacesConfig']; self::assertSame( [], array_diff($parameterNames, $expectedTestFixPotentialParamsOrder), \sprintf('Public method "%s::%s" has unexpected parameters.', $reflectionClass->getName(), $method->getName()), ); self::assertSame( array_values(array_intersect($expectedTestFixPotentialParamsOrder, $parameterNames)), $parameterNames, \sprintf('Public method "%s::%s" has invalid parameters order.', $reflectionClass->getName(), $method->getName()), ); } } } /** * @dataProvider provideDataProviderMethodCases * * @param class-string<TestCase> $testClassName * @param non-empty-string $dataProviderName */ public function testDataProvidersAreNonPhpVersionConditional(string $testClassName, string $dataProviderName): void { $tokens = $this->createTokensForClass($testClassName); $tokensAnalyzer = new TokensAnalyzer($tokens); $dataProviderElements = array_filter($tokensAnalyzer->getClassyElements(), static function (array $v, int $k) use ($tokens, $dataProviderName) { $nextToken = $tokens[$tokens->getNextMeaningfulToken($k)]; // element is data provider method return 'method' === $v['type'] && $nextToken->equals([\T_STRING, $dataProviderName]); }, \ARRAY_FILTER_USE_BOTH); if (1 !== \count($dataProviderElements)) { throw new \UnexpectedValueException(\sprintf('Data provider "%s::%s" should be found exactly once, got %d times.', $testClassName, $dataProviderName, \count($dataProviderElements))); } $methodIndex = array_key_first($dataProviderElements); $startIndex = $tokens->getNextTokenOfKind($methodIndex, ['{']); $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex); $versionTokens = array_filter($tokens->findGivenKind(\T_STRING, $startIndex, $endIndex), static fn (Token $v): bool => $v->equalsAny([ [\T_STRING, 'PHP_VERSION_ID'], [\T_STRING, 'PHP_MAJOR_VERSION'], [\T_STRING, 'PHP_MINOR_VERSION'], [\T_STRING, 'PHP_RELEASE_VERSION'], [\T_STRING, 'phpversion'], ], false)); self::assertCount( 0, $versionTokens, \sprintf( 'Data provider "%s::%s" should not check PHP version and provide different cases depends on it. It leads to situation when DataProvider provides "sometimes 10, sometimes 11" test cases, depends on PHP version. That makes John Doe to see "you run 10/10" and thinking all tests are executed, instead of actually seeing "you run 10/11 and 1 skipped".', $testClassName, $dataProviderName, ), ); } /** * @dataProvider provideDataProviderMethodCases */ public function testDataProvidersDeclaredReturnType(string $testClassName, string $dataProviderName): void { $dataProvider = new \ReflectionMethod($testClassName, $dataProviderName); self::assertSame('iterable', $dataProvider->hasReturnType() && $dataProvider->getReturnType() instanceof \ReflectionNamedType ? $dataProvider->getReturnType()->getName() : null, \sprintf('Data provider "%s::%s" must provide `iterable` as return in method prototype.', $testClassName, $dataProviderName)); $doc = new DocBlock(false !== $dataProvider->getDocComment() ? $dataProvider->getDocComment() : '/** */'); $returnDocs = $doc->getAnnotationsOfType('return'); if (\count($returnDocs) > 1) { throw new \UnexpectedValueException(\sprintf('Multiple "%s::%s@return" annotations.', $testClassName, $dataProviderName)); } if (1 !== \count($returnDocs)) { $this->addToAssertionCount(1); // no @return annotation, all good! return; } $returnDoc = $returnDocs[0]; $content = $returnDoc->getContent(); self::assertMatchesRegularExpression('/iterable\</', $content, \sprintf('Data provider "%s::%s@return" must return iterable.', $testClassName, $dataProviderName)); self::assertMatchesRegularExpression('/iterable\<(?:(int|string|int\|string), )?(?:array\{|_PhpTokenArray)/', $content, \sprintf('Data provider "%s::%s@return" must return iterable of tuples (eg `iterable<string, array{string, string}>`).', $testClassName, $dataProviderName)); } /** * @dataProvider provideSrcClassCases * @dataProvider provideTestClassCases * * @param class-string $className */ public function testAllCodeContainSingleClassy(string $className): void { // @TODO v4 remove me @MARKER_deprecated_DeprecatedRuleSetDescriptionInterface if (\in_array( $className, [ DeprecatedRuleSetDescriptionInterface::class, // @phpstan-ignore class.notFound ], true, )) { self::markTestSkipped(\sprintf("Classy '%s' is deprecated alias and thus exception.", $className)); } $headerTypes = [ \T_ABSTRACT, \T_AS, \T_COMMENT, \T_DECLARE, \T_DOC_COMMENT, \T_FINAL, \T_LNUMBER, \T_NAMESPACE, \T_NS_SEPARATOR, \T_OPEN_TAG, \T_STRING, \T_USE, \T_WHITESPACE, FCT::T_READONLY, ]; $tokens = $this->createTokensForClass($className); $classyIndex = null; self::assertTrue($tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()), \sprintf('File for "%s" should contains a classy.', $className)); $count = \count($tokens); for ($index = 1; $index < $count; ++$index) { if ($tokens[$index]->isClassy()) { $classyIndex = $index; break; } if ($tokens[$index]->isGivenKind(FCT::T_ATTRIBUTE)) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); continue; } if (!$tokens[$index]->isGivenKind($headerTypes) && !$tokens[$index]->equalsAny([';', '=', '(', ')'])) {
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
true
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/RuleSetsTest.php
tests/RuleSet/RuleSetsTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; use PhpCsFixer\Preg; use PhpCsFixer\RuleSet\RuleSet; use PhpCsFixer\RuleSet\RuleSets; use PhpCsFixer\Tests\Fixtures\ExternalRuleSet\ExampleRuleSet; use PhpCsFixer\Tests\Test\CiReader; use PhpCsFixer\Tests\Test\TestCaseUtils; use PhpCsFixer\Tests\TestCase; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\RuleSet\RuleSets * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class RuleSetsTest extends TestCase { protected function setUp(): void { parent::setUp(); // Since we register custom rule sets statically, we need to clear custom rule sets between runs. // We don't need to clear the built-in rule sets, because they don't change between runs. \Closure::bind( static function (): void { RuleSets::$customRuleSetDefinitions = []; }, null, RuleSets::class, )(); } public function testGetSetDefinitionNames(): void { self::assertSame( array_keys(RuleSets::getSetDefinitions()), RuleSets::getSetDefinitionNames(), ); } public function testGetSetDefinitions(): void { $sets = RuleSets::getBuiltInSetDefinitions(); foreach ($sets as $name => $set) { self::assertIsString($name); self::assertStringStartsWith('@', $name); self::assertIsArray($set->getRules()); self::assertSame($set, RuleSets::getSetDefinition($name)); } } public function testGetUnknownSetDefinition(): void { $name = 'Unknown'; $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessageMatches(\sprintf('#^Set "%s" does not exist\.$#', $name)); RuleSets::getSetDefinition($name); } public function testThatPhpMigrationSetsAreDefinedForEachSupportedPhpVersion(): void { $supportedPhpVersions = CiReader::getAllPhpVersionsUsedByCiForTests(); $sets = RuleSets::getSetDefinitions(); self::assertNotEmpty($supportedPhpVersions); foreach ($supportedPhpVersions as $version) { foreach (['', ':risky'] as $suffix) { $setName = \sprintf('@PHP%sMigration%s', str_replace('.', 'x', $version), $suffix); // var_dump($setName); self::assertArrayHasKey($setName, $sets, \sprintf('Set "%s" is not defined.', $setName)); } } } /** * @dataProvider provideSetDefinitionNameCases */ public function testHasIntegrationTest(string $setDefinitionName): void { /** @TODO v4 remove deprecated sets */ $setsWithoutTests = [ '@PER-CS:risky', '@PER-CS', '@PER-CS1.0:risky', '@PER-CS1.0', '@PER-CS2.0:risky', '@PER-CS2.0', '@PER-CS3.0:risky', '@PER-CS3.0', '@PER:risky', '@PER', '@PHP5x6Migration:risky', '@PHP5x6Migration', '@PHP7x0Migration:risky', '@PHP7x0Migration', '@PHP7x1Migration:risky', '@PHP7x1Migration', '@PHP7x3Migration', '@PHP8x0Migration', '@PhpCsFixer:risky', '@PhpCsFixer', '@PHPUnit10x0Migration:risky', '@PHPUnit11x0Migration:risky', '@PHPUnit4x8Migration', '@PHPUnit5x5Migration:risky', '@PHPUnit7x5Migration:risky', '@PHPUnit8x4Migration:risky', '@PHPUnit9x1Migration:risky', '@PSR1', ]; if (\in_array($setDefinitionName, $setsWithoutTests, true)) { self::markTestIncomplete(\sprintf('Set "%s" has no integration test.', $setDefinitionName)); } // @TODO v4: remove me @MARKER_deprecated_migration_ruleset if (Preg::match('/^@PHP(Unit)?\d+Migration(:risky)?$/', $setDefinitionName)) { self::markTestSkipped(\sprintf('Set "%s" is deprecated and will be removed in next MAJOR.', $setDefinitionName)); } if (str_starts_with($setDefinitionName, '@auto')) { self::markTestSkipped(\sprintf('Set "%s" is automatic and it\'s definition depends on individual project.', $setDefinitionName)); } \assert(\array_key_exists($setDefinitionName, RuleSets::getSetDefinitions())); $setDefinition = RuleSets::getSetDefinitions()[$setDefinitionName]->getRules(); if (1 === \count($setDefinition) && str_starts_with($setDefinitionName, '@PHP') && str_starts_with(array_key_first($setDefinition), '@PHP') ) { self::markTestSkipped(\sprintf('Set "%s" only includes previous, no own rules to test.', $setDefinitionName)); } $setDefinitionFileNamePrefix = str_replace(':', '-', $setDefinitionName); $dir = __DIR__.'/../../tests/Fixtures/Integration/set'; $file = \sprintf('%s/%s.test', $dir, $setDefinitionFileNamePrefix); self::assertFileExists($file); self::assertFileExists(\sprintf('%s/%s.test-in.php', $dir, $setDefinitionFileNamePrefix)); self::assertFileExists(\sprintf('%s/%s.test-out.php', $dir, $setDefinitionFileNamePrefix)); $template = '--TEST-- Integration of %s. --RULESET-- {"%s": true} '; self::assertStringStartsWith( \sprintf($template, $setDefinitionName, $setDefinitionName), (string) file_get_contents($file), ); } /** * @dataProvider provideSetDefinitionNameCases */ public function testBuildInSetDefinitionNames(string $setName): void { self::assertStringStartsWith('@', $setName); } /** * @dataProvider provideSetDefinitionNameCases */ public function testSetDefinitionsAreSorted(string $setDefinitionName): void { \assert(\array_key_exists($setDefinitionName, RuleSets::getSetDefinitions())); $setDefinition = RuleSets::getSetDefinitions()[$setDefinitionName]->getRules(); $sortedSetDefinition = $setDefinition; $this->sort($sortedSetDefinition); self::assertSame($sortedSetDefinition, $setDefinition, \sprintf( 'Failed to assert that the set definition for "%s" is sorted by key.', $setDefinitionName, )); } /** * @return iterable<int, array{string}> */ public static function provideSetDefinitionNameCases(): iterable { $setDefinitionNames = RuleSets::getSetDefinitionNames(); return array_map(static fn (string $setDefinitionName): array => [$setDefinitionName], $setDefinitionNames); } public function testSetDefinitionsItselfIsSorted(): void { $setDefinition = array_keys(RuleSets::getSetDefinitions()); $sortedSetDefinition = $setDefinition; natsort($sortedSetDefinition); self::assertSame($sortedSetDefinition, $setDefinition); } /** * @dataProvider providePHPUnitMigrationTargetVersionsCases */ public function testPHPUnitMigrationTargetVersions(string $setName): void { $ruleSet = new RuleSet([$setName => true]); foreach ($ruleSet->getRules() as $ruleName => $ruleConfig) { $targetVersion = $ruleConfig['target'] ?? $this->getDefaultPHPUnitTargetOfRule($ruleName); if (null === $targetVersion) { // fixer does not have "target" option $this->addToAssertionCount(1); continue; } self::assertPHPUnitVersionIsLargestAllowed($setName, $ruleName, $targetVersion); } } /** * @return iterable<int, array{string}> */ public static function providePHPUnitMigrationTargetVersionsCases(): iterable { $setDefinitionNames = RuleSets::getSetDefinitionNames(); $setDefinitionPHPUnitMigrationNames = array_filter($setDefinitionNames, static fn (string $setDefinitionName): bool => Preg::match('/^@PHPUnit\d+Migration:risky$/', $setDefinitionName)); return array_map(static fn (string $setDefinitionName): array => [$setDefinitionName], $setDefinitionPHPUnitMigrationNames); } public function testRegisteringRulesetMultipleTimesCausesAnException(): void { RuleSets::registerCustomRuleSet(new ExampleRuleSet()); self::expectException(\InvalidArgumentException::class); RuleSets::registerCustomRuleSet(new ExampleRuleSet()); } public function testCanReadCustomRegisteredRuleSet(): void { RuleSets::registerCustomRuleSet(new ExampleRuleSet()); $set = RuleSets::getSetDefinition('@Vendor/RuleSet'); self::assertSame('@Vendor/RuleSet', $set->getName()); } private static function assertPHPUnitVersionIsLargestAllowed(string $setName, string $ruleName, string $actualTargetVersion): void { $maximumVersionForRuleset = Preg::replace('/^@PHPUnit(\d+)(\d)Migration:risky$/', '$1.$2', $setName); $fixer = TestCaseUtils::getFixerByName($ruleName); self::assertInstanceOf(ConfigurableFixerInterface::class, $fixer, \sprintf('The fixer "%s" shall be configurable.', $fixer->getName())); foreach ($fixer->getConfigurationDefinition()->getOptions() as $option) { if ('target' === $option->getName()) { /** @var non-empty-list<PhpUnitTargetVersion::VERSION_*> */ $allowedValues = $option->getAllowedValues(); $allowedVersionsForFixer = array_diff( $allowedValues, [PhpUnitTargetVersion::VERSION_NEWEST], ); break; } } if (!isset($allowedVersionsForFixer)) { throw new \Exception(\sprintf('The fixer "%s" does not have option "target".', $fixer->getName())); } /** @var list<PhpUnitTargetVersion::VERSION_*> */ $allowedVersionsForRuleset = array_filter( $allowedVersionsForFixer, static fn (string $version): bool => version_compare($maximumVersionForRuleset, $version) >= 0, ); self::assertTrue(\in_array($actualTargetVersion, $allowedVersionsForRuleset, true), \sprintf( 'Rule "%s" (in rule set "%s") has target "%s", but the rule set is not allowing it (allowed are only "%s")', $fixer->getName(), $setName, $actualTargetVersion, implode('", "', $allowedVersionsForRuleset), )); rsort($allowedVersionsForRuleset); $maximumAllowedVersionForRuleset = reset($allowedVersionsForRuleset); self::assertSame($maximumAllowedVersionForRuleset, $actualTargetVersion, \sprintf( 'Rule "%s" (in rule set "%s") has target "%s", but there is higher available target "%s"', $fixer->getName(), $setName, $actualTargetVersion, $maximumAllowedVersionForRuleset, )); } /** * Sorts an array of rule set definitions recursively. * * Sometimes keys are all string, sometimes they are integers - we need to account for that. * * @param array<array-key, mixed> $data */ private function sort(array &$data): void { $this->doSort($data, ''); } /** * @param array<array-key, mixed> $data */ private function doSort(array &$data, string $path): void { if (\in_array($path, ['ordered_imports.imports_order', 'phpdoc_order.order'], true)) { // order matters return; } $keys = array_keys($data); if ($this->allInteger($keys)) { sort($data); } else { ksort($data); } foreach ($data as $key => $value) { if (\is_array($value)) { $this->doSort( $data[$key], $path.('' !== $path ? '.' : '').$key, ); } } } /** * @param array<array-key, mixed> $values */ private function allInteger(array $values): bool { foreach ($values as $value) { if (!\is_int($value)) { return false; } } return true; } private function getDefaultPHPUnitTargetOfRule(string $ruleName): ?string { $targetVersion = null; $fixer = TestCaseUtils::getFixerByName($ruleName); if ($fixer instanceof ConfigurableFixerInterface) { foreach ($fixer->getConfigurationDefinition()->getOptions() as $option) { if ('target' === $option->getName()) { $targetVersion = $option->getDefault(); break; } } } return $targetVersion; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/RuleSetTest.php
tests/RuleSet/RuleSetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet; use PhpCsFixer\ConfigurationException\InvalidForEnvFixerConfigurationException; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; use PhpCsFixer\FixerConfiguration\DeprecatedFixerOptionInterface; use PhpCsFixer\FixerFactory; use PhpCsFixer\RuleSet\RuleSet; use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; use PhpCsFixer\RuleSet\RuleSets; use PhpCsFixer\Tests\Test\TestCaseUtils; use PhpCsFixer\Tests\TestCase; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @group legacy * * @covers \PhpCsFixer\RuleSet\RuleSet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class RuleSetTest extends TestCase { /** * Options for which order of array elements matters. * * @var list<string> */ private const ORDER_MATTERS = [ 'ordered_imports.imports_order', 'phpdoc_order.order', ]; /** * @param array<string, mixed>|true $ruleConfig * * @dataProvider provideAllRulesFromSetsCases */ public function testIfAllRulesInSetsExists(string $setName, string $ruleName, $ruleConfig): void { $factory = new FixerFactory(); $factory->registerBuiltInFixers(); $fixers = []; foreach ($factory->getFixers() as $fixer) { $fixers[$fixer->getName()] = $fixer; } self::assertArrayHasKey($ruleName, $fixers, \sprintf('RuleSet "%s" contains unknown rule.', $setName)); if (true === $ruleConfig) { return; // rule doesn't need configuration. } \assert(\array_key_exists($ruleName, $fixers)); $fixer = $fixers[$ruleName]; self::assertInstanceOf(ConfigurableFixerInterface::class, $fixer, \sprintf('RuleSet "%s" contains configuration for rule "%s" which cannot be configured.', $setName, $ruleName)); try { $fixer->configure($ruleConfig); // test fixer accepts the configuration } catch (InvalidForEnvFixerConfigurationException $exception) { // ignore } } /** * @param array<string, mixed>|true $ruleConfig * * @dataProvider provideAllRulesFromSetsCases */ public function testThatDefaultConfigIsNotPassed(string $setName, string $ruleName, $ruleConfig): void { $fixer = TestCaseUtils::getFixerByName($ruleName); if (!$fixer instanceof ConfigurableFixerInterface || \is_bool($ruleConfig)) { $this->expectNotToPerformAssertions(); return; } if (\in_array($ruleName, [ 'type_declaration_spaces', // @TODO v4: default value for this rule will changed, remove it when they are changed ], true)) { $this->expectNotToPerformAssertions(); return; } $defaultConfig = []; foreach ($fixer->getConfigurationDefinition()->getOptions() as $option) { if ($option instanceof DeprecatedFixerOptionInterface) { continue; } $defaultConfig[$option->getName()] = $option->getDefault(); } self::assertNotSame( $this->sortNestedArray($defaultConfig, $ruleName), $this->sortNestedArray($ruleConfig, $ruleName), \sprintf('Rule "%s" (in RuleSet "%s") has default config passed.', $ruleName, $setName), ); } /** * @param array<string, mixed>|true $ruleConfig * * @dataProvider provideAllRulesFromSetsCases */ public function testThatThereIsNoDeprecatedFixerInRuleSet(string $setName, string $ruleName, $ruleConfig): void { $fixer = TestCaseUtils::getFixerByName($ruleName); self::assertNotInstanceOf(DeprecatedFixerInterface::class, $fixer, \sprintf('RuleSet "%s" contains deprecated rule "%s".', $setName, $ruleName)); } /** * @return iterable<string, array{string, string, array<string, mixed>|true}> */ public static function provideAllRulesFromSetsCases(): iterable { foreach (RuleSets::getSetDefinitionNames() as $setName) { $ruleSet = new RuleSet([$setName => true]); foreach ($ruleSet->getRules() as $rule => $config) { yield $setName.':'.$rule => [ $setName, $rule, $config, ]; } } } public function testGetBuildInSetDefinitionNames(): void { $setNames = RuleSets::getSetDefinitionNames(); self::assertNotEmpty($setNames); } public function testResolveRulesWithInvalidSet(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Set "@foo" does not exist.'); new RuleSet(['@foo' => true]); } public function testResolveRulesWithMissingRuleValue(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Missing value for "braces" rule/set.'); // @phpstan-ignore-next-line new RuleSet(['braces']); } public function testResolveRulesWithSet(): void { $ruleSet = new RuleSet([ '@PSR1' => true, 'braces' => true, 'encoding' => false, 'line_ending' => true, 'strict_comparison' => true, ]); self::assertSameRules( [ 'braces' => true, 'full_opening_tag' => true, 'line_ending' => true, 'strict_comparison' => true, ], $ruleSet->getRules(), ); } public function testResolveRulesWithNestedSet(): void { $ruleSet = new RuleSet([ '@PHP70Migration' => true, 'strict_comparison' => true, ]); self::assertSameRules( [ 'array_syntax' => true, 'strict_comparison' => true, 'ternary_to_null_coalescing' => true, ], $ruleSet->getRules(), ); } public function testResolveRulesWithDisabledSet(): void { $ruleSet = new RuleSet([ '@PHP70Migration' => true, '@PHP54Migration' => false, 'strict_comparison' => true, ]); self::assertSameRules( [ 'strict_comparison' => true, 'ternary_to_null_coalescing' => true, ], $ruleSet->getRules(), ); } /** * @param array<string, array<string, mixed>|bool> $set * * @dataProvider provideRiskyRulesInSetCases */ public function testRiskyRulesInSet(array $set, bool $safe): void { /** @TODO 4.0 Remove this expectations */ $expectedDeprecations = [ '@PER' => 'Rule set "@PER" is deprecated. Use "@PER-CS" instead.', '@PER:risky' => 'Rule set "@PER:risky" is deprecated. Use "@PER-CS:risky" instead.', ]; if (\array_key_exists(array_key_first($set), $expectedDeprecations)) { $this->expectDeprecation($expectedDeprecations[array_key_first($set)]); } try { $fixers = (new FixerFactory()) ->registerBuiltInFixers() ->useRuleSet(new RuleSet($set)) ->getFixers() ; } catch (InvalidForEnvFixerConfigurationException $exception) { self::markTestSkipped($exception->getMessage()); } $fixerNames = []; foreach ($fixers as $fixer) { if ($safe === $fixer->isRisky()) { $fixerNames[] = $fixer->getName(); } } self::assertCount( 0, $fixerNames, \sprintf( 'Set should only contain %s fixers, got: \'%s\'.', $safe ? 'safe' : 'risky', implode('\', \'', $fixerNames), ), ); } /** * @return iterable<string, array{array<string, array<string, mixed>|bool>, bool}> */ public static function provideRiskyRulesInSetCases(): iterable { foreach (RuleSets::getSetDefinitionNames() as $name) { yield $name => [ [$name => true], !str_contains($name, ':risky'), ]; } yield '@Symfony:risky_and_@Symfony' => [ [ '@Symfony:risky' => true, '@Symfony' => false, ], false, ]; } public function testInvalidConfigNestedSets(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageMatches('#^Nested rule set "@PSR1" configuration must be a boolean\.$#'); new RuleSet( ['@PSR1' => ['@PSR2' => 'no']], ); } public function testGetMissingRuleConfiguration(): void { $ruleSet = new RuleSet(); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessageMatches('#^Rule "_not_exists" is not in the set\.$#'); $ruleSet->getRuleConfiguration('_not_exists'); } /** * @dataProvider provideDuplicateRuleConfigurationInSetDefinitionsCases */ public function testDuplicateRuleConfigurationInSetDefinitions(RuleSetDefinitionInterface $set): void { $rules = []; $setRules = []; foreach ($set->getRules() as $ruleName => $ruleConfig) { if (str_starts_with($ruleName, '@')) { if (true !== $ruleConfig && false !== $ruleConfig) { throw new \LogicException('Disallowed configuration for RuleSet.'); } $setRules = array_merge($setRules, $this->resolveSet($ruleName, $ruleConfig)); } else { $rules[$ruleName] = $ruleConfig; } } $duplicates = []; foreach ($rules as $ruleName => $ruleConfig) { if (!\array_key_exists($ruleName, $setRules)) { continue; } if ($ruleConfig !== $setRules[$ruleName]) { continue; } $duplicates[] = $ruleName; } if (0 === \count($duplicates)) { $this->addToAssertionCount(1); return; } self::fail(\sprintf( '"%s" defines rules the same as it extends from: %s', $set->getName(), implode(', ', $duplicates), )); } /** * @return iterable<string, array{RuleSetDefinitionInterface}> */ public static function provideDuplicateRuleConfigurationInSetDefinitionsCases(): iterable { foreach (RuleSets::getBuiltInSetDefinitions() as $name => $set) { yield $name => [$set]; } } /** * @dataProvider providePhpUnitTargetVersionHasSetCases */ public function testPhpUnitTargetVersionHasSet(string $version): void { self::assertContains( \sprintf('@PHPUnit%sMigration:risky', str_replace('.', 'x', $version)), RuleSets::getSetDefinitionNames(), \sprintf('PHPUnit target version %s is missing its set in %s.', $version, RuleSet::class), ); } /** * @return iterable<int, array{string}> */ public static function providePhpUnitTargetVersionHasSetCases(): iterable { foreach ((new \ReflectionClass(PhpUnitTargetVersion::class))->getConstants() as $constant) { if ('newest' === $constant) { continue; } yield [$constant]; } } public function testEmptyName(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Rule/set name must not be empty.'); new RuleSet(['' => true]); } public function testInvalidConfig(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('[@Symfony:risky] Set must be enabled (true) or disabled (false). Other values are not allowed. To disable the set, use "FALSE" instead of "NULL".'); // @phpstan-ignore-next-line new RuleSet(['@Symfony:risky' => null]); } /** * @param array<array-key, mixed> $array * * @return array<array-key, mixed> $array */ private function sortNestedArray(array $array, string $ruleName): array { $this->doSort($array, $ruleName); return $array; } /** * Sorts an array of fixer definition recursively. * * Sometimes keys are all string, sometimes they are integers - we need to account for that. * * @param array<array-key, mixed> $data */ private function doSort(array &$data, string $path): void { // if order matters do not sort! if (\in_array($path, self::ORDER_MATTERS, true)) { return; } $keys = array_keys($data); if ($this->allInteger($keys)) { sort($data); } else { ksort($data); } foreach ($data as $key => $value) { if (\is_array($value)) { $this->doSort( $data[$key], $path.('' !== $path ? '.' : '').$key, ); } } } /** * @param array<int|string, mixed> $values */ private function allInteger(array $values): bool { foreach ($values as $value) { if (!\is_int($value)) { return false; } } return true; } /** * @return array<string, array<string, mixed>|bool> */ private function resolveSet(string $setName, bool $setValue): array { $rules = RuleSets::getSetDefinition($setName)->getRules(); foreach ($rules as $name => $value) { if (str_starts_with($name, '@')) { $set = $this->resolveSet($name, $setValue); unset($rules[$name]); $rules = array_merge($rules, $set); } elseif (!$setValue) { $rules[$name] = false; } else { $rules[$name] = $value; } } return $rules; } /** * @param array<string, array<string, mixed>|bool> $expected * @param array<string, array<string, mixed>|bool> $actual */ private static function assertSameRules(array $expected, array $actual): void { ksort($expected); ksort($actual); self::assertSame($expected, $actual); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/AbstractMigrationSetDefinitionTest.php
tests/RuleSet/AbstractMigrationSetDefinitionTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet; use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\RuleSet\AbstractMigrationSetDefinition * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class AbstractMigrationSetDefinitionTest extends TestCase { public function testGetDescriptionForPhpMigrationSet(): void { $set = new class extends AbstractMigrationSetDefinition { public function getName(): string { return '@PHP9x9MigrationSet'; } public function getRules(): array { return []; } }; self::assertSame('Rules to improve code for PHP 9.9 compatibility.', $set->getDescription()); } /** * @TODO v4 - remove the test while solving @MARKER_deprecated_migration_name_pattern */ public function testGetDescriptionForPhpMigrationSetLegacy(): void { $set = new class extends AbstractMigrationSetDefinition { public function getName(): string { return '@PHP99MigrationSet'; } public function getRules(): array { return []; } }; self::assertSame('Rules to improve code for PHP 9.9 compatibility.', $set->getDescription()); } public function testGetDescriptionForPhpUnitMigrationSet(): void { $set = new class extends AbstractMigrationSetDefinition { public function getName(): string { return '@PHPUnit3x0Migration'; } public function getRules(): array { return []; } }; self::assertSame('Rules to improve tests code for PHPUnit 3.0 compatibility.', $set->getDescription()); } public function testGetDescriptionForNoneMigrationSet(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessageMatches('/^Cannot generate name of ".*" \/ "foo"\.$/'); $set = new class extends AbstractMigrationSetDefinition { public function getName(): string { return 'foo'; } public function getRules(): array { return []; } }; $set->getName(); // @phpstan-ignore method.resultUnused } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/AbstractRuleSetDefinitionTest.php
tests/RuleSet/AbstractRuleSetDefinitionTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet; use PhpCsFixer\Tests\Fixtures\TestRuleSet; use PhpCsFixer\Tests\TestCase; /** * @internal * * @covers \PhpCsFixer\RuleSet\AbstractRuleSetDefinition * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class AbstractRuleSetDefinitionTest extends TestCase { public function testAbstractRuleSet(): void { $set = new TestRuleSet(); self::assertSame('@TestRule', $set->getName()); self::assertFalse($set->isRisky()); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PERCSRiskySetTest.php
tests/RuleSet/Sets/PERCSRiskySetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PERCSRiskySet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PERCSRiskySetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHPUnit3x0MigrationRiskySetTest.php
tests/RuleSet/Sets/PHPUnit3x0MigrationRiskySetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHPUnit3x0MigrationRiskySet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHPUnit3x0MigrationRiskySetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/AutoPHPMigrationSetTest.php
tests/RuleSet/Sets/AutoPHPMigrationSetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\AutoPHPMigrationSet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class AutoPHPMigrationSetTest extends AbstractSetTestCase { /** * @covers \PhpCsFixer\RuleSet\AutomaticMigrationSetTrait */ public function testCorrectResolutionTowardsOurOwnRepoConfig(): void { $set = self::getSet(); $rules = $set->getRules(); self::assertSame( ['@PHP7x4Migration' => true], // bump me when updating minimum supported version in composer.json $rules, ); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/AutoPHPMigrationRiskySetTest.php
tests/RuleSet/Sets/AutoPHPMigrationRiskySetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\AutoPHPMigrationRiskySet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class AutoPHPMigrationRiskySetTest extends AbstractSetTestCase { /** * @covers \PhpCsFixer\RuleSet\AutomaticMigrationSetTrait */ public function testCorrectResolutionTowardsOurOwnRepoConfig(): void { $set = self::getSet(); $rules = $set->getRules(); self::assertSame( ['@PHP7x4Migration:risky' => true], // bump me when updating minimum supported version in composer.json $rules, ); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHP8x1MigrationSetTest.php
tests/RuleSet/Sets/PHP8x1MigrationSetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHP8x1MigrationSet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHP8x1MigrationSetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PERCS3x0SetTest.php
tests/RuleSet/Sets/PERCS3x0SetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PERCS3x0Set * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PERCS3x0SetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHP5x4MigrationSetTest.php
tests/RuleSet/Sets/PHP5x4MigrationSetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHP5x4MigrationSet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHP5x4MigrationSetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHP8x4MigrationRiskySetTest.php
tests/RuleSet/Sets/PHP8x4MigrationRiskySetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHP8x4MigrationRiskySet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHP8x4MigrationRiskySetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/SymfonySetTest.php
tests/RuleSet/Sets/SymfonySetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\SymfonySet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SymfonySetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHP8x4MigrationSetTest.php
tests/RuleSet/Sets/PHP8x4MigrationSetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHP8x4MigrationSet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHP8x4MigrationSetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHPUnit10x0MigrationRiskySetTest.php
tests/RuleSet/Sets/PHPUnit10x0MigrationRiskySetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHPUnit10x0MigrationRiskySet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHPUnit10x0MigrationRiskySetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHP8x2MigrationRiskySetTest.php
tests/RuleSet/Sets/PHP8x2MigrationRiskySetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHP8x2MigrationRiskySet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHP8x2MigrationRiskySetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHPUnit4x8MigrationRiskySetTest.php
tests/RuleSet/Sets/PHPUnit4x8MigrationRiskySetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHPUnit4x8MigrationRiskySet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHPUnit4x8MigrationRiskySetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHPUnit5x2MigrationRiskySetTest.php
tests/RuleSet/Sets/PHPUnit5x2MigrationRiskySetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHPUnit5x2MigrationRiskySet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHPUnit5x2MigrationRiskySetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHP8x1MigrationRiskySetTest.php
tests/RuleSet/Sets/PHP8x1MigrationRiskySetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHP8x1MigrationRiskySet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHP8x1MigrationRiskySetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PSR1SetTest.php
tests/RuleSet/Sets/PSR1SetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PSR1Set * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PSR1SetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PHP7x0MigrationSetTest.php
tests/RuleSet/Sets/PHP7x0MigrationSetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PHP7x0MigrationSet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PHP7x0MigrationSetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/PERCSSetTest.php
tests/RuleSet/Sets/PERCSSetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\PERCSSet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PERCSSetTest extends AbstractSetTestCase {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/tests/RuleSet/Sets/AutoSetTest.php
tests/RuleSet/Sets/AutoSetTest.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\RuleSet\Sets; /** * @internal * * @covers \PhpCsFixer\RuleSet\Sets\AutoSet * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class AutoSetTest extends AbstractSetTestCase { public function testCorrectResolutionTowardsOurOwnRepoConfig(): void { $set = self::getSet(); $rules = $set->getRules(); self::assertSame( [ '@PER-CS' => true, '@autoPHPMigration' => true, ], $rules, ); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false