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/Fixtures/DescribeCommand/.php-cs-fixer.custom-set.php | tests/Fixtures/DescribeCommand/.php-cs-fixer.custom-set.php | <?php
use PhpCsFixer\Config;
use PhpCsFixer\Finder;
use PhpCsFixer\Tests\Fixtures\ExternalRuleSet\ExampleRuleSet;
return (new Config())
->setFinder((new Finder())->in(__DIR__))
->registerCustomRuleSets([new ExampleRuleSet()]);
| 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/Fixtures/DescribeCommand/DescribeFixtureFixer.php | tests/Fixtures/DescribeCommand/DescribeFixtureFixer.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\Fixtures\DescribeCommand;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class DescribeFixtureFixer extends AbstractFixer
{
public function getName(): string
{
return 'Vendor/describe_fixture';
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(T_CONSTANT_ENCAPSED_STRING);
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Fixture for describe command.',
[
new CodeSample(
"<?php\necho 'describe fixture';\n"
),
],
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index > 0; --$index) {
if (!$tokens[$index]->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) {
continue;
}
if ('\'describe fixture\'' !== strtolower($tokens[$index]->getContent())) {
continue;
}
$tokens[$index] = new Token([T_CONSTANT_ENCAPSED_STRING, '\'fixture for describe\'']);
}
}
}
| 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/Fixtures/DescribeCommand/.php-cs-fixer.custom-rule.php | tests/Fixtures/DescribeCommand/.php-cs-fixer.custom-rule.php | <?php
use PhpCsFixer\Config;
use PhpCsFixer\Finder;
use PhpCsFixer\Tests\Fixtures\DescribeCommand\DescribeFixtureFixer;
return (new Config())
->setFinder((new Finder())->in(__DIR__))
->registerCustomFixers([new DescribeFixtureFixer()]);
| 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/Fixtures/Test/AbstractTransformerTest/FooTransformer.php | tests/Fixtures/Test/AbstractTransformerTest/FooTransformer.php | <?php
/*
* 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\Fixtures\Test\AbstractTransformerTest;
use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*/
final class FooTransformer extends AbstractTransformer
{
/**
* {@inheritdoc}
*/
public function getRequiredPhpVersionId(): int
{
return 50000;
}
/**
* {@inheritdoc}
*/
public function process(Tokens $tokens, Token $token, int $index): void
{
}
/**
* {@inheritdoc}
*/
public function getCustomTokens(): array
{
return [];
}
}
| 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/Fixtures/FinderDirectory/somefile.php | tests/Fixtures/FinderDirectory/somefile.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/Fixtures/ConfigurationResolverConfigFile/case_7/.php-cs-fixer.php | tests/Fixtures/ConfigurationResolverConfigFile/case_7/.php-cs-fixer.php | <?php
return (new PhpCsFixer\Config())->setFormat('xls');
| 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/Fixtures/ConfigurationResolverConfigFile/case_5/.php-cs-fixer.dist.php | tests/Fixtures/ConfigurationResolverConfigFile/case_5/.php-cs-fixer.dist.php | <?php
return "foo";
| 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/Fixtures/ConfigurationResolverConfigFile/case_8/.php-cs-fixer.php | tests/Fixtures/ConfigurationResolverConfigFile/case_8/.php-cs-fixer.php | <?php
$config = new PhpCsFixer\Config();
$config->setRiskyAllowed(true);
$config->setRules(array('php_unit_construct' => true));
$config->setUsingCache(false);
$config->setFormat('xml');
return $config;
| 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/Fixtures/ConfigurationResolverConfigFile/case_2/.php-cs-fixer.php | tests/Fixtures/ConfigurationResolverConfigFile/case_2/.php-cs-fixer.php | <?php
if (!class_exists('Test2Config')) {
class Test2Config extends PhpCsFixer\Config {}
}
return new Test2Config();
| 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/Fixtures/ConfigurationResolverConfigFile/case_6/.php-cs-fixer.dist.php | tests/Fixtures/ConfigurationResolverConfigFile/case_6/.php-cs-fixer.dist.php | <?php
if (!class_exists('Test6Config')) {
class Test6Config extends PhpCsFixer\Config {}
}
return new Test6Config();
| 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/Fixtures/ConfigurationResolverConfigFile/case_6/subdir/empty_file.php | tests/Fixtures/ConfigurationResolverConfigFile/case_6/subdir/empty_file.php | <?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/Fixtures/ConfigurationResolverConfigFile/case_9/.php-cs-fixer.php | tests/Fixtures/ConfigurationResolverConfigFile/case_9/.php-cs-fixer.php | <?php
return (new PhpCsFixer\Config())
->setFinder(
PhpCsFixer\Finder::create()
->filter(function ($x) { return 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/Fixtures/ConfigurationResolverConfigFile/case_3/.php-cs-fixer.php | tests/Fixtures/ConfigurationResolverConfigFile/case_3/.php-cs-fixer.php | <?php
if (!class_exists('Test3Config')) {
class Test3Config extends PhpCsFixer\Config {}
}
return new Test3Config();
| 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/Fixtures/ConfigurationResolverConfigFile/case_3/.php-cs-fixer.dist.php | tests/Fixtures/ConfigurationResolverConfigFile/case_3/.php-cs-fixer.dist.php | <?php
return new PhpCsFixer\Config();
| 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/Fixtures/ConfigurationResolverConfigFile/case_1/foo.php | tests/Fixtures/ConfigurationResolverConfigFile/case_1/foo.php | <?php
function 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/Fixtures/ConfigurationResolverConfigFile/case_1/.php-cs-fixer.dist.php | tests/Fixtures/ConfigurationResolverConfigFile/case_1/.php-cs-fixer.dist.php | <?php
if (!class_exists('Test1Config')) {
class Test1Config extends PhpCsFixer\Config {}
}
return new Test1Config();
| 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/Fixtures/ConfigurationResolverConfigFile/case_4/my.php-cs-fixer.php | tests/Fixtures/ConfigurationResolverConfigFile/case_4/my.php-cs-fixer.php | <?php
if (!class_exists(\Test4Config::class)) {
class Test4Config extends PhpCsFixer\Config {}
}
return new Test4Config();
| 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/Fixtures/ListFilesTest/.php-cs-fixer.php | tests/Fixtures/ListFilesTest/.php-cs-fixer.php | <?php
$finder = PhpCsFixer\Finder::create()
->in([
__DIR__.'/needs-fixing/',
])
->exclude([
__DIR__.'/excluded/',
])
;
$config = new PhpCsFixer\Config();
return $config
->setUsingCache(false)
->setRules([
'@Symfony' => true,
])
->setRiskyAllowed(true)
->setFinder($finder)
;
| 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/Fixtures/ListFilesTest/.php-cs-fixer.using-getcwd.php | tests/Fixtures/ListFilesTest/.php-cs-fixer.using-getcwd.php | <?php
/** @var PhpCsFixer\Config $config */
$config = require __DIR__.'/.php-cs-fixer.php';
return $config
->setFinder((new PhpCsFixer\Finder())->in([__DIR__.'/using-getcwd']))
;
| 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/Fixtures/ListFilesTest/excluded/needs-fixing.php | tests/Fixtures/ListFilesTest/excluded/needs-fixing.php | <?php
function abc() {}
function def()
{
}
| 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/Fixtures/ListFilesTest/needs-fixing/needs-fixing.php | tests/Fixtures/ListFilesTest/needs-fixing/needs-fixing.php | <?php
function abc() {}
function def()
{
}
| 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/Fixtures/ExternalRuleSet/ExampleRuleSet.php | tests/Fixtures/ExternalRuleSet/ExampleRuleSet.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\Fixtures\ExternalRuleSet;
use PhpCsFixer\RuleSet\RuleSetDefinitionInterface;
/**
* Sample external RuleSet.
*
* The name is intentionally NOT ending with "Set" to better test real-life usage.
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
class ExampleRuleSet implements RuleSetDefinitionInterface
{
/**
* @var string
*
* @readonly
*/
private $nameSuffix;
public function __construct(string $nameSuffix = '')
{
if ('' !== $nameSuffix) {
$nameSuffix = '___'.str_replace([':', '\\'], '_', $nameSuffix);
}
$this->nameSuffix = $nameSuffix;
}
public function getName(): string
{
return '@Vendor/RuleSet'.$this->nameSuffix;
}
public function isRisky(): bool
{
return false;
}
public function getDescription(): string
{
return 'Purpose of example rule set description.';
}
public function getRules(): array
{
return [
'align_multiline_comment' => false,
];
}
}
| 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/Fixtures/FixCommand/TextDiffTestInput.php | tests/Fixtures/FixCommand/TextDiffTestInput.php | <?php
/*
* 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.
*/
/**
* Input for @see \PhpCsFixer\Tests\TextDiffTest.
*
* @internal
*/
final class TextDiffTestInput
{
public function foo($output)
{
$output->writeln('<error>'.(int)$output.'</error>');
$output->writeln('<error> TEST </error>');
$output->writeln('<error>'.(int)$output.'</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/Fixtures/ConfigurationResolverPathsIntersection/a1.php | tests/Fixtures/ConfigurationResolverPathsIntersection/a1.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/Fixtures/ConfigurationResolverPathsIntersection/a2.php | tests/Fixtures/ConfigurationResolverPathsIntersection/a2.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/Fixtures/ConfigurationResolverPathsIntersection/b_b/b_b1.php | tests/Fixtures/ConfigurationResolverPathsIntersection/b_b/b_b1.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/Fixtures/ConfigurationResolverPathsIntersection/d/.php-cs-fixer.php | tests/Fixtures/ConfigurationResolverPathsIntersection/d/.php-cs-fixer.php | <?php
/*
* 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.
*/
if (!class_exists('ConfigurationResolverPathsIntersection_d_Config')) {
class ConfigurationResolverPathsIntersection_d_Config extends PhpCsFixer\Config
{
}
}
return (new ConfigurationResolverPathsIntersection_d_Config())
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__.'/..')
)
;
| 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/Fixtures/ConfigurationResolverPathsIntersection/d/d2.php | tests/Fixtures/ConfigurationResolverPathsIntersection/d/d2.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/Fixtures/ConfigurationResolverPathsIntersection/d/d1.php | tests/Fixtures/ConfigurationResolverPathsIntersection/d/d1.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/Fixtures/ConfigurationResolverPathsIntersection/d/f/df1.php | tests/Fixtures/ConfigurationResolverPathsIntersection/d/f/df1.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/Fixtures/ConfigurationResolverPathsIntersection/d/e/de1.php | tests/Fixtures/ConfigurationResolverPathsIntersection/d/e/de1.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/Fixtures/ConfigurationResolverPathsIntersection/c/c1.php | tests/Fixtures/ConfigurationResolverPathsIntersection/c/c1.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/Fixtures/ConfigurationResolverPathsIntersection/c/d/cd1.php | tests/Fixtures/ConfigurationResolverPathsIntersection/c/d/cd1.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/Fixtures/ConfigurationResolverPathsIntersection/b/b2.php | tests/Fixtures/ConfigurationResolverPathsIntersection/b/b2.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/Fixtures/ConfigurationResolverPathsIntersection/b/b1.php | tests/Fixtures/ConfigurationResolverPathsIntersection/b/b1.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/ConfigurationException/UnresolvableAutoRuleSetConfigurationExceptionTest.php | tests/ConfigurationException/UnresolvableAutoRuleSetConfigurationExceptionTest.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\ConfigurationException;
use PhpCsFixer\ConfigurationException\UnresolvableAutoRuleSetConfigurationException;
use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator;
use PhpCsFixer\Tests\TestCase;
/**
* @internal
*
* @covers \PhpCsFixer\ConfigurationException\UnresolvableAutoRuleSetConfigurationException
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class UnresolvableAutoRuleSetConfigurationExceptionTest extends TestCase
{
public function testDefaults(): void
{
$message = 'I cannot do that, Dave.';
$exception = new UnresolvableAutoRuleSetConfigurationException($message);
self::assertSame($message, $exception->getMessage());
self::assertSame(FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_CONFIG, $exception->getCode());
self::assertNull($exception->getPrevious());
}
public function testConstructorSetsValues(): void
{
$message = 'I cannot do that, Dave.';
$code = 9_000;
$previous = new \RuntimeException();
$exception = new UnresolvableAutoRuleSetConfigurationException(
$message,
$code,
$previous,
);
self::assertSame($message, $exception->getMessage());
self::assertSame($code, $exception->getCode());
self::assertSame($previous, $exception->getPrevious());
}
}
| 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/ConfigurationException/InvalidForEnvFixerConfigurationExceptionTest.php | tests/ConfigurationException/InvalidForEnvFixerConfigurationExceptionTest.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\ConfigurationException;
use PhpCsFixer\ConfigurationException\InvalidForEnvFixerConfigurationException;
use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator;
use PhpCsFixer\Tests\TestCase;
/**
* @internal
*
* @covers \PhpCsFixer\ConfigurationException\InvalidForEnvFixerConfigurationException
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class InvalidForEnvFixerConfigurationExceptionTest extends TestCase
{
public function testDefaults(): void
{
$fixerName = 'hal';
$message = 'I cannot do that, Andreas!';
$exception = new InvalidForEnvFixerConfigurationException(
$fixerName,
$message,
);
self::assertSame(\sprintf('[%s] %s', $fixerName, $message), $exception->getMessage());
self::assertSame(FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG, $exception->getCode());
self::assertSame($fixerName, $exception->getFixerName());
self::assertNull($exception->getPrevious());
}
}
| 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/ConfigurationException/RequiredFixerConfigurationExceptionTest.php | tests/ConfigurationException/RequiredFixerConfigurationExceptionTest.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\ConfigurationException;
use PhpCsFixer\ConfigurationException\RequiredFixerConfigurationException;
use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator;
use PhpCsFixer\Tests\TestCase;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @internal
*
* @covers \PhpCsFixer\ConfigurationException\RequiredFixerConfigurationException
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class RequiredFixerConfigurationExceptionTest extends TestCase
{
public function testDefaults(): void
{
$fixerName = 'hal';
$message = 'I cannot do that, Dave.';
$exception = new RequiredFixerConfigurationException(
$fixerName,
$message,
);
self::assertSame(\sprintf('[%s] %s', $fixerName, $message), $exception->getMessage());
self::assertSame(FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG, $exception->getCode());
self::assertNull($exception->getPrevious());
}
public function testConstructorSetsValues(): void
{
$fixerName = 'hal';
$message = 'I cannot do that, Dave.';
$previous = new \RuntimeException();
$exception = new RequiredFixerConfigurationException(
$fixerName,
$message,
$previous,
);
self::assertSame(\sprintf('[%s] %s', $fixerName, $message), $exception->getMessage());
self::assertSame(FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG, $exception->getCode());
self::assertSame($previous, $exception->getPrevious());
}
}
| 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/ConfigurationException/InvalidConfigurationExceptionTest.php | tests/ConfigurationException/InvalidConfigurationExceptionTest.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\ConfigurationException;
use PhpCsFixer\ConfigurationException\InvalidConfigurationException;
use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator;
use PhpCsFixer\Tests\TestCase;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @internal
*
* @covers \PhpCsFixer\ConfigurationException\InvalidConfigurationException
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class InvalidConfigurationExceptionTest extends TestCase
{
public function testDefaults(): void
{
$message = 'I cannot do that, Dave.';
$exception = new InvalidConfigurationException($message);
self::assertSame($message, $exception->getMessage());
self::assertSame(FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_CONFIG, $exception->getCode());
self::assertNull($exception->getPrevious());
}
public function testConstructorSetsValues(): void
{
$message = 'I cannot do that, Dave.';
$code = 9_000;
$previous = new \RuntimeException();
$exception = new InvalidConfigurationException(
$message,
$code,
$previous,
);
self::assertSame($message, $exception->getMessage());
self::assertSame($code, $exception->getCode());
self::assertSame($previous, $exception->getPrevious());
}
}
| 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/ConfigurationException/InvalidFixerConfigurationExceptionTest.php | tests/ConfigurationException/InvalidFixerConfigurationExceptionTest.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\ConfigurationException;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator;
use PhpCsFixer\Tests\TestCase;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @internal
*
* @covers \PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class InvalidFixerConfigurationExceptionTest extends TestCase
{
public function testDefaults(): void
{
$fixerName = 'hal';
$message = 'I cannot do that, Dave.';
$exception = new InvalidFixerConfigurationException(
$fixerName,
$message,
);
self::assertSame(\sprintf('[%s] %s', $fixerName, $message), $exception->getMessage());
self::assertSame(FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG, $exception->getCode());
self::assertSame($fixerName, $exception->getFixerName());
self::assertNull($exception->getPrevious());
}
public function testConstructorSetsValues(): void
{
$fixerName = 'hal';
$message = 'I cannot do that, Dave.';
$previous = new \RuntimeException();
$exception = new InvalidFixerConfigurationException(
$fixerName,
$message,
$previous,
);
self::assertSame(\sprintf('[%s] %s', $fixerName, $message), $exception->getMessage());
self::assertSame(FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG, $exception->getCode());
self::assertSame($fixerName, $exception->getFixerName());
self::assertSame($previous, $exception->getPrevious());
}
}
| 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/Test/AbstractIntegrationTestCase.php | tests/Test/AbstractIntegrationTestCase.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\Test;
use PhpCsFixer\Cache\NullCacheManager;
use PhpCsFixer\Differ\UnifiedDiffer;
use PhpCsFixer\Error\Error;
use PhpCsFixer\Error\ErrorsManager;
use PhpCsFixer\FileRemoval;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\FixerFactory;
use PhpCsFixer\Linter\CachingLinter;
use PhpCsFixer\Linter\Linter;
use PhpCsFixer\Linter\LinterInterface;
use PhpCsFixer\Linter\ProcessLinter;
use PhpCsFixer\PhpunitConstraintIsIdenticalString\Constraint\IsIdenticalString;
use PhpCsFixer\Runner\Runner;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\WhitespacesFixerConfig;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
/**
* Integration test base class.
*
* This test searches for '.test' fixture files in the given directory.
* Each fixture file will be parsed and tested against the expected result.
*
* Fixture files have the following format:
*
* --TEST--
* Example test description.
* --RULESET--
* {"@PSR2": true, "strict": true}
* --CONFIG--
* {"indent": " ", "lineEnding": "\n"}
* --SETTINGS--
* {"key": "value"} # optional extension point for custom IntegrationTestCase class
* --REQUIREMENTS--
* {"php": 70400, "php<": 80000}
* --EXPECT--
* Expected code after fixing
* --INPUT--
* Code to fix
*
**************
* IMPORTANT! *
**************
*
* Some sections (like `--CONFIG--`) may be omitted. The required sections are:
* - `--TEST--`
* - `--RULESET--`
* - `--EXPECT--` (works as input too if `--INPUT--` is not provided, that means no changes are expected)
*
* The `--REQUIREMENTS--` section can define additional constraints for running (or not) the test.
* You can use these fields to fine-tune run conditions for test cases:
* - `php` represents minimum PHP version test should be run on. Defaults to current running PHP version (no effect).
* - `php<` represents maximum PHP version test should be run on. Defaults to PHP's maximum integer value (no effect).
* - `os` represents operating system(s) test should be run on. Supported operating systems: Linux, Darwin and Windows.
* By default test is run on all supported operating systems.
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
abstract class AbstractIntegrationTestCase extends TestCase
{
protected ?LinterInterface $linter = null;
private static ?FileRemoval $fileRemoval = null;
public static function setUpBeforeClass(): void
{
parent::setUpBeforeClass();
$tmpFile = static::getTempFile();
self::$fileRemoval = new FileRemoval();
self::$fileRemoval->observe($tmpFile);
if (!is_file($tmpFile)) {
$dir = \dirname($tmpFile);
if (!is_dir($dir)) {
$fs = new Filesystem();
$fs->mkdir($dir, 0766);
}
}
}
public static function tearDownAfterClass(): void
{
parent::tearDownAfterClass();
$tmpFile = static::getTempFile();
self::$fileRemoval->delete($tmpFile);
self::$fileRemoval = null;
}
protected function setUp(): void
{
parent::setUp();
$this->linter = $this->getLinter();
}
protected function tearDown(): void
{
parent::tearDown();
$this->linter = null;
}
/**
* @dataProvider provideIntegrationCases
*
* @see doTest()
*
* @large
*
* @group legacy
*/
public function testIntegration(IntegrationCase $case): void
{
foreach ($case->getSettings()['deprecations'] as $deprecation) {
$this->expectDeprecation($deprecation);
}
$this->doTest($case);
// run the test again with the `expected` part, this should always stay the same
$this->doTest(
new IntegrationCase(
$case->getFileName(),
$case->getTitle().' "--EXPECT-- part run"',
$case->getSettings(),
$case->getRequirements(),
$case->getConfig(),
$case->getRuleset(),
$case->getExpectedCode(),
null,
),
);
}
/**
* Creates test data by parsing '.test' files.
*
* @return iterable<string, array{IntegrationCase}>
*/
public static function provideIntegrationCases(): iterable
{
$dir = static::getFixturesDir();
$fixturesDir = realpath($dir);
\assert(\is_string($fixturesDir));
if (!is_dir($fixturesDir)) {
throw new \UnexpectedValueException(\sprintf('Given fixture dir "%s" is not a directory.', $fixturesDir));
}
$factory = static::createIntegrationCaseFactory();
foreach (Finder::create()->files()->in($fixturesDir) as $file) {
if ('test' !== $file->getExtension()) {
continue;
}
$relativePath = substr($file->getPathname(), \strlen((string) realpath(__DIR__.'/../../')) + 1);
yield $relativePath => [$factory->create($file)];
}
}
protected static function createIntegrationCaseFactory(): IntegrationCaseFactoryInterface
{
return new IntegrationCaseFactory();
}
/**
* Returns the full path to directory which contains the tests.
*/
protected static function getFixturesDir(): string
{
throw new \BadMethodCallException('Method "getFixturesDir" must be overridden by the extending class.');
}
/**
* Returns the full path to the temporary file where the test will write to.
*/
protected static function getTempFile(): string
{
throw new \BadMethodCallException('Method "getTempFile" must be overridden by the extending class.');
}
/**
* Applies the given fixers on the input and checks the result.
*
* It will write the input to a temp file. The file will be fixed by a Fixer instance
* configured with the given fixers. The result is compared with the expected output.
* It checks if no errors were reported during the fixing.
*/
protected function doTest(IntegrationCase $case): void
{
$phpLowerLimit = $case->getRequirement('php');
if (\PHP_VERSION_ID < $phpLowerLimit) {
self::markTestSkipped(\sprintf('PHP %d (or later) is required for "%s", current "%d".', $phpLowerLimit, $case->getFileName(), \PHP_VERSION_ID));
}
$phpUpperLimit = $case->getRequirement('php<');
if (\PHP_VERSION_ID >= $phpUpperLimit) {
self::markTestSkipped(\sprintf('PHP lower than %d is required for "%s", current "%d".', $phpUpperLimit, $case->getFileName(), \PHP_VERSION_ID));
}
if (!\in_array(\PHP_OS_FAMILY, $case->getRequirement('os'), true)) {
self::markTestSkipped(
\sprintf(
'Unsupported OS (%s) for "%s", allowed are: %s.',
\PHP_OS,
$case->getFileName(),
implode(', ', $case->getRequirement('os')),
),
);
}
$input = $case->getInputCode();
$expected = $case->getExpectedCode();
$input = $case->hasInputCode() ? $input : $expected;
$tmpFile = static::getTempFile();
if (false === @file_put_contents($tmpFile, $input)) {
throw new IOException(\sprintf('Failed to write to tmp. file "%s".', $tmpFile));
}
$errorsManager = new ErrorsManager();
$fixers = self::createFixers($case);
$runner = new Runner(
new \ArrayIterator([new \SplFileInfo($tmpFile)]),
$fixers,
new UnifiedDiffer(),
null,
$errorsManager,
$this->linter,
false,
new NullCacheManager(),
);
Tokens::clearCache();
$result = $runner->fix();
$changed = array_pop($result);
if (!$errorsManager->isEmpty()) {
$errors = $errorsManager->getExceptionErrors();
self::assertEmpty($errors, \sprintf('Errors reported during fixing of file "%s": %s', $case->getFileName(), $this->implodeErrors($errors)));
$errors = $errorsManager->getInvalidErrors();
self::assertEmpty($errors, \sprintf('Errors reported during linting before fixing file "%s": %s.', $case->getFileName(), $this->implodeErrors($errors)));
$errors = $errorsManager->getLintErrors();
self::assertEmpty($errors, \sprintf('Errors reported during linting after fixing file "%s": %s.', $case->getFileName(), $this->implodeErrors($errors)));
}
if (!$case->hasInputCode()) {
self::assertEmpty(
$changed,
\sprintf(
"Expected no changes made to test \"%s\" in \"%s\".\nFixers applied:\n%s.\nDiff.:\n%s.",
$case->getTitle(),
$case->getFileName(),
null === $changed ? '[None]' : implode(',', $changed['appliedFixers']),
null === $changed ? '[None]' : $changed['diff'],
),
);
return;
}
self::assertNotEmpty($changed, \sprintf('Expected changes made to test "%s" in "%s".', $case->getTitle(), $case->getFileName()));
$fixedInputCode = file_get_contents($tmpFile);
self::assertIsString($fixedInputCode);
self::assertThat(
$fixedInputCode,
new IsIdenticalString($expected),
\sprintf(
"Expected changes do not match result for \"%s\" in \"%s\".\nFixers applied:\n%s.",
$case->getTitle(),
$case->getFileName(),
implode(',', $changed['appliedFixers']),
),
);
if (1 < \count($fixers)) {
$tmpFile = static::getTempFile();
if (false === @file_put_contents($tmpFile, $input)) {
throw new IOException(\sprintf('Failed to write to tmp. file "%s".', $tmpFile));
}
$runner = new Runner(
new \ArrayIterator([new \SplFileInfo($tmpFile)]),
array_reverse($fixers),
new UnifiedDiffer(),
null,
$errorsManager,
$this->linter,
false,
new NullCacheManager(),
);
Tokens::clearCache();
$runner->fix();
$fixedInputCodeWithReversedFixers = file_get_contents($tmpFile);
self::assertIsString($fixedInputCodeWithReversedFixers);
static::assertRevertedOrderFixing($case, $fixedInputCode, $fixedInputCodeWithReversedFixers);
}
}
protected static function assertRevertedOrderFixing(IntegrationCase $case, string $fixedInputCode, string $fixedInputCodeWithReversedFixers): void
{
// If output is different depends on rules order - we need to verify that the rules are ordered by priority.
// If not, any order is valid.
if ($fixedInputCode !== $fixedInputCodeWithReversedFixers) {
self::assertGreaterThan(
1,
\count(array_unique(array_map(
static fn (FixerInterface $fixer): int => $fixer->getPriority(),
self::createFixers($case),
))),
\sprintf(
'Rules priorities are not differential enough. If rules would be used in reverse order then final output would be different than the expected one. For that, different priorities must be set up for used rules to ensure stable order of them. In "%s".',
$case->getFileName(),
),
);
}
}
/**
* @return list<FixerInterface>
*/
private static function createFixers(IntegrationCase $case): array
{
$config = $case->getConfig();
return (new FixerFactory())
->registerBuiltInFixers()
->useRuleSet($case->getRuleset())
->setWhitespacesConfig(
new WhitespacesFixerConfig($config['indent'], $config['lineEnding']),
)
->getFixers()
;
}
/**
* @param list<Error> $errors
*/
private function implodeErrors(array $errors): string
{
$errorStr = '';
foreach ($errors as $error) {
$source = $error->getSource();
$errorStr .= \sprintf(
"\n\n[%s] %s\n\nDIFF:\n\n%s\n\nAPPLIED FIXERS:\n\n%s\n\nSTACKTRACE:\n\n%s\n",
$error->getFilePath(),
null === $source ? '' : $source->getMessage(),
$error->getDiff(),
implode(', ', $error->getAppliedFixers()),
$source->getTraceAsString(),
);
}
return $errorStr;
}
private function getLinter(): LinterInterface
{
static $linter = null;
if (null === $linter) {
$linter = new CachingLinter(
filter_var(getenv('PHP_CS_FIXER_FAST_LINT_TEST_CASES'), \FILTER_VALIDATE_BOOLEAN)
? new Linter()
: new ProcessLinter(),
);
}
return $linter;
}
}
| 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/Test/CiReader.php | tests/Test/CiReader.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\Test;
use PhpCsFixer\Preg;
use Symfony\Component\Yaml\Yaml;
/**
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CiReader
{
/**
* @return list<numeric-string>
*/
public static function getAllPhpVersionsUsedByCiForTests(): array
{
$phpVersions = array_filter(
self::getAllPhpBuildsUsedByCiForTests(),
static fn ($version) => is_numeric($version),
);
return $phpVersions; // @phpstan-ignore return.type (we know it's a list of parsed strings)
}
/**
* @return list<string>
*/
public static function getAllPhpBuildsUsedByCiForTests(): array
{
$yaml = Yaml::parseFile(__DIR__.'/../../.github/workflows/ci.yml');
$phpVersions = []
+ ($yaml['jobs']['tests']['strategy']['matrix']['php-version'] ?? [])
+ array_map(
static fn (array $job) => $job['php-version'] ?? null,
$yaml['jobs']['tests']['strategy']['matrix']['include'],
);
$phpVersions = array_filter(
array_unique($phpVersions),
static fn ($version) => 'nightly' === $version || Preg::match('/^\d+(\.\d+)?(snapshot)?$/', $version),
);
return $phpVersions; // @phpstan-ignore return.type (we know it's a list of parsed strings)
}
public static function getPhpVersionUsedByCiForDeployments(): string
{
$yaml = Yaml::parseFile(__DIR__.'/../../.github/workflows/ci.yml');
$version = $yaml['jobs']['deployment']['env']['php-version'];
return \is_string($version) ? $version : \sprintf('%.1f', $version);
}
/**
* @return array<string, string>
*/
public static function getGitHubCiEnvs(): array
{
$yaml = Yaml::parseFile(__DIR__.'/../../.github/workflows/ci.yml');
return $yaml['env'];
}
}
| 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/Test/AbstractIntegrationCaseFactory.php | tests/Test/AbstractIntegrationCaseFactory.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\Test;
use PhpCsFixer\Preg;
use PhpCsFixer\RuleSet\RuleSet;
use Symfony\Component\Finder\SplFileInfo;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
abstract class AbstractIntegrationCaseFactory implements IntegrationCaseFactoryInterface
{
public function create(SplFileInfo $file): IntegrationCase
{
try {
if (!Preg::match(
'/^
--TEST-- \r?\n(?<title> .*?)
\s --RULESET-- \r?\n(?<ruleset> .*?)
(?:\s --CONFIG-- \r?\n(?<config> .*?))?
(?:\s --SETTINGS-- \r?\n(?<settings> .*?))?
(?:\s --REQUIREMENTS-- \r?\n(?<requirements> .*?))?
(?:\s --EXPECT-- \r?\n(?<expect> .*?\r?\n*))?
(?:\s --INPUT-- \r?\n(?<input> .*))?
$/sx',
$file->getContents(),
$match,
)) {
throw new \InvalidArgumentException('File format is invalid.');
}
$match = array_merge(
[
'config' => null,
'settings' => null,
'requirements' => null,
'expect' => null,
'input' => null,
],
$match,
);
return new IntegrationCase(
$file->getRelativePathname(),
$this->determineTitle($file, $match['title']),
$this->determineSettings($file, $match['settings']),
$this->determineRequirements($file, $match['requirements']),
$this->determineConfig($file, $match['config']),
$this->determineRuleset($file, $match['ruleset']),
$this->determineExpectedCode($file, $match['expect']),
$this->determineInputCode($file, $match['input']),
);
} catch (\InvalidArgumentException $e) {
throw new \InvalidArgumentException(
\sprintf('%s Test file: "%s".', $e->getMessage(), $file->getPathname()),
$e->getCode(),
$e,
);
}
}
/**
* Parses the '--CONFIG--' block of a '.test' file.
*
* @return array{indent: non-empty-string, lineEnding: non-empty-string}
*/
protected function determineConfig(SplFileInfo $file, ?string $config): array
{
/** @var array{indent: non-empty-string, lineEnding: non-empty-string} $parsed */
$parsed = $this->parseJson($config, [
'indent' => ' ',
'lineEnding' => "\n",
]);
if (!\is_string($parsed['indent']) || '' === $parsed['indent']) {
throw new \InvalidArgumentException(\sprintf(
'Expected string value for "indent", got "%s".',
\is_object($parsed['indent']) ? \get_class($parsed['indent']) : \gettype($parsed['indent']).'#'.$parsed['indent'],
));
}
if (!\is_string($parsed['lineEnding']) || '' === $parsed['lineEnding']) {
throw new \InvalidArgumentException(\sprintf(
'Expected string value for "lineEnding", got "%s".',
\is_object($parsed['lineEnding']) ? \get_class($parsed['lineEnding']) : \gettype($parsed['lineEnding']).'#'.$parsed['lineEnding'],
));
}
return $parsed;
}
/**
* Parses the '--REQUIREMENTS--' block of a '.test' file and determines requirements.
*
* @return array{php: int, "php<": int, os: list<string>}
*/
protected function determineRequirements(SplFileInfo $file, ?string $config): array
{
/** @var array{php: int, "php<": int, os: list<string>} $parsed */
$parsed = $this->parseJson($config, [
'php' => \PHP_VERSION_ID,
'php<' => \PHP_INT_MAX,
'os' => ['Linux', 'Darwin', 'Windows'],
]);
if (!\is_int($parsed['php'])) {
throw new \InvalidArgumentException(\sprintf(
'Expected int value like 50509 for "php", got "%s".',
get_debug_type($parsed['php']).'#'.$parsed['php'],
));
}
if (!\is_int($parsed['php<'])) {
throw new \InvalidArgumentException(\sprintf(
'Expected int value like 80301 for "php<", got "%s".',
get_debug_type($parsed['php<']).'#'.$parsed['php<'],
));
}
if (!\is_array($parsed['os'])) {
throw new \InvalidArgumentException(\sprintf(
'Expected array of OS names for "os", got "%s".',
get_debug_type($parsed['os']).' ('.$parsed['os'].')',
));
}
return $parsed;
}
/**
* Parses the '--RULESET--' block of a '.test' file and determines what fixers should be used.
*/
protected function determineRuleset(SplFileInfo $file, string $config): RuleSet
{
return new RuleSet($this->parseJson($config));
}
/**
* Parses the '--TEST--' block of a '.test' file and determines title.
*/
protected function determineTitle(SplFileInfo $file, string $config): string
{
return $config;
}
/**
* Parses the '--SETTINGS--' block of a '.test' file and determines settings.
*
* @return array{checkPriority: bool, deprecations: list<string>}
*/
protected function determineSettings(SplFileInfo $file, ?string $config): array
{
/** @var array{checkPriority: bool, deprecations: list<string>} $parsed */
$parsed = $this->parseJson($config, [
'checkPriority' => true,
'deprecations' => [],
]);
if (!\is_bool($parsed['checkPriority'])) {
throw new \InvalidArgumentException(\sprintf(
'Expected bool value for "checkPriority", got "%s".',
\is_object($parsed['checkPriority']) ? \get_class($parsed['checkPriority']) : \gettype($parsed['checkPriority']).'#'.$parsed['checkPriority'],
));
}
if (!\is_array($parsed['deprecations'])) {
throw new \InvalidArgumentException(\sprintf(
'Expected array value for "deprecations", got "%s".',
\is_object($parsed['deprecations']) ? \get_class($parsed['deprecations']) : \gettype($parsed['deprecations']).'#'.$parsed['deprecations'],
));
}
foreach ($parsed['deprecations'] as $index => $deprecation) {
if (!\is_string($deprecation)) {
throw new \InvalidArgumentException(\sprintf(
'Expected only string value for "deprecations", got "%s" @ index %d.',
\is_object($deprecation) ? \get_class($deprecation) : \gettype($deprecation).'#'.$deprecation,
$index,
));
}
}
return $parsed;
}
protected function determineExpectedCode(SplFileInfo $file, ?string $code): string
{
$code = $this->determineCode($file, $code, '-out.php');
if (null === $code) {
throw new \InvalidArgumentException('Missing expected code.');
}
return $code;
}
protected function determineInputCode(SplFileInfo $file, ?string $code): ?string
{
return $this->determineCode($file, $code, '-in.php');
}
private function determineCode(SplFileInfo $file, ?string $code, string $suffix): ?string
{
if (null !== $code) {
return $code;
}
$candidateFile = new SplFileInfo($file->getPathname().$suffix, '', '');
if ($candidateFile->isFile()) {
return $candidateFile->getContents();
}
return null;
}
/**
* @param null|array<string, mixed> $template
*
* @return array<string, mixed>
*/
private function parseJson(?string $encoded, ?array $template = null): array
{
// content is optional if template is provided
if ((null === $encoded || '' === $encoded) && null !== $template) {
$decoded = [];
} else {
$decoded = json_decode($encoded, true, 512, \JSON_THROW_ON_ERROR);
}
if (null !== $template) {
foreach ($template as $index => $value) {
if (!\array_key_exists($index, $decoded)) {
$decoded[$index] = $value;
}
}
}
return $decoded;
}
}
| 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/Test/AbstractFixerWithAliasedOptionsTestCase.php | tests/Test/AbstractFixerWithAliasedOptionsTestCase.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\Test;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\FixerConfiguration\AliasedFixerOption;
/**
* @internal
*
* @template TFixer of AbstractFixer
*
* @extends AbstractFixerTestCase<TFixer>
*
* @author ntzm
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
abstract class AbstractFixerWithAliasedOptionsTestCase extends AbstractFixerTestCase
{
/**
* @var null|TFixer
*/
private ?AbstractFixer $fixerWithAliasedConfig = null;
protected function tearDown(): void
{
parent::tearDown();
$this->fixerWithAliasedConfig = null;
}
protected function doTest(string $expected, ?string $input = null, ?\SplFileInfo $file = null): void
{
parent::doTest($expected, $input, $file);
if (null !== $this->fixerWithAliasedConfig) {
$fixer = $this->fixer;
$fixerWithAliasedConfig = $this->fixerWithAliasedConfig;
$this->fixer = $fixerWithAliasedConfig;
$this->fixerWithAliasedConfig = null;
$this->doTest($expected, $input, $file);
$this->fixerWithAliasedConfig = $fixerWithAliasedConfig;
$this->fixer = $fixer;
}
}
/**
* @param array<string, mixed> $configuration
*/
protected function configureFixerWithAliasedOptions(array $configuration): void
{
if (!$this->fixer instanceof ConfigurableFixerInterface) {
throw new \LogicException('Fixer is not configurable.');
}
$this->fixer->configure($configuration);
$options = $this->fixer->getConfigurationDefinition()->getOptions();
$hasAliasedOptions = false;
foreach ($options as $option) {
if (!$option instanceof AliasedFixerOption) {
continue;
}
$hasAliasedOptions = true;
$alias = $option->getAlias();
if (\array_key_exists($alias, $configuration)) {
$configuration[$option->getName()] = $configuration[$alias];
unset($configuration[$alias]);
}
}
if (!$hasAliasedOptions) {
throw new \LogicException('Fixer has no aliased options.');
}
$this->fixerWithAliasedConfig = clone $this->fixer;
$this->fixerWithAliasedConfig->configure($configuration);
}
}
| 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/Test/IntegrationCaseFactory.php | tests/Test/IntegrationCaseFactory.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\Test;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class IntegrationCaseFactory extends AbstractIntegrationCaseFactory {}
| 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/Test/IntegrationCase.php | tests/Test/IntegrationCase.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\Test;
use PhpCsFixer\RuleSet\RuleSet;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class IntegrationCase
{
/**
* @var array{indent: non-empty-string, lineEnding: non-empty-string}
*/
private array $config;
private string $expectedCode;
private string $fileName;
private ?string $inputCode;
/**
* @var array{php: int, "php<": int, os: list<string>}
*/
private array $requirements;
private RuleSet $ruleset;
/**
* Settings how to perform the test (possible keys: none in base class, use as extension point for custom IntegrationTestCase).
*
* @var array{checkPriority: bool, deprecations: list<string>, isExplicitPriorityCheck?: bool}
*/
private array $settings;
private string $title;
/**
* @param array{checkPriority: bool, deprecations: list<string>, isExplicitPriorityCheck?: bool} $settings
* @param array{php: int, "php<": int, os: list<string>} $requirements
* @param array{indent: non-empty-string, lineEnding: non-empty-string} $config
*/
public function __construct(
string $fileName,
string $title,
array $settings,
array $requirements,
array $config,
RuleSet $ruleset,
string $expectedCode,
?string $inputCode
) {
$this->fileName = $fileName;
$this->title = $title;
$this->settings = $settings;
$this->requirements = $requirements;
$this->config = $config;
$this->ruleset = $ruleset;
$this->expectedCode = $expectedCode;
$this->inputCode = $inputCode;
}
public function hasInputCode(): bool
{
return null !== $this->inputCode;
}
/**
* @return array{indent: non-empty-string, lineEnding: non-empty-string}
*/
public function getConfig(): array
{
return $this->config;
}
public function getExpectedCode(): string
{
return $this->expectedCode;
}
public function getFileName(): string
{
return $this->fileName;
}
public function getInputCode(): ?string
{
return $this->inputCode;
}
/**
* @return mixed
*/
public function getRequirement(string $name)
{
if (!\array_key_exists($name, $this->requirements)) {
throw new \InvalidArgumentException(\sprintf(
'Unknown requirement key "%s", expected any of "%s".',
$name,
implode('","', array_keys($this->requirements)),
));
}
return $this->requirements[$name];
}
/**
* @return array{php: int, "php<": int, os: list<string>}
*/
public function getRequirements(): array
{
return $this->requirements;
}
public function getRuleset(): RuleSet
{
return $this->ruleset;
}
/**
* @return array{checkPriority: bool, deprecations: list<string>, isExplicitPriorityCheck?: bool}
*/
public function getSettings(): array
{
return $this->settings;
}
public function getTitle(): string
{
return $this->title;
}
}
| 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/Test/TokensWithObservedTransformers.php | tests/Test/TokensWithObservedTransformers.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\Test;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\Transformers;
/**
* @phpstan-import-type _PhpTokenKind from Token
* @phpstan-import-type _PhpTokenPrototypePartial from Token
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TokensWithObservedTransformers extends Tokens
{
public ?string $currentTransformer = null;
/**
* @var array<string, list<_PhpTokenKind>>
*/
public array $observedModificationsPerTransformer = [];
public function offsetSet($index, $newval): void
{
if (null !== $this->currentTransformer) {
$this->observedModificationsPerTransformer[$this->currentTransformer][] = $this->extractTokenKind($newval);
}
parent::offsetSet($index, $newval);
}
/**
* @internal
*/
protected function applyTransformers(): void
{
$this->observedModificationsPerTransformer = [];
$transformers = Transformers::createSingleton();
$items = \Closure::bind(
static fn (Transformers $transformers): array => $transformers->items,
null,
Transformers::class,
)($transformers);
foreach ($items as $transformer) {
$this->currentTransformer = $transformer->getName();
$this->observedModificationsPerTransformer[$this->currentTransformer] = [];
foreach ($this as $index => $token) {
$transformer->process($this, $token, $index);
}
}
$this->currentTransformer = null;
}
/**
* @param _PhpTokenPrototypePartial|Token $token token prototype
*
* @return _PhpTokenKind
*/
private function extractTokenKind($token)
{
return $token instanceof Token
? ($token->isArray() ? $token->getId() : $token->getContent())
: (\is_array($token) ? $token[0] : $token);
}
}
| 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/Test/TestCaseUtils.php | tests/Test/TestCaseUtils.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\Test;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\FixerFactory;
/**
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TestCaseUtils
{
public static function getFixerByName(string $name): FixerInterface
{
static $fixers = null;
if (null === $fixers) {
$factory = new FixerFactory();
$factory->registerBuiltInFixers();
$fixers = [];
foreach ($factory->getFixers() as $fixer) {
$fixers[$fixer->getName()] = $fixer;
}
}
if (!\array_key_exists($name, $fixers)) {
throw new \InvalidArgumentException(\sprintf('Fixer "%s" does not exist.', $name));
}
return $fixers[$name];
}
}
| 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/Test/InternalIntegrationCaseFactory.php | tests/Test/InternalIntegrationCaseFactory.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\Test;
use Symfony\Component\Finder\SplFileInfo;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class InternalIntegrationCaseFactory extends AbstractIntegrationCaseFactory
{
/**
* @return array{checkPriority: bool, deprecations: list<string>, isExplicitPriorityCheck: bool}
*/
protected function determineSettings(SplFileInfo $file, ?string $config): array
{
$parsed = parent::determineSettings($file, $config);
$parsed['isExplicitPriorityCheck'] = \in_array('priority', explode(\DIRECTORY_SEPARATOR, $file->getRelativePathname()), true);
return $parsed;
}
}
| 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/Test/AbstractTransformerTestCase.php | tests/Test/AbstractTransformerTestCase.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\Test;
use PhpCsFixer\Preg;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TransformerInterface;
/**
* @phpstan-import-type _PhpTokenKind from Token
* @phpstan-import-type _PhpTokenPrototypePartial from Token
*
* @internal
*
* @phpstan-type _TransformerTestExpectedKindsUnderIndex array<int, _PhpTokenKind>
* @phpstan-type _TransformerTestObservedKinds list<_PhpTokenKind>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
abstract class AbstractTransformerTestCase extends TestCase
{
protected ?TransformerInterface $transformer = null;
protected function setUp(): void
{
parent::setUp();
$this->transformer = $this->createTransformer();
}
protected function tearDown(): void
{
parent::tearDown();
$this->transformer = null;
}
public function testGetPriority(): void
{
self::assertIsInt($this->transformer->getPriority(), $this->transformer->getName());
}
public function testGetName(): void
{
$name = $this->transformer->getName();
self::assertMatchesRegularExpression('/^[a-z]+[a-z_]*[a-z]$/', $name);
}
public function testGetCustomTokens(): void
{
$name = $this->transformer->getName();
$customTokens = $this->transformer->getCustomTokens();
self::assertIsArray($customTokens, $name);
foreach ($customTokens as $customToken) {
self::assertIsInt($customToken, $name);
}
}
public function testGetRequiredPhpVersionId(): void
{
$name = $this->transformer->getName();
$requiredPhpVersionId = $this->transformer->getRequiredPhpVersionId();
self::assertIsInt($requiredPhpVersionId, $name);
self::assertGreaterThanOrEqual(5_00_00, $requiredPhpVersionId, $name);
}
public function testTransformersIsFinal(): void
{
$transformerRef = new \ReflectionClass($this->transformer);
self::assertTrue(
$transformerRef->isFinal(),
\sprintf('Transformer "%s" must be declared "final."', $this->transformer->getName()),
);
}
public function testTransformDoesNotChangeSimpleCode(): void
{
if (\PHP_VERSION_ID < $this->transformer->getRequiredPhpVersionId()) {
$this->expectNotToPerformAssertions();
return;
}
Tokens::clearCache();
$tokens = Tokens::fromCode('<?php ');
foreach ($tokens as $index => $token) {
$this->transformer->process($tokens, $token, $index);
}
self::assertFalse($tokens->isChanged());
}
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
* @param _TransformerTestObservedKinds $observedKindsOrPrototypes
*/
protected function doTest(string $source, array $expectedTokens, array $observedKindsOrPrototypes = []): void
{
Tokens::clearCache();
$tokens = new TokensWithObservedTransformers();
$tokens->setCode($source);
$prototypes = array_map(
static fn ($kindOrPrototype) => \is_int($kindOrPrototype) ? [$kindOrPrototype] : $kindOrPrototype,
array_unique([...$observedKindsOrPrototypes, ...$expectedTokens]),
);
\assert(array_is_list($prototypes));
self::assertSame(
\count($expectedTokens),
$this->countTokenPrototypes(
$tokens,
$prototypes,
),
'Number of expected tokens does not match actual token count.',
);
$transformerName = $this->transformer->getName();
$customTokensOfTransformer = $this->transformer->getCustomTokens();
foreach ($customTokensOfTransformer as $customTokenOfTransformer) {
self::assertTrue(CT::has($customTokenOfTransformer), \sprintf('Unknown custom token id "%d" in "%s".', $transformerName, $customTokenOfTransformer));
self::assertStringStartsWith('CT::', CT::getName($customTokenOfTransformer));
}
$customTokensOfTransformerList = implode(', ', array_map(
static fn (int $ct): string => CT::getName($ct),
$customTokensOfTransformer,
));
foreach ($tokens->observedModificationsPerTransformer as $appliedTransformerName => $modificationsOfTransformer) {
foreach ($modificationsOfTransformer as $modification) {
self::assertIsInt($modification);
$customTokenName = Token::getNameForId($modification);
if ($appliedTransformerName === $transformerName) {
self::assertContains(
$modification,
$customTokensOfTransformer,
\sprintf(
'Transformation into "%s" must be allowed in self-documentation of the Transformer, currently allowed custom tokens are: %s',
$customTokenName,
$customTokensOfTransformerList,
),
);
} else {
self::assertNotContains(
$modification,
$customTokensOfTransformer,
\sprintf(
'Transformation into "%s" must NOT be applied by other Transformer than "%s".',
$customTokenName,
$transformerName,
),
);
}
}
}
foreach ($expectedTokens as $index => $tokenIdOrContent) {
if (\is_string($tokenIdOrContent)) {
self::assertTrue(
$tokens[$index]->equals($tokenIdOrContent),
\sprintf('The token at index %d should be %s, got %s', $index, json_encode($tokenIdOrContent, \JSON_THROW_ON_ERROR), $tokens[$index]->toJson()),
);
continue;
}
self::assertSame(
CT::has($tokenIdOrContent) ? CT::getName($tokenIdOrContent) : token_name($tokenIdOrContent),
$tokens[$index]->getName(),
\sprintf('Token name should be the same. Got token "%s" at index %d.', $tokens[$index]->toJson(), $index),
);
self::assertSame(
$tokenIdOrContent,
$tokens[$index]->getId(),
\sprintf('Token id should be the same. Got token "%s" at index %d.', $tokens[$index]->toJson(), $index),
);
}
}
/**
* @param list<_PhpTokenPrototypePartial> $prototypes
*/
private function countTokenPrototypes(Tokens $tokens, array $prototypes): int
{
$count = 0;
foreach ($tokens as $token) {
if ($token->equalsAny($prototypes)) {
++$count;
}
}
return $count;
}
private function createTransformer(): TransformerInterface
{
$transformerClassName = Preg::replace('/^(PhpCsFixer)\\\Tests(\\\.+)Test$/', '$1$2', static::class);
\assert(is_a($transformerClassName, TransformerInterface::class, true));
return new $transformerClassName();
}
}
| 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/Test/AbstractFixerTestCase.php | tests/Test/AbstractFixerTestCase.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\Test;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\Fixer\Whitespace\SingleBlankLineAtEofFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerOptionInterface;
use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface;
use PhpCsFixer\Linter\CachingLinter;
use PhpCsFixer\Linter\Linter;
use PhpCsFixer\Linter\LinterInterface;
use PhpCsFixer\Linter\ProcessLinter;
use PhpCsFixer\PhpunitConstraintIsIdenticalString\Constraint\IsIdenticalString;
use PhpCsFixer\Preg;
use PhpCsFixer\StdinFileInfo;
use PhpCsFixer\Tests\Fixer\ClassNotation\ClassAttributesSeparationFixerTest;
use PhpCsFixer\Tests\Fixer\ClassNotation\ClassDefinitionFixerTest;
use PhpCsFixer\Tests\Fixer\Comment\NoEmptyCommentFixerTest;
use PhpCsFixer\Tests\Fixer\ControlStructure\NoUselessElseFixerTest;
use PhpCsFixer\Tests\Fixer\PhpUnit\PhpUnitTestCaseStaticMethodCallsFixerTest;
use PhpCsFixer\Tests\Test\Assert\AssertTokensTrait;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @template TFixer of FixerInterface
*
* @phpstan-import-type _PhpTokenArrayPartial from Token
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
abstract class AbstractFixerTestCase extends TestCase
{
use AssertTokensTrait;
/**
* do not modify this structure without prior discussion.
*
* @var array<string, array<string, bool>>
*/
private const ALLOWED_REQUIRED_OPTIONS = [
'header_comment' => ['header' => true],
];
protected ?LinterInterface $linter = null;
/**
* @var null|TFixer
*/
protected ?FixerInterface $fixer = null;
/**
* do not modify this structure without prior discussion.
*
* @var array<string, bool>
*/
private array $allowedFixersWithoutDefaultCodeSample = [
'general_phpdoc_annotation_remove' => true,
'general_attribute_remove' => true,
'general_phpdoc_tag_rename' => true,
];
protected function setUp(): void
{
parent::setUp();
$this->linter = $this->getLinter();
$this->fixer = $this->createFixer();
}
protected function tearDown(): void
{
parent::tearDown();
$this->linter = null;
$this->fixer = null;
}
final public function testIsRisky(): void
{
if ($this->fixer->isRisky()) {
self::assertValidDescription($this->fixer->getName(), 'risky description', $this->fixer->getDefinition()->getRiskyDescription());
} else {
self::assertNull($this->fixer->getDefinition()->getRiskyDescription(), \sprintf('[%s] Fixer is not risky so no description of it expected.', $this->fixer->getName()));
}
if ($this->fixer instanceof AbstractProxyFixer) {
return;
}
$reflection = new \ReflectionMethod($this->fixer, 'isRisky');
// If fixer is not risky then the method `isRisky` from `AbstractFixer` must be used
self::assertSame(
!$this->fixer->isRisky(),
AbstractFixer::class === $reflection->getDeclaringClass()->getName(),
);
}
final public function testFixerDefinitions(): void
{
$fixerName = $this->fixer->getName();
$definition = $this->fixer->getDefinition();
$fixerIsConfigurable = $this->fixer instanceof ConfigurableFixerInterface;
self::assertValidDescription($fixerName, 'summary', $definition->getSummary());
if (null !== $definition->getDescription()) {
self::assertValidDescription($fixerName, 'description', $definition->getDescription());
}
$samples = $definition->getCodeSamples();
self::assertNotEmpty($samples, \sprintf('[%s] Code samples are required.', $fixerName));
$configSamplesProvided = [];
$dummyFileInfo = new StdinFileInfo();
foreach ($samples as $sampleCounter => $sample) {
$code = $sample->getCode();
self::assertNotEmpty($code, \sprintf('[%s] Sample #%d', $fixerName, $sampleCounter));
self::assertStringStartsNotWith("\n", $code, \sprintf('[%s] Sample #%d must not start with linebreak', $fixerName, $sampleCounter));
if (!$this->fixer instanceof SingleBlankLineAtEofFixer) {
self::assertStringEndsWith("\n", $code, \sprintf('[%s] Sample #%d must end with linebreak', $fixerName, $sampleCounter));
}
$config = $sample->getConfiguration();
if (null !== $config) {
self::assertTrue($fixerIsConfigurable, \sprintf('[%s] Sample #%d has configuration, but the fixer is not configurable.', $fixerName, $sampleCounter));
$configSamplesProvided[$sampleCounter] = $config;
} elseif ($fixerIsConfigurable) {
if (!$sample instanceof VersionSpecificCodeSampleInterface) {
self::assertArrayNotHasKey('default', $configSamplesProvided, \sprintf('[%s] Multiple non-versioned samples with default configuration.', $fixerName));
}
$configSamplesProvided['default'] = true;
}
if ($sample instanceof VersionSpecificCodeSampleInterface) {
$supportedPhpVersions = [7_04_00, 8_00_00, 8_01_00, 8_02_00, 8_03_00, 8_04_00];
$hasSuitableSupportedVersion = false;
foreach ($supportedPhpVersions as $version) {
if ($sample->isSuitableFor($version)) {
$hasSuitableSupportedVersion = true;
}
}
self::assertTrue($hasSuitableSupportedVersion, 'Version specific code sample must be suitable for at least 1 supported PHP version.');
$hasUnsuitableSupportedVersion = false;
foreach ($supportedPhpVersions as $version) {
if (!$sample->isSuitableFor($version)) {
$hasUnsuitableSupportedVersion = true;
}
}
self::assertTrue($hasUnsuitableSupportedVersion, 'Version specific code sample must be unsuitable for at least 1 supported PHP version.');
if (!$sample->isSuitableFor(\PHP_VERSION_ID)) {
continue;
}
}
if ($this->fixer instanceof ConfigurableFixerInterface) {
// always re-configure as the fixer might have been configured with diff. configuration form previous sample
$this->fixer->configure($config ?? []);
}
Tokens::clearCache();
$tokens = Tokens::fromCode($code);
$this->fixer->fix(
$sample instanceof FileSpecificCodeSampleInterface ? $sample->getSplFileInfo() : $dummyFileInfo,
$tokens,
);
self::assertTrue($tokens->isChanged(), \sprintf('[%s] Sample #%d is not changed during fixing.', $fixerName, $sampleCounter));
$duplicatedCodeSample = array_search(
$sample,
\array_slice($samples, 0, $sampleCounter),
true,
);
self::assertFalse(
$duplicatedCodeSample,
\sprintf('[%s] Sample #%d duplicates #%d.', $fixerName, $sampleCounter, $duplicatedCodeSample),
);
}
if ($this->fixer instanceof ConfigurableFixerInterface) {
if (isset($configSamplesProvided['default'])) {
self::assertSame('default', array_key_first($configSamplesProvided), \sprintf('[%s] First sample must be for the default configuration.', $fixerName));
} elseif (!isset($this->allowedFixersWithoutDefaultCodeSample[$fixerName])) {
self::assertArrayHasKey($fixerName, self::ALLOWED_REQUIRED_OPTIONS, \sprintf('[%s] Has no sample for default configuration.', $fixerName));
}
if (\count($configSamplesProvided) < 2) {
self::fail(\sprintf('[%s] Configurable fixer only provides a default configuration sample and none for its configuration options.', $fixerName));
}
// @phpstan-ignore-next-line method.notFound
$options = $this->fixer->getConfigurationDefinition()->getOptions();
foreach ($options as $option) {
self::assertMatchesRegularExpression('/^[a-z_]+[a-z]$/', $option->getName(), \sprintf('[%s] Option %s is not snake_case.', $fixerName, $option->getName()));
self::assertMatchesRegularExpression(
'/^[A-Z].+\.$/s',
$option->getDescription(),
\sprintf('[%s] Description of option "%s" must start with capital letter and end with dot.', $fixerName, $option->getName()),
);
}
}
self::assertIsInt($this->fixer->getPriority());
}
final public function testFixersAreFinal(): void
{
$reflection = $this->getFixerReflection();
self::assertTrue(
$reflection->isFinal(),
\sprintf('Fixer "%s" must be declared "final".', $this->fixer->getName()),
);
}
final public function testDeprecatedFixersHaveCorrectSummary(): void
{
self::assertStringNotContainsString(
'DEPRECATED',
$this->fixer->getDefinition()->getSummary(),
'Fixer cannot contain word "DEPRECATED" in summary',
);
$reflection = $this->getFixerReflection();
$comment = $reflection->getDocComment();
if ($this->fixer instanceof DeprecatedFixerInterface) {
self::assertIsString($comment, \sprintf('Missing class PHPDoc for deprecated fixer "%s".', $this->fixer->getName()));
self::assertStringContainsString('@deprecated', $comment);
} elseif (\is_string($comment)) {
self::assertStringNotContainsString('@deprecated', $comment);
}
}
final public function testDeprecatedFixersDoNotHaveDeprecatedSuccessor(): void
{
if (!$this->fixer instanceof DeprecatedFixerInterface || [] === $this->fixer->getSuccessorsNames()) {
$this->addToAssertionCount(1);
return;
}
foreach ($this->fixer->getSuccessorsNames() as $successorName) {
self::assertNotInstanceOf(
DeprecatedFixerInterface::class,
TestCaseUtils::getFixerByName($successorName),
\sprintf(
'Successor fixer `%s` for deprecated fixer `%s` is deprecated itself.',
$successorName,
$this->fixer->getName(),
),
);
}
}
/**
* Blur filter that find candidate fixer for performance optimization to use only `insertSlices` instead of multiple `insertAt` if there is no other collection manipulation.
*/
public function testFixerUseInsertSlicesWhenOnlyInsertionsArePerformed(): void
{
$reflection = $this->getFixerReflection();
$filePath = $reflection->getFileName();
if (false === $filePath) {
throw new \RuntimeException('Cannot determine sourcefile for class.');
}
$tokens = Tokens::fromCode((string) file_get_contents($filePath));
$sequences = $this->findAllTokenSequences($tokens, [[\T_VARIABLE, '$tokens'], [\T_OBJECT_OPERATOR], [\T_STRING]]);
$usedMethods = array_unique(array_map(static function (array $sequence): string {
$last = end($sequence);
return $last->getContent();
}, $sequences));
// if there is no `insertAt`, it's not a candidate
if (!\in_array('insertAt', $usedMethods, true)) {
$this->expectNotToPerformAssertions();
return;
}
$usedMethods = array_filter($usedMethods, static fn (string $method): bool => !Preg::match('/^(count|find|generate|get|is|rewind)/', $method));
$allowedMethods = ['insertAt'];
$nonAllowedMethods = array_diff($usedMethods, $allowedMethods);
if ([] === $nonAllowedMethods) {
$fixerName = $this->fixer->getName();
if (\in_array($fixerName, [
// DO NOT add anything to this list at ease, align with core contributors whether it makes sense to insert tokens individually or by bulk for your case.
// The original list of the fixers being exceptions and insert tokens individually came from legacy reasons when it was the only available methods to insert tokens.
'PhpCsFixerInternal/configurable_fixer_template',
'blank_line_after_namespace',
'blank_line_after_opening_tag',
'blank_line_before_statement',
'class_attributes_separation',
'date_time_immutable',
'declare_strict_types',
'doctrine_annotation_braces',
'doctrine_annotation_spaces',
'final_internal_class',
'final_public_method_for_abstract_class',
'function_typehint_space',
'heredoc_indentation',
'method_chaining_indentation',
'native_constant_invocation',
'new_with_braces',
'new_with_parentheses',
'no_short_echo_tag',
'not_operator_with_space',
'not_operator_with_successor_space',
'php_unit_internal_class',
'php_unit_no_expectation_annotation',
'php_unit_set_up_tear_down_visibility',
'php_unit_size_class',
'php_unit_test_annotation',
'php_unit_test_class_requires_covers',
'phpdoc_to_param_type',
'phpdoc_to_property_type',
'phpdoc_to_return_type',
'random_api_migration',
'semicolon_after_instruction',
'single_line_after_imports',
'static_lambda',
'strict_param',
'void_return',
], true)) {
self::markTestIncomplete(\sprintf('Fixer "%s" may be optimized to use `Tokens::insertSlices` instead of `%s`, please help and optimize it.', $fixerName, implode(', ', $allowedMethods)));
}
self::fail(\sprintf('Fixer "%s" shall be optimized to use `Tokens::insertSlices` instead of `%s`.', $fixerName, implode(', ', $allowedMethods)));
}
$this->addToAssertionCount(1);
}
final public function testFixerConfigurationDefinitions(): void
{
if (!$this->fixer instanceof ConfigurableFixerInterface) {
$this->expectNotToPerformAssertions(); // not applied to the fixer without configuration
return;
}
$configurationDefinition = $this->fixer->getConfigurationDefinition();
foreach ($configurationDefinition->getOptions() as $option) {
self::assertInstanceOf(FixerOptionInterface::class, $option);
self::assertOption($option, $this->fixer);
}
}
final public function testProperMethodNaming(): void
{
if ($this->fixer instanceof DeprecatedFixerInterface) {
self::markTestSkipped('Not worth refactoring tests for deprecated fixers.');
}
/** @var array<class-string, list<string>> */
$allowedExtraMethods = [
ClassAttributesSeparationFixerTest::class => ['testCommentBlockStartDetection', 'provideCommentBlockStartDetectionCases'],
ClassDefinitionFixerTest::class => ['testClassyDefinitionInfo', 'provideClassyDefinitionInfoCases', 'testClassyInheritanceInfo', 'provideClassyInheritanceInfoCases', 'testClassyInheritanceInfoPre80', 'provideClassyInheritanceInfoPre80Cases'],
NoEmptyCommentFixerTest::class => ['testGetCommentBlock', 'provideGetCommentBlockCases'],
NoUselessElseFixerTest::class => ['testBlockDetection', 'provideBlockDetectionCases', 'testIsInConditionWithoutBraces', 'provideIsInConditionWithoutBracesCases'],
PhpUnitTestCaseStaticMethodCallsFixerTest::class => ['testFixerContainsAllPhpunitStaticMethodsInItsList', 'testWrongConfigTypeForMethodsAndTargetVersion', 'testPHPUnit10', 'testPHPUnit11', 'testPHPUnit12', 'testPHPUnit13'],
];
$names = ['Fix', 'FixDeprecated', 'FixPre80', 'Fix80', 'FixPre81', 'Fix81', 'Fix82', 'Fix83', 'FixPre84', 'Fix84', 'FixPre85', 'Fix85', 'WithShortOpenTag', 'WithWhitespacesConfig', 'InvalidConfiguration'];
$methodNames = ['testConfigure'];
foreach ($names as $name) {
$methodNames[] = 'test'.$name;
$methodNames[] = 'provide'.$name.'Cases';
}
$reflectionClass = new \ReflectionObject($this);
$extraMethods = array_map(
static fn (\ReflectionMethod $method): string => $method->getName(),
array_values(array_filter(
$reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC),
static fn (\ReflectionMethod $method): bool => $method->getDeclaringClass()->getName() === $reflectionClass->getName()
&& !\in_array($method->getName(), $methodNames, true),
)),
);
if (isset($allowedExtraMethods[static::class])) {
self::assertSame($allowedExtraMethods[static::class], $extraMethods);
} else {
self::assertTrue(method_exists($this, 'testFix'), \sprintf('Method testFix does not exist in %s.', static::class));
self::assertTrue(method_exists($this, 'provideFixCases'), \sprintf('Method provideFixCases does not exist in %s.', static::class));
self::assertSame(
[],
$extraMethods,
\sprintf('Methods "%s" should not be present in %s.', implode('". "', $extraMethods), static::class),
);
}
}
public function testImplementingWhitespacesAwareFixerInterface(): void
{
$tokens = Tokens::fromCode((string) file_get_contents((string) $this->getFixerReflection()->getFileName()));
if ($this->fixer instanceof AbstractPhpUnitFixer) {
// AbstractPhpUnitFixer is using `$this->whitespacesConfig` and we cannot verify it is needed for the child class
$this->addToAssertionCount(1);
return;
}
if ($this->fixer instanceof AbstractProxyFixer) {
self::assertSame(
array_any(
\Closure::bind(static fn (AbstractProxyFixer $fixer): array => $fixer->createProxyFixers(), null, AbstractProxyFixer::class)($this->fixer),
static fn (FixerInterface $fixer): bool => $fixer instanceof WhitespacesAwareFixerInterface,
),
$this->fixer instanceof WhitespacesAwareFixerInterface,
);
return;
}
self::assertSame(
null !== $tokens->findSequence([
[\T_VARIABLE, '$this'],
[\T_OBJECT_OPERATOR],
[\T_STRING, 'whitespacesConfig'],
]),
$this->fixer instanceof WhitespacesAwareFixerInterface,
);
}
/**
* @return TFixer
*/
protected function createFixer(): FixerInterface
{
/** @var class-string<TFixer> $fixerClassName */
$fixerClassName = Preg::replace('/^(PhpCsFixer)\\\Tests(\\\.+)Test$/', '$1$2', static::class);
return new $fixerClassName();
}
/**
* Tests if a fixer fixes a given string to match the expected result.
*
* It is used both if you want to test if something is fixed or if it is not touched by the fixer.
* It also makes sure that the expected output does not change when run through the fixer. That means that you
* do not need two test cases like [$expected] and [$expected, $input] (where $expected is the same in both cases)
* as the latter covers both of them.
* This method throws an exception if $expected and $input are equal to prevent test cases that accidentally do
* not test anything.
*
* @param string $expected The expected fixer output
* @param null|string $input The fixer input, or null if it should intentionally be equal to the output
* @param null|\SplFileInfo $file The file to fix, or null if unneeded
*/
protected function doTest(string $expected, ?string $input = null, ?\SplFileInfo $file = null): void
{
if ($expected === $input) {
throw new \InvalidArgumentException('Input parameter must not be equal to expected parameter.');
}
$file ??= new \SplFileInfo(__FILE__);
$fileIsSupported = $this->fixer->supports($file);
if (null !== $input) {
self::assertNull($this->lintSource($input));
Tokens::clearCache();
$tokens = Tokens::fromCode($input);
if ($fileIsSupported) {
self::assertTrue($this->fixer->isCandidate($tokens), 'Fixer must be a candidate for input code.');
self::assertFalse($tokens->isChanged(), 'Fixer must not touch Tokens on candidate check.');
$this->fixer->fix($file, $tokens);
}
self::assertThat(
$tokens->generateCode(),
new IsIdenticalString($expected),
'Code built on input code must match expected code.',
);
self::assertTrue($tokens->isChanged(), 'Tokens collection built on input code must be marked as changed after fixing.');
$tokens->clearEmptyTokens();
self::assertSameSize(
$tokens,
array_unique(array_map(static fn (Token $token): string => spl_object_hash($token), $tokens->toArray())),
'Token items inside Tokens collection must be unique.',
);
Tokens::clearCache();
$expectedTokens = Tokens::fromCode($expected);
self::assertTokens($expectedTokens, $tokens);
}
self::assertNull($this->lintSource($expected));
Tokens::clearCache();
$tokens = Tokens::fromCode($expected);
if ($fileIsSupported) {
$this->fixer->fix($file, $tokens);
}
self::assertThat(
$tokens->generateCode(),
new IsIdenticalString($expected),
'Code built on expected code must not change.',
);
self::assertFalse($tokens->isChanged(), 'Tokens collection built on expected code must not be marked as changed after fixing.');
}
protected function lintSource(string $source): ?string
{
try {
$this->linter->lintSource($source)->check();
} catch (\Exception $e) {
return $e->getMessage()."\n\nSource:\n{$source}";
}
return null;
}
protected static function assertCorrectCasing(string $haystack, string $needle, string $fixerName, string $descriptionType): void
{
self::assertSame(
substr_count(strtolower($haystack), strtolower($needle)),
substr_count($haystack, $needle),
\sprintf('[%s] `%s` must be in correct casing in %s.', $fixerName, $needle, $descriptionType),
);
}
/**
* @return \ReflectionClass<FixerInterface>
*/
private function getFixerReflection(): \ReflectionClass
{
if (null === $this->fixer) {
throw new \LogicException('Too early call of getFixerReflection(), fixer not yet provided.');
}
return new \ReflectionClass($this->fixer);
}
private function getLinter(): LinterInterface
{
static $linter = null;
if (null === $linter) {
$linter = new CachingLinter(
filter_var(getenv('PHP_CS_FIXER_FAST_LINT_TEST_CASES'), \FILTER_VALIDATE_BOOLEAN)
? new Linter()
: new ProcessLinter(),
);
}
return $linter;
}
private static function assertValidDescription(string $fixerName, string $descriptionType, string $description): void
{
// Description:
// "Option `a` and `b_c` are allowed."
// becomes:
// "Option `_` and `_` are allowed."
// so values in backticks are excluded from check
$descriptionWithExcludedNames = Preg::replace('/`([^`]+)`/', '`_`', $description);
self::assertMatchesRegularExpression('/^[A-Z`].+\.$/s', $description, \sprintf('[%s] The %s must start with capital letter or a ` and end with dot.', $fixerName, $descriptionType));
self::assertStringNotContainsString('phpdocs', $descriptionWithExcludedNames, \sprintf('[%s] `PHPDoc` must not be in the plural in %s.', $fixerName, $descriptionType));
self::assertCorrectCasing($descriptionWithExcludedNames, 'PHPDoc', $fixerName, $descriptionType);
self::assertCorrectCasing($descriptionWithExcludedNames, 'PHPUnit', $fixerName, $descriptionType);
self::assertFalse(strpos($descriptionType, '``'), \sprintf('[%s] The %s must no contain sequential backticks.', $fixerName, $descriptionType));
}
private static function assertOption(FixerOptionInterface $option, FixerInterface $fixer): void
{
self::assertNotEmpty($option->getDescription());
self::assertValidDescription($fixer->getName(), 'option:'.$option->getName(), $option->getDescription());
self::assertSame(
!isset(self::ALLOWED_REQUIRED_OPTIONS[$fixer->getName()][$option->getName()]),
$option->hasDefault(),
\sprintf(
$option->hasDefault()
? 'Option `%s` of fixer `%s` is wrongly listed in `ALLOWED_REQUIRED_OPTIONS` structure, as it is not required. If you just changed that option to not be required anymore, please adjust mentioned structure.'
: 'Option `%s` of fixer `%s` shall not be required. If you want to introduce new required option please adjust `ALLOWED_REQUIRED_OPTIONS` structure.',
$option->getName(),
$fixer->getName(),
),
);
self::assertStringNotContainsString(
'DEPRECATED',
$option->getDescription(),
'Option description cannot contain word "DEPRECATED"',
);
if (!$option->hasDefault()) {
return;
}
$allowedValues = $option->getAllowedValues();
if (null === $allowedValues) {
return;
}
$allowedValueSubset = $allowedValues[0];
if (
!$allowedValueSubset instanceof AllowedValueSubset
|| \count($option->getDefault()) !== \count($allowedValueSubset->getAllowedValues())
) {
return;
}
self::assertSame(
$option->getDefault(),
$allowedValueSubset->getAllowedValues(),
\sprintf('[%s] `%s` has default and allowed sets of the same size, so they must be the same.', $fixer->getName(), $option->getName()),
);
}
/**
* @param non-empty-list<_PhpTokenArrayPartial> $sequence
*
* @return list<non-empty-array<int, Token>>
*/
private function findAllTokenSequences(Tokens $tokens, array $sequence): array
{
$lastIndex = 0;
$sequences = [];
while (($found = $tokens->findSequence($sequence, $lastIndex)) !== null) {
$keys = array_keys($found);
$sequences[] = $found;
\assert(\array_key_exists(2, $keys));
$lastIndex = $keys[2];
}
return $sequences;
}
}
| 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/Test/IntegrationCaseFactoryInterface.php | tests/Test/IntegrationCaseFactoryInterface.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\Test;
use Symfony\Component\Finder\SplFileInfo;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
interface IntegrationCaseFactoryInterface
{
public function create(SplFileInfo $file): IntegrationCase;
}
| 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/Test/Assert/AssertJsonSchemaTrait.php | tests/Test/Assert/AssertJsonSchemaTrait.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\Test\Assert;
use JsonSchema\Validator;
use PhpCsFixer\Tests\TestCase;
/**
* @internal
*
* @phpstan-require-extends TestCase
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
trait AssertJsonSchemaTrait
{
private static function assertJsonSchema(string $schemaFile, string $json): void
{
$data = json_decode($json, null, 512, \JSON_THROW_ON_ERROR);
$validator = new Validator();
$validator->validate($data, (object) ['$ref' => 'file://'.realpath($schemaFile)]);
/** @var list<array{property: string, message: string}> $errors */
$errors = $validator->getErrors();
self::assertTrue(
$validator->isValid(),
implode(
"\n",
array_map(
static fn (array $item): string => \sprintf('Property `%s`: %s.', $item['property'], $item['message']),
$errors,
),
),
);
}
}
| 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/Test/Assert/AssertTokensTrait.php | tests/Test/Assert/AssertTokensTrait.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\Test\Assert;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @phpstan-require-extends TestCase
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
trait AssertTokensTrait
{
protected static function assertTokens(Tokens $expectedTokens, Tokens $inputTokens): void
{
foreach ($expectedTokens as $index => $expectedToken) {
if (!isset($inputTokens[$index])) {
static::fail(\sprintf("The token at index %d must be:\n%s, but is not set in the input collection.", $index, $expectedToken->toJson()));
}
$inputToken = $inputTokens[$index];
self::assertTrue(
$expectedToken->equals($inputToken),
\sprintf("The token at index %d must be:\n%s,\ngot:\n%s.", $index, $expectedToken->toJson(), $inputToken->toJson()),
);
$expectedTokenKind = $expectedToken->isArray() ? $expectedToken->getId() : $expectedToken->getContent();
self::assertTrue(
$inputTokens->isTokenKindFound($expectedTokenKind),
\sprintf(
'The token kind %s (%s) must be found in tokens collection.',
$expectedTokenKind,
\is_string($expectedTokenKind) ? $expectedTokenKind : Token::getNameForId($expectedTokenKind),
),
);
}
self::assertSameSize($expectedTokens, $inputTokens, 'Both collections must have the same length.');
}
}
| 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/Tokenizer/TokensAnalyzerTest.php | tests/Tokenizer/TokensAnalyzerTest.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\Tokenizer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
* @author Max Voloshin <voloshin.dp@gmail.com>
* @author Gregor Harlan <gharlan@web.de>
*
* @internal
*
* @phpstan-import-type _ClassyElementType from \PhpCsFixer\Tokenizer\TokensAnalyzer
*
* @covers \PhpCsFixer\Tokenizer\TokensAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TokensAnalyzerTest extends TestCase
{
/**
* @param array<int, array{classIndex: int, type: string}> $expectedElements
*
* @dataProvider provideGetClassyElementsCases
*/
public function testGetClassyElements(array $expectedElements, string $source): void
{
$tokens = Tokens::fromCode($source);
array_walk(
$expectedElements,
static function (array &$element, int $index) use ($tokens): void {
$element['token'] = $tokens[$index];
ksort($element);
},
);
$tokensAnalyzer = new TokensAnalyzer($tokens);
self::assertSame(
$expectedElements,
$tokensAnalyzer->getClassyElements(),
);
}
/**
* @return iterable<array{array<int, array{classIndex: int, type: string}>, string}>
*/
public static function provideGetClassyElementsCases(): iterable
{
yield 'trait import' => [
[
10 => [
'classIndex' => 4,
'type' => 'trait_import',
],
19 => [
'classIndex' => 4,
'type' => 'trait_import',
],
24 => [
'classIndex' => 4,
'type' => 'const',
],
35 => [
'classIndex' => 4,
'type' => 'method',
],
55 => [
'classIndex' => 49,
'type' => 'trait_import',
],
64 => [
'classIndex' => 49,
'type' => 'method',
],
],
'<?php
/** */
class Foo
{
use A\B;
//
use Foo;
const A = 1;
public function foo()
{
$a = new class()
{
use Z; // nested trait import
public function bar()
{
echo 123;
}
};
$a->bar();
}
}',
];
yield [
[
9 => [
'classIndex' => 1,
'type' => 'property',
],
14 => [
'classIndex' => 1,
'type' => 'property',
],
19 => [
'classIndex' => 1,
'type' => 'property',
],
28 => [
'classIndex' => 1,
'type' => 'property',
],
42 => [
'classIndex' => 1,
'type' => 'const',
],
53 => [
'classIndex' => 1,
'type' => 'method',
],
83 => [
'classIndex' => 1,
'type' => 'method',
],
140 => [
'classIndex' => 1,
'type' => 'method',
],
164 => [
'classIndex' => 158,
'type' => 'const',
],
173 => [
'classIndex' => 158,
'type' => 'trait_import',
],
],
<<<'PHP'
<?php
class Foo
{
public $prop0;
protected $prop1;
private $prop2 = 1;
var $prop3 = array(1,2,3);
const CONSTANT = 'constant value';
public function bar4()
{
$a = 5;
return " ({$a})";
}
public function bar5($data)
{
$message = $data;
$example = function ($arg) use ($message) {
echo $arg . ' ' . $message;
};
$example('hello');
}function A(){}
}
function test(){}
class Foo2
{
const CONSTANT = 'constant value';
use Foo\Bar; // expected in the return value
}
PHP,
];
yield [
[
11 => [
'classIndex' => 1,
'type' => 'property',
],
23 => [
'classIndex' => 1,
'type' => 'property',
],
31 => [
'classIndex' => 1,
'type' => 'property',
],
44 => [
'classIndex' => 1,
'type' => 'property',
],
51 => [
'classIndex' => 1,
'type' => 'property',
],
54 => [
'classIndex' => 1,
'type' => 'property',
],
61 => [
'classIndex' => 1,
'type' => 'property',
],
69 => [
'classIndex' => 1,
'type' => 'property',
],
],
<<<'PHP'
<?php
class Foo
{
public int $bar = 3;
protected ?string $baz;
private ?string $bazNull = null;
public static iterable $staticProp;
public float $x, $y;
var bool $flag1;
var ?bool $flag2;
}
PHP,
];
}
public function testGetClassyElementsWithNullableProperties(): void
{
$source = <<<'PHP'
<?php
class Foo
{
public int $prop0;
protected ?array $prop1;
private string $prop2 = 1;
var ? Foo\Bar $prop3 = array(1,2,3);
}
PHP;
$tokens = Tokens::fromCode($source);
$tokensAnalyzer = new TokensAnalyzer($tokens);
$elements = $tokensAnalyzer->getClassyElements();
self::assertSame(
[
11 => [
'classIndex' => 1,
'token' => $tokens[11],
'type' => 'property',
],
19 => [
'classIndex' => 1,
'token' => $tokens[19],
'type' => 'property',
],
26 => [
'classIndex' => 1,
'token' => $tokens[26],
'type' => 'property',
],
41 => [
'classIndex' => 1,
'token' => $tokens[41],
'type' => 'property',
],
],
$elements,
);
}
public function testGetClassyElementsWithAnonymousClass(): void
{
$source = <<<'PHP'
<?php
class A {
public $A;
private function B()
{
return new class(){
protected $level1;
private function XYZ() {
return new class(){private $level2 = 1;};
}
};
}
private function C() {
}
}
function B() {} // do not count this
PHP;
$tokens = Tokens::fromCode($source);
$tokensAnalyzer = new TokensAnalyzer($tokens);
$elements = $tokensAnalyzer->getClassyElements();
self::assertSame(
[
9 => [
'classIndex' => 1,
'token' => $tokens[9],
'type' => 'property', // $A
],
14 => [
'classIndex' => 1,
'token' => $tokens[14],
'type' => 'method', // B
],
33 => [
'classIndex' => 26,
'token' => $tokens[33],
'type' => 'property', // $level1
],
38 => [
'classIndex' => 26,
'token' => $tokens[38],
'type' => 'method', // XYZ
],
56 => [
'classIndex' => 50,
'token' => $tokens[56],
'type' => 'property', // $level2
],
74 => [
'classIndex' => 1,
'token' => $tokens[74],
'type' => 'method', // C
],
],
$elements,
);
}
public function testGetClassyElementsWithMultipleAnonymousClass(): void
{
$source = <<<'PHP'
<?php class A0
{
public function AA0()
{
return new class
{
public function BB0()
{
}
};
}
public function otherFunction0()
{
}
}
class A1
{
public function AA1()
{
return new class
{
public function BB1()
{
return new class
{
public function CC1()
{
return new class
{
public function DD1()
{
return new class{};
}
public function DD2()
{
return new class{};
}
};
}
};
}
public function BB2()
{
return new class
{
public function CC2()
{
return new class
{
public function DD2()
{
return new class{};
}
};
}
};
}
};
}
public function otherFunction1()
{
}
}
PHP;
$tokens = Tokens::fromCode($source);
$tokensAnalyzer = new TokensAnalyzer($tokens);
$elements = $tokensAnalyzer->getClassyElements();
self::assertSame(
[
9 => [
'classIndex' => 1,
'token' => $tokens[9],
'type' => 'method',
],
27 => [
'classIndex' => 21,
'token' => $tokens[27],
'type' => 'method',
],
44 => [
'classIndex' => 1,
'token' => $tokens[44],
'type' => 'method',
],
64 => [
'classIndex' => 56,
'token' => $tokens[64],
'type' => 'method',
],
82 => [
'classIndex' => 76,
'token' => $tokens[82],
'type' => 'method',
],
100 => [
'classIndex' => 94,
'token' => $tokens[100],
'type' => 'method',
],
118 => [
'classIndex' => 112,
'token' => $tokens[118],
'type' => 'method',
],
139 => [
'classIndex' => 112,
'token' => $tokens[139],
'type' => 'method',
],
170 => [
'classIndex' => 76,
'token' => $tokens[170],
'type' => 'method',
],
188 => [
'classIndex' => 182,
'token' => $tokens[188],
'type' => 'method',
],
206 => [
'classIndex' => 200,
'token' => $tokens[206],
'type' => 'method',
],
242 => [
'classIndex' => 56,
'token' => $tokens[242],
'type' => 'method',
],
],
$elements,
);
}
/**
* @param array<int, array{classIndex: int, type: string}> $expected
*
* @dataProvider provideGetClassyElements80Cases
*
* @requires PHP >= 8.0
*/
public function testGetClassyElements80(array $expected, string $source): void
{
$this->testGetClassyElements($expected, $source);
}
/**
* @return iterable<string, array{array<int, array{classIndex: int, type: string}>, string}>
*/
public static function provideGetClassyElements80Cases(): iterable
{
yield 'promoted properties' => [
[
9 => [
'classIndex' => 1,
'type' => 'method',
],
18 => [
'classIndex' => 1,
'type' => 'promoted_property',
],
26 => [
'classIndex' => 1,
'type' => 'promoted_property',
],
37 => [
'classIndex' => 1,
'type' => 'promoted_property',
],
],
<<<'PHP'
<?php class Foo {
public function __construct(
public bool $b,
protected ?int $i,
private bool|int|string $x,
) {}
}
PHP,
];
}
/**
* @param array<int, array{classIndex: int, type: string}> $expected
*
* @dataProvider provideGetClassyElements81Cases
*
* @requires PHP 8.1
*/
public function testGetClassyElements81(array $expected, string $source): void
{
$this->testGetClassyElements($expected, $source);
}
/**
* @return iterable<array{array<int, array{classIndex: int, type: string}>, string}>
*/
public static function provideGetClassyElements81Cases(): iterable
{
yield [
[
11 => [
'classIndex' => 1,
'type' => 'property', // $prop1
],
20 => [
'classIndex' => 1,
'type' => 'property', // $prop2
],
29 => [
'classIndex' => 1,
'type' => 'property', // $prop13
],
],
'<?php
class Foo
{
readonly string $prop1;
readonly public string $prop2;
public readonly string $prop3;
}
',
];
yield 'final const' => [
[
11 => [
'classIndex' => 1,
'type' => 'const', // A
],
24 => [
'classIndex' => 1,
'type' => 'const', // B
],
],
'<?php
class Foo
{
final public const A = "1";
public final const B = "2";
}
',
];
yield 'enum final const' => [
[
11 => [
'classIndex' => 1,
'type' => 'const', // A
],
24 => [
'classIndex' => 1,
'type' => 'const', // B
],
],
'<?php
enum Foo
{
final public const A = "1";
public final const B = "2";
}
',
];
yield 'enum case' => [
[
12 => [
'classIndex' => 1,
'type' => 'const', // Spades
],
21 => [
'classIndex' => 1,
'type' => 'case', // Hearts
],
32 => [
'classIndex' => 1,
'type' => 'method', // function tests
],
81 => [
'classIndex' => 75,
'type' => 'method', // function bar123
],
135 => [
'classIndex' => 127,
'type' => 'method', // function bar7
],
],
'<?php
enum Foo: string
{
private const Spades = 123;
case Hearts = "H";
private function test($foo) {
switch ($foo) {
case 1:
// case 2
case 3:
echo 123;
break;
}
return new class {
public function bar123($foo) {
switch ($foo) {
case 1:
// case 2
case 3:
echo 123;
};
}
};
}
}
class Bar {
public function bar7($foo) {
switch ($foo) {
case 1:
// case 2
case 3:
echo 123;
};
}
}
',
];
yield 'enum' => [
[
10 => [
'classIndex' => 1,
'type' => 'case',
],
19 => [
'classIndex' => 1,
'type' => 'case',
],
28 => [
'classIndex' => 1,
'type' => 'method',
],
],
'<?php
enum Foo: string
{
case Bar = "bar";
case Baz = "baz";
function qux() {
switch (true) {
case "x": break;
}
}
}
',
];
yield 'readonly promoted property' => [
[
9 => [
'classIndex' => 1,
'type' => 'method',
],
19 => [
'classIndex' => 1,
'type' => 'promoted_property',
],
],
<<<'PHP'
<?php class Foo {
public function __construct(public readonly bool $b) {}
}
PHP,
];
yield 'promoted property without visibility' => [
[
9 => [
'classIndex' => 1,
'type' => 'method',
],
17 => [
'classIndex' => 1,
'type' => 'promoted_property',
],
],
<<<'PHP'
<?php class Foo {
public function __construct(readonly bool $b) {}
}
PHP,
];
}
/**
* @param array<int, array{classIndex: int, type: string}> $expected
*
* @dataProvider provideGetClassyElements82Cases
*
* @requires PHP 8.2
*/
public function testGetClassyElements82(array $expected, string $source): void
{
$this->testGetClassyElements($expected, $source);
}
/**
* @return iterable<string, array{array<int, array{classIndex: int, type: string}>, string}>
*/
public static function provideGetClassyElements82Cases(): iterable
{
yield 'constant in trait' => [
[
7 => [
'classIndex' => 1,
'type' => 'const',
],
18 => [
'classIndex' => 1,
'type' => 'const',
],
],
<<<'PHP'
<?php
trait Foo
{
const BAR = 0;
final const BAZ = 1;
}
PHP,
];
yield 'readonly class' => [
[
11 => [
'classIndex' => 3,
'type' => 'method',
],
22 => [
'classIndex' => 3,
'type' => 'method',
],
],
<<<'PHP'
<?php readonly class Foo {
public function __construct() {}
public function process(object $event): void {}
}
PHP,
];
}
/**
* @param array<int, array{classIndex: int, type: string}> $expected
*
* @dataProvider provideGetClassyElements84Cases
*
* @requires PHP >= 8.4
*/
public function testGetClassyElements84(array $expected, string $source): void
{
$this->testGetClassyElements($expected, $source);
}
/**
* @return iterable<string, array{array<int, array{classIndex: int, type: _ClassyElementType}>, string}>
*/
public static function provideGetClassyElements84Cases(): iterable
{
yield 'property hooks' => [
[
11 => [
'classIndex' => 1,
'type' => 'property',
],
],
<<<'PHP'
<?php
class Foo
{
protected int $bar {
set => $this->bar = $value;
}
}
PHP,
];
}
/**
* @param array<int, array{classIndex: int, type: _ClassyElementType}> $expected
*
* @dataProvider provideGetClassyElements85Cases
*
* @requires PHP 8.5
*/
public function testGetClassyElements85(array $expected, string $source): void
{
$this->testGetClassyElements($expected, $source);
}
/**
* @return iterable<string, array{array<int, array{classIndex: int, type: _ClassyElementType}>, string}>
*/
public static function provideGetClassyElements85Cases(): iterable
{
yield 'final promoted property' => [
[
9 => [
'classIndex' => 1,
'type' => 'method',
],
19 => [
'classIndex' => 1,
'type' => 'promoted_property',
],
],
<<<'PHP'
<?php class Foo {
public function __construct(public final bool $b) {}
}
PHP,
];
yield 'promoted property without visibility' => [
[
9 => [
'classIndex' => 1,
'type' => 'method',
],
17 => [
'classIndex' => 1,
'type' => 'promoted_property',
],
],
<<<'PHP'
<?php class Foo {
public function __construct(final bool $b) {}
}
PHP,
];
}
/**
* @param array<int, bool> $expected
*
* @dataProvider provideIsAnonymousClassCases
*/
public function testIsAnonymousClass(array $expected, string $source): void
{
$tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
foreach ($expected as $index => $expectedValue) {
self::assertSame($expectedValue, $tokensAnalyzer->isAnonymousClass($index));
}
}
/**
* @return iterable<int, array{array<int, bool>, string}>
*/
public static function provideIsAnonymousClassCases(): iterable
{
yield [
[1 => false],
'<?php class foo {}',
];
yield [
[7 => true],
'<?php $foo = new class() {};',
];
yield [
[7 => true],
'<?php $foo = new class() extends Foo implements Bar, Baz {};',
];
yield [
[1 => false, 19 => true],
'<?php class Foo { function bar() { return new class() {}; } }',
];
yield [
[7 => true, 11 => true],
'<?php $a = new class(new class($d->a) implements B{}) extends C{};',
];
yield [
[1 => false],
'<?php interface foo {}',
];
}
/**
* @param array<int, bool> $expected
*
* @dataProvider provideIsAnonymousClass80Cases
*
* @requires PHP 8.0
*/
public function testIsAnonymousClass80(array $expected, string $source): void
{
$this->testIsAnonymousClass($expected, $source);
}
/**
* @return iterable<int, array{array<int, bool>, string}>
*/
public static function provideIsAnonymousClass80Cases(): iterable
{
yield [
[11 => true],
'<?php $object = new #[ExampleAttribute] class(){};',
];
yield [
[27 => true],
'<?php $object = new #[A] #[B] #[C]#[D]/* */ /** */#[E]class(){};',
];
}
/**
* @param array<int, bool> $expected
*
* @dataProvider provideIsAnonymousClass81Cases
*
* @requires PHP 8.1
*/
public function testIsAnonymousClass81(array $expected, string $source): void
{
$this->testIsAnonymousClass($expected, $source);
}
/**
* @return iterable<int, array{array<int, bool>, string}>
*/
public static function provideIsAnonymousClass81Cases(): iterable
{
yield [
[1 => false],
'<?php enum foo {}',
];
}
/**
* @param array<int, bool> $expected
*
* @dataProvider provideIsAnonymousClass83Cases
*
* @requires PHP 8.3
*/
public function testIsAnonymousClass83(array $expected, string $source): void
{
$this->testIsAnonymousClass($expected, $source);
}
/**
* @return iterable<string, array{array<int, bool>, string}>
*/
public static function provideIsAnonymousClass83Cases(): iterable
{
yield 'simple readonly anonymous class' => [
[9 => true],
'<?php $instance = new readonly class {};',
];
yield 'readonly anonymous class with attribute' => [
[13 => true],
'<?php $instance = new #[Foo] readonly class {};',
];
yield 'readonly anonymous class with multiple attributes' => [
[17 => true],
'<?php $instance = new #[Foo] #[BAR] readonly class {};',
];
}
/**
* @param array<int, bool> $expected
*
* @dataProvider provideIsLambdaCases
*/
public function testIsLambda(array $expected, string $source): void
{
$tokensAnalyzer = new TokensAnalyzer(Tokens::fromCode($source));
foreach ($expected as $index => $isLambda) {
self::assertSame($isLambda, $tokensAnalyzer->isLambda($index));
}
}
/**
* @return iterable<int, array{array<int, bool>, string}>
*/
public static function provideIsLambdaCases(): iterable
{
yield [
[1 => false],
'<?php function foo () {};',
];
yield [
[1 => false],
'<?php function /** foo */ foo () {};',
];
yield [
[5 => true],
'<?php $foo = function () {};',
];
yield [
[5 => true],
'<?php $foo = function /** foo */ () {};',
];
yield [
[7 => true],
'<?php
preg_replace_callback(
"/(^|[a-z])/",
function (array $matches) {
return "a";
},
$string
);',
];
yield [
[5 => true],
'<?php $foo = function &() {};',
];
yield [
[6 => true],
'<?php
$a = function (): array {
return [];
};',
];
yield [
[2 => false],
'<?php
function foo (): array {
return [];
};',
];
yield [
[6 => true],
'<?php
$a = function (): void {
return [];
};',
];
yield [
[2 => false],
'<?php
function foo (): void {
return [];
};',
];
yield [
[6 => true],
'<?php
$a = function (): ?int {
return [];
};',
];
yield [
[6 => true],
'<?php
$a = function (): int {
return [];
};',
];
yield [
[2 => false],
'<?php
function foo (): ?int {
return [];
};',
];
yield [
[5 => true],
'<?php $fn = fn() => [];',
];
yield [
[5 => true],
'<?php $fn = fn () => [];',
];
}
/**
* @param array<int, bool> $expected
*
* @dataProvider provideIsLambda80Cases
*
* @requires PHP 8.0
*/
public function testIsLambda80(array $expected, string $source): void
{
$this->testIsLambda($expected, $source);
}
/**
* @return iterable<int, array{array<int, bool>, string}>
*/
public static function provideIsLambda80Cases(): iterable
{
yield [
[6 => true],
'<?php
$a = function (): ?static {
return [];
};',
];
yield [
[6 => true],
'<?php
$a = function (): static {
return [];
};',
];
yield [
[14 => true],
'<?php
$c = 4; //
$a = function(
$a,
$b,
) use (
$c,
) {
echo $a + $b + $c;
};
$a(1,2);',
| 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/Tokenizer/AbstractTransformerTest.php | tests/Tokenizer/AbstractTransformerTest.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\Tokenizer;
use PhpCsFixer\Tests\Fixtures\Test\AbstractTransformerTest\FooTransformer;
use PhpCsFixer\Tests\TestCase;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\AbstractTransformer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class AbstractTransformerTest extends TestCase
{
public function testNameAndPriorityDefault(): void
{
$transformer = new FooTransformer();
self::assertSame(0, $transformer->getPriority());
self::assertSame('foo', $transformer->getName());
}
public function testCustomTokens(): void
{
$transformer = new FooTransformer();
self::assertSame([], $transformer->getCustomTokens());
}
}
| 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/Tokenizer/TokensTest.php | tests/Tokenizer/TokensTest.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\Tokenizer;
use PhpCsFixer\Tests\Test\Assert\AssertTokensTrait;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-import-type _PhpTokenPrototypePartial from Token
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Tokens
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TokensTest extends TestCase
{
use AssertTokensTrait;
public function testReadFromCacheAfterClearing(): void
{
$code = '<?php echo 1;';
$tokens = Tokens::fromCode($code);
$countBefore = $tokens->count();
for ($i = 0; $i < $countBefore; ++$i) {
$tokens->clearAt($i);
}
$tokens = Tokens::fromCode($code);
self::assertCount($countBefore, $tokens);
}
/**
* @param null|array<int, Token> $expected
* @param non-empty-list<_PhpTokenPrototypePartial|Token> $sequence
* @param bool|list<bool> $caseSensitive
*
* @dataProvider provideFindSequenceCases
*/
public function testFindSequence(
string $source,
?array $expected,
array $sequence,
int $start = 0,
?int $end = null,
$caseSensitive = true
): void {
$tokens = Tokens::fromCode($source);
self::assertEqualsTokensArray(
$expected,
$tokens->findSequence(
$sequence,
$start,
$end,
$caseSensitive,
),
);
}
/**
* @return iterable<int, array{0: string, 1: null|array<int, Token>, 2: list<_PhpTokenPrototypePartial|Token>, 3?: int, 4?: int, 5?: array<int, bool>|bool}>
*/
public static function provideFindSequenceCases(): iterable
{
yield [
'<?php $x = 1;',
null,
[
new Token(';'),
],
7,
];
yield [
'<?php $x = 2;',
null,
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$y'],
],
];
yield [
'<?php $x = 3;',
[
0 => new Token([\T_OPEN_TAG, '<?php ']),
1 => new Token([\T_VARIABLE, '$x']),
],
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$x'],
],
];
yield [
'<?php $x = 4;',
[
3 => new Token('='),
5 => new Token([\T_LNUMBER, '4']),
6 => new Token(';'),
],
[
'=',
[\T_LNUMBER, '4'],
';',
],
];
yield [
'<?php $x = 5;',
[
0 => new Token([\T_OPEN_TAG, '<?php ']),
1 => new Token([\T_VARIABLE, '$x']),
],
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$x'],
],
0,
];
yield [
'<?php $x = 6;',
null,
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$x'],
],
1,
];
yield [
'<?php $x = 7;',
[
3 => new Token('='),
5 => new Token([\T_LNUMBER, '7']),
6 => new Token(';'),
],
[
'=',
[\T_LNUMBER, '7'],
';',
],
3,
6,
];
yield [
'<?php $x = 8;',
null,
[
'=',
[\T_LNUMBER, '8'],
';',
],
4,
6,
];
yield [
'<?php $x = 9;',
null,
[
'=',
[\T_LNUMBER, '9'],
';',
],
3,
5,
];
yield [
'<?php $x = 10;',
[
0 => new Token([\T_OPEN_TAG, '<?php ']),
1 => new Token([\T_VARIABLE, '$x']),
],
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$x'],
],
0,
1,
true,
];
yield [
'<?php $x = 11;',
null,
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$X'],
],
0,
1,
true,
];
yield [
'<?php $x = 12;',
null,
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$X'],
],
0,
1,
[1 => true],
];
yield [
'<?php $x = 13;',
[
0 => new Token([\T_OPEN_TAG, '<?php ']),
1 => new Token([\T_VARIABLE, '$x']),
],
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$X'],
],
0,
1,
false,
];
yield [
'<?php $x = 14;',
[
0 => new Token([\T_OPEN_TAG, '<?php ']),
1 => new Token([\T_VARIABLE, '$x']),
],
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$X'],
],
0,
1,
[1 => false],
];
yield [
'<?php $x = 15;',
[
0 => new Token([\T_OPEN_TAG, '<?php ']),
1 => new Token([\T_VARIABLE, '$x']),
],
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$X'],
],
0,
1,
[1 => false],
];
yield [
'<?php $x = 16;',
null,
[
[\T_OPEN_TAG],
[\T_VARIABLE, '$X'],
],
0,
1,
[2 => false],
];
yield [
'<?php $x = 17;',
null,
[
[\T_VARIABLE, '$X'],
'=',
],
0,
10,
];
}
/**
* @param non-empty-list<_PhpTokenPrototypePartial|Token> $sequence sequence of token prototypes
*
* @dataProvider provideFindSequenceExceptionCases
*/
public function testFindSequenceException(string $message, array $sequence): void
{
$tokens = Tokens::fromCode('<?php $x = 1;');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage($message);
$tokens->findSequence($sequence);
}
/**
* @return iterable<int, array{string, list<mixed>}>
*/
public static function provideFindSequenceExceptionCases(): iterable
{
$emptyToken = new Token('');
yield ['Invalid sequence.', []];
yield [
'Non-meaningful token at position: "0".',
[[\T_WHITESPACE, ' ']],
];
yield [
'Non-meaningful token at position: "1".',
['{', [\T_COMMENT, '// Foo'], '}'],
];
yield [
'Non-meaningful (empty) token at position: "2".',
['{', '!', $emptyToken, '}'],
];
}
public function testClearRange(): void
{
$source = <<<'PHP'
<?php
class FooBar
{
public function foo()
{
return 'bar';
}
public function bar()
{
return 'foo';
}
}
PHP;
$tokens = Tokens::fromCode($source);
// @phpstan-ignore-next-line offsetAccess.notFound
[$fooIndex, $barIndex] = array_keys($tokens->findGivenKind(\T_PUBLIC));
$tokens->clearRange($fooIndex, $barIndex - 1);
$newPublicIndexes = array_keys($tokens->findGivenKind(\T_PUBLIC));
self::assertSame($barIndex, reset($newPublicIndexes));
for ($i = $fooIndex; $i < $barIndex; ++$i) {
self::assertTrue($tokens[$i]->isWhitespace());
}
}
/**
* @dataProvider provideMonolithicPhpDetectionCases
*/
public function testMonolithicPhpDetection(bool $isMonolithic, string $source): void
{
$tokens = Tokens::fromCode($source);
self::assertSame($isMonolithic, $tokens->isMonolithicPhp());
}
/**
* @return iterable<int, array{bool, string}>
*/
public static function provideMonolithicPhpDetectionCases(): iterable
{
yield [true, "<?php\n"];
yield [true, "<?php\n?>"];
yield [false, "#!\n<?php\n"];
yield [false, "#!/usr/bin/bash\ncat <?php\n"];
yield [false, "#!/usr/bin/env bash\ncat <?php\n"];
yield [true, "#!/usr/bin/php\n<?php\n"];
yield [true, "#!/usr/bin/php7.4-cli\n<?php\n"];
yield [false, "#!/usr/bin/php\n\n<?php\n"]; // empty line after shebang would be printed to console before PHP executes
yield [true, "#!/usr/bin/php8\n<?php\n"];
yield [true, "#!/usr/bin/env php\n<?php\n"];
yield [true, "#!/usr/bin/env php7.4\n<?php\n"];
yield [true, "#!/usr/bin/env php7.4-cli\n<?php\n"];
yield [false, "#!/usr/bin/env this-is\ntoo-much\n<?php\n"];
yield [false, "#!/usr/bin/php\nFoo bar<?php\n"];
yield [false, "#!/usr/bin/env php -n \nFoo bar\n<?php\n"];
yield [false, ''];
yield [false, ' '];
yield [false, " <?php\n"];
yield [false, "<?php\n?> "];
yield [false, "<?php\n?><?php\n"];
yield [false, 'Hello<?php echo "World!"; ?>'];
yield [false, '<?php echo "Hello"; ?> World!'];
// short open tag
yield [(bool) \ini_get('short_open_tag'), "<?\n"];
yield [(bool) \ini_get('short_open_tag'), "<?\n?>"];
yield [false, " <?\n"];
yield [false, "<?\n?> "];
yield [false, "<?\n?><?\n"];
yield [false, "<?\n?><?php\n"];
yield [false, "<?\n?><?=' ';\n"];
yield [false, "<?php\n?><?\n"];
yield [false, "<?=' '\n?><?\n"];
// short open tag echo
yield [true, "<?=' ';\n"];
yield [true, "<?=' '?>"];
yield [false, " <?=' ';\n"];
yield [false, "<?=' '?> "];
yield [false, "<?php\n?><?=' ';\n"];
yield [false, "<?=' '\n?><?php\n"];
yield [false, "<?=' '\n?><?=' ';\n"];
}
public function testTokenKindsFound(): void
{
$code = <<<'EOF'
<?php
class Foo
{
public $foo;
}
if (!function_exists('bar')) {
function bar()
{
return 'bar';
}
}
EOF;
$tokens = Tokens::fromCode($code);
self::assertTrue($tokens->isTokenKindFound(\T_CLASS));
self::assertTrue($tokens->isTokenKindFound(\T_RETURN));
self::assertFalse($tokens->isTokenKindFound(\T_INTERFACE));
self::assertFalse($tokens->isTokenKindFound(\T_ARRAY));
self::assertTrue($tokens->isAllTokenKindsFound([\T_CLASS, \T_RETURN]));
self::assertFalse($tokens->isAllTokenKindsFound([\T_CLASS, \T_INTERFACE]));
self::assertTrue($tokens->isAnyTokenKindsFound([\T_CLASS, \T_RETURN]));
self::assertTrue($tokens->isAnyTokenKindsFound([\T_CLASS, \T_INTERFACE]));
self::assertFalse($tokens->isAnyTokenKindsFound([\T_INTERFACE, \T_ARRAY]));
}
public function testFindGivenKind(): void
{
$source = <<<'PHP'
<?php
class FooBar
{
public function foo()
{
return 'bar';
}
public function bar()
{
return 'foo';
}
}
PHP;
$tokens = Tokens::fromCode($source);
$found = $tokens->findGivenKind(\T_CLASS);
self::assertCount(1, $found);
self::assertArrayHasKey(1, $found);
self::assertSame(\T_CLASS, $found[1]->getId());
$found = $tokens->findGivenKind([\T_CLASS, \T_FUNCTION]);
self::assertCount(2, $found);
self::assertArrayHasKey(\T_CLASS, $found);
self::assertIsArray($found[\T_CLASS]);
self::assertCount(1, $found[\T_CLASS]);
self::assertArrayHasKey(1, $found[\T_CLASS]);
self::assertSame(\T_CLASS, $found[\T_CLASS][1]->getId());
self::assertArrayHasKey(\T_FUNCTION, $found);
self::assertIsArray($found[\T_FUNCTION]);
self::assertCount(2, $found[\T_FUNCTION]);
self::assertArrayHasKey(9, $found[\T_FUNCTION]);
self::assertSame(\T_FUNCTION, $found[\T_FUNCTION][9]->getId());
self::assertArrayHasKey(26, $found[\T_FUNCTION]);
self::assertSame(\T_FUNCTION, $found[\T_FUNCTION][26]->getId());
// test offset and limits of the search
$found = $tokens->findGivenKind([\T_CLASS, \T_FUNCTION], 10);
self::assertArrayHasKey(\T_CLASS, $found);
self::assertCount(0, $found[\T_CLASS]);
self::assertArrayHasKey(\T_FUNCTION, $found);
self::assertCount(1, $found[\T_FUNCTION]);
self::assertArrayHasKey(26, $found[\T_FUNCTION]);
$found = $tokens->findGivenKind([\T_CLASS, \T_FUNCTION], 2, 10);
self::assertArrayHasKey(\T_CLASS, $found);
self::assertCount(0, $found[\T_CLASS]);
self::assertArrayHasKey(\T_FUNCTION, $found);
self::assertCount(1, $found[\T_FUNCTION]);
self::assertArrayHasKey(9, $found[\T_FUNCTION]);
}
/**
* @param list<int> $indexes to clear
* @param list<Token> $expected tokens
*
* @dataProvider provideClearTokenAndMergeSurroundingWhitespaceCases
*/
public function testClearTokenAndMergeSurroundingWhitespace(string $source, array $indexes, array $expected): void
{
$this->doTestClearTokens($source, $indexes, $expected);
if (\count($indexes) > 1) {
$this->doTestClearTokens($source, array_reverse($indexes), $expected);
}
}
/**
* @return iterable<int, array{string, list<int>, list<Token>}>
*/
public static function provideClearTokenAndMergeSurroundingWhitespaceCases(): iterable
{
$clearToken = new Token('');
yield [
'<?php if($a){}else{}',
[7, 8, 9],
[
new Token([\T_OPEN_TAG, '<?php ']),
new Token([\T_IF, 'if']),
new Token('('),
new Token([\T_VARIABLE, '$a']),
new Token(')'),
new Token('{'),
new Token('}'),
$clearToken,
$clearToken,
$clearToken,
],
];
yield [
'<?php $a;/**/;',
[2],
[
// <?php $a /**/;
new Token([\T_OPEN_TAG, '<?php ']),
new Token([\T_VARIABLE, '$a']),
$clearToken,
new Token([\T_COMMENT, '/**/']),
new Token(';'),
],
];
yield [
'<?php ; ; ;',
[3],
[
// <?php ; ;
new Token([\T_OPEN_TAG, '<?php ']),
new Token(';'),
new Token([\T_WHITESPACE, ' ']),
$clearToken,
$clearToken,
new Token(';'),
],
];
yield [
'<?php ; ; ;',
[1, 5],
[
// <?php ;
new Token([\T_OPEN_TAG, '<?php ']),
new Token([\T_WHITESPACE, ' ']),
$clearToken,
new Token(';'),
new Token([\T_WHITESPACE, ' ']),
$clearToken,
],
];
yield [
'<?php ; ; ;',
[1, 3],
[
// <?php ;
new Token([\T_OPEN_TAG, '<?php ']),
new Token([\T_WHITESPACE, ' ']),
$clearToken,
$clearToken,
$clearToken,
new Token(';'),
],
];
yield [
'<?php ; ; ;',
[1],
[
// <?php ; ;
new Token([\T_OPEN_TAG, '<?php ']),
new Token([\T_WHITESPACE, ' ']),
$clearToken,
new Token(';'),
new Token([\T_WHITESPACE, ' ']),
new Token(';'),
],
];
}
/**
* @param -1|1 $direction
* @param list<_PhpTokenPrototypePartial|Token> $findTokens
*
* @dataProvider provideTokenOfKindSiblingCases
*/
public function testTokenOfKindSibling(
?int $expectedIndex,
int $direction,
int $index,
array $findTokens,
bool $caseSensitive = true
): void {
$source = '<?php
$a = function ($b) {
return $b;
};
echo $a(1);
// test
return 123;';
Tokens::clearCache();
$tokens = Tokens::fromCode($source);
if (1 === $direction) {
self::assertSame($expectedIndex, $tokens->getNextTokenOfKind($index, $findTokens, $caseSensitive));
} else {
self::assertSame($expectedIndex, $tokens->getPrevTokenOfKind($index, $findTokens, $caseSensitive));
}
self::assertSame($expectedIndex, $tokens->getTokenOfKindSibling($index, $direction, $findTokens, $caseSensitive));
}
/**
* @return iterable<int, array{null|int, int, int, list<_PhpTokenPrototypePartial|Token>}>
*/
public static function provideTokenOfKindSiblingCases(): iterable
{
// find next cases
yield [
35, 1, 34, [';'],
];
yield [
14, 1, 0, [[\T_RETURN]],
];
yield [
32, 1, 14, [[\T_RETURN]],
];
yield [
6, 1, 0, [[\T_RETURN], [\T_FUNCTION]],
];
// find previous cases
yield [
14, -1, 32, [[\T_RETURN], [\T_FUNCTION]],
];
yield [
6, -1, 7, [[\T_FUNCTION]],
];
yield [
null, -1, 6, [[\T_FUNCTION]],
];
}
/**
* @dataProvider provideFindBlockEndCases
*
* @param Tokens::BLOCK_TYPE_* $type
*/
public function testFindBlockEnd(int $expectedIndex, string $source, int $type, int $searchIndex): void
{
self::assertFindBlockEnd($expectedIndex, $source, $type, $searchIndex);
}
/**
* @return iterable<int, array{int, string, int, int}>
*/
public static function provideFindBlockEndCases(): iterable
{
yield [4, '<?php ${$bar};', Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, 2];
yield [4, '<?php test(1);', Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 2];
yield [4, '<?php $a[1];', Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, 2];
yield [6, '<?php [1, "foo"];', Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, 1];
yield [5, '<?php $foo->{$bar};', Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, 3];
yield [4, '<?php list($a) = $b;', Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 2];
yield [6, '<?php if($a){}?>', Tokens::BLOCK_TYPE_CURLY_BRACE, 5];
yield [11, '<?php $foo = (new Foo());', Tokens::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION, 5];
yield [10, '<?php $object->{"set_{$name}"}(42);', Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, 3];
yield [19, '<?php $foo = (new class () implements Foo {});', Tokens::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION, 5];
yield [10, '<?php use a\{ClassA, ClassB};', Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, 5];
yield [3, '<?php [$a] = $array;', Tokens::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE, 1];
yield [8, '<?php "start__${array[key]}__end";', Tokens::BLOCK_TYPE_COMPLEX_STRING_VARIABLE, 3];
}
/**
* @requires PHP 8.0
*
* @dataProvider provideFindBlockEnd80Cases
*
* @param Tokens::BLOCK_TYPE_* $type
*/
public function testFindBlockEnd80(int $expectedIndex, string $source, int $type, int $searchIndex): void
{
self::assertFindBlockEnd($expectedIndex, $source, $type, $searchIndex);
}
/**
* @return iterable<int, array{int, string, int, int}>
*/
public static function provideFindBlockEnd80Cases(): iterable
{
yield [
9,
'<?php class Foo {
#[Required]
public $bar;
}',
Tokens::BLOCK_TYPE_ATTRIBUTE,
7,
];
}
/**
* @requires PHP 8.2
*
* @dataProvider provideFindBlockEnd82Cases
*
* @param Tokens::BLOCK_TYPE_* $type
*/
public function testFindBlockEnd82(int $expectedIndex, string $source, int $type, int $searchIndex): void
{
self::assertFindBlockEnd($expectedIndex, $source, $type, $searchIndex);
}
/**
* @return iterable<int, array{int, string, int, int}>
*/
public static function provideFindBlockEnd82Cases(): iterable
{
yield [
11,
'<?php function foo(A|(B&C) $x) {}',
Tokens::BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS,
7,
];
yield [
11,
'<?php function foo((A&B&C)|D $x) {}',
Tokens::BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS,
5,
];
foreach ([7 => 11, 19 => 23, 27 => 35] as $openIndex => $closeIndex) {
yield [
$closeIndex,
'<?php function foo(A|(B&C)|D $x): (A&B)|bool|(C&D&E&F) {}',
Tokens::BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS,
$openIndex,
];
}
}
/**
* @requires PHP 8.3
*
* @dataProvider provideFindBlockEnd83Cases
*
* @param Tokens::BLOCK_TYPE_* $type
*/
public function testFindBlockEnd83(int $expectedIndex, string $source, int $type, int $searchIndex): void
{
self::assertFindBlockEnd($expectedIndex, $source, $type, $searchIndex);
}
/**
* @return iterable<string, array{int, string, int, int}>
*/
public static function provideFindBlockEnd83Cases(): iterable
{
yield 'simple dynamic class constant fetch' => [
7,
'<?php echo Foo::{$bar};',
Tokens::BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE,
5,
];
foreach ([[5, 7], [9, 11]] as $startEnd) {
yield 'chained dynamic class constant fetch: '.$startEnd[0] => [
$startEnd[1],
"<?php echo Foo::{'BAR'}::{'BLA'}::{static_method}(1,2) ?>",
Tokens::BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE,
$startEnd[0],
];
}
}
/**
* @param Tokens::BLOCK_TYPE_* $type
*
* @dataProvider provideFindBlockEndPre84Cases
*
* @requires PHP <8.4
*/
public function testFindBlockEndPre84(int $expectedIndex, string $source, int $type, int $searchIndex): void
{
self::assertFindBlockEnd($expectedIndex, $source, $type, $searchIndex);
}
/**
* @return iterable<int, array{int, string, int, int}>
*/
public static function provideFindBlockEndPre84Cases(): iterable
{
yield [4, '<?php $a{1};', Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, 2];
}
public function testFindBlockEndInvalidType(): void
{
Tokens::clearCache();
$tokens = Tokens::fromCode('<?php ');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches('/^Invalid param type: "-1"\.$/');
// @phpstan-ignore-next-line
$tokens->findBlockEnd(-1, 0);
}
public function testFindBlockEndInvalidStart(): void
{
Tokens::clearCache();
$tokens = Tokens::fromCode('<?php ');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches('/^Invalid param \$startIndex - not a proper block "start"\.$/');
$tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, 0);
}
public function testFindBlockEndCalledMultipleTimes(): void
{
Tokens::clearCache();
$tokens = Tokens::fromCode('<?php foo(1, 2);');
self::assertSame(7, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 2));
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches('/^Invalid param \$startIndex - not a proper block "start"\.$/');
$tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 7);
}
public function testFindBlockStartEdgeCalledMultipleTimes(): void
{
Tokens::clearCache();
$tokens = Tokens::fromCode('<?php foo(1, 2);');
self::assertSame(2, $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 7));
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageMatches('/^Invalid param \$startIndex - not a proper block "end"\.$/');
$tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, 2);
}
public function testEmptyTokens(): void
{
$code = '';
$tokens = Tokens::fromCode($code);
self::assertCount(0, $tokens);
self::assertFalse($tokens->isTokenKindFound(\T_OPEN_TAG));
}
public function testEmptyTokensMultiple(): void
{
$code = '';
$tokens = Tokens::fromCode($code);
self::assertFalse($tokens->isChanged());
$tokens->insertAt(0, new Token([\T_WHITESPACE, ' ']));
self::assertCount(1, $tokens);
self::assertFalse($tokens->isTokenKindFound(\T_OPEN_TAG));
self::assertTrue($tokens->isChanged());
$tokens2 = Tokens::fromCode($code);
self::assertCount(0, $tokens2);
self::assertFalse($tokens->isTokenKindFound(\T_OPEN_TAG));
}
public function testFromArray(): void
{
$code = '<?php echo 1;';
$tokens1 = Tokens::fromCode($code);
$tokens2 = Tokens::fromArray($tokens1->toArray());
self::assertTrue($tokens1->isTokenKindFound(\T_OPEN_TAG));
self::assertTrue($tokens2->isTokenKindFound(\T_OPEN_TAG));
self::assertSame($tokens1->getCodeHash(), $tokens2->getCodeHash());
}
public function testFromArrayEmpty(): void
{
$tokens = Tokens::fromArray([]);
self::assertFalse($tokens->isTokenKindFound(\T_OPEN_TAG));
}
/**
* @dataProvider provideIsEmptyCases
*/
public function testIsEmpty(Token $token, bool $isEmpty): void
{
$tokens = Tokens::fromArray([$token]);
Tokens::clearCache();
self::assertSame($isEmpty, $tokens->isEmptyAt(0), $token->toJson());
}
/**
* @return iterable<int, array{Token, bool}>
*/
public static function provideIsEmptyCases(): iterable
{
yield [new Token(''), true];
yield [new Token('('), false];
yield [new Token([\T_WHITESPACE, ' ']), false];
}
public function testClone(): void
{
$code = '<?php echo 1;';
$tokens = Tokens::fromCode($code);
$tokensClone = clone $tokens;
self::assertTrue($tokens->isTokenKindFound(\T_OPEN_TAG));
self::assertTrue($tokensClone->isTokenKindFound(\T_OPEN_TAG));
$count = \count($tokens);
self::assertCount($count, $tokensClone);
for ($i = 0; $i < $count; ++$i) {
self::assertTrue($tokens[$i]->equals($tokensClone[$i]));
self::assertNotSame($tokens[$i], $tokensClone[$i]);
}
}
/**
* @dataProvider provideEnsureWhitespaceAtIndexCases
*/
public function testEnsureWhitespaceAtIndex(string $expected, string $input, int $index, int $offset, string $whiteSpace): void
{
$tokens = Tokens::fromCode($input);
$tokens->ensureWhitespaceAtIndex($index, $offset, $whiteSpace);
$tokens->clearEmptyTokens();
self::assertTokens(Tokens::fromCode($expected), $tokens);
}
/**
* @return iterable<int, array{string, string, int, int, string}>
*/
public static function provideEnsureWhitespaceAtIndexCases(): iterable
{
yield [
'<?php echo 1;',
'<?php echo 1;',
1,
1,
' ',
];
yield [
'<?php echo 7;',
'<?php echo 7;',
1,
1,
' ',
];
yield [
'<?php ',
'<?php ',
1,
1,
' ',
];
yield [
'<?php $a. $b;',
'<?php $a.$b;',
2,
1,
' ',
];
yield [
'<?php $a .$b;',
'<?php $a.$b;',
2,
0,
' ',
];
yield [
"<?php\r\n",
'<?php ',
0,
1,
"\r\n",
];
yield [
'<?php $a.$b;',
'<?php $a.$b;',
2,
-1,
' ',
];
yield [
"<?php\t ",
"<?php\n",
0,
1,
"\t ",
];
yield [
'<?php ',
'<?php ',
0,
1,
' ',
];
yield [
"<?php\n",
'<?php ',
0,
1,
"\n",
];
yield [
"<?php\t",
'<?php ',
0,
1,
"\t",
];
yield [
'<?php
//
echo $a;',
'<?php
//
echo $a;',
2,
1,
"\n ",
];
yield [
'<?php
echo $a;',
'<?php
echo $a;',
0,
1,
"\n ",
];
yield [
'<?php
echo $a;',
'<?php echo $a;',
0,
1,
"\n",
];
yield [
"<?php\techo \$a;",
'<?php echo $a;',
0,
1,
"\t",
];
}
public function testAssertTokensAfterChanging(): void
{
$template = '<?php class SomeClass {
%s//
public function __construct($name)
{
$this->name = $name;
}
}';
$tokens = Tokens::fromCode(\sprintf($template, ''));
$commentIndex = $tokens->getNextTokenOfKind(0, [[\T_COMMENT]]);
$tokens->insertAt(
$commentIndex,
[
new Token([\T_PRIVATE, 'private']),
new Token([\T_WHITESPACE, ' ']),
new Token([\T_VARIABLE, '$name']),
new Token(';'),
],
);
self::assertTrue($tokens->isChanged());
$expected = Tokens::fromCode(\sprintf($template, 'private $name;'));
self::assertFalse($expected->isChanged());
self::assertTokens($expected, $tokens);
}
/**
* @dataProvider provideRemoveLeadingWhitespaceCases
*/
public function testRemoveLeadingWhitespace(int $index, ?string $whitespaces, string $expected, ?string $input = null): void
{
Tokens::clearCache();
$tokens = Tokens::fromCode($input ?? $expected);
$tokens->removeLeadingWhitespace($index, $whitespaces);
self::assertSame($expected, $tokens->generateCode());
}
/**
* @return iterable<int, array{0: int, 1: null|string, 2: string, 3?: string}>
*/
| 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/Tokenizer/CTTest.php | tests/Tokenizer/CTTest.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\Tokenizer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\CT;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\CT
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CTTest extends TestCase
{
public function testUniqueValues(): void
{
$constants = self::getConstants();
self::assertSame($constants, array_unique($constants), 'Values of CT::T_* constants must be unique.');
}
/**
* @dataProvider provideConstantsCases
*/
public function testHas(string $name, int $value): void
{
self::assertTrue(CT::has($value));
}
public function testHasNotExists(): void
{
self::assertFalse(CT::has(123));
}
/**
* @dataProvider provideConstantsCases
*/
public function testGetName(string $name, int $value): void
{
self::assertSame('CT::'.$name, CT::getName($value));
}
public function testGetNameNotExists(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('No custom token was found for "123".');
CT::getName(123);
}
/**
* @dataProvider provideConstantsCases
*/
public function testConstants(string $name, int $value): void
{
self::assertGreaterThan(10_000, $value);
self::assertFalse(\defined($name), 'The CT name must not use native T_* name.');
}
/**
* @return iterable<int, array{string, int}>
*/
public static function provideConstantsCases(): iterable
{
foreach (self::getConstants() as $name => $value) {
yield [$name, $value];
}
}
/**
* @return array<string, int>
*/
private static function getConstants(): array
{
static $constants;
if (null === $constants) {
$reflection = new \ReflectionClass(CT::class);
$constants = $reflection->getConstants();
}
return $constants;
}
}
| 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/Tokenizer/TransformersTest.php | tests/Tokenizer/TransformersTest.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\Tokenizer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Dave van der Brugge <dmvdbrugge@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Transformers
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TransformersTest extends TestCase
{
/**
* @param array<int, int> $expectedTokenKinds
*
* @dataProvider provideTransformCases
*/
public function testTransform(string $input, array $expectedTokenKinds): void
{
$tokens = Tokens::fromCode($input);
foreach ($expectedTokenKinds as $index => $expected) {
self::assertTrue($tokens->offsetExists($index));
self::assertTrue($tokens[$index]->isGivenKind($expected));
}
}
/**
* @return iterable<string, array{string, array<int, int>}>
*/
public static function provideTransformCases(): iterable
{
yield 'use trait after complex string variable' => [
<<<'SOURCE'
<?php
class TransformTest extends TestCase
{
public function testSomething()
{
$a = 1;
$this->assertSame('1', "{$a}");
}
use TestTrait;
public function testUsingTrait()
{
$this->testTraitFunction();
}
}
SOURCE,
[46 => CT::T_USE_TRAIT],
];
}
}
| 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/Tokenizer/FCTTest.php | tests/Tokenizer/FCTTest.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\Tokenizer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\FCT;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\FCT
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FCTTest extends TestCase
{
public function testConstantsHaveUniqueValues(): void
{
$constants = (new \ReflectionClass(FCT::class))->getConstants();
self::assertSame(array_unique($constants), $constants, 'Values of FCT::T_* constants must be unique.');
}
public function testConstantsHaveCorrectValues(): void
{
foreach ((new \ReflectionClass(FCT::class))->getReflectionConstants() as $constant) {
if (\defined($constant->getName())) {
self::assertSame(\constant($constant->getName()), $constant->getValue());
} else {
self::assertLessThan(0, $constant->getValue());
}
}
}
/**
* @requires PHP 8.5
*/
public function testHighestSupportedPhpVersionHaveOnlyPositiveValues(): void
{
foreach ((new \ReflectionClass(FCT::class))->getReflectionConstants() as $constant) {
self::assertGreaterThan(0, $constant->getValue());
}
}
/**
* @requires PHP < 8.0
*/
public function testLowestSupportedPhpVersionHaveOnlyNegativeValues(): void
{
foreach ((new \ReflectionClass(FCT::class))->getReflectionConstants() as $constant) {
self::assertLessThan(0, $constant->getValue());
}
}
}
| 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/Tokenizer/TokenTest.php | tests/Tokenizer/TokenTest.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\Tokenizer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
/**
* @phpstan-import-type _PhpTokenPrototypePartial from Token
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Token
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TokenTest extends TestCase
{
/**
* @param mixed $input
*
* @dataProvider provideConstructorValidationCases
*/
public function testConstructorValidation($input): void
{
$this->expectException(\InvalidArgumentException::class);
new Token($input);
}
/**
* @return iterable<int, array{mixed}>
*/
public static function provideConstructorValidationCases(): iterable
{
yield [null];
yield [123];
yield [new \stdClass()];
yield [['asd', 'asd']];
yield [[null, 'asd']];
yield [[new \stdClass(), 'asd']];
yield [[\T_WHITESPACE, null]];
yield [[\T_WHITESPACE, 123]];
yield [[\T_WHITESPACE, '']];
yield [[\T_WHITESPACE, new \stdClass()]];
}
public function testGetPrototype(): void
{
self::assertSame('(', self::getBraceToken()->getPrototype());
self::assertSame([\T_FOREACH, 'foreach'], self::getForeachToken()->getPrototype());
}
public function testIsArray(): void
{
self::assertFalse(self::getBraceToken()->isArray());
self::assertTrue(self::getForeachToken()->isArray());
}
/**
* @dataProvider provideIsCastCases
*/
public function testIsCast(Token $token, bool $isCast): void
{
self::assertSame($isCast, $token->isCast());
}
/**
* @return iterable<int, array{Token, bool}>
*/
public static function provideIsCastCases(): iterable
{
yield [self::getBraceToken(), false];
yield [self::getForeachToken(), false];
yield [new Token([\T_ARRAY_CAST, '(array)', 1]), true];
yield [new Token([\T_BOOL_CAST, '(bool)', 1]), true];
yield [new Token([\T_DOUBLE_CAST, '(double)', 1]), true];
yield [new Token([\T_INT_CAST, '(int)', 1]), true];
yield [new Token([\T_OBJECT_CAST, '(object)', 1]), true];
yield [new Token([\T_STRING_CAST, '(string)', 1]), true];
yield [new Token([\T_UNSET_CAST, '(unset)', 1]), true];
}
/**
* @dataProvider provideIsClassyCases
*/
public function testIsClassy(Token $token, bool $isClassy): void
{
self::assertSame($isClassy, $token->isClassy());
}
/**
* @return iterable<int, array{Token, bool}>
*/
public static function provideIsClassyCases(): iterable
{
yield [self::getBraceToken(), false];
yield [self::getForeachToken(), false];
yield [new Token([\T_CLASS, 'class', 1]), true];
yield [new Token([\T_INTERFACE, 'interface', 1]), true];
yield [new Token([\T_TRAIT, 'trait', 1]), true];
}
/**
* @requires PHP 8.1
*/
public function testEnumIsClassy(): void
{
$enumToken = new Token([\T_ENUM, 'enum', 1]);
self::assertTrue($enumToken->isClassy());
}
/**
* @dataProvider provideIsCommentCases
*/
public function testIsComment(Token $token, bool $isComment): void
{
self::assertSame($isComment, $token->isComment());
}
/**
* @return iterable<int, array{Token, bool}>
*/
public static function provideIsCommentCases(): iterable
{
yield [self::getBraceToken(), false];
yield [self::getForeachToken(), false];
yield [new Token([\T_COMMENT, '/* comment */', 1]), true];
yield [new Token([\T_DOC_COMMENT, '/** docs */', 1]), true];
}
/**
* @dataProvider provideIsComment81Cases
*
* @requires PHP 8.0
*/
public function testIsComment81(Token $token, bool $isComment): void
{
self::assertSame($isComment, $token->isComment());
}
/**
* @return iterable<int, array{Token, bool}>
*/
public static function provideIsComment81Cases(): iterable
{
yield [new Token([FCT::T_ATTRIBUTE, '#[', 1]), false];
}
/**
* @dataProvider provideIsObjectOperatorCases
*/
public function testIsObjectOperator(Token $token, bool $isObjectOperator): void
{
self::assertSame($isObjectOperator, $token->isObjectOperator());
}
/**
* @return iterable<int, array{Token, bool}>
*/
public static function provideIsObjectOperatorCases(): iterable
{
yield [self::getBraceToken(), false];
yield [self::getForeachToken(), false];
yield [new Token([\T_COMMENT, '/* comment */']), false];
yield [new Token([\T_DOUBLE_COLON, '::']), false];
yield [new Token([\T_OBJECT_OPERATOR, '->']), true];
}
/**
* @dataProvider provideIsObjectOperator80Cases
*
* @requires PHP 8.0
*/
public function testIsObjectOperator80(Token $token, bool $isObjectOperator): void
{
self::assertSame($isObjectOperator, $token->isObjectOperator());
}
/**
* @return iterable<int, array{Token, bool}>
*/
public static function provideIsObjectOperator80Cases(): iterable
{
yield [new Token([FCT::T_NULLSAFE_OBJECT_OPERATOR, '?->']), true];
}
public function testIsGivenKind(): void
{
$braceToken = self::getBraceToken();
$foreachToken = self::getForeachToken();
self::assertFalse($braceToken->isGivenKind(\T_FOR));
self::assertFalse($braceToken->isGivenKind(\T_FOREACH));
self::assertFalse($braceToken->isGivenKind([\T_FOR]));
self::assertFalse($braceToken->isGivenKind([\T_FOREACH]));
self::assertFalse($braceToken->isGivenKind([\T_FOR, \T_FOREACH]));
self::assertFalse($foreachToken->isGivenKind(\T_FOR));
self::assertTrue($foreachToken->isGivenKind(\T_FOREACH));
self::assertFalse($foreachToken->isGivenKind([\T_FOR]));
self::assertTrue($foreachToken->isGivenKind([\T_FOREACH]));
self::assertTrue($foreachToken->isGivenKind([\T_FOR, \T_FOREACH]));
}
public function testIsKeywords(): void
{
self::assertTrue(self::getForeachToken()->isKeyword());
self::assertFalse(self::getBraceToken()->isKeyword());
}
/**
* @dataProvider provideIsMagicConstantCases
*/
public function testIsMagicConstant(?int $tokenId, string $content, bool $isConstant = true): void
{
$token = new Token(
null === $tokenId ? $content : [$tokenId, $content],
);
self::assertSame($isConstant, $token->isMagicConstant());
}
/**
* @return iterable<int, array{0: null|int, 1: string, 2?: bool}>
*/
public static function provideIsMagicConstantCases(): iterable
{
$cases = [
[\T_CLASS_C, '__CLASS__'],
[\T_DIR, '__DIR__'],
[\T_FILE, '__FILE__'],
[\T_FUNC_C, '__FUNCTION__'],
[\T_LINE, '__LINE__'],
[\T_METHOD_C, '__METHOD__'],
[\T_NS_C, '__NAMESPACE__'],
[\T_TRAIT_C, '__TRAIT__'],
];
foreach ($cases as $case) {
yield [$case[0], strtolower($case[1])];
}
$foreachToken = self::getForeachToken();
yield [$foreachToken->getId(), $foreachToken->getContent(), false];
yield [$foreachToken->getId(), strtoupper($foreachToken->getContent()), false];
$braceToken = self::getBraceToken();
yield [$braceToken->getId(), $braceToken->getContent(), false];
}
/**
* @dataProvider provideIsNativeConstantCases
*/
public function testIsNativeConstant(Token $token, bool $isNativeConstant): void
{
self::assertSame($isNativeConstant, $token->isNativeConstant());
}
/**
* @return iterable<int, array{Token, bool}>
*/
public static function provideIsNativeConstantCases(): iterable
{
yield [self::getBraceToken(), false];
yield [self::getForeachToken(), false];
yield [new Token([\T_STRING, 'null', 1]), true];
yield [new Token([\T_STRING, 'false', 1]), true];
yield [new Token([\T_STRING, 'true', 1]), true];
yield [new Token([\T_STRING, 'tRuE', 1]), true];
yield [new Token([\T_STRING, 'TRUE', 1]), true];
}
/**
* @dataProvider provideIsWhitespaceCases
*/
public function testIsWhitespace(Token $token, bool $isWhitespace, ?string $whitespaces = null): void
{
if (null !== $whitespaces) {
self::assertSame($isWhitespace, $token->isWhitespace($whitespaces));
} else {
self::assertSame($isWhitespace, $token->isWhitespace(null));
self::assertSame($isWhitespace, $token->isWhitespace());
}
}
/**
* @return iterable<int, array{0: Token, 1: bool, 2?: string}>
*/
public static function provideIsWhitespaceCases(): iterable
{
yield [self::getBraceToken(), false];
yield [self::getForeachToken(), false];
yield [new Token(' '), true];
yield [new Token("\t "), true];
yield [new Token("\t "), false, ' '];
yield [new Token([\T_WHITESPACE, "\r", 1]), true];
yield [new Token([\T_WHITESPACE, "\0", 1]), true];
yield [new Token([\T_WHITESPACE, "\x0B", 1]), true];
yield [new Token([\T_WHITESPACE, "\n", 1]), true];
yield [new Token([\T_WHITESPACE, "\n", 1]), false, " \t"];
}
/**
* @param mixed $prototype
* @param ?class-string<\Throwable> $expectedExceptionClass
*
* @dataProvider provideCreatingTokenCases
*/
public function testCreatingToken($prototype, ?int $expectedId, ?string $expectedContent, ?bool $expectedIsArray, ?string $expectedExceptionClass = null): void
{
if (null !== $expectedExceptionClass) {
$this->expectException($expectedExceptionClass);
}
$token = new Token($prototype);
self::assertSame($expectedId, $token->getId());
self::assertSame($expectedContent, $token->getContent());
self::assertSame($expectedIsArray, $token->isArray());
}
/**
* @return iterable<int, array{0: mixed, 1: null|int, 2: null|string, 3: null|bool, 4?: string}>
*/
public static function provideCreatingTokenCases(): iterable
{
yield [[\T_FOREACH, 'foreach'], \T_FOREACH, 'foreach', true];
yield ['(', null, '(', false];
yield [123, null, null, null, \InvalidArgumentException::class];
yield [false, null, null, null, \InvalidArgumentException::class];
yield [null, null, null, null, \InvalidArgumentException::class];
}
public function testEqualsDefaultIsCaseSensitive(): void
{
$token = new Token([\T_FUNCTION, 'function', 1]);
self::assertTrue($token->equals([\T_FUNCTION, 'function']));
self::assertFalse($token->equals([\T_FUNCTION, 'Function']));
}
/**
* @param _PhpTokenPrototypePartial|Token $other
*
* @dataProvider provideEqualsCases
*/
public function testEquals(Token $token, bool $equals, $other, bool $caseSensitive = true): void
{
self::assertSame($equals, $token->equals($other, $caseSensitive));
}
/**
* @return iterable<int, array{0: Token, 1: bool, 2: _PhpTokenPrototypePartial|Token, 3?: bool}>
*/
public static function provideEqualsCases(): iterable
{
$brace = self::getBraceToken();
$function = new Token([\T_FUNCTION, 'function', 1]);
yield [$brace, false, '!'];
yield [$brace, false, '!', false];
yield [$brace, true, '('];
yield [$brace, true, '(', false];
yield [$function, false, '('];
yield [$function, false, '(', false];
yield [$function, false, [\T_NAMESPACE]];
yield [$function, false, [\T_NAMESPACE], false];
yield [$function, false, [\T_VARIABLE, 'function']];
yield [$function, false, [\T_VARIABLE, 'function'], false];
yield [$function, false, [\T_VARIABLE, 'Function']];
yield [$function, false, [\T_VARIABLE, 'Function'], false];
yield [$function, true, [\T_FUNCTION]];
yield [$function, true, [\T_FUNCTION], false];
yield [$function, true, [\T_FUNCTION, 'function']];
yield [$function, true, [\T_FUNCTION, 'function'], false];
yield [$function, false, [\T_FUNCTION, 'Function']];
yield [$function, true, [\T_FUNCTION, 'Function'], false];
yield [$function, false, [\T_FUNCTION, 'junction'], false];
yield [$function, true, new Token([\T_FUNCTION, 'function'])];
yield [$function, false, new Token([\T_FUNCTION, 'Function'])];
yield [$function, true, new Token([\T_FUNCTION, 'Function']), false];
// if it is an array any additional field is checked too
yield [$function, false, [\T_FUNCTION, 'function', 'unexpected']];
yield [new Token('&'), true, '&'];
}
/**
* @param _PhpTokenPrototypePartial|Token $other
*
* @dataProvider provideEquals81Cases
*
* @requires PHP 8.1
*/
public function testEquals81(Token $token, bool $equals, $other): void
{
self::assertSame($equals, $token->equals($other));
}
/**
* @return iterable<int, array{0: Token, 1: bool, 2: _PhpTokenPrototypePartial|Token}>
*/
public static function provideEquals81Cases(): iterable
{
yield [new Token('&'), true, new Token([FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, '&'])];
yield [new Token('&'), true, new Token([FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, '&'])];
yield [new Token([FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, '&']), true, '&'];
yield [new Token([FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, '&']), true, new Token([FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, '&'])];
yield [new Token([FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, '&']), true, '&'];
yield [new Token([FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, '&']), true, new Token([FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, '&'])];
}
public function testEqualsAnyDefaultIsCaseSensitive(): void
{
$token = new Token([\T_FUNCTION, 'function', 1]);
self::assertTrue($token->equalsAny([[\T_FUNCTION, 'function']]));
self::assertFalse($token->equalsAny([[\T_FUNCTION, 'Function']]));
}
/**
* @param list<_PhpTokenPrototypePartial|Token> $other
*
* @dataProvider provideEqualsAnyCases
*/
public function testEqualsAny(bool $equalsAny, array $other, bool $caseSensitive = true): void
{
$token = new Token([\T_FUNCTION, 'function', 1]);
self::assertSame($equalsAny, $token->equalsAny($other, $caseSensitive));
}
/**
* @return iterable<int, array{0: bool, 1: list<_PhpTokenPrototypePartial|Token>, 2?: bool}>
*/
public static function provideEqualsAnyCases(): iterable
{
$brace = self::getBraceToken();
$foreach = self::getForeachToken();
yield [false, []];
yield [false, [$brace]];
yield [false, [$brace, $foreach]];
yield [true, [$brace, $foreach, [\T_FUNCTION]]];
yield [true, [$brace, $foreach, [\T_FUNCTION, 'function']]];
yield [false, [$brace, $foreach, [\T_FUNCTION, 'Function']]];
yield [true, [$brace, $foreach, [\T_FUNCTION, 'Function']], false];
yield [false, [[\T_VARIABLE, 'junction'], [\T_FUNCTION, 'junction']], false];
}
/**
* @param bool|list<bool> $caseSensitive
*
* @dataProvider provideIsKeyCaseSensitiveCases
*
* @group legacy
*/
public function testIsKeyCaseSensitive(bool $isKeyCaseSensitive, $caseSensitive, int $key): void
{
$this->expectDeprecation('Method "PhpCsFixer\Tokenizer\Token::isKeyCaseSensitive" is deprecated and will be removed in the next major version.');
self::assertSame($isKeyCaseSensitive, Token::isKeyCaseSensitive($caseSensitive, $key));
}
/**
* @return iterable<int, array{bool, array<int, bool>|bool, int}>
*/
public static function provideIsKeyCaseSensitiveCases(): iterable
{
yield [true, true, 0];
yield [true, true, 1];
yield [true, [], 0];
yield [true, [true], 0];
yield [true, [false, true], 1];
yield [true, [false, true, false], 1];
yield [true, [false], 10];
yield [false, false, 10];
yield [false, [false], 0];
yield [false, [true, false], 1];
yield [false, [true, false, true], 1];
yield [false, [1 => false], 1];
}
/**
* @dataProvider provideTokenGetNameForIdCases
*/
public function testTokenGetNameForId(?string $expected, int $id): void
{
self::assertSame($expected, Token::getNameForId($id));
}
/**
* @return iterable<int, array{null|string, int}>
*/
public static function provideTokenGetNameForIdCases(): iterable
{
yield [
null,
-1,
];
yield [
'T_CLASS',
\T_CLASS,
];
yield [
'CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE',
CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE,
];
}
/**
* @dataProvider provideGetNameCases
*/
public function testGetName(Token $token, ?string $expected = null): void
{
self::assertSame($expected, $token->getName());
}
/**
* @return iterable<int, array{Token, null|string}>
*/
public static function provideGetNameCases(): iterable
{
yield [
new Token([\T_FUNCTION, 'function', 1]),
'T_FUNCTION',
];
yield [
new Token(')'),
null,
];
yield [
new Token(''),
null,
];
}
/**
* @param array<string, mixed> $expected
*
* @dataProvider provideToArrayCases
*/
public function testToArray(Token $token, array $expected): void
{
self::assertSame($expected, $token->toArray());
}
/**
* @return iterable<int, array{Token, array<string, mixed>}>
*/
public static function provideToArrayCases(): iterable
{
yield [
new Token([\T_FUNCTION, 'function', 1]),
[
'id' => \T_FUNCTION,
'name' => 'T_FUNCTION',
'content' => 'function',
'isArray' => true,
'changed' => false,
],
];
yield [
new Token(')'),
[
'id' => null,
'name' => null,
'content' => ')',
'isArray' => false,
'changed' => false,
],
];
yield [
new Token(''),
[
'id' => null,
'name' => null,
'content' => '',
'isArray' => false,
'changed' => false,
],
];
}
private static function getBraceToken(): Token
{
return new Token('(');
}
private static function getForeachToken(): Token
{
return new Token([\T_FOREACH, 'foreach']);
}
}
| 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/Tokenizer/Processor/ImportProcessorTest.php | tests/Tokenizer/Processor/ImportProcessorTest.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\Tokenizer\Processor;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Processor\ImportProcessor;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\WhitespacesFixerConfig;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Processor\ImportProcessor
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ImportProcessorTest extends TestCase
{
/**
* @param non-empty-string $symbol
*
* @dataProvider provideTokenizeNameCases
*/
public function testTokenizeName(string $symbol): void
{
self::assertSame(
$symbol,
implode(
'',
array_map(
static fn (Token $token): string => $token->getContent(),
ImportProcessor::tokenizeName($symbol),
),
),
);
}
/**
* @return iterable<int, array{0: string}>
*/
public static function provideTokenizeNameCases(): iterable
{
yield [__CLASS__];
yield ['Foo\Bar'];
yield ['\Foo\Bar'];
yield ['FooBar'];
yield ['\FooBar'];
yield ['\Foo\Bar\Baz\Buzz'];
yield ['\Foo1\Bar_\baz\buzz'];
}
/**
* @param array{
* const?: array<int|string, non-empty-string>,
* class?: array<int|string, non-empty-string>,
* function?: array<int|string, non-empty-string>
* } $imports
*
* @dataProvider provideInsertImportsCases
*/
public function testInsertImports(string $expected, string $input, array $imports, int $atIndex): void
{
$processor = new ImportProcessor(new WhitespacesFixerConfig());
$tokens = Tokens::fromCode($input);
$processor->insertImports($tokens, $imports, $atIndex);
self::assertSame($expected, $tokens->generateCode());
}
/**
* @return iterable<string, array{0: string, 1: string, 2: array{class?: list<string>, const?: list<string>, function?: list<string>}, 3: int}>
*/
public static function provideInsertImportsCases(): iterable
{
yield 'class import in single namespace' => [
'<?php
namespace Foo;
use Other\A;
use Other\B;
',
'<?php
namespace Foo;
',
[
'class' => ['Other\A', 'Other\B'],
],
6,
];
yield 'class import in single {} namespace' => [
'<?php
namespace Foo {
use Other\A;
use Other\B;
}
',
'<?php
namespace Foo {
}
',
[
'class' => ['Other\A', 'Other\B'],
],
7,
];
}
}
| 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/Tokenizer/Analyzer/ArgumentsAnalyzerTest.php | tests/Tokenizer/Analyzer/ArgumentsAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ArgumentsAnalyzerTest extends TestCase
{
/**
* @param array<int, int> $arguments
*
* @dataProvider provideArgumentsCases
*/
public function testArguments(string $code, int $openIndex, int $closeIndex, array $arguments): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new ArgumentsAnalyzer();
self::assertSame(\count($arguments), $analyzer->countArguments($tokens, $openIndex, $closeIndex));
self::assertSame($arguments, $analyzer->getArguments($tokens, $openIndex, $closeIndex));
}
/**
* @return iterable<array{string, int, int, array<int, int>}>
*/
public static function provideArgumentsCases(): iterable
{
yield ['<?php function(){};', 2, 3, []];
yield ['<?php foo();', 2, 3, []];
yield ['<?php function($a){};', 2, 4, [3 => 3]];
yield ['<?php \foo($a);', 3, 5, [4 => 4]];
yield ['<?php function($a, $b){};', 2, 7, [3 => 3, 5 => 6]];
yield ['<?php function($a, $b = array(1,2), $c = 3){};', 2, 23, [3 => 3, 5 => 15, 17 => 22]];
yield 'non condition (hardcoded)' => [
'<?php $x = strpos("foo", 123);',
6,
11,
[7 => 7, 9 => 10],
];
yield ['<?php \test($a+$b++, !$c);', 3, 12, [4 => 7, 9 => 11]];
yield ['<?php $a = function(array &$a = array()){};', 6, 17, [7 => 16]];
yield ['<?php $a = function( ... $z){};', 6, 11, [7 => 10]];
yield ['<?php $a = function(array ... $a){};', 6, 12, [7 => 11]];
yield ['<?php $a = function(\Foo\Bar $a, \Foo\Bar $b){};', 6, 21, [7 => 12, 14 => 20]];
yield ['<?php foo($a,);', 2, 5, [3 => 3]];
yield ['<?php foo($a,/**/);', 2, 6, [3 => 3]];
yield ['<?php foo($a(1,2,3,4,5),);', 2, 16, [3 => 14]];
yield ['<?php foo($a(1,2,3,4,5,),);', 2, 17, [3 => 15]];
yield ['<?php foo($a(1,2,3,4,5,),);', 4, 15, [5 => 5, 7 => 7, 9 => 9, 11 => 11, 13 => 13]];
yield ['<?php bar($a, $b , ) ;', 2, 10, [3 => 3, 5 => 7]];
}
/**
* @param array<int, int> $arguments
*
* @requires PHP 8.0
*
* @dataProvider provideArguments80Cases
*/
public function testArguments80(string $code, int $openIndex, int $closeIndex, array $arguments): void
{
$this->testArguments($code, $openIndex, $closeIndex, $arguments);
}
/**
* @return iterable<int, array{string, int, int, array<int, int>}>
*/
public static function provideArguments80Cases(): iterable
{
yield ['<?php class Foo { public function __construct(public ?string $param = null) {} }', 12, 23, [13 => 22]];
yield ['<?php class Foo { public function __construct(protected ?string $param = null) {} }', 12, 23, [13 => 22]];
yield ['<?php class Foo { public function __construct(private ?string $param = null) {} }', 12, 23, [13 => 22]];
yield ['<?php $a = function(?\Foo\Bar $a, ?\Foo\Bar $b){};', 6, 23, [7 => 13, 15 => 22]];
yield ['<?php function setFoo(null|int $param1, ?int $param2){}', 4, 16, [5 => 9, 11 => 15]];
}
/**
* @param array<int, int> $arguments
*
* @requires PHP 8.1
*
* @dataProvider provideArguments81Cases
*/
public function testArguments81(string $code, int $openIndex, int $closeIndex, array $arguments): void
{
$this->testArguments($code, $openIndex, $closeIndex, $arguments);
}
/**
* @return iterable<int, array{string, int, int, array<int, int>}>
*/
public static function provideArguments81Cases(): iterable
{
yield ['<?php function setFoo(\A\B&C $param1, C&D $param2){}', 4, 20, [5 => 12, 14 => 19]];
}
/**
* @dataProvider provideArgumentInfoCases
*/
public function testArgumentInfo(string $code, int $openIndex, int $closeIndex, ArgumentAnalysis $expected): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new ArgumentsAnalyzer();
self::assertArgumentAnalysis($expected, $analyzer->getArgumentInfo($tokens, $openIndex, $closeIndex));
}
/**
* @return iterable<int, array{string, int, int, ArgumentAnalysis}>
*/
public static function provideArgumentInfoCases(): iterable
{
yield ['<?php function($a){};', 3, 3, new ArgumentAnalysis(
'$a',
3,
null,
null,
)];
yield ['<?php \test($a);', 4, 4, new ArgumentAnalysis(
'$a',
4,
null,
null,
)];
yield ['<?php function($a, $b){};', 5, 6, new ArgumentAnalysis(
'$b',
6,
null,
null,
)];
yield ['<?php foo($a, $b)?>', 5, 6, new ArgumentAnalysis(
'$b',
6,
null,
null,
)];
yield ['<?php foo($a, "b")?>', 5, 6, new ArgumentAnalysis(
null,
null,
null,
null,
)];
yield ['<?php function($a, $b = array(1,2), $c = 3){};', 3, 3, new ArgumentAnalysis(
'$a',
3,
null,
null,
)];
yield ['<?php function($a, $b = array(1, /* */ 2), $c = 3){};', 5, 18, new ArgumentAnalysis(
'$b',
6,
'array(1,2)',
null,
)];
yield ['<?php function($a, $b = array(1,2), $c = 3){};', 17, 22, new ArgumentAnalysis(
'$c',
18,
'3',
null,
)];
yield ['<?php function(array $a = array()){};', 3, 11, new ArgumentAnalysis(
'$a',
5,
'array()',
new TypeAnalysis(
'array',
3,
3,
),
)];
yield ['<?php function(array &$a = array()){};', 3, 12, new ArgumentAnalysis(
'$a',
6,
'array()',
new TypeAnalysis(
'array',
3,
3,
),
)];
yield ['<?php function( ... $z){};', 3, 6, new ArgumentAnalysis(
'$z',
6,
null,
null,
)];
yield ['<?php function(array ... $a){};', 3, 7, new ArgumentAnalysis(
'$a',
7,
null,
new TypeAnalysis(
'array',
3,
3,
),
)];
yield ['<?php function(\Foo\Bar $a){};', 3, 8, new ArgumentAnalysis(
'$a',
8,
null,
new TypeAnalysis(
'\Foo\Bar',
3,
6,
),
)];
yield [
'<?php function(?\Foo\Bar $a){};', 3, 9, new ArgumentAnalysis(
'$a',
9,
null,
new TypeAnalysis(
'?\Foo\Bar',
3,
7,
),
),
];
yield ['<?php function($a, $b = \'\'){};', 5, 10, new ArgumentAnalysis(
'$b',
6,
"''",
null,
)];
}
/**
* @requires PHP 8.0
*
* @dataProvider provideArgumentInfo80Cases
*/
public function testArgumentInfo80(string $code, int $openIndex, int $closeIndex, ArgumentAnalysis $expected): void
{
$this->testArgumentInfo($code, $openIndex, $closeIndex, $expected);
}
/**
* @return iterable<int, array{string, int, int, ArgumentAnalysis}>
*/
public static function provideArgumentInfo80Cases(): iterable
{
yield [
'<?php function foo(#[AnAttribute] ?string $param = null) {}',
5,
16,
new ArgumentAnalysis(
'$param',
12,
'null',
new TypeAnalysis(
'?string',
9,
10,
),
),
];
foreach (['public', 'protected', 'private'] as $visibility) {
yield [
\sprintf('<?php class Foo { public function __construct(%s ?string $param = null) {} }', $visibility),
13,
22,
new ArgumentAnalysis(
'$param',
18,
'null',
new TypeAnalysis(
'?string',
15,
16,
),
),
];
}
}
/**
* @requires PHP 8.1
*
* @dataProvider provideArgumentInfo81Cases
*/
public function testArgumentInfo81(string $code, int $openIndex, int $closeIndex, ArgumentAnalysis $expected): void
{
$this->testArgumentInfo($code, $openIndex, $closeIndex, $expected);
}
/**
* @return iterable<int, array{string, int, int, ArgumentAnalysis}>
*/
public static function provideArgumentInfo81Cases(): iterable
{
yield [
'<?php
class Foo
{
public function __construct(
protected readonly ?bool $nullable = true,
) {}
}
',
13,
25,
new ArgumentAnalysis(
'$nullable',
21,
'true',
new TypeAnalysis(
'?bool',
18,
19,
),
),
];
}
/**
* @requires PHP 8.4
*
* @dataProvider provideArgumentInfo84Cases
*/
public function testArgumentInfo84(string $code, int $openIndex, int $closeIndex, ArgumentAnalysis $expected): void
{
$this->testArgumentInfo($code, $openIndex, $closeIndex, $expected);
}
/**
* @return iterable<string, array{string, int, int, ArgumentAnalysis}>
*/
public static function provideArgumentInfo84Cases(): iterable
{
yield 'asymmetric visibility public write' => [
<<<'PHP'
<?php
class Foo {
public function __construct(
public public(set) Bar $x,
) {}
}
PHP,
13,
20,
new ArgumentAnalysis(
'$x',
20,
null,
new TypeAnalysis(
'Bar',
18,
18,
),
),
];
yield 'asymmetric visibility protected write' => [
<<<'PHP'
<?php
class Foo {
public function __construct(
public protected(set) Bar $x,
) {}
}
PHP,
13,
20,
new ArgumentAnalysis(
'$x',
20,
null,
new TypeAnalysis(
'Bar',
18,
18,
),
),
];
yield 'asymmetric visibility private write' => [
<<<'PHP'
<?php
class Foo {
public function __construct(
public private(set) Bar $x,
) {}
}
PHP,
13,
20,
new ArgumentAnalysis(
'$x',
20,
null,
new TypeAnalysis(
'Bar',
18,
18,
),
),
];
}
/**
* @requires PHP 8.5
*
* @dataProvider provideArgumentInfo85Cases
*/
public function testArgumentInfo85(string $code, int $openIndex, int $closeIndex, ArgumentAnalysis $expected): void
{
$this->testArgumentInfo($code, $openIndex, $closeIndex, $expected);
}
/**
* @return iterable<string, array{string, int, int, ArgumentAnalysis}>
*/
public static function provideArgumentInfo85Cases(): iterable
{
yield 'final promoted properties' => [
'<?php class Foo { public function __construct(
public final Bar $x,
) {} }',
13,
20,
new ArgumentAnalysis(
'$x',
20,
null,
new TypeAnalysis(
'Bar',
18,
18,
),
),
];
}
private static function assertArgumentAnalysis(ArgumentAnalysis $expected, ArgumentAnalysis $actual): void
{
self::assertSame($expected->getDefault(), $actual->getDefault(), 'Default.');
self::assertSame($expected->getName(), $actual->getName(), 'Name.');
self::assertSame($expected->getNameIndex(), $actual->getNameIndex(), 'Name index.');
self::assertSame($expected->hasDefault(), $actual->hasDefault(), 'Has default.');
self::assertSame($expected->hasTypeAnalysis(), $actual->hasTypeAnalysis(), 'Has type analysis.');
if ($expected->hasTypeAnalysis()) {
$expectedTypeAnalysis = $expected->getTypeAnalysis();
$actualTypeAnalysis = $actual->getTypeAnalysis();
self::assertSame($expectedTypeAnalysis->getEndIndex(), $actualTypeAnalysis->getEndIndex(), 'Type analysis end index.');
self::assertSame($expectedTypeAnalysis->getName(), $actualTypeAnalysis->getName(), 'Type analysis name.');
self::assertSame($expectedTypeAnalysis->getStartIndex(), $actualTypeAnalysis->getStartIndex(), 'Type analysis start index.');
self::assertSame($expectedTypeAnalysis->isNullable(), $actualTypeAnalysis->isNullable(), 'Type analysis nullable.');
self::assertSame($expectedTypeAnalysis->isReservedType(), $actualTypeAnalysis->isReservedType(), 'Type analysis reserved type.');
} else {
self::assertNull($actual->getTypeAnalysis());
}
self::assertSame(serialize($expected), serialize($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/Tokenizer/Analyzer/ControlCaseStructuresAnalyzerTest.php | tests/Tokenizer/Analyzer/ControlCaseStructuresAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\AbstractControlCaseStructuresAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\EnumAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\MatchAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @covers \PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ControlCaseStructuresAnalyzerTest extends TestCase
{
/**
* @param array<int, AbstractControlCaseStructuresAnalysis> $expectedAnalyses
*
* @dataProvider provideFindControlStructuresCases
*/
public function testFindControlStructures(array $expectedAnalyses, string $source): void
{
$tokens = Tokens::fromCode($source);
$analyses = iterator_to_array(ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]));
self::assertCount(\count($expectedAnalyses), $analyses);
foreach ($expectedAnalyses as $index => $expectedAnalysis) {
\assert(\array_key_exists($index, $analyses));
self::assertAnalysis($expectedAnalysis, $analyses[$index]);
}
}
/**
* @return iterable<array{0: array<int, AbstractControlCaseStructuresAnalysis>, 1: string, 2?: int}>
*/
public static function provideFindControlStructuresCases(): iterable
{
yield 'two cases' => [
[1 => new SwitchAnalysis(1, 7, 46, [new CaseAnalysis(9, 12), new CaseAnalysis(36, 39)], null)],
'<?php switch ($foo) {
case 1: $x = bar() ? 1 : 0; return true;
case 2: return false;
}',
];
yield 'case without code' => [
[1 => new SwitchAnalysis(1, 7, 34, [new CaseAnalysis(9, 12), new CaseAnalysis(19, 22), new CaseAnalysis(24, 27)], null)],
'<?php switch ($foo) {
case 1: return true;
case 2:
case 3: return false;
}',
];
yield 'advanced cases' => [
[
1 => new SwitchAnalysis(
1,
7,
132,
[
new CaseAnalysis(17, 22),
new CaseAnalysis(29, 40),
new CaseAnalysis(47, 53),
new CaseAnalysis(60, 71),
new CaseAnalysis(78, 125),
],
new DefaultAnalysis(9, 10),
),
],
'<?php switch (true) {
default: return 0;
case ("a"): return 1;
case [1, 2, 3]: return 2;
case getValue($foo): return 3;
case getValue2($foo)["key"]->bar: return 4;
case $a->$b::$c->${$d}->${$e}::foo(function ($x) { return $x * 2 + 2; })->$g::$h: return 5;
}',
];
yield 'two case and default' => [
[1 => new SwitchAnalysis(1, 7, 38, [new CaseAnalysis(9, 12), new CaseAnalysis(19, 22)], new DefaultAnalysis(29, 30))],
'<?php switch ($foo) { case 10: return true; case 100: return false; default: return -1; }',
];
yield 'two case and default with semicolon instead of colon' => [
[1 => new SwitchAnalysis(1, 7, 38, [new CaseAnalysis(9, 12), new CaseAnalysis(19, 22)], new DefaultAnalysis(29, 30))],
'<?php switch ($foo) { case 10; return true; case 100; return false; default; return -1; }',
];
yield 'ternary operator in case' => [
[1 => new SwitchAnalysis(1, 7, 39, [new CaseAnalysis(9, 22), new CaseAnalysis(29, 32)], null)],
'<?php switch ($foo) { case ($bar ? 10 : 20): return true; case 100: return false; }',
];
yield 'nested switch' => [
[
1 => new SwitchAnalysis(1, 7, 67, [new CaseAnalysis(9, 12), new CaseAnalysis(57, 60)], null),
14 => new SwitchAnalysis(14, 20, 52, [new CaseAnalysis(22, 25), new CaseAnalysis(32, 35), new CaseAnalysis(42, 45)], null),
],
'<?php switch ($foo) { case 10:
switch ($bar) { case "a": return "b"; case "c": return "d"; case "e": return "f"; }
return;
case 100: return false; }',
];
yield 'switch in case' => [
[
1 => new SwitchAnalysis(1, 7, 98, [new CaseAnalysis(9, 81), new CaseAnalysis(88, 91)], null),
25 => new SwitchAnalysis(25, 31, 63, [new CaseAnalysis(33, 36), new CaseAnalysis(43, 46), new CaseAnalysis(53, 56)], null),
],
'<?php
switch ($foo) {
case (
array_sum(array_map(function ($x) { switch ($bar) { case "a": return "b"; case "c": return "d"; case "e": return "f"; } }, [1, 2, 3]))
):
return true;
case 100:
return false;
}
',
];
yield 'alternative syntax' => [
[1 => new SwitchAnalysis(1, 7, 30, [new CaseAnalysis(9, 12), new CaseAnalysis(19, 22)], null)],
'<?php switch ($foo) : case 10: return true; case 100: return false; endswitch;',
];
yield 'alternative syntax with closing tag' => [
[1 => new SwitchAnalysis(1, 7, 31, [new CaseAnalysis(9, 12), new CaseAnalysis(19, 22)], null)],
'<?php switch ($foo) : case 10: return true; case 100: return false; endswitch ?>',
];
yield 'alternative syntax nested' => [
[
1 => new SwitchAnalysis(1, 7, 69, [new CaseAnalysis(9, 12), new CaseAnalysis(58, 61)], null),
14 => new SwitchAnalysis(14, 20, 53, [new CaseAnalysis(22, 25), new CaseAnalysis(32, 35), new CaseAnalysis(42, 45)], null),
],
'<?php switch ($foo) : case 10:
switch ($bar) : case "a": return "b"; case "c": return "d"; case "e": return "f"; endswitch;
return;
case 100: return false; endswitch;',
];
yield 'alternative syntax nested with mixed colon/semicolon' => [
[
1 => new SwitchAnalysis(1, 7, 69, [new CaseAnalysis(9, 12), new CaseAnalysis(58, 61)], null),
14 => new SwitchAnalysis(14, 20, 53, [new CaseAnalysis(22, 25), new CaseAnalysis(32, 35), new CaseAnalysis(42, 45)], null),
],
'<?php switch ($foo) : case 10;
switch ($bar) : case "a": return "b"; case "c"; return "d"; case "e": return "f"; endswitch;
return;
case 100: return false; endswitch;',
];
yield 'alternative syntax nested with closing tab and mixed colon/semicolon' => [
[
1 => new SwitchAnalysis(1, 7, 70, [new CaseAnalysis(9, 12), new CaseAnalysis(58, 61)], null),
14 => new SwitchAnalysis(14, 20, 53, [new CaseAnalysis(22, 25), new CaseAnalysis(32, 35), new CaseAnalysis(42, 45)], null),
],
'<?php switch ($foo) : case 10;
switch ($bar) : case "a": return "b"; case "c"; return "d"; case "e": return "f"; endswitch;
return;
case 100: return false; endswitch ?> <?php echo 1;',
];
$expected = [
1 => new SwitchAnalysis(
1,
6,
22,
[
new CaseAnalysis(8, 11),
],
new DefaultAnalysis(16, 17),
),
];
$code = '<?php switch($a) {
case 1:
break;
default:
break;
}';
yield 'case :' => [$expected, $code];
$code = str_replace('case 1:', 'case 1;', $code);
$code = str_replace('default:', 'DEFAULT;', $code);
yield 'case ;' => [$expected, $code];
yield 'no default, comments' => [
[
1 => new SwitchAnalysis(
1,
6,
18,
[
new CaseAnalysis(8, 12),
],
null,
),
],
'<?php switch($a) {
case 1/* 1 */:
break;
/* 2 */}',
];
yield 'ternary case' => [
[
2 => new SwitchAnalysis(
2,
8,
27,
[
new CaseAnalysis(10, 22),
],
null,
),
],
'<?php
switch ($a) {
case $b ? "c" : "d" ;
break;
}',
];
yield 'nested' => [
[
1 => new SwitchAnalysis(
1,
8,
55,
[
new CaseAnalysis(10, 13),
new CaseAnalysis(18, 21),
new CaseAnalysis(47, 50),
],
null,
),
23 => new SwitchAnalysis(
23,
30,
42,
[
new CaseAnalysis(32, 35),
],
null,
),
],
'<?php
switch(foo()) {
CASE 1:
break;
case 2:
switch(bar()) {
case 1:
echo 1;
}
break;
case 3:
break;
}
',
];
yield 'alternative syntax 2' => [
[
3 => new SwitchAnalysis(
3,
8,
32,
[
new CaseAnalysis(10, 13),
],
null,
),
],
'<?php /* */ switch ($foo):
case 1:
$foo = new class {};
break;
endswitch ?>',
];
yield [
[],
'<?php',
];
yield 'function with return type' => [
[1 => new SwitchAnalysis(1, 7, 43, [new CaseAnalysis(9, 12), new CaseAnalysis(33, 36)], null)],
'<?php switch ($foo) { case 10: function foo($x): int {}; return true; case 100: return false; }',
];
yield 'function with nullable parameter' => [
[1 => new SwitchAnalysis(1, 7, 43, [new CaseAnalysis(9, 12), new CaseAnalysis(33, 36)], null)],
'<?php switch ($foo) { case 10: function foo(?int $x) {}; return true; case 100: return false; }',
];
}
/**
* @param array<int, AbstractControlCaseStructuresAnalysis> $expectedAnalyses
* @param list<int> $types
*
* @requires PHP 8.1
*
* @dataProvider provideFindControlStructuresPhp81Cases
*/
public function testFindControlStructuresPhp81(array $expectedAnalyses, string $source, array $types): void
{
$tokens = Tokens::fromCode($source);
$analyses = iterator_to_array(ControlCaseStructuresAnalyzer::findControlStructures($tokens, $types));
self::assertCount(\count($expectedAnalyses), $analyses);
foreach ($expectedAnalyses as $index => $expectedAnalysis) {
\assert(\array_key_exists($index, $analyses));
self::assertAnalysis($expectedAnalysis, $analyses[$index]);
}
}
/**
* @return iterable<int, array{array<int, AbstractControlCaseStructuresAnalysis>, string, list<int>}>
*/
public static function provideFindControlStructuresPhp81Cases(): iterable
{
$switchAnalysis = new SwitchAnalysis(1, 6, 26, [new CaseAnalysis(8, 11)], new DefaultAnalysis(18, 19));
$enumAnalysis = new EnumAnalysis(28, 35, 51, [new CaseAnalysis(37, 41), new CaseAnalysis(46, 49)]);
$matchAnalysis = new MatchAnalysis(57, 63, 98, new DefaultAnalysis(89, 91));
$code = '<?php
switch($a) {
case 1:
echo 2;
default:
echo 1;
}
enum Suit: string {
case Hearts = "foo";
case Hearts2;
}
$expressionResult = match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
default => baz(),
};
';
yield [
[
1 => $switchAnalysis,
],
$code,
[\T_SWITCH],
];
yield [
[
1 => $switchAnalysis,
28 => $enumAnalysis,
],
$code,
[\T_SWITCH, FCT::T_ENUM],
];
yield [
[
57 => $matchAnalysis,
],
$code,
[FCT::T_MATCH],
];
}
public function testNoSupportedControlStructure(): void
{
$tokens = Tokens::fromCode('<?php if(time() > 0){ echo 1; }');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(\sprintf('Unexpected type "%d".', \T_IF));
// we use `iterator_to_array` to ensure generator is consumed and it has possibility to raise exception
iterator_to_array(ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_IF]));
}
private static function assertAnalysis(AbstractControlCaseStructuresAnalysis $expectedAnalysis, AbstractControlCaseStructuresAnalysis $analysis): void
{
self::assertSame($expectedAnalysis->getIndex(), $analysis->getIndex(), 'index');
self::assertSame($expectedAnalysis->getOpenIndex(), $analysis->getOpenIndex(), 'open index');
self::assertSame($expectedAnalysis->getCloseIndex(), $analysis->getCloseIndex(), 'close index');
self::assertInstanceOf(\get_class($expectedAnalysis), $analysis);
if ($expectedAnalysis instanceof MatchAnalysis || $expectedAnalysis instanceof SwitchAnalysis) {
$expectedDefault = $expectedAnalysis->getDefaultAnalysis();
$actualDefault = $analysis->getDefaultAnalysis(); // @phpstan-ignore-line already type checked against expected
if (null === $expectedDefault) {
self::assertNull($actualDefault, 'default not null');
} else {
self::assertSame($expectedDefault->getIndex(), $actualDefault->getIndex(), 'default index');
self::assertSame($expectedDefault->getColonIndex(), $actualDefault->getColonIndex(), 'default colon index');
}
}
if ($expectedAnalysis instanceof EnumAnalysis || $expectedAnalysis instanceof SwitchAnalysis) {
$expectedCases = $expectedAnalysis->getCases();
$actualCases = $analysis->getCases(); // @phpstan-ignore-line already type checked against expected
self::assertCount(\count($expectedCases), $actualCases);
foreach ($expectedCases as $i => $expectedCase) {
self::assertSame($expectedCase->getIndex(), $actualCases[$i]->getIndex(), 'case index');
self::assertSame($expectedCase->getColonIndex(), $actualCases[$i]->getColonIndex(), 'case colon index');
}
}
self::assertSame(
serialize($expectedAnalysis),
serialize($analysis),
);
}
}
| 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/Tokenizer/Analyzer/FixerAnnotationAnalyzerTest.php | tests/Tokenizer/Analyzer/FixerAnnotationAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\FixerAnnotationAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\FixerAnnotationAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FixerAnnotationAnalyzerTest extends TestCase
{
/**
* @dataProvider provideFindCases
*
* @param array<string, list<string>> $expectedAnnotations
*/
public function testFind(string $source, array $expectedAnnotations, ?string $error = null): void
{
$analyzer = new FixerAnnotationAnalyzer();
if (null !== $error) {
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage($error);
}
$actualAnnotations = $analyzer->find(Tokens::fromCode($source));
self::assertSame($expectedAnnotations, $actualAnnotations);
}
/**
* @return iterable<string, array{string, array<string, list<string>>, 3?: string}>
*/
public static function provideFindCases(): iterable
{
yield 'no annotations' => [
<<<'PHP'
<?php
declare(strict_types=1);
class MyApp {}
PHP,
[],
];
yield 'annotations somewhere on head and on bottom' => [
<<<'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.
*/
// @php-cs-fixer-ignore no_binary_string Ignore because of reasons
/*
* @php-cs-fixer-ignore no_trailing_whitespace also ignore
*/
/*
* @php-cs-fixer-ignore no_unneeded_braces,no_unset_on_property,no_useless_else ignore multiple
*/
/**
* @php-cs-fixer-ignore no_empty_phpdoc also ignore
*/
class MyApp {}
// @php-cs-fixer-ignore no_empty_statement
// @php-cs-fixer-ignore no_extra_blank_lines
?>
PHP,
[
'php-cs-fixer-ignore' => [
'no_binary_string',
'no_empty_phpdoc',
'no_empty_statement',
'no_extra_blank_lines',
'no_trailing_whitespace',
'no_unneeded_braces',
'no_unset_on_property',
'no_useless_else',
],
],
];
yield 'duplicated values' => [
<<<'PHP'
<?php
// @php-cs-fixer-ignore no_extra_blank_lines
declare(strict_types=1);
class MyApp {}
// @php-cs-fixer-ignore no_empty_statement
// @php-cs-fixer-ignore no_extra_blank_lines
PHP,
[],
'Duplicated values found for annotation "@php-cs-fixer-ignore": "no_extra_blank_lines".',
];
// verify that exception is not considered duplicated when no code and iterating a) from top, b) from bottom
yield 'exception without actual code' => [
<<<'PHP'
<?php
// @php-cs-fixer-ignore header_comment No need for header in empty file
PHP,
[
'php-cs-fixer-ignore' => [
'header_comment',
],
],
];
yield 'custom fixer' => [
<<<'PHP'
<?php
// @php-cs-fixer-ignore Vendor/custom_fixer_name A custom reason for a custom fixer
PHP,
[
'php-cs-fixer-ignore' => [
'Vendor/custom_fixer_name',
],
],
];
}
}
| 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/Tokenizer/Analyzer/RangeAnalyzerTest.php | tests/Tokenizer/Analyzer/RangeAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class RangeAnalyzerTest extends TestCase
{
/**
* @param array{start: int, end: int} $range1
* @param array{start: int, end: int} $range2
*
* @dataProvider provideRangeEqualsRangeCases
*/
public function testRangeEqualsRange(bool $expected, string $code, array $range1, array $range2): void
{
$tokens = Tokens::fromCode($code);
self::assertSame($expected, RangeAnalyzer::rangeEqualsRange($tokens, $range1, $range2));
}
/**
* @return iterable<array{bool, string, array{start: int, end: int}, array{start: int, end: int}}>
*/
public static function provideRangeEqualsRangeCases(): iterable
{
$ranges = [
[['start' => 2, 'end' => 6], ['start' => 10, 'end' => 14]],
[['start' => 10, 'end' => 14], ['start' => 20, 'end' => 24]],
[['start' => 1, 'end' => 6], ['start' => 20, 'end' => 25]],
];
foreach ($ranges as $i => [$range1, $range2]) {
yield 'extra "()" and space #'.$i => [
true,
'<?php
$a = 1;
($a = 1);
(($a = 1 ));
',
$range1,
$range2,
];
}
yield [
false,
'<?php echo 1;',
['start' => 0, 'end' => 1],
['start' => 1, 'end' => 2],
];
yield 'comment + space' => [
true,
'<?php
foo(1);
/* */ foo/* */(1) /* */ ;
',
['start' => 1, 'end' => 5],
['start' => 9, 'end' => 17],
];
}
/**
* @requires PHP <8.0
*/
public function testFixPrePHP8x0(): void
{
$code = '<?php
$a = [1,2,3];
echo $a[1];
echo $a{1};
';
$tokens = Tokens::fromCode($code);
$ranges = [
[
['start' => 15, 'end' => 21],
['start' => 23, 'end' => 29],
],
[
['start' => 17, 'end' => 20],
['start' => 24, 'end' => 28],
],
];
foreach ($ranges as [$range1, $range2]) {
self::assertTrue(RangeAnalyzer::rangeEqualsRange($tokens, $range1, $range2));
}
}
}
| 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/Tokenizer/Analyzer/ReferenceAnalyzerTest.php | tests/Tokenizer/Analyzer/ReferenceAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\ReferenceAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Kuba Werłos <werlos@gmail.com>
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\ReferenceAnalyzer
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ReferenceAnalyzerTest extends TestCase
{
public function testNonAmpersand(): void
{
$analyzer = new ReferenceAnalyzer();
self::assertFalse($analyzer->isReference(Tokens::fromCode('<?php $foo;$bar;$baz;'), 3));
}
public function testReferenceAndNonReferenceTogether(): void
{
$analyzer = new ReferenceAnalyzer();
$tokens = Tokens::fromCode('<?php function foo(&$bar = BAZ & QUX) {};');
self::assertTrue($analyzer->isReference($tokens, 5));
self::assertFalse($analyzer->isReference($tokens, 12));
}
/**
* @dataProvider provideReferenceCases
*/
public function testReference(string $code): void
{
$this->doTestCode(true, $code);
}
/**
* @return iterable<int, array{string}>
*/
public static function provideReferenceCases(): iterable
{
yield ['<?php $foo =& $bar;'];
yield ['<?php $foo =& find_var($bar);'];
yield ['<?php $foo["bar"] =& $baz;'];
yield ['<?php function foo(&$bar) {};'];
yield ['<?php function foo($bar, &$baz) {};'];
yield ['<?php function &() {};'];
yield ['<?php
class Foo {
public $value = 42;
public function &getValue() {
return $this->value;
}
}'];
yield ['<?php function foo(\Bar\Baz &$qux) {};'];
yield ['<?php function foo(array &$bar) {};'];
yield ['<?php function foo(callable &$bar) {};'];
yield ['<?php function foo(int &$bar) {};'];
yield ['<?php function foo(string &$bar) {};'];
yield ['<?php foreach($foos as &$foo) {}'];
yield ['<?php foreach($foos as $key => &$foo) {}'];
yield ['<?php function foo(?int &$bar) {};'];
}
/**
* @dataProvider provideNonReferenceCases
*/
public function testNonReference(string $code): void
{
$this->doTestCode(false, $code);
}
/**
* @return iterable<int, array{string}>
*/
public static function provideNonReferenceCases(): iterable
{
yield ['<?php $foo & $bar;'];
yield ['<?php FOO & $bar;'];
yield ['<?php Foo::BAR & $baz;'];
yield ['<?php foo(1, 2) & $bar;'];
yield ['<?php foo($bar & $baz);'];
yield ['<?php foo($bar, $baz & $qux);'];
yield ['<?php foo($bar->baz & $qux);'];
yield ['<?php foo(Bar::BAZ & $qux);'];
yield ['<?php foo(Bar\Baz::qux & $quux);'];
yield ['<?php foo(\Bar\Baz::qux & $quux);'];
yield ['<?php foo($bar["mode"] & $baz);'];
yield ['<?php foo(0b11111111 & $bar);'];
yield ['<?php foo(127 & $bar);'];
yield ['<?php foo("bar" & $baz);'];
yield ['<?php foo($bar = BAZ & $qux);'];
yield ['<?php function foo($bar = BAZ & QUX) {};'];
yield ['<?php function foo($bar = BAZ::QUX & QUUX) {};'];
yield ['<?php function foo(array $bar = BAZ & QUX) {};'];
yield ['<?php function foo(callable $bar = BAZ & QUX) {};'];
yield ['<?php foreach($foos as $foo) { $foo & $bar; }'];
yield ['<?php if ($foo instanceof Bar & 0b01010101) {}'];
yield ['<?php function foo(?int $bar = BAZ & QUX) {};'];
}
/**
* @dataProvider provideNonReferencePre84Cases
*
* @requires PHP <8.4
*/
public function testNonReferencePre84(string $code): void
{
$this->doTestCode(false, $code);
}
/**
* @return iterable<int, array{string}>
*/
public static function provideNonReferencePre84Cases(): iterable
{
yield ['<?php foo($bar{"mode"} & $baz);'];
}
private function doTestCode(bool $expected, string $code): void
{
$analyzer = new ReferenceAnalyzer();
$tokens = Tokens::fromCode($code);
foreach ($tokens as $index => $token) {
if ('&' === $token->getContent()) {
self::assertSame($expected, $analyzer->isReference($tokens, $index));
}
}
}
}
| 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/Tokenizer/Analyzer/CommentsAnalyzerTest.php | tests/Tokenizer/Analyzer/CommentsAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Kuba Werłos <werlos@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CommentsAnalyzerTest extends TestCase
{
public function testWhenNotPointingToComment(): void
{
$analyzer = new CommentsAnalyzer();
$tokens = Tokens::fromCode('<?php $no; $comment; $here;');
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Given index must point to a comment.');
$analyzer->getCommentBlockIndices($tokens, 4);
}
/**
* @param list<int> $borders
*
* @dataProvider provideCommentsCases
*/
public function testComments(string $code, int $index, array $borders): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new CommentsAnalyzer();
self::assertSame($borders, $analyzer->getCommentBlockIndices($tokens, $index));
self::assertFalse($analyzer->isHeaderComment($tokens, $index));
}
/**
* @return iterable<string, array{string, int, list<int>}>
*/
public static function provideCommentsCases(): iterable
{
yield 'discover all 4 comments for the 1st comment with slash' => [
'<?php
$foo;
// one
// two
// three
// four
$bar;',
4,
[4, 6, 8, 10],
];
yield 'discover all 4 comments for the 1st comment with hash' => [
'<?php
$foo;
# one
# two
# three
# four
$bar;',
4,
[4, 6, 8, 10],
];
yield 'discover 3 comments out of 4 for the 2nd comment' => [
'<?php
$foo;
// one
// two
// three
// four
$bar;',
6,
[6, 8, 10],
];
yield 'discover 3 comments when empty line separates 4th' => [
'<?php
$foo;
// one
// two
// three
// four
$bar;',
4,
[4, 6, 8],
];
yield 'discover 3 comments when empty line of CR separates 4th' => [
str_replace("\n", "\r", '<?php
$foo;
// one
// two
// three
// four
$bar;'),
4,
[4, 6, 8],
];
yield 'discover correctly when mix of slash and hash' => [
'<?php
$foo;
// one
// two
# three
// four
$bar;',
4,
[4, 6],
];
yield 'do not group asterisk comments' => [
'<?php
$foo;
/* one */
/* two */
/* three */
$bar;',
4,
[4],
];
yield 'handle fancy indent' => [
'<?php
$foo;
// one
// two
// three
// four
$bar;',
4,
[4, 6, 8, 10],
];
}
public function testHeaderCommentAcceptsOnlyComments(): void
{
$tokens = Tokens::fromCode('<?php 1; 2; 3;');
$analyzer = new CommentsAnalyzer();
$this->expectException(\InvalidArgumentException::class);
$analyzer->isHeaderComment($tokens, 2);
}
/**
* @dataProvider provideHeaderCommentCases
*/
public function testHeaderComment(string $code, int $index): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new CommentsAnalyzer();
self::assertTrue($analyzer->isHeaderComment($tokens, $index));
}
/**
* @return iterable<int, array{string, int}>
*/
public static function provideHeaderCommentCases(): iterable
{
yield ['<?php /* Comment */ namespace Foo;', 1];
yield ['<?php /** Comment */ namespace Foo;', 1];
yield ['<?php declare(strict_types=1); /* Comment */ namespace Foo;', 9];
yield ['<?php /* We test this one */ /* Foo */ namespace Bar;', 1];
yield ['<?php /** Comment */ namespace Foo; declare(strict_types=1); /* Comment */ namespace Foo;', 1];
}
/**
* @dataProvider provideNotHeaderCommentCases
*/
public function testNotHeaderComment(string $code, int $index): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new CommentsAnalyzer();
self::assertFalse($analyzer->isHeaderComment($tokens, $index));
}
/**
* @return iterable<int, array{string, int}>
*/
public static function provideNotHeaderCommentCases(): iterable
{
yield ['<?php $foo; /* Comment */ $bar;', 4];
yield ['<?php foo(); /* Comment */ $bar;', 6];
yield ['<?php namespace Foo; /* Comment */ class Bar {};', 6];
yield ['<?php /* It is not header when no content after */', 1];
yield ['<?php /* Foo */ /* We test this one */ namespace Bar;', 3];
yield ['<?php /* Foo */ declare(strict_types=1); /* We test this one */ namespace Bar;', 11];
}
public function testPhpdocCandidateAcceptsOnlyComments(): void
{
$tokens = Tokens::fromCode('<?php 1; 2; 3;');
$analyzer = new CommentsAnalyzer();
$this->expectException(\InvalidArgumentException::class);
$analyzer->isBeforeStructuralElement($tokens, 2);
}
/**
* @dataProvider providePhpdocCandidateCases
*/
public function testPhpdocCandidate(string $code): void
{
$tokens = Tokens::fromCode($code);
$index = $tokens->getNextTokenOfKind(0, [[\T_COMMENT], [\T_DOC_COMMENT]]);
$analyzer = new CommentsAnalyzer();
self::assertTrue($analyzer->isBeforeStructuralElement($tokens, $index));
}
/**
* @return iterable<int, array{string}>
*/
public static function providePhpdocCandidateCases(): iterable
{
yield ['<?php /* @var Foo */ $bar = "baz";'];
yield ['<?php /* Before namespace */ namespace Foo;'];
yield ['<?php /* Before class */ class Foo {}'];
yield ['<?php /* Before class */ abstract class Foo {}'];
yield ['<?php /* Before class */ final class Foo {}'];
yield ['<?php /* Before trait */ trait Foo {}'];
yield ['<?php /* Before interface */ interface Foo {}'];
yield ['<?php /* Before anonymous function */ function () {};'];
yield ['<?php class Foo { /* Before property */ private $bar; }'];
yield ['<?php class Foo { /* Before property */ protected $bar; }'];
yield ['<?php class Foo { /* Before property */ public $bar; }'];
yield ['<?php class Foo { /* Before property */ var $bar; }'];
yield ['<?php class Foo { /* Before function */ function bar() {} }'];
yield ['<?php class Foo { /* Before use */ use Bar; }'];
yield ['<?php class Foo { /* Before function */ final function bar() {} }'];
yield ['<?php class Foo { /* Before function */ private function bar() {} }'];
yield ['<?php class Foo { /* Before function */ protected function bar() {} }'];
yield ['<?php class Foo { /* Before function */ public function bar() {} }'];
yield ['<?php class Foo { /* Before function */ static function bar() {} }'];
yield ['<?php class Foo { /* Before function */ abstract function bar(); }'];
yield ['<?php class Foo { /* Before constant */ const FOO = 42; }'];
yield ['<?php /* Before require */ require "foo/php";'];
yield ['<?php /* Before require_once */ require_once "foo/php";'];
yield ['<?php /* Before include */ include "foo/php";'];
yield ['<?php /* Before include_once */ include_once "foo/php";'];
yield ['<?php /* @var array $foo */ foreach ($foo as $bar) {};'];
yield ['<?php /* @var int $foo */ if ($foo === -1) {};'];
yield ['<?php /* @var SomeClass $foo */ switch ($foo) { default: exit; };'];
yield ['<?php /* @var bool $foo */ while ($foo) { $foo--; };'];
yield ['<?php /* @var int $i */ for ($i = 0; $i < 16; $i++) {};'];
yield ['<?php /* @var int $i @var int $j */ list($i, $j) = getValues();'];
yield ['<?php /* @var string $s */ print($s);'];
yield ['<?php /* @var string $s */ echo($s);'];
yield ['<?php /* @var User $bar */ ($baz = tmp())->doSomething();'];
yield ['<?php /* @var User $bar */ list($bar) = a();'];
yield ['<?php /* Before anonymous function */ $fn = fn($x) => $x + 1;'];
yield ['<?php /* Before anonymous function */ fn($x) => $x + 1;'];
yield ['<?php /* @var int $x */ [$x] = [2];'];
yield ['<?php /* @var string $x */ $x ??= $y;'];
yield ['<?php /* @var string $x */ $x .= $y;'];
yield ['<?php /* @var int $x */ $x &= 1;'];
yield ['<?php /* @var int $x */ $x |= 1;'];
yield ['<?php /* @var int $x */ $x ^= 1;'];
yield ['<?php /* @var int $x */ $x >>= 1;'];
yield ['<?php /* @var int $x */ $x <<= 1;'];
yield ['<?php /* @var float $x */ $x += 10;'];
yield ['<?php /* @var float $x */ $x -= 10;'];
yield ['<?php /* @var float $x */ $x *= 10;'];
yield ['<?php /* @var float $x */ $x /= 10;'];
yield ['<?php /* @var float $x */ $x %= 10;'];
yield ['<?php /* @var float $x */ $x **= 10;'];
}
/**
* @dataProvider providePhpdocCandidate84Cases
*
* @requires PHP 8.4
*/
public function testPhpdocCandidate84(string $code): void
{
$this->testPhpdocCandidate($code);
}
/**
* @return iterable<int, array{string}>
*/
public static function providePhpdocCandidate84Cases(): iterable
{
yield ['<?php class Foo { /* comment */ public(set) int $i; }'];
yield ['<?php class Foo { /* comment */ protected(set) int $i; }'];
yield ['<?php class Foo { /* comment */ private(set) int $i; }'];
}
/**
* @dataProvider provideNotPhpdocCandidateCases
*/
public function testNotPhpdocCandidate(string $code): void
{
$tokens = Tokens::fromCode($code);
$index = $tokens->getNextTokenOfKind(0, [[\T_COMMENT], [\T_DOC_COMMENT]]);
$analyzer = new CommentsAnalyzer();
self::assertFalse($analyzer->isBeforeStructuralElement($tokens, $index));
}
/**
* @return iterable<int, array{string}>
*/
public static function provideNotPhpdocCandidateCases(): iterable
{
yield ['<?php class Foo {} /* At the end of file */'];
yield ['<?php class Foo { public $baz; public function baz(); /* At the end of class */ }'];
yield ['<?php /* Before increment */ $i++;'];
yield ['<?php /* Comment, but not doc block */ if ($foo === -1) {};'];
yield ['<?php
$a = $b[1]; // @phpstan-ignore-line
static::bar();',
];
yield ['<?php /* @var int $a */ [$b] = [2];'];
}
/**
* @dataProvider providePhpdocCandidatePhp80Cases
*
* @requires PHP 8.0
*/
public function testPhpdocCandidatePhp80(string $code): void
{
$this->testPhpdocCandidate($code);
}
/**
* @return iterable<string, array{string}>
*/
public static function providePhpdocCandidatePhp80Cases(): iterable
{
yield 'attribute between class and phpDoc' => [
'<?php
/**
* @Annotation
*/
#[CustomAnnotationA]
Class MyAnnotation3 {}',
];
}
/**
* @dataProvider providePhpdocCandidatePhp81Cases
*
* @requires PHP 8.1
*/
public function testPhpdocCandidatePhp81(string $code): void
{
$this->testPhpdocCandidate($code);
}
/**
* @return iterable<string, array{string}>
*/
public static function providePhpdocCandidatePhp81Cases(): iterable
{
yield 'public readonly' => [
'<?php class Foo { /* */ public readonly int $a1; }',
];
yield 'readonly public' => [
'<?php class Foo { /* */ readonly public int $a1; }',
];
yield 'readonly union' => [
'<?php class Foo { /* */ readonly A|B $a1; }',
];
yield 'public final const' => [
'<?php final class Foo2 extends B implements A
{
/* */
public final const Y = "i";
}',
];
yield 'final public const' => [
'<?php final class Foo2 extends B implements A
{
/* */
final public const Y = "i";
}',
];
yield 'enum' => [
'<?php /* Before enum */ enum Foo {}',
];
yield 'enum with deprecated case' => [
'<?php
enum Foo: int {
/**
* @deprecated Lorem ipsum
*/
case BAR = 1;
}',
];
}
/**
* @dataProvider provideNotPhpdocCandidatePhp81Cases
*
* @requires PHP 8.1
*/
public function testNotPhpdocCandidatePhp81(string $code): void
{
$this->testNotPhpdocCandidate($code);
}
/**
* @return iterable<string, array{string}>
*/
public static function provideNotPhpdocCandidatePhp81Cases(): iterable
{
yield 'enum and switch' => [
'<?php
enum E {}
switch ($x) {
/* */
case 1: return 2;
}
',
];
yield 'switch and enum' => [
'<?php
switch ($x) {
/* */
case 1: return 2;
}
enum E {}
',
];
}
/**
* @dataProvider provideReturnStatementCases
*/
public function testReturnStatement(string $code, bool $expected): void
{
$tokens = Tokens::fromCode($code);
$index = $tokens->getNextTokenOfKind(0, [[\T_COMMENT], [\T_DOC_COMMENT]]);
$analyzer = new CommentsAnalyzer();
self::assertSame($expected, $analyzer->isBeforeReturn($tokens, $index));
}
/**
* @return iterable<string, array{string, bool}>
*/
public static function provideReturnStatementCases(): iterable
{
yield 'docblock before var' => [
'<?php
function returnClassName()
{
/** @todo something */
$var = 123;
return;
}
',
false,
];
yield 'comment before var' => [
'<?php
function returnClassName()
{
// @todo something
$var = 123;
return;
}
',
false,
];
yield 'docblock return' => [
'<?php
function returnClassName()
{
/** @todo something */
return;
}
',
true,
];
yield 'comment return' => [
'<?php
function returnClassName()
{
// @todo something
return;
}
',
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/Tokenizer/Analyzer/PhpUnitTestCaseAnalyzerTest.php | tests/Tokenizer/Analyzer/PhpUnitTestCaseAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\PhpUnitTestCaseAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\PhpUnitTestCaseAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitTestCaseAnalyzerTest extends TestCase
{
/**
* @param list<array{0: int, 1: int}> $expectedIndexes
*
* @dataProvider provideFindPhpUnitClassesCases
*/
public function testFindPhpUnitClasses(array $expectedIndexes, string $code): void
{
$tokens = Tokens::fromCode($code);
$classes = (new PhpUnitTestCaseAnalyzer())->findPhpUnitClasses($tokens);
$classes = iterator_to_array($classes);
self::assertSame($expectedIndexes, $classes);
}
/**
* @return iterable<string, array{list<array{int, int}>, string}>
*/
public static function provideFindPhpUnitClassesCases(): iterable
{
yield 'empty' => [
[],
'',
];
yield 'empty script' => [
[],
"<?php\n",
];
yield 'no test class' => [
[],
'<?php class Foo{}',
];
yield 'single Test class' => [
[
[10, 11],
],
'<?php
class MyTest extends Foo {}
',
];
yield 'single TestCase class' => [
[
[11, 12],
],
'<?php final class SomeTestCase extends A {}',
];
yield 'two PHPUnit classes' => [
[
[21, 34],
[10, 11],
],
'<?php
class My1Test extends Foo1 {}
class My2Test extends Foo2 { public function A8() {} }
',
];
yield 'mixed classes' => [
[
[71, 84],
[29, 42],
],
'<?php
class Foo1 { public function A1() {} }
class My1Test extends Foo1 { public function A2() {} }
class Foo2 { public function A3() {} }
class My2Test extends Foo2 { public function A4() {} }
class Foo3 { public function A5() { return function (){}; } }
',
];
yield 'mixed classes that all extends' => [
[
[50, 51],
[21, 22],
],
'<?php
class A extends Foo {}
class B extends TestCase {}
class C extends Bar {}
class D extends Foo implements TestCaseInterface, Bar {}
class E extends Baz {}
',
];
yield 'class with anonymous class inside' => [
[],
'<?php
class Foo
{
public function getClass()
{
return new class {};
}
}
',
];
yield 'anonymous class extending TestCase' => [
[
[17, 18],
],
<<<'PHP'
<?php
$myTest = new class () extends \PHPUnit_Framework_TestCase {};
PHP,
];
yield 'extends Test' => [
[
[11, 12],
],
'<?php final class Foo extends Test {}',
];
yield 'extends TestCase' => [
[
[11, 12],
],
'<?php final class bar extends TestCase {}',
];
yield 'implements AbstractFixerTest' => [
[
[21, 22],
],
'<?php class A extends Foo implements PhpCsFixer\Tests\Fixtures\Test\AbstractFixerTest {}',
];
yield 'extends TestCase implements Foo' => [
[
[13, 14],
],
'<?php class A extends TestCase implements Foo {}',
];
yield 'implements TestInterface' => [
[
[13, 14],
],
'<?php class Foo extends A implements SomeTestInterface {}',
];
yield 'implements TestInterface, SomethingElse' => [
[
[16, 17],
],
'<?php class Foo extends A implements TestInterface, SomethingElse {}',
];
yield 'anonymous class' => [
[],
'<?php $a = new class {};',
];
yield 'test class that does not extends' => [
[],
'<?php final class MyTest {}',
];
yield 'testCase class that does not extends' => [
[],
'<?php final class SomeTestCase implements PhpCsFixer\Tests\Fixtures\Test\AbstractFixerTest {}',
];
}
}
| 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/Tokenizer/Analyzer/BlocksAnalyzerTest.php | tests/Tokenizer/Analyzer/BlocksAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\BlocksAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Kuba Werłos <werlos@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\BlocksAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class BlocksAnalyzerTest extends TestCase
{
/**
* @dataProvider provideBlocksCases
*/
public function testBlocks(string $code, int $openIndex, int $closeIndex): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new BlocksAnalyzer();
self::assertTrue($analyzer->isBlock($tokens, $openIndex, $closeIndex));
}
/**
* @return iterable<int, array{string, int, int}>
*/
public static function provideBlocksCases(): iterable
{
yield ['<?php foo(1);', 2, 4];
yield ['<?php foo((1));', 3, 5];
yield ['<?php foo((1));', 2, 6];
yield ['<?php foo(1, 2, 3);', 2, 10];
yield ['<?php foo(1, bar(2, 3), 4);', 2, 16];
yield ['<?php $foo["bar"];', 2, 4];
yield ['<?php [1, 2, 3];', 1, 9];
yield ['<?php $foo = function ($x) { return $x + 10; };', 7, 9];
yield ['<?php $foo = function ($x) { return $x + 10; };', 11, 22];
yield ['<?php list($a, $b, $c) = [1, 2, 3];', 2, 10];
yield ['<?php list($a, $b, $c) = [1, 2, 3];', 14, 22];
yield ['<?php list($a, $b, $c) = array(1, 2, 3);', 15, 23];
yield ['<?php $fn = fn($x) => $x + 10;', 6, 8];
}
/**
* @dataProvider provideNonBlocksCases
*/
public function testNonBlocks(string $code, int $openIndex, int $closeIndex): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new BlocksAnalyzer();
self::assertFalse($analyzer->isBlock($tokens, $openIndex, $closeIndex));
}
/**
* @return iterable<int, array{string, int, int}>
*/
public static function provideNonBlocksCases(): iterable
{
yield ['<?php foo(1);', 1, 4];
yield ['<?php foo(1);', 3, 4];
yield ['<?php foo(1);', 2, 3];
yield ['<?php foo((1));', 2, 5];
yield ['<?php foo((1));', 3, 6];
}
/**
* @dataProvider provideInvalidIndexCases
*/
public function testInvalidIndex(string $code, int $openIndex, int $closeIndex): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new BlocksAnalyzer();
$this->expectException(\InvalidArgumentException::class);
$analyzer->isBlock($tokens, $openIndex, $closeIndex);
}
/**
* @return iterable<int, array{string, int, int}>
*/
public static function provideInvalidIndexCases(): iterable
{
yield ['<?php foo(1);', 1_000, 4];
yield ['<?php foo(1);', 2, 1_000];
}
}
| 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/Tokenizer/Analyzer/GotoLabelAnalyzerTest.php | tests/Tokenizer/Analyzer/GotoLabelAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class GotoLabelAnalyzerTest extends TestCase
{
/**
* @param list<int> $expectedTrue
*
* @dataProvider provideGotoLabelCases
*/
public function testGotoLabel(string $source, array $expectedTrue): void
{
$tokens = Tokens::fromCode($source);
$analyzer = new GotoLabelAnalyzer();
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
self::assertSame(
\in_array($index, $expectedTrue, true),
$analyzer->belongsToGoToLabel($tokens, $index),
);
}
}
/**
* @return iterable<string, array{string, list<int>}>
*/
public static function provideGotoLabelCases(): iterable
{
yield 'no candidates' => [
'<?php
$a = \InvalidArgumentException::class;
$this->fixer->configure($legacy ? [$statement] : [1]);
',
[],
];
yield 'after php tag' => [
'<?php
beginning:
echo $guard?1:2;',
[3],
];
yield 'after closing brace' => [
'<?php
function A(){}
beginning:
echo $guard?1:2;',
[11],
];
yield 'after statement' => [
'<?php
echo 1;
beginning:
echo $guard?1:2;',
[8],
];
yield 'after opening brace' => [
'<?php
echo 1;
{
beginning:
echo $guard?1:2;
}
',
[10],
];
yield 'after use statements' => [
'<?php
use Bar1;
use const Bar2;
use function Bar3;
Bar1:
Bar2:
Bar3:
',
[21, 24, 27],
];
}
/**
* @param list<int> $expectedTrue
*
* @dataProvider provideGotoLabel80Cases
*
* @requires PHP 8.0
*/
public function testGotoLabel80(string $source, array $expectedTrue): void
{
$this->testGotoLabel($source, $expectedTrue);
}
/**
* @return iterable<int, array{string, list<int>}>
*/
public static function provideGotoLabel80Cases(): iterable
{
yield [
'<?php array_fill(start_index: 0, num: 100, value: 50);',
[],
];
}
}
| 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/Tokenizer/Analyzer/NamespacesAnalyzerTest.php | tests/Tokenizer/Analyzer/NamespacesAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author VeeWee <toonverwerft@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NamespacesAnalyzerTest extends TestCase
{
/**
* @param list<NamespaceAnalysis> $expected
*
* @dataProvider provideNamespacesCases
*/
public function testNamespaces(string $code, array $expected): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new NamespacesAnalyzer();
self::assertSame(
serialize($expected),
serialize($analyzer->getDeclarations($tokens)),
);
}
/**
* @return iterable<int, array{string, list<NamespaceAnalysis>}>
*/
public static function provideNamespacesCases(): iterable
{
yield ['<?php // no namespaces', [
new NamespaceAnalysis(
'',
'',
0,
0,
0,
1,
),
]];
yield ['<?php namespace Foo\Bar;', [
new NamespaceAnalysis(
'Foo\Bar',
'Bar',
1,
6,
1,
6,
),
]];
yield ['<?php namespace Foo\Bar{}; namespace Foo\Baz {};', [
new NamespaceAnalysis(
'Foo\Bar',
'Bar',
1,
6,
1,
7,
),
new NamespaceAnalysis(
'Foo\Baz',
'Baz',
10,
16,
10,
17,
),
]];
yield [
<<<'PHP'
#!/usr/bin/php
<?php
return true;
PHP,
[
new NamespaceAnalysis(
'',
'',
1,
1,
1,
5,
),
],
];
yield [
'there is no namespace if there is no PHP code',
[],
];
}
/**
* @dataProvider provideGetNamespaceAtCases
*/
public function testGetNamespaceAt(string $code, int $index, NamespaceAnalysis $expected): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new NamespacesAnalyzer();
self::assertSame(
serialize($expected),
serialize($analyzer->getNamespaceAt($tokens, $index)),
);
}
/**
* @return iterable<int, array{string, int, NamespaceAnalysis}>
*/
public static function provideGetNamespaceAtCases(): iterable
{
yield [
'<?php // no namespaces',
1,
new NamespaceAnalysis(
'',
'',
0,
0,
0,
1,
),
];
yield [
'<?php namespace Foo\Bar;',
5,
new NamespaceAnalysis(
'Foo\Bar',
'Bar',
1,
6,
1,
6,
),
];
yield [
'<?php namespace Foo\Bar{}; namespace Foo\Baz {};',
5,
new NamespaceAnalysis(
'Foo\Bar',
'Bar',
1,
6,
1,
7,
),
];
yield [
'<?php namespace Foo\Bar{}; namespace Foo\Baz {};',
13,
new NamespaceAnalysis(
'Foo\Baz',
'Baz',
10,
16,
10,
17,
),
];
}
public function testInvalidIndex(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Token index 666 does not exist.');
$analyzer = new NamespacesAnalyzer();
$analyzer->getNamespaceAt(new Tokens(), 666);
}
}
| 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/Tokenizer/Analyzer/DataProviderAnalyzerTest.php | tests/Tokenizer/Analyzer/DataProviderAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\DataProviderAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DataProviderAnalyzerTest extends TestCase
{
/**
* @param list<DataProviderAnalysis> $expected
*
* @dataProvider provideGettingDataProvidersCases
*/
public function testGettingDataProviders(array $expected, string $code, int $startIndex = 0, ?int $endIndex = null): void
{
$tokens = Tokens::fromCode($code);
if (null === $endIndex) {
$endIndex = $tokens->count() - 1;
}
$analyzer = new DataProviderAnalyzer();
self::assertSame(serialize($expected), serialize($analyzer->getDataProviders($tokens, $startIndex, $endIndex)));
}
/**
* @return iterable<string, array{list<DataProviderAnalysis>, string}>
*/
public static function provideGettingDataProvidersCases(): iterable
{
yield 'single data provider' => [
[new DataProviderAnalysis('provider', 28, [[11, 23]])],
'<?php class FooTest extends TestCase {
/**
* @dataProvider provider
*/
public function testFoo() {}
public function provider() {}
}',
];
yield 'single data provider with different casing' => [
[new DataProviderAnalysis('dataProvider', 28, [[11, 23]])],
'<?php class FooTest extends TestCase {
/**
* @dataProvider dataPROVIDER
*/
public function testFoo() {}
public function dataProvider() {}
}',
];
yield 'single static data provider' => [
[new DataProviderAnalysis('provider', 30, [[11, 23]])],
'<?php class FooTest extends TestCase {
/**
* @dataProvider provider
*/
public function testFoo() {}
public static function provider() {}
}',
];
yield 'multiple data provider' => [
[
new DataProviderAnalysis('provider1', 28, [[11, 23]]),
new DataProviderAnalysis('provider2', 39, [[11, 66]]),
new DataProviderAnalysis('provider3', 50, [[11, 109]]),
],
'<?php class FooTest extends TestCase {
/**
* @dataProvider provider1
* @dataProvider provider2
* @dataProvider provider3
*/
public function testFoo() {}
public function provider1() {}
public function provider2() {}
public function provider3() {}
}',
];
yield 'single data provider with multiple usage' => [
[
new DataProviderAnalysis('provider', 28, [[11, 23], [35, 23]]),
],
'<?php class FooTest extends TestCase {
/**
* @dataProvider provider
*/
public function testFoo() {}
public function provider() {}
/**
* @dataProvider provider
*/
public function testFoo2() {}
}',
];
foreach (['abstract', 'final', 'private', 'protected', 'static', '/* private */'] as $modifier) {
yield \sprintf('test function with %s modifier', $modifier) => [
[
new DataProviderAnalysis('provider1', 54, [[37, 4]]),
new DataProviderAnalysis('provider2', 65, [[11, 4]]),
new DataProviderAnalysis('provider3', 76, [[24, 4]]),
],
\sprintf('<?php class FooTest extends TestCase {
/** @dataProvider provider2 */
public function testFoo1() {}
/** @dataProvider provider3 */
%s function testFoo2() {}
/** @dataProvider provider1 */
public function testFoo3() {}
public function provider1() {}
public function provider2() {}
public function provider3() {}
}', $modifier),
];
}
yield 'not existing data provider used' => [
[],
'<?php class FooTest extends TestCase {
/**
* @dataProvider provider
*/
public function testFoo() {}
}',
];
yield 'data provider being constant' => [
[],
'<?php class FooTest extends TestCase {
private const provider = [];
/**
* @dataProvider provider
*/
public function testFoo() {}
}',
];
yield 'ignore anonymous function' => [
[
new DataProviderAnalysis('provider2', 93, [[65, 27]]),
],
'<?php class FooTest extends TestCase {
public function testFoo0() {}
/**
* @dataProvider provider0
*/
public function testFoo1()
{
/**
* @dataProvider provider1
*/
$f = function ($x, $y) { return $x + $y; };
}
/**
* @dataProvider provider2
*/
public function testFoo2() {}
public function provider1() {}
public function provider2() {}
}',
];
}
/**
* @param list<DataProviderAnalysis> $expected
*
* @requires PHP ^8.0
*
* @dataProvider provideGettingDataProviders80Cases
*/
public function testGettingDataProviders80(array $expected, string $code, int $startIndex = 0, ?int $endIndex = null): void
{
$this->testGettingDataProviders($expected, $code, $startIndex, $endIndex);
}
/**
* @return iterable<string, array{list<DataProviderAnalysis>, string}>
*/
public static function provideGettingDataProviders80Cases(): iterable
{
yield 'with an attribute between PHPDoc and test method' => [
[new DataProviderAnalysis('provideFooCases', 35, [[11, 11]])],
<<<'PHP'
<?php
class FooTest extends TestCase {
/**
* @dataProvider provideFooCases
*/
#[CustomAttribute]
public function testFoo(): void {}
public function provideFooCases(): iterable {}
}
PHP,
];
yield 'with multiple DataProvider attributes' => [
[
new DataProviderAnalysis('provider1', 70, [[21, 0]]),
new DataProviderAnalysis('provider2', 84, [[35, 0]]),
new DataProviderAnalysis('provider3', 98, [[48, 0]]),
],
<<<'PHP'
<?php
class FooTest extends TestCase {
#[\PHPUnit\Framework\Attributes\DataProvider('provider1')]
#[\PHPUnit\Framework\Attributes\DataProvider('provider2')]
#[PHPUnit\Framework\Attributes\DataProvider('provider3')]
public function testFoo(): void {}
public function provider1(): iterable {}
public function provider2(): iterable {}
public function provider3(): iterable {}
}
PHP,
];
yield 'with incorrect DataProvider attributes' => [
[],
<<<'PHP'
<?php
namespace NamespaceToMakeAttributeWithoutLeadingSlashIgnored;
class FooTest extends TestCase {
#[PHPUnit\Framework\Attributes\DataProvider('provider1')]
#[\PHPUnit\Framework\Attributes\DataProvider]
#[\PHPUnit\Framework\Attributes\DataProvider(123)]
#[\PHPUnit\Framework\Attributes\DataProvider('doNotGetFooledByConcatenation' . 'provider3')]
public function testFoo(): void {}
public function provider1(): iterable {}
public function provider2(): iterable {}
public function provider3(): iterable {}
}
PHP,
];
yield 'with DataProvider attributes use in a tricky way' => [
[
new DataProviderAnalysis('provider1', 151, [[60, 0], [126, 0]]),
new DataProviderAnalysis('provider2', 165, [[84, 0]]),
new DataProviderAnalysis('provider3', 179, [[95, 0]]),
],
<<<'PHP'
<?php
namespace N;
use PHPUnit\Framework as PphUnitAlias;
use PHPUnit\Framework\Attributes;
class FooTest extends TestCase {
#[
\PHPUnit\Framework\Attributes\BackupGlobals(true),
\PHPUnit\Framework\Attributes\DataProvider('provider1'),
\PHPUnit\Framework\Attributes\Group('foo'),
]
#[Attributes\DataProvider('provider2')]
#[PphUnitAlias\Attributes\DataProvider('provider3')]
public function testFoo(int $x): void {}
#[\PHPUnit\Framework\Attributes\DataProvider('provider1')]
public function testBar(int $x): void {}
public function provider1(): iterable {}
public function provider2(): iterable {}
public function provider3(): iterable {}
}
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/Tokenizer/Analyzer/AlternativeSyntaxAnalyzerTest.php | tests/Tokenizer/Analyzer/AlternativeSyntaxAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class AlternativeSyntaxAnalyzerTest extends TestCase
{
/**
* @param list<int> $expectedPositives
*
* @dataProvider provideBelongsToAlternativeSyntaxCases
*/
public function testBelongsToAlternativeSyntax(array $expectedPositives, string $source): void
{
$tokens = Tokens::fromCode($source);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
self::assertSame(
\in_array($index, $expectedPositives, true),
(new AlternativeSyntaxAnalyzer())->belongsToAlternativeSyntax($tokens, $index),
'@ index: '.$index,
);
}
}
/**
* @return iterable<string, array{list<int>, string}>
*/
public static function provideBelongsToAlternativeSyntaxCases(): iterable
{
yield 'declare' => [
[7],
'<?php declare(ticks=1):enddeclare;',
];
yield 'for' => [
[20],
'<?php for($i = 0; $i < 10; $i++): echo $i; endfor;',
];
yield 'foreach' => [
[17],
'<?php foreach([1, 2, 3] as $i): echo $i; endforeach;',
];
yield 'if, elseif, else' => [
[6, 17, 25],
'<?php if ($condition): echo 1; elseif($a): echo 2; else: echo 3; endif;',
];
yield 'switch' => [
[6],
'<?php switch ($value): default: echo 4; endswitch;',
];
yield 'while' => [
[5],
'<?php while(true): echo "na"; endwhile;',
];
yield 'multiple expressions' => [
[7, 15, 51],
'<?php
if ($condition1): echo 1; else: echo 2; endif;
somelabel: echo 3;
echo $condition2 ? 4 : 5;
if ($condition3): echo 6; endif;
',
];
}
/**
* @dataProvider provideItFindsTheEndOfAnAlternativeSyntaxBlockCases
*/
public function testItFindsTheEndOfAnAlternativeSyntaxBlock(string $code, int $startIndex, int $expectedResult): void
{
$analyzer = new AlternativeSyntaxAnalyzer();
self::assertSame(
$expectedResult,
$analyzer->findAlternativeSyntaxBlockEnd(
Tokens::fromCode($code),
$startIndex,
),
);
}
/**
* @return iterable<int, array{string, int, int}>
*/
public static function provideItFindsTheEndOfAnAlternativeSyntaxBlockCases(): iterable
{
yield ['<?php if ($foo): foo(); endif;', 1, 13];
yield ['<?php if ($foo): foo(); else: bar(); endif;', 1, 13];
yield ['<?php if ($foo): foo(); elseif ($bar): bar(); endif;', 1, 13];
yield ['<?php if ($foo): foo(); elseif ($bar): bar(); endif;', 13, 25];
yield ['<?php if ($foo): foo(); elseif ($bar): bar(); else: baz(); endif;', 13, 25];
yield ['<?php if ($foo): foo(); else: bar(); endif;', 13, 21];
yield ['<?php for (;;): foo(); endfor;', 1, 14];
yield ['<?php foreach ($foo as $bar): foo(); endforeach;', 1, 17];
yield ['<?php while ($foo): foo(); endwhile;', 1, 13];
yield ['<?php switch ($foo): case 1: foo(); endswitch;', 1, 18];
$nested = <<<'PHP'
<?php
switch (foo()):
case 1:
switch (foo2()):
case 2:
if (bar()) {
}
switch (foo2()):
case 4:
{
switch (foo3()) {
case 4:
{
}
}
}
endswitch;
endswitch;
case 2:
switch (foo5()) {
case 4:
echo 1;
}
endswitch;
PHP;
yield [$nested, 1, 113];
yield [$nested, 15, 83];
yield [$nested, 41, 80];
$nestedWithHtml = <<<'PHP'
<?php if (1): ?>
<div></div>
<?php else: ?>
<?php if (2): ?>
<div></div>
<?php else: ?>
<div></div>
<?php endif; ?>
<?php endif; ?>
PHP;
yield [$nestedWithHtml, 1, 11];
yield [$nestedWithHtml, 11, 38];
yield [$nestedWithHtml, 17, 27];
yield [$nestedWithHtml, 27, 33];
}
/**
* @dataProvider provideItThrowsOnInvalidAlternativeSyntaxBlockStartIndexCases
*/
public function testItThrowsOnInvalidAlternativeSyntaxBlockStartIndex(string $code, int $startIndex, string $expectedMessage): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new AlternativeSyntaxAnalyzer();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage($expectedMessage);
$analyzer->findAlternativeSyntaxBlockEnd($tokens, $startIndex);
}
/**
* @return iterable<int, array{string, int, string}>
*/
public static function provideItThrowsOnInvalidAlternativeSyntaxBlockStartIndexCases(): iterable
{
yield ['<?php if ($foo): foo(); endif;', 0, 'Token at index 0 is not the start of an alternative syntax block.'];
yield ['<?php if ($foo): foo(); endif;', 2, 'Token at index 2 is not the start of an alternative syntax block.'];
yield ['<?php if ($foo): foo(); endif;', 999, 'There is no token at index 999.'];
yield ['<?php if ($foo): foo(); else: bar(); endif;', 0, 'Token at index 0 is not the start of an alternative syntax block.'];
yield ['<?php if ($foo): foo(); else: bar(); endif;', 2, 'Token at index 2 is not the start of an alternative syntax block.'];
yield ['<?php if ($foo): foo(); else: bar(); endif;', 999, 'There is no token at index 999.'];
yield ['<?php if ($foo): foo(); elseif ($bar): bar(); endif;', 0, 'Token at index 0 is not the start of an alternative syntax block.'];
yield ['<?php if ($foo): foo(); elseif ($bar): bar(); endif;', 2, 'Token at index 2 is not the start of an alternative syntax block.'];
yield ['<?php if ($foo): foo(); elseif ($bar): bar(); endif;', 999, 'There is no token at index 999.'];
yield ['<?php if ($foo): foo(); elseif ($bar): bar(); else: baz(); endif;', 0, 'Token at index 0 is not the start of an alternative syntax block.'];
yield ['<?php if ($foo): foo(); elseif ($bar): bar(); else: baz(); endif;', 2, 'Token at index 2 is not the start of an alternative syntax block.'];
yield ['<?php if ($foo): foo(); elseif ($bar): bar(); else: baz(); endif;', 999, 'There is no token at index 999.'];
yield ['<?php for (;;): foo(); endfor;', 0, 'Token at index 0 is not the start of an alternative syntax block.'];
yield ['<?php for (;;): foo(); endfor;', 2, 'Token at index 2 is not the start of an alternative syntax block.'];
yield ['<?php for (;;): foo(); endfor;', 999, 'There is no token at index 999.'];
yield ['<?php foreach ($foo as $bar): foo(); endforeach;', 0, 'Token at index 0 is not the start of an alternative syntax block.'];
yield ['<?php foreach ($foo as $bar): foo(); endforeach;', 2, 'Token at index 2 is not the start of an alternative syntax block.'];
yield ['<?php foreach ($foo as $bar): foo(); endforeach;', 999, 'There is no token at index 999.'];
yield ['<?php while ($foo): foo(); endwhile;', 0, 'Token at index 0 is not the start of an alternative syntax block.'];
yield ['<?php while ($foo): foo(); endwhile;', 2, 'Token at index 2 is not the start of an alternative syntax block.'];
yield ['<?php while ($foo): foo(); endwhile;', 999, 'There is no token at index 999.'];
yield ['<?php switch ($foo): case 1: foo(); endswitch;', 0, 'Token at index 0 is not the start of an alternative syntax block.'];
yield ['<?php switch ($foo): case 1: foo(); endswitch;', 2, 'Token at index 2 is not the start of an alternative syntax block.'];
yield ['<?php switch ($foo): case 1: foo(); endswitch;', 999, 'There is no token at index 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/Tokenizer/Analyzer/SwitchAnalyzerTest.php | tests/Tokenizer/Analyzer/SwitchAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SwitchAnalyzerTest extends TestCase
{
/**
* @param list<int> $indices
*
* @dataProvider provideColonCases
*/
public function testColon(string $code, array $indices): void
{
$tokens = Tokens::fromCode($code);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
self::assertSame(
\in_array($index, $indices, true),
SwitchAnalyzer::belongsToSwitch($tokens, $index),
\sprintf('Index %d failed check.', $index),
);
}
}
/**
* @return iterable<string, array{string, list<int>}>
*/
public static function provideColonCases(): iterable
{
yield 'ternary operator' => [
'<?php $x ? 1 : 0;',
[],
];
yield 'alternative syntax' => [
'<?php if(true): 3; endif;',
[],
];
yield 'label' => [
'<?php gotoHere: echo "here";',
[],
];
yield 'switch' => [
'<?php
switch ($value1) {
case 1: return 2;
case 3: return 4;
default: return 5;
}
',
[13, 23, 31],
];
yield 'switch with alternative syntax' => [
'<?php
switch ($value1):
case 1: return 2;
default: return 3;
case 4: return 5;
endswitch;
',
[7, 12, 20, 30],
];
}
public function testWithEmptyTokens(): void
{
$tokensWithEmpty = Tokens::fromCode(<<<'PHP'
<?php
switch/* to remove */($value1) {
case 1: return 2;
}
PHP);
$tokensWithEmpty->clearAt(2);
$tokensWithoutEmpty = clone $tokensWithEmpty;
$tokensWithoutEmpty->clearEmptyTokens();
self::assertStringNotContainsString('to remove', $tokensWithEmpty->generateCode());
self::assertStringNotContainsString('to remove', $tokensWithoutEmpty->generateCode());
self::assertSame(
$tokensWithEmpty->count(),
$tokensWithoutEmpty->count() + 1,
);
self::assertTrue(SwitchAnalyzer::belongsToSwitch($tokensWithEmpty, 12));
self::assertTrue(SwitchAnalyzer::belongsToSwitch($tokensWithoutEmpty, 11));
}
}
| 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/Tokenizer/Analyzer/AttributeAnalyzerTest.php | tests/Tokenizer/Analyzer/AttributeAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class AttributeAnalyzerTest extends TestCase
{
/**
* Check it's not crashing for PHP lower than 8.0 as other tests run for PHP 8.0 only.
*/
public function testNotAnAttribute(): void
{
$tokens = Tokens::fromCode('<?php class Foo { private $bar; }');
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
self::assertFalse(AttributeAnalyzer::isAttribute($tokens, $index));
}
}
/**
* @requires PHP 8.0
*
* @dataProvider provideIsAttributeCases
*/
public function testIsAttribute(bool $isInAttribute, string $code): void
{
$tokens = Tokens::fromCode($code);
foreach ($tokens as $index => $token) {
if ($token->equals([\T_STRING, 'Foo'])) {
if (isset($testedIndex)) {
self::fail('Test is run against index of "Foo", multiple occurrences found.');
}
$testedIndex = $index;
}
}
if (!isset($testedIndex)) {
self::fail('Test is run against index of "Foo", but it was not found in the code.');
}
self::assertSame($isInAttribute, AttributeAnalyzer::isAttribute($tokens, $testedIndex));
}
/**
* Test case requires to having "Foo" as it will be searched for to test its index.
*
* @return iterable<int, array{bool, string}>
*/
public static function provideIsAttributeCases(): iterable
{
yield [false, '<?php Foo; #[Attr] class Bar {}'];
yield [false, '<?php Foo(); #[Attr] class Bar {};'];
yield [false, '<?php \Foo(); #[Attr] class Bar {}'];
yield [false, '<?php #[Attr] class Foo {};'];
yield [false, '<?php #[Attr] class Bar {}; Foo;'];
yield [false, '<?php #[Attr] class Bar {}; \Foo();'];
yield [false, '<?php #[Attr] class Bar { const Foo = 42; };'];
yield [false, '<?php #[Attr] class Bar { function Foo() {} };'];
yield [false, '<?php #[Attr(Foo)] class Bar {}'];
yield [false, '<?php #[Attr(Foo::Bar)] class Baz {}'];
yield [false, '<?php #[Attr(Bar::Foo)] class Baz {}'];
yield [false, '<?php #[Attr(1, 2, Foo)] class Bar {}'];
yield [false, '<?php #[Attr(Foo, 1, 2)] class Bar {}'];
yield [false, '<?php #[Attr(1, 2, Foo, 3, 4)] class Bar {}'];
yield [false, '<?php #[Attr(2 * (3 + 7), 2, Foo)] class Bar {}'];
yield [false, '<?php #[Attr(2 * (3 + 7), 2, Foo, 5)] class Bar {}'];
yield [false, '<?php #[Attr(2 * (3 + 7), 2, Foo, (16 + 4) / 5 )] class Bar {}'];
yield [false, '<?php #[Attr] function Foo() {};'];
yield [false, '<?php #[Attr("Foo()")] class Foo {}'];
yield [true, '<?php #[Foo] class Bar {}'];
yield [true, '<?php #[Foo, Bar] class Baz {}'];
yield [true, '<?php #[Bar, Foo] class Baz {}'];
yield [true, '<?php #[Bar, Foo, Baz] class Qux {}'];
yield [true, '<?php #[Foo(), Bar()] class Baz {}'];
yield [true, '<?php #[Bar(), Foo()] class Baz {}'];
yield [true, '<?php #[Bar(), Foo(), Baz()] class Qux {}'];
yield [true, '<?php #[Bar(), Foo, Baz()] class Qux {}'];
yield [true, '<?php #[\Foo] class Bar {}'];
yield [true, '<?php #[\Bar, \Foo] class Baz {}'];
yield [true, '<?php #[Attr1(2 * (3 + 7)), Foo, Attr2((16 + 4) / 5 )] class Bar {}'];
yield [true, '<?php #[Foo("(")] class Bar {}'];
}
/**
* @requires PHP 8.0
*
* @dataProvider provideGetAttributeDeclarationsCases
*
* @param list<AttributeAnalysis> $expectedAnalyses
*/
public function testGetAttributeDeclarations(string $code, int $startIndex, array $expectedAnalyses): void
{
$tokens = Tokens::fromCode($code);
$actualAnalyses = AttributeAnalyzer::collect($tokens, $startIndex);
foreach ($expectedAnalyses as $expectedAnalysis) {
self::assertSame(\T_ATTRIBUTE, $tokens[$expectedAnalysis->getOpeningBracketIndex()]->getId());
self::assertSame(CT::T_ATTRIBUTE_CLOSE, $tokens[$expectedAnalysis->getClosingBracketIndex()]->getId());
}
self::assertSame(
serialize($expectedAnalyses),
serialize($actualAnalyses),
);
}
/**
* @return iterable<string, array{0: string, 1: int, 2: list<AttributeAnalysis>}>
*/
public static function provideGetAttributeDeclarationsCases(): iterable
{
yield 'multiple #[] in a multiline group' => [
'<?php
/**
* Start docblock
*/
#[AB\Baz(prop: \'baz\')]
#[A\B\Quux(prop1: [1, 2, 4], prop2: true, prop3: \'foo bar\')]
#[\A\B\Qux()]
#[BarAlias(3)]
/**
* Corge docblock
*/
#[Corge]
#[Foo(4, \'baz qux\')]
/**
* End docblock
*/
function foo() {}
',
4,
[
new AttributeAnalysis(4, 15, 4, 14, [[
'start' => 5,
'end' => 13,
'name' => 'AB\Baz',
]]),
new AttributeAnalysis(16, 49, 16, 48, [[
'start' => 17,
'end' => 47,
'name' => 'A\B\Quux',
]]),
new AttributeAnalysis(50, 60, 50, 59, [[
'start' => 51,
'end' => 58,
'name' => '\A\B\Qux',
]]),
new AttributeAnalysis(61, 67, 61, 66, [[
'start' => 62,
'end' => 65,
'name' => 'BarAlias',
]]),
new AttributeAnalysis(68, 73, 70, 72, [[
'start' => 71,
'end' => 71,
'name' => 'Corge',
]]),
new AttributeAnalysis(74, 83, 74, 82, [[
'start' => 75,
'end' => 81,
'name' => 'Foo',
]]),
],
];
yield 'multiple #[] in a single line group' => [
'<?php
/** Start docblock */#[AB\Baz(prop: \'baz\')] #[A\B\Quux(prop1: [1, 2, 4], prop2: true, prop3: \'foo bar\')] #[\A\B\Qux()] #[BarAlias(3)] /** Corge docblock */#[Corge] #[Foo(4, \'baz qux\')]/** End docblock */
function foo() {}
',
3,
[
new AttributeAnalysis(3, 14, 3, 13, [[
'start' => 4,
'end' => 12,
'name' => 'AB\Baz',
]]),
new AttributeAnalysis(15, 48, 15, 47, [[
'start' => 16,
'end' => 46,
'name' => 'A\B\Quux',
]]),
new AttributeAnalysis(49, 59, 49, 58, [[
'start' => 50,
'end' => 57,
'name' => '\A\B\Qux',
]]),
new AttributeAnalysis(60, 66, 60, 65, [[
'start' => 61,
'end' => 64,
'name' => 'BarAlias',
]]),
new AttributeAnalysis(67, 71, 68, 70, [[
'start' => 69,
'end' => 69,
'name' => 'Corge',
]]),
new AttributeAnalysis(72, 80, 72, 80, [[
'start' => 73,
'end' => 79,
'name' => 'Foo',
]]),
],
];
yield 'comma-separated attributes in a multiline #[]' => [
'<?php
#[
/*
* AB\Baz comment
*/
AB\Baz(prop: \'baz\'),
A\B\Quux(prop1: [1, 2, 4], prop2: true, prop3: \'foo bar\'),
\A\B\Qux(),
BarAlias(3),
/*
* Corge comment
*/
Corge,
/**
* Foo docblock
*/
Foo(4, \'baz qux\'),
]
function foo() {}
',
2,
[
new AttributeAnalysis(2, 83, 2, 82, [[
'start' => 3,
'end' => 14,
'name' => 'AB\Baz',
], [
'start' => 16,
'end' => 47,
'name' => 'A\B\Quux',
], [
'start' => 49,
'end' => 57,
'name' => '\A\B\Qux',
], [
'start' => 59,
'end' => 63,
'name' => 'BarAlias',
], [
'start' => 65,
'end' => 68,
'name' => 'Corge',
], [
'start' => 70,
'end' => 79,
'name' => 'Foo',
]]),
],
];
yield 'comma-separated attributes in a single line #[]' => [
'<?php
#[/* AB\Baz comment */AB\Baz(prop: \'baz\'), A\B\Quux(prop1: [1, 2, 4], prop2: true, prop3: \'foo bar\'), \A\B\Qux(), BarAlias(3), /* Corge comment */Corge, /** Foo docblock */Foo(4, \'baz qux\')]
function foo() {}
',
2,
[
new AttributeAnalysis(2, 77, 2, 76, [[
'start' => 3,
'end' => 12,
'name' => 'AB\Baz',
], [
'start' => 14,
'end' => 45,
'name' => 'A\B\Quux',
], [
'start' => 47,
'end' => 55,
'name' => '\A\B\Qux',
], [
'start' => 57,
'end' => 61,
'name' => 'BarAlias',
], [
'start' => 63,
'end' => 65,
'name' => 'Corge',
], [
'start' => 67,
'end' => 75,
'name' => 'Foo',
]]),
],
];
}
/**
* @requires PHP 8.1
*
* @dataProvider provideGetAttributeDeclarations81Cases
*
* @param list<AttributeAnalysis> $expectedAnalyses
*/
public function testGetAttributeDeclarations81(string $code, int $startIndex, array $expectedAnalyses): void
{
$this->testGetAttributeDeclarations($code, $startIndex, $expectedAnalyses);
}
/**
* @return iterable<string, array{0: string, 1: int, 2: list<AttributeAnalysis>}>
*/
public static function provideGetAttributeDeclarations81Cases(): iterable
{
yield 'multiple #[] in a group, including `new` in arguments' => [
'<?php
#[AB\Baz(prop: \'baz\')]
#[\A\B\Qux(prop: new P\R())]
#[Corge]
function foo() {}
',
2,
[
new AttributeAnalysis(2, 13, 2, 12, [[
'start' => 3,
'end' => 11,
'name' => 'AB\Baz',
]]),
new AttributeAnalysis(14, 34, 14, 33, [[
'start' => 15,
'end' => 32,
'name' => '\A\B\Qux',
]]),
new AttributeAnalysis(35, 38, 35, 37, [[
'start' => 36,
'end' => 36,
'name' => 'Corge',
]]),
],
];
yield 'comma-separated attributes in single #[] group, including `new` in arguments' => [
'<?php
#[
AB\Baz(prop: \'baz\'),
\A\B\Qux(prop: new P\R()),
Corge,
]
function foo() {}
',
2,
[
new AttributeAnalysis(2, 39, 2, 38, [[
'start' => 3,
'end' => 12,
'name' => 'AB\Baz',
], [
'start' => 14,
'end' => 32,
'name' => '\A\B\Qux',
], [
'start' => 34,
'end' => 35,
'name' => 'Corge',
]]),
],
];
}
}
| 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/Tokenizer/Analyzer/WhitespacesAnalyzerTest.php | tests/Tokenizer/Analyzer/WhitespacesAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class WhitespacesAnalyzerTest extends TestCase
{
/**
* @dataProvider provideIndentCases
*/
public function testIndent(string $code, string $indent, int $index): void
{
$tokens = Tokens::fromCode($code);
self::assertSame($indent, WhitespacesAnalyzer::detectIndent($tokens, $index));
}
/**
* @return iterable<int, array{string, string, int}>
*/
public static function provideIndentCases(): iterable
{
yield ['<?php function foo() { return true; }', '', 10];
yield [
'<?php
function foo() { return true; }
',
' ',
8,
];
$code = '<?php
// wrong indent
function foo() { /* foo */ return true; }
';
$tokens = Tokens::fromCode($code);
foreach (range(4, $tokens->count() - 2) as $index) {
yield [$code, ' ', $index];
}
}
}
| 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/Tokenizer/Analyzer/ClassyAnalyzerTest.php | tests/Tokenizer/Analyzer/ClassyAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ClassyAnalyzerTest extends TestCase
{
/**
* @param array<int, bool> $expected
*
* @dataProvider provideIsClassyInvocationCases
*/
public function testIsClassyInvocation(string $source, array $expected): void
{
self::assertClassyInvocation($source, $expected);
}
/**
* @return iterable<array{string, array<int, bool>}>
*/
public static function provideIsClassyInvocationCases(): iterable
{
yield [
'<?php new Foo;',
[3 => true],
];
yield [
'<?php new \Foo;',
[4 => true],
];
yield [
'<?php new Bar\Foo;',
[3 => false, 5 => true],
];
yield [
'<?php new namespace\Foo;',
[5 => true],
];
yield [
'<?php Foo::bar();',
[1 => true, 3 => false],
];
yield [
'<?php \Foo::bar();',
[2 => true, 4 => false],
];
yield [
'<?php Bar\Foo::bar();',
[1 => false, 3 => true, 5 => false],
];
yield [
'<?php $foo instanceof Foo;',
[5 => true],
];
yield [
'<?php class Foo extends \A {}',
[3 => false, 8 => true],
];
yield [
'<?php class Foo implements A, B\C, \D, E {}',
[3 => false, 7 => true, 10 => false, 12 => true, 16 => true, 19 => true],
];
yield [
'<?php class Foo { use A, B\C, \D, E { A::bar insteadof \E; } }',
[3 => false, 9 => true, 12 => false, 14 => true, 18 => true, 21 => true, 25 => true, 32 => true],
];
yield 'with reference' => [
'<?php function foo(Foo $foo, Bar &$bar, \Baz ...$baz, Foo\Bar $fooBar) {}',
[3 => false, 5 => true, 10 => true, 17 => true, 23 => false, 25 => true],
];
yield [
'<?php class Foo { function bar() { parent::bar(); self::baz(); $a instanceof self; } }',
[3 => false, 9 => false, 15 => false, 17 => false, 22 => false, 24 => false, 33 => false],
];
yield [
'<?php echo FOO, \BAR;',
[3 => false, 7 => false],
];
yield [
'<?php FOO & $bar;',
[1 => false],
];
yield [
'<?php foo(); \bar();',
[1 => false, 7 => false],
];
yield [
'<?php function foo(): \Foo {}',
[3 => false, 9 => true],
];
yield [
'<?php function foo(?Foo $foo, ?Foo\Bar $fooBar): ?\Foo {}',
[3 => false, 6 => true, 12 => false, 14 => true, 22 => true],
];
yield [
'<?php function foo(iterable $foo): string {}',
[3 => false, 5 => false, 11 => false],
];
yield [
'<?php function foo(?int $foo): ?string {}',
[3 => false, 6 => false, 13 => false],
];
yield [
'<?php function foo(int $foo, string &$bar): self {}',
[3 => false, 5 => false, 10 => false, 17 => false],
];
yield [
'<?php function foo(): Foo {}',
[3 => false, 8 => true],
];
foreach (['bool', 'float', 'int', 'parent', 'self', 'string', 'void'] as $returnType) {
yield [
\sprintf('<?php function foo(): %s {}', $returnType),
[3 => false, 8 => false],
];
}
yield [
'<?php try {} catch (Foo $e) {}',
[9 => true],
];
yield [
'<?php try {} catch (\Foo $e) {}',
[10 => true],
];
yield [
'<?php try {} catch (/* ... */ Foo $e /* ... */) {}',
[11 => true],
];
yield [
'<?php try {} catch (/* ... */ \Foo $e /* ... */) {}',
[12 => true],
];
}
/**
* @param array<int, bool> $expected
*
* @dataProvider provideIsClassyInvocation80Cases
*
* @requires PHP 8.0
*/
public function testIsClassyInvocation80(string $source, array $expected): void
{
self::assertClassyInvocation($source, $expected);
}
/**
* @return iterable<int, array{string, array<int, bool>}>
*/
public static function provideIsClassyInvocation80Cases(): iterable
{
yield [
'<?php function foo(): \Foo|int {}',
[3 => false, 9 => true, 11 => false],
];
yield [
'<?php function foo(): \Foo|A|int {}',
[3 => false, 9 => true, 11 => true, 13 => false],
];
yield [
'<?php function foo(): int|A|NULL {}',
[3 => false, 8 => false, 10 => true, 12 => false],
];
yield [
'<?php function foo(): int|A|false {}',
[3 => false, 8 => false, 10 => true, 12 => false],
];
yield [
'<?php #[AnAttribute] class Foo {}',
[2 => true],
];
yield [
'<?php try {} catch (Foo) {}',
[9 => true],
];
yield [
'<?php try {} catch (\Foo) {}',
[10 => true],
];
yield [
'<?php try {} catch (/* non-capturing catch */ Foo /* just because! */) {}',
[11 => true],
];
yield [
'<?php try {} catch (/* non-capturing catch */ \Foo /* just because! */) {}',
[12 => true],
];
}
/**
* @param array<int, bool> $expected
*
* @dataProvider provideIsClassyInvocation81Cases
*
* @requires PHP 8.1
*/
public function testIsClassyInvocation81(string $source, array $expected): void
{
self::assertClassyInvocation($source, $expected);
}
/**
* @return iterable<string, array{string, array<int, bool>}>
*/
public static function provideIsClassyInvocation81Cases(): iterable
{
yield 'never' => [
'<?php function foo(): never {}',
[3 => false, 8 => false],
];
yield 'intersection' => [
'<?php function foo(): \Foo&Bar {}',
[3 => false, 9 => true, 11 => true],
];
}
/**
* @param array<int, bool> $expected
*/
private static function assertClassyInvocation(string $source, array $expected): void
{
$tokens = Tokens::fromCode($source);
$analyzer = new ClassyAnalyzer();
foreach ($expected as $index => $isClassy) {
self::assertSame($isClassy, $analyzer->isClassyInvocation($tokens, $index), \sprintf('Token at index %d should match the expected value "%s".', $index, true === $isClassy ? 'true' : 'false'));
}
}
}
| 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/Tokenizer/Analyzer/NamespaceUsesAnalyzerTest.php | tests/Tokenizer/Analyzer/NamespaceUsesAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author VeeWee <toonverwerft@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NamespaceUsesAnalyzerTest extends TestCase
{
/**
* @param list<NamespaceUseAnalysis> $expected
*
* @dataProvider provideUsesFromTokensCases
*/
public function testUsesFromTokens(string $code, array $expected, bool $allowMulti = false): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new NamespaceUsesAnalyzer();
self::assertSame(
serialize($expected),
serialize($analyzer->getDeclarationsFromTokens($tokens, $allowMulti)),
);
}
/**
* @return iterable<array{0: string, 1: list<NamespaceUseAnalysis>, 2?: bool}>
*/
public static function provideUsesFromTokensCases(): iterable
{
yield ['<?php // no uses', []];
yield ['<?php use Foo\Bar;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Bar',
'Bar',
false,
false,
1,
6,
),
]];
yield ['<?php use Foo\Bar; use Foo\Baz;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Bar',
'Bar',
false,
false,
1,
6,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Baz',
'Baz',
false,
false,
8,
13,
),
]];
yield ['<?php use \Foo\Bar;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'\Foo\Bar',
'Bar',
false,
false,
1,
7,
),
]];
yield ['<?php use Foo\Bar as Baz;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Bar',
'Baz',
true,
false,
1,
10,
),
]];
yield ['<?php use Foo\Bar as Baz; use Foo\Buz as Baz;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Bar',
'Baz',
true,
false,
1,
10,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Buz',
'Baz',
true,
false,
12,
21,
),
]];
yield ['<?php use function My\count;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'My\count',
'count',
false,
false,
1,
8,
),
]];
yield ['<?php use function My\count as myCount;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'My\count',
'myCount',
true,
false,
1,
12,
),
]];
yield ['<?php use const My\Full\CONSTANT;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CONSTANT,
'My\Full\CONSTANT',
'CONSTANT',
false,
false,
1,
10,
),
]];
yield 'Comma-separated class import with multi-use parsing disabled' => ['<?php use Foo\Bar, Foo\Baz;', [], false];
yield 'Group class import with multi-use parsing disabled' => ['<?php use Foo\{Bar, Baz};', [], false];
yield 'Comma-separated class import' => ['<?php use Foo\Bar, Foo\Baz;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Bar',
'Bar',
false,
true,
1,
11,
3,
5,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Baz',
'Baz',
false,
true,
1,
11,
8,
10,
),
], true];
yield 'group class import' => ['<?php use Foo\{Bar, Baz};', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Bar',
'Bar',
false,
true,
1,
11,
6,
6,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Baz',
'Baz',
false,
true,
1,
11,
9,
9,
),
], true];
yield 'Comma-separated function import' => ['<?php use function Foo\bar, Foo\baz;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'Foo\bar',
'bar',
false,
true,
1,
13,
5,
7,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'Foo\baz',
'baz',
false,
true,
1,
13,
10,
12,
),
], true];
yield 'group function import' => ['<?php use function Foo\{bar, baz};', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'Foo\bar',
'bar',
false,
true,
1,
13,
8,
8,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'Foo\baz',
'baz',
false,
true,
1,
13,
11,
11,
),
], true];
yield 'Comma-separated constant import' => ['<?php use const Foo\BAR, Foo\BAZ;', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CONSTANT,
'Foo\BAR',
'BAR',
false,
true,
1,
13,
5,
7,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CONSTANT,
'Foo\BAZ',
'BAZ',
false,
true,
1,
13,
10,
12,
),
], true];
yield 'group constant import' => ['<?php use const Foo\{BAR, BAZ};', [
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CONSTANT,
'Foo\BAR',
'BAR',
false,
true,
1,
13,
8,
8,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CONSTANT,
'Foo\BAZ',
'BAZ',
false,
true,
1,
13,
11,
11,
),
], true];
yield 'multiple multi-imports with comments' => [
<<<'PHP'
<?php
use Foo\Bar, /* Foo\Baz, */ Foo\Buzz, /** Foo\Bazzz, */ Foo\Bazzzz;
use function Bar\f1, /* Bar\f2, */ Bar\f3, /** Bar\f4, */ Bar\f5;
use const Buzz\C1, /* Buzz\C2, */ Buzz\C3, /** Buzz\C4, */ Buzz\C5;
PHP,
[
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Bar',
'Bar',
false,
true,
1,
20,
3,
5,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Buzz',
'Buzz',
false,
true,
1,
20,
10,
12,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Bazzzz',
'Bazzzz',
false,
true,
1,
20,
17,
19,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'Bar\f1',
'f1',
false,
true,
22,
43,
26,
28,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'Bar\f3',
'f3',
false,
true,
22,
43,
33,
35,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'Bar\f5',
'f5',
false,
true,
22,
43,
40,
42,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CONSTANT,
'Buzz\C1',
'C1',
false,
true,
45,
66,
49,
51,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CONSTANT,
'Buzz\C3',
'C3',
false,
true,
45,
66,
56,
58,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CONSTANT,
'Buzz\C5',
'C5',
false,
true,
45,
66,
63,
65,
),
],
true,
];
yield 'multiple multi-imports with aliases' => [
<<<'PHP'
<?php
use Foo\Bar, Foo\Baz as Buzz;
use function Bar\f1, Bar\f2 as func2;
use const Buzz\C1, Buzz\C2 as CONST2;
PHP,
[
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Bar',
'Bar',
false,
true,
1,
15,
3,
5,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Baz',
'Buzz',
true,
true,
1,
15,
8,
14,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'Bar\f1',
'f1',
false,
true,
17,
33,
21,
23,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_FUNCTION,
'Bar\f2',
'func2',
true,
true,
17,
33,
26,
32,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CONSTANT,
'Buzz\C1',
'C1',
false,
true,
35,
51,
39,
41,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CONSTANT,
'Buzz\C2',
'CONST2',
true,
true,
35,
51,
44,
50,
),
],
true,
];
yield 'multiline grouped class import with trailing comma' => [
<<<'PHP'
<?php
use Foo\{
Bar,
Baz,
};
PHP,
[
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Bar',
'Bar',
false,
true,
1,
14,
7,
7,
),
new NamespaceUseAnalysis(
NamespaceUseAnalysis::TYPE_CLASS,
'Foo\Baz',
'Baz',
false,
true,
1,
14,
10,
10,
),
],
true,
];
}
/**
* @param list<NamespaceUseAnalysis> $expected
*
* @dataProvider provideGetDeclarationsInNamespaceCases
*/
public function testGetDeclarationsInNamespace(string $code, NamespaceAnalysis $namespace, array $expected): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new NamespaceUsesAnalyzer();
self::assertSame(
serialize($expected),
serialize($analyzer->getDeclarationsInNamespace($tokens, $namespace)),
);
}
/**
* @return iterable<int, array{0: string, 1: NamespaceAnalysis, 2: list<NamespaceUseAnalysis>}>
*/
public static function provideGetDeclarationsInNamespaceCases(): iterable
{
yield [
'<?php
namespace Foo;
use Bar;
use Baz;',
new NamespaceAnalysis('Foo', 'Foo', 2, 5, 2, 15),
[
new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Bar', 'Bar', false, false, 7, 10),
new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Baz', 'Baz', false, false, 12, 15),
],
];
yield [
'<?php
namespace Foo1 {
use Bar1;
use Baz1;
}
namespace Foo2 {
use Bar2;
use Baz2;
}',
new NamespaceAnalysis('Foo1', 'Foo1', 2, 4, 2, 18),
[
new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Bar1', 'Bar1', false, false, 8, 11),
new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Baz1', 'Baz1', false, false, 13, 16),
],
];
yield [
'<?php
namespace Foo1 {
use Bar1;
use Baz1;
}
namespace Foo2 {
use Bar2;
use Baz2;
}',
new NamespaceAnalysis('Foo2', 'Foo2', 20, 22, 20, 36),
[
new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Bar2', 'Bar2', false, false, 26, 29),
new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Baz2', 'Baz2', false, false, 31, 34),
],
];
}
}
| 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/Tokenizer/Analyzer/FullyQualifiedNameAnalyzerTest.php | tests/Tokenizer/Analyzer/FullyQualifiedNameAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FullyQualifiedNameAnalyzerTest extends TestCase
{
/**
* @dataProvider provideGetFullyQualifiedNameCases
*
* @param NamespaceUseAnalysis::TYPE_* $importType
*/
public function testGetFullyQualifiedName(string $fullyQualifiedName, string $code, string $name, int $indexInNamespace, int $importType): void
{
$analyzer = new FullyQualifiedNameAnalyzer(Tokens::fromCode($code));
self::assertSame(
$fullyQualifiedName,
$analyzer->getFullyQualifiedName($name, $indexInNamespace, $importType),
);
}
/**
* @return iterable<string, array{string, string, string, int}>
*/
public static function provideGetFullyQualifiedNameCases(): iterable
{
yield 'no namespace and no import' => [
'Foo\Bar\Baz',
'<?php function f(Foo\Bar\Baz $x) {}',
'Foo\Bar\Baz',
5,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'no namespace and import' => [
'Foo\Bar\Baz',
'<?php use Foo\Bar\Baz; function f(Baz $x) {}',
'Baz',
14,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'no namespace and import with leading slash' => [
'Foo\Bar\Baz',
'<?php use \Foo\Bar\Baz; function f(Baz $x) {}',
'Baz',
15,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'no namespace and partial import' => [
'Foo\Bar\Baz',
'<?php use Foo\Bar; function f(Bar\Baz $x) {}',
'Bar\Baz',
12,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'no namespace and aliased import' => [
'Foo\Bar\Baz',
'<?php use Foo\Bar\Baz as TheClass; function f(TheClass $x) {}',
'TheClass',
18,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'no namespace and partial aliased import' => [
'Foo\Bar\Baz',
'<?php use Foo\Bar as TheClass; function f(TheClass\Baz $x) {}',
'TheClass\Baz',
16,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'namespaced with no import' => [
'Foo\Bar\Baz',
'<?php namespace N; function f(\Foo\Bar\Baz $x) {}',
'\Foo\Bar\Baz',
10,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'namespaced with import' => [
'Foo\Bar\Baz',
'<?php namespace N; use Foo\Bar\Baz; function f(Baz $x) {}',
'Baz',
19,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'namespaced with import with leading slash' => [
'Foo\Bar\Baz',
'<?php namespace N; use \Foo\Bar\Baz; function f(Baz $x) {}',
'Baz',
20,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'namespaced with partial import' => [
'Foo\Bar\Baz',
'<?php namespace N; use Foo\Bar; function f(Bar\Baz $x) {}',
'Bar\Baz',
17,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'namespaced with aliased import' => [
'Foo\Bar\Baz',
'<?php namespace N; use Foo\Bar\Baz as TheClass; function f(TheClass $x) {}',
'TheClass',
23,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'namespaced with partial aliased import' => [
'Foo\Bar\Baz',
'<?php namespace N; use Foo\Bar as TheClass; function f(TheClass\Baz $x) {}',
'TheClass\Baz',
21,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'multiple imports' => [
'FooClass\Bar',
<<<'PHP'
<?php
namespace N;
use FooClass\Foo;
use FooClass\Bar;
use FooClass\Baz;
function f(Bar $x) {}
PHP,
'Bar',
20,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'imports of all kinds - resolve classy' => [
'FooClass\Bar',
<<<'PHP'
<?php
namespace N;
use const FooConst\Bar;
use FooClass\Bar;
use function FooFunction\Bar;
function f(Bar $x) {}
PHP,
'Bar',
35,
NamespaceUseAnalysis::TYPE_CLASS,
];
yield 'imports of all kinds - resolve constant' => [
'FooConst\Bar',
<<<'PHP'
<?php
namespace N;
use const FooConst\Bar;
use FooClass\Bar;
use function FooFunction\Bar;
function f(Bar $x) {}
PHP,
'Bar',
35,
NamespaceUseAnalysis::TYPE_CONSTANT,
];
yield 'imports of all kinds - resolve function' => [
'FooFunction\Bar',
<<<'PHP'
<?php
namespace N;
use const FooConst\Bar;
use FooClass\Bar;
use function FooFunction\Bar;
function f(Bar $x) {}
PHP,
'Bar',
35,
NamespaceUseAnalysis::TYPE_FUNCTION,
];
$indexToNameMap = [
11 => ['Foo', 'Namespace1\Foo'],
31 => ['Foo', 'Namespace2\Foo'],
51 => ['Foo', 'Namespace3\Foo'],
55 => ['Bar', 'Namespace3\Bar'],
];
foreach ($indexToNameMap as $index => [$shortName, $fullName]) {
yield \sprintf('multiple namespaces with class %s', $fullName) => [
$fullName,
<<<'PHP'
<?php
namespace Namespace1 { function f(Foo $x) {} }
namespace Namespace2 { function f(Foo $x) {} }
namespace Namespace3 { function f(Foo $x, Bar $t) {} }
PHP,
$shortName,
$index,
NamespaceUseAnalysis::TYPE_CLASS,
];
}
}
public function testMultipleGetFullyQualifiedNameCalls(): void
{
$analyzer = new FullyQualifiedNameAnalyzer(Tokens::fromCode(
<<<'PHP'
<?php
namespace Namespace1 { use Vendor1\Foo; function f(Foo $x) {} }
namespace Namespace2 { use Vendor1\Bar; function f(Bar $x) {} }
namespace Namespace1 { use Vendor2\Foo; function f(Foo $x) {} }
PHP,
));
self::assertSame('Vendor1\Foo', $analyzer->getFullyQualifiedName('Foo', 18, NamespaceUseAnalysis::TYPE_CLASS));
self::assertSame('Vendor1\Bar', $analyzer->getFullyQualifiedName('Bar', 45, NamespaceUseAnalysis::TYPE_CLASS));
self::assertSame('Vendor2\Foo', $analyzer->getFullyQualifiedName('Foo', 72, NamespaceUseAnalysis::TYPE_CLASS));
}
}
| 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/Tokenizer/Analyzer/FunctionsAnalyzerTest.php | tests/Tokenizer/Analyzer/FunctionsAnalyzerTest.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\Tokenizer\Analyzer;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author VeeWee <toonverwerft@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FunctionsAnalyzerTest extends TestCase
{
/**
* @param list<int> $expectedIndices
*
* @dataProvider provideIsGlobalFunctionCallCases
*/
public function testIsGlobalFunctionCall(string $code, array $expectedIndices): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new FunctionsAnalyzer();
$calculatedIndices = [];
foreach ($tokens as $index => $token) {
if ($analyzer->isGlobalFunctionCall($tokens, $index)) {
$calculatedIndices[] = $index;
}
}
self::assertSame(
$expectedIndices,
$calculatedIndices,
\sprintf(
'Global function calls found at positions: [%s], expected at [%s].',
implode(', ', $calculatedIndices),
implode(', ', $expectedIndices),
),
);
}
/**
* @return iterable<array{string, list<int>}>
*/
public static function provideIsGlobalFunctionCallCases(): iterable
{
yield [
'<?php CONSTANT;',
[],
];
yield [
'<?php foo();',
[1],
];
yield [
'<?php foo("bar");',
[1],
];
yield [
'<?php \foo("bar");',
[2],
];
yield [
'<?php foo\bar("baz");',
[],
];
yield [
'<?php foo::bar("baz");',
[],
];
yield [
'<?php $foo->bar("baz");',
[],
];
yield [
'<?php new bar("baz");',
[],
];
yield [
'<?php function foo() {}',
[],
];
yield 'function with ref. return' => [
'<?php function & foo() {}',
[],
];
yield [
'<?php namespace\foo("bar");',
[],
];
yield [
'<?php
namespace A {
use function A;
}
namespace B {
use function D;
A();
}
',
[30],
];
yield [
'<?php
function A(){}
A();
',
[10],
];
yield [
'<?php
function A(){}
a();
',
[10],
];
yield [
'<?php
namespace {
function A(){}
A();
}
',
[14],
];
yield [
'<?php
namespace Z {
function A(){}
A();
}
',
[],
];
yield [
'<?php
namespace Z;
function A(){}
A();
',
[],
];
yield 'function signature ref. return, calls itself' => [
'<?php
function & A(){}
A();
',
[12],
];
yield [
'<?php
class Foo
{
public function A(){}
}
A();
',
[20],
];
yield [
'<?php
namespace A {
function A(){}
}
namespace B {
A();
}
',
[24],
];
yield [
'<?php
use function X\a;
A();
',
[],
];
yield [
'<?php
use A;
A();
',
[7],
];
yield [
'<?php
use const A;
A();
',
[9],
];
yield [
'<?php
use function A;
str_repeat($a, $b);
',
[9],
];
yield [
'<?php
namespace {
function A(){}
A();
$b = function(){};
}
',
[14],
];
yield [
'<?php implode($a);implode($a);implode($a);implode($a);implode($a);implode($a);',
[1, 6, 11, 16, 21, 26],
];
yield [
'<?php
$z = new class(
new class(){ private function A(){} }
){
public function A() {}
};
A();
',
[46],
];
yield [
'<?php $foo = fn() => false;',
[],
];
yield [
'<?php foo("bar"); class A { function Foo(){ foo(); } }',
[1, 20],
];
yield 'functions that can be confused with a property hook' => [
<<<'PHP'
<?php
$array = [
1 => 2,
set() => 3,
$foo . set() => 3,
];
$x = set(set(), set());
set();
if (true) { set(); }
set();
PHP,
[14, 27, 43, 45, 50, 56, 69, 76],
];
}
/**
* @param list<int> $indices
*
* @dataProvider provideIsGlobalFunctionCallPre80Cases
*
* @requires PHP <8.0
*/
public function testIsGlobalFunctionCallPre80(string $code, array $indices): void
{
$this->testIsGlobalFunctionCall($code, $indices);
}
/**
* @return iterable<int, array{string, list<int>}>
*/
public static function provideIsGlobalFunctionCallPre80Cases(): iterable
{
yield [
'<?php
use function \ str_repeat;
str_repeat($a, $b);
',
[11],
];
}
/**
* @param list<int> $indices
*
* @dataProvider provideIsGlobalFunctionCallPhp80Cases
*
* @requires PHP 8.0
*/
public function testIsGlobalFunctionCallPhp80(string $code, array $indices): void
{
$this->testIsGlobalFunctionCall($code, $indices);
}
/**
* @return iterable<int, array{string, list<int>}>
*/
public static function provideIsGlobalFunctionCallPhp80Cases(): iterable
{
yield [
'<?php $a = new (foo());',
[8],
];
yield [
'<?php $b = $foo instanceof (foo());',
[10],
];
yield [
'<?php
#[\Attribute(\Attribute::TARGET_CLASS)]
class Foo {}
',
[],
];
yield [
'<?php $x?->count();',
[],
];
yield [
'<?php
#[Foo(), Bar(), Baz()]
class Foo {}
',
[],
];
}
/**
* @param list<int> $indices
*
* @dataProvider provideIsGlobalFunctionCallPhp81Cases
*
* @requires PHP 8.1
*/
public function testIsGlobalFunctionCallPhp81(string $code, array $indices): void
{
$this->testIsGlobalFunctionCall($code, $indices);
}
/**
* @return iterable<array{string, list<int>}>
*/
public static function provideIsGlobalFunctionCallPhp81Cases(): iterable
{
yield 'first class callable cases' => [
'<?php
strlen(...);
\strlen(...);
$closure(...);
$invokableObject(...);
$obj->method(...);
$obj->$methodStr(...);
($obj->property)(...);
Foo::method(...);
$classStr::$methodStr(...);
self::{$complex . $expression}(...);
\'strlen\'(...);
[$obj, \'method\'](...);
[Foo::class, \'method\'](...);
$c = new class{};
$b = new class(){};
$a = new #[foo]
class(){};
',
[],
];
yield [
'<?php foo("bar"); enum A { function Foo(){ foo(); } }',
[1, 20],
];
}
/**
* @param list<int> $indices
*
* @dataProvider provideIsGlobalFunctionCallPhp84Cases
*
* @requires PHP 8.4
*/
public function testIsGlobalFunctionCallPhp84(string $code, array $indices): void
{
$this->testIsGlobalFunctionCall($code, $indices);
}
/**
* @return iterable<string, array{string, list<int>}>
*/
public static function provideIsGlobalFunctionCallPhp84Cases(): iterable
{
yield 'property hooks' => [
<<<'PHP'
<?php
class GetFirst
{
public string $bothWithDoubleArrow = '' {
get => '';
set(string $x) => $x;
}
public string $getWithDoubleArrow = '' {
get => '';
set(string $x) { ''; }
}
public string $setWithDoubleArrow = '' {
get { ''; }
set(string $x) => $x;
}
public string $bothWithBraces = '' {
get { ''; }
set(string $x) { ''; }
}
public string $setUppercase = '' {
get { ''; }
SET(string $x) { ''; }
}
}
class SetFirst
{
public string $bothWithDoubleArrow = '' {
set(string $x) => $x;
get => '';
}
public string $getWithDoubleArrow = '' {
set(string $x) { ''; }
get => '';
}
public string $setWithDoubleArrow = '' {
set(string $x) => $x;
get { ''; }
}
public string $bothWithBraces = '' {
set(string $x) { ''; }
get { ''; }
}
public string $setUppercase = '' {
SET(string $x) { ''; }
get { ''; }
}
}
PHP,
[],
];
}
/**
* @param array<string, ArgumentAnalysis> $expected
*
* @dataProvider provideFunctionArgumentInfoCases
*/
public function testFunctionArgumentInfo(string $code, int $methodIndex, array $expected): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new FunctionsAnalyzer();
self::assertSame(serialize($expected), serialize($analyzer->getFunctionArguments($tokens, $methodIndex)));
}
/**
* @return iterable<int, array{string, int, array<string, ArgumentAnalysis>}>
*/
public static function provideFunctionArgumentInfoCases(): iterable
{
yield ['<?php function(){};', 1, []];
yield ['<?php function($a){};', 1, [
'$a' => new ArgumentAnalysis(
'$a',
3,
null,
null,
),
]];
yield ['<?php function($a, $b){};', 1, [
'$a' => new ArgumentAnalysis(
'$a',
3,
null,
null,
),
'$b' => new ArgumentAnalysis(
'$b',
6,
null,
null,
),
]];
yield ['<?php function($a, $b = array(1,2), $c = 3){};', 1, [
'$a' => new ArgumentAnalysis(
'$a',
3,
null,
null,
),
'$b' => new ArgumentAnalysis(
'$b',
6,
'array(1,2)',
null,
),
'$c' => new ArgumentAnalysis(
'$c',
18,
'3',
null,
),
]];
yield ['<?php function(array $a = array()){};', 1, [
'$a' => new ArgumentAnalysis(
'$a',
5,
'array()',
new TypeAnalysis(
'array',
3,
3,
),
),
]];
yield ['<?php function(array ... $a){};', 1, [
'$a' => new ArgumentAnalysis(
'$a',
7,
null,
new TypeAnalysis(
'array',
3,
3,
),
),
]];
yield ['<?php function(\Foo\Bar $a){};', 1, [
'$a' => new ArgumentAnalysis(
'$a',
8,
null,
new TypeAnalysis(
'\Foo\Bar',
3,
6,
),
),
]];
yield ['<?php fn() => null;', 1, []];
yield ['<?php fn($a) => null;', 1, [
'$a' => new ArgumentAnalysis(
'$a',
3,
null,
null,
),
]];
yield ['<?php fn($a, $b) => null;', 1, [
'$a' => new ArgumentAnalysis(
'$a',
3,
null,
null,
),
'$b' => new ArgumentAnalysis(
'$b',
6,
null,
null,
),
]];
yield ['<?php fn($a, $b = array(1,2), $c = 3) => null;', 1, [
'$a' => new ArgumentAnalysis(
'$a',
3,
null,
null,
),
'$b' => new ArgumentAnalysis(
'$b',
6,
'array(1,2)',
null,
),
'$c' => new ArgumentAnalysis(
'$c',
18,
'3',
null,
),
]];
yield ['<?php fn(array $a = array()) => null;', 1, [
'$a' => new ArgumentAnalysis(
'$a',
5,
'array()',
new TypeAnalysis(
'array',
3,
3,
),
),
]];
yield ['<?php fn(array ... $a) => null;', 1, [
'$a' => new ArgumentAnalysis(
'$a',
7,
null,
new TypeAnalysis(
'array',
3,
3,
),
),
]];
yield ['<?php fn(\Foo\Bar $a) => null;', 1, [
'$a' => new ArgumentAnalysis(
'$a',
8,
null,
new TypeAnalysis(
'\Foo\Bar',
3,
6,
),
),
]];
}
/**
* @param array<string, ArgumentAnalysis> $expected
*
* @dataProvider provideFunctionArgumentInfoPre80Cases
*
* @requires PHP <8.0
*/
public function testFunctionArgumentInfoPre80(string $code, int $methodIndex, array $expected): void
{
$this->testFunctionArgumentInfo($code, $methodIndex, $expected);
}
/**
* @return iterable<int, array{string, int, array<string, ArgumentAnalysis>}>
*/
public static function provideFunctionArgumentInfoPre80Cases(): iterable
{
yield ['<?php fn(\Foo/** TODO: change to something else */\Bar $a) => null;', 1, [
'$a' => new ArgumentAnalysis(
'$a',
9,
null,
new TypeAnalysis(
'\Foo\Bar',
3,
7,
),
),
]];
yield ['<?php function(\Foo/** TODO: change to something else */\Bar $a){};', 1, [
'$a' => new ArgumentAnalysis(
'$a',
9,
null,
new TypeAnalysis(
'\Foo\Bar',
3,
7,
),
),
]];
}
/**
* @dataProvider provideFunctionReturnTypeInfoCases
*/
public function testFunctionReturnTypeInfo(string $code, int $methodIndex, ?TypeAnalysis $expected): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new FunctionsAnalyzer();
$actual = $analyzer->getFunctionReturnType($tokens, $methodIndex);
self::assertSame(serialize($expected), serialize($actual));
}
/**
* @return iterable<int, array{string, int, null|TypeAnalysis}>
*/
public static function provideFunctionReturnTypeInfoCases(): iterable
{
yield ['<?php function(){};', 1, null];
yield ['<?php function($a): array {};', 1, new TypeAnalysis('array', 7, 7)];
yield ['<?php function($a): \Foo\Bar {};', 1, new TypeAnalysis('\Foo\Bar', 7, 10)];
yield ['<?php function($a): /* not sure if really an array */array {};', 1, new TypeAnalysis('array', 8, 8)];
yield ['<?php fn() => null;', 1, null];
yield ['<?php fn(array $a) => null;', 1, null];
yield ['<?php fn($a): array => null;', 1, new TypeAnalysis('array', 7, 7)];
yield ['<?php fn($a): \Foo\Bar => null;', 1, new TypeAnalysis('\Foo\Bar', 7, 10)];
yield ['<?php fn($a): /* not sure if really an array */array => null;', 1, new TypeAnalysis('array', 8, 8)];
}
/**
* @dataProvider provideFunctionReturnTypeInfoPre80Cases
*
* @requires PHP <8.0
*/
public function testFunctionReturnTypeInfoPre80(string $code, int $methodIndex, ?TypeAnalysis $expected): void
{
$this->testFunctionReturnTypeInfo($code, $methodIndex, $expected);
}
/**
* @return iterable<int, array{string, int, null|TypeAnalysis}>
*/
public static function provideFunctionReturnTypeInfoPre80Cases(): iterable
{
yield ['<?php function($a): \Foo/** TODO: change to something else */\Bar {};', 1, new TypeAnalysis('\Foo\Bar', 7, 11)];
yield ['<?php fn($a): \Foo/** TODO: change to something else */\Bar => null;', 1, new TypeAnalysis('\Foo\Bar', 7, 11)];
}
public function testIsTheSameClassCallInvalidIndex(): void
{
$tokens = Tokens::fromCode('<?php 1;2;');
$analyzer = new FunctionsAnalyzer();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Token index 666 does not exist.');
$analyzer->isTheSameClassCall($tokens, 666);
}
/**
* @dataProvider provideIsTheSameClassCallCases
*
* @param list<int> $sameClassCallIndices
*/
public function testIsTheSameClassCall(string $code, array $sameClassCallIndices): void
{
$tokens = Tokens::fromCode($code);
$analyzer = new FunctionsAnalyzer();
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
self::assertSame(
\in_array($index, $sameClassCallIndices, true),
$analyzer->isTheSameClassCall($tokens, $index),
\sprintf('Index %d failed check.', $index),
);
}
}
/**
* @return iterable<int, array{string, list<int>}>
*/
public static function provideIsTheSameClassCallCases(): iterable
{
$template = '<?php
class Foo {
public function methodOne() {
$x = %sotherMethod(1, 2, 3);
}
}
';
yield [
\sprintf($template, '$this->'),
[24],
];
yield [
\sprintf($template, 'self::'),
[24],
];
yield [
\sprintf($template, 'static::'),
[24],
];
yield [
\sprintf($template, '$THIS->'),
[24],
];
yield [
\sprintf($template, '$notThis->'),
[],
];
yield [
\sprintf($template, 'Bar::'),
[],
];
yield [
\sprintf($template, '$this::'),
[24],
];
yield [
<<<'PHP'
<?php
class Foo {
private $bar;
public function bar() {
return $this->bar;
}
}
PHP,
[],
];
}
/**
* @dataProvider provideIsTheSameClassCall80Cases
*
* @param list<int> $sameClassCallIndices
*
* @requires PHP 8.0
*/
public function testIsTheSameClassCall80(string $code, array $sameClassCallIndices): void
{
$this->testIsTheSameClassCall($code, $sameClassCallIndices);
}
/**
* @return iterable<int, array{string, list<int>}>
*/
public static function provideIsTheSameClassCall80Cases(): iterable
{
yield [
'<?php
class Foo {
public function methodOne() {
$x = $this?->otherMethod(1, 2, 3);
}
}
',
[24],
];
}
/**
* @param array<string, ArgumentAnalysis> $expected
*
* @dataProvider provideFunctionArgumentInfoPhp80Cases
*
* @requires PHP 8.0
*/
public function testFunctionArgumentInfoPhp80(string $code, int $methodIndex, array $expected): void
{
$this->testFunctionArgumentInfo($code, $methodIndex, $expected);
}
/**
* @return iterable<int, array{string, int, array<string, ArgumentAnalysis>}>
*/
public static function provideFunctionArgumentInfoPhp80Cases(): iterable
{
yield ['<?php function($aa,){};', 1, [
'$aa' => new ArgumentAnalysis(
'$aa',
3,
null,
null,
),
]];
yield ['<?php fn($a, $bc ,) => null;', 1, [
'$a' => new ArgumentAnalysis(
'$a',
3,
null,
null,
),
'$bc' => new ArgumentAnalysis(
'$bc',
6,
null,
null,
),
]];
}
/**
* @param array<string, ArgumentAnalysis> $expected
*
* @dataProvider provideFunctionArgumentInfoPhp84Cases
*
* @requires PHP 8.4
*/
public function testFunctionArgumentInfoPhp84(string $code, int $methodIndex, array $expected): void
{
$this->testFunctionArgumentInfo($code, $methodIndex, $expected);
}
/**
* @return iterable<string, array{string, int, array<string, ArgumentAnalysis>}>
*/
public static function provideFunctionArgumentInfoPhp84Cases(): iterable
{
yield 'asymmetric visibility' => [
<<<'PHP'
<?php
class Foo {
public function __construct(
public public(set) bool $b,
public protected(set) int|null $i,
protected private(set) ?string $s,
) {}
}
PHP,
9,
[
'$b' => new ArgumentAnalysis(
'$b',
20,
null,
new TypeAnalysis(
'bool',
18,
18,
),
),
'$i' => new ArgumentAnalysis(
'$i',
31,
null,
new TypeAnalysis(
'int|null',
27,
29,
),
),
'$s' => new ArgumentAnalysis(
'$s',
41,
null,
new TypeAnalysis(
'?string',
38,
39,
),
),
],
];
}
}
| 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/Tokenizer/Analyzer/Analysis/EnumAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/EnumAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\EnumAnalysis;
/**
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\EnumAnalysis
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class EnumAnalysisTest extends TestCase
{
public function testEnumAnalysis(): void
{
$analysis = new EnumAnalysis(10, 11, 15, []);
self::assertSame(10, $analysis->getIndex());
self::assertSame(11, $analysis->getOpenIndex());
self::assertSame(15, $analysis->getCloseIndex());
self::assertSame([], $analysis->getCases());
}
public function testEnumAnalysis2(): void
{
$caseAnalysis = new CaseAnalysis(20, 21);
$analysis = new EnumAnalysis(15, 17, 190, [$caseAnalysis]);
self::assertSame(15, $analysis->getIndex());
self::assertSame(17, $analysis->getOpenIndex());
self::assertSame(190, $analysis->getCloseIndex());
self::assertSame([$caseAnalysis], $analysis->getCases());
}
}
| 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/Tokenizer/Analyzer/Analysis/MatchAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/MatchAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\MatchAnalysis;
/**
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\MatchAnalysis
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class MatchAnalysisTest extends TestCase
{
public function testMatchAnalysis(): void
{
$analysis = new MatchAnalysis(10, 11, 15, null);
self::assertSame(10, $analysis->getIndex());
self::assertSame(11, $analysis->getOpenIndex());
self::assertSame(15, $analysis->getCloseIndex());
self::assertNull($analysis->getDefaultAnalysis());
}
public function testMatchAnalysis2(): void
{
$defaultAnalysis = new DefaultAnalysis(45, 48);
$analysis = new MatchAnalysis(22, 26, 290, $defaultAnalysis);
self::assertSame(22, $analysis->getIndex());
self::assertSame(26, $analysis->getOpenIndex());
self::assertSame(290, $analysis->getCloseIndex());
self::assertSame($defaultAnalysis, $analysis->getDefaultAnalysis());
}
}
| 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/Tokenizer/Analyzer/Analysis/SwitchAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/SwitchAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis;
/**
* @author Kuba Werłos <werlos@gmail.com>
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SwitchAnalysisTest extends TestCase
{
public function testSwitchAnalysis(): void
{
$analysis = new SwitchAnalysis(10, 11, 15, [], null);
self::assertSame(10, $analysis->getIndex());
self::assertSame(11, $analysis->getOpenIndex());
self::assertSame(15, $analysis->getCloseIndex());
self::assertSame([], $analysis->getCases());
self::assertNull($analysis->getDefaultAnalysis());
}
public function testSwitchAnalysis2(): void
{
$caseAnalysis = new CaseAnalysis(20, 21);
$defaultAnalysis = new DefaultAnalysis(45, 48);
$analysis = new SwitchAnalysis(15, 17, 190, [$caseAnalysis], $defaultAnalysis);
self::assertSame(15, $analysis->getIndex());
self::assertSame(17, $analysis->getOpenIndex());
self::assertSame(190, $analysis->getCloseIndex());
self::assertSame([$caseAnalysis], $analysis->getCases());
self::assertSame($defaultAnalysis, $analysis->getDefaultAnalysis());
}
}
| 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/Tokenizer/Analyzer/Analysis/DataProviderAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/DataProviderAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\DataProviderAnalysis;
/**
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\DataProviderAnalysis
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DataProviderAnalysisTest extends TestCase
{
public function testDataProviderAnalysis(): void
{
$analysis = new DataProviderAnalysis('Foo', 1, [[2, 10], [3, 11]]);
self::assertSame('Foo', $analysis->getName());
self::assertSame(1, $analysis->getNameIndex());
self::assertSame([[2, 10], [3, 11]], $analysis->getUsageIndices());
}
}
| 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/Tokenizer/Analyzer/Analysis/TypeAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/TypeAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
/**
* @author VeeWee <toonverwerft@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TypeAnalysisTest extends TestCase
{
public function testName(): void
{
$analysis = new TypeAnalysis('string', 1, 2);
self::assertSame('string', $analysis->getName());
self::assertFalse($analysis->isNullable());
$analysis = new TypeAnalysis('?\foo\bar', 1, 2);
self::assertSame('\foo\bar', $analysis->getName());
self::assertTrue($analysis->isNullable());
}
public function testStartIndex(): void
{
$analysis = new TypeAnalysis('string', 10, 20);
self::assertSame(10, $analysis->getStartIndex());
}
public function testEndIndex(): void
{
$analysis = new TypeAnalysis('string', 1, 27);
self::assertSame(27, $analysis->getEndIndex());
}
/**
* @dataProvider provideReservedCases
*/
public function testReserved(string $type, bool $expected): void
{
$analysis = new TypeAnalysis($type, 1, 2);
self::assertSame($expected, $analysis->isReservedType());
}
/**
* @return iterable<int, array{string, bool}>
*/
public static function provideReservedCases(): iterable
{
yield ['array', true];
yield ['bool', true];
yield ['callable', true];
yield ['float', true];
yield ['int', true];
yield ['iterable', true];
yield ['list', true];
yield ['mixed', true];
yield ['never', true];
yield ['null', true];
yield ['object', true];
yield ['resource', true];
yield ['self', true];
yield ['string', true];
yield ['void', true];
yield ['VOID', true];
yield ['Void', true];
yield ['voId', true];
yield ['other', false];
yield ['OTHER', false];
yield ['numeric', false];
}
/**
* @dataProvider provideIsNullableCases
*/
public function testIsNullable(bool $expected, string $input): void
{
$analysis = new TypeAnalysis($input, 1, 2);
self::assertSame($expected, $analysis->isNullable());
}
/**
* @return iterable<int, array{bool, string}>
*/
public static function provideIsNullableCases(): iterable
{
yield [false, 'string'];
yield [true, '?string'];
yield [false, 'String'];
yield [true, '?String'];
yield [false, '\foo\bar'];
yield [true, '?\foo\bar'];
}
/**
* @dataProvider provideIsNullable80Cases
*
* @requires PHP 8.0
*/
public function testIsNullable80(bool $expected, string $input): void
{
$this->testIsNullable($expected, $input);
}
/**
* @return iterable<int, array{bool, string}>
*/
public static function provideIsNullable80Cases(): iterable
{
yield [false, 'string|int'];
yield [true, 'string|null'];
yield [true, 'null|string'];
yield [true, 'string|NULL'];
yield [true, 'NULL|string'];
yield [true, 'string|int|null'];
yield [true, 'null|string|int'];
yield [true, 'string|null|int'];
yield [true, 'string|int|NULL'];
yield [true, 'NULL|string|int'];
yield [true, 'string|NULL|int'];
yield [false, 'string|\foo\bar'];
yield [true, 'string|\foo\bar|null'];
yield [true, 'null|string|\foo\bar'];
yield [true, 'string|null|\foo\bar'];
yield [true, 'string |null| int'];
yield [true, 'string| null |int'];
yield [true, 'string | null | int'];
yield [false, 'Null2|int'];
yield [false, 'string|Null2'];
yield [false, 'string |Null2'];
yield [false, 'Null2| int'];
yield [false, 'string | Null2 | int'];
}
/**
* @dataProvider provideIsNullable81Cases
*
* @requires PHP 8.1
*/
public function testIsNullable81(bool $expected, string $input): void
{
$this->testIsNullable($expected, $input);
}
/**
* @return iterable<int, array{bool, string}>
*/
public static function provideIsNullable81Cases(): iterable
{
yield [false, '\foo\bar&\foo\baz'];
yield [false, '\foo\bar & \foo\baz'];
yield [false, '\foo\bar&Null2'];
}
/**
* @dataProvider provideIsNullable82Cases
*
* @requires PHP 8.2
*/
public function testIsNullable82(bool $expected, string $input): void
{
$this->testIsNullable($expected, $input);
}
/**
* @return iterable<int, array{bool, string}>
*/
public static function provideIsNullable82Cases(): iterable
{
yield [true, '(\foo\bar&\foo\baz)|null'];
yield [true, '(\foo\bar&\foo\baz) | null'];
yield [false, '(\foo\bar&\foo\baz)|Null2'];
yield [true, 'null'];
yield [true, 'Null'];
yield [true, '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/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
/**
* @author VeeWee <toonverwerft@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NamespaceUseAnalysisTest extends TestCase
{
public function testFullName(): void
{
$analysis = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Full\NamespaceName', 'NamespaceName', false, false, 11, 21);
self::assertSame('Full\NamespaceName', $analysis->getFullName());
}
public function testAliased(): void
{
$analysis = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Full\NamespaceName', 'NamespaceName', false, false, 12, 22);
self::assertFalse($analysis->isAliased());
$analysis = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Full\NamespaceName', 'NamespaceName', true, false, 1, 2);
self::assertTrue($analysis->isAliased());
}
public function testIsInMulti(): void
{
$analysis = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Full\NamespaceName', 'NamespaceName', false, false, 12, 22);
self::assertFalse($analysis->isInMulti());
$analysis = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Full\NamespaceName', 'NamespaceName', false, true, 1, 20, 5, 10);
self::assertTrue($analysis->isInMulti());
}
public function testChunkStartIndexAndChunkEndIndexAreRequiredWhenIsInMulti(): void
{
$this->expectException(\LogicException::class);
new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Full\NamespaceName', 'NamespaceName', false, true, 1, 20);
}
public function testShortName(): void
{
$analysis = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Full\NamespaceName', 'NamespaceName', false, false, 1, 2);
self::assertSame('NamespaceName', $analysis->getShortName());
}
public function testStartIndex(): void
{
$analysis = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Full\NamespaceName', 'NamespaceName', false, false, 1, 2);
self::assertSame(1, $analysis->getStartIndex());
}
public function testEndIndex(): void
{
$analysis = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Full\NamespaceName', 'NamespaceName', false, false, 1, 72);
self::assertSame(72, $analysis->getEndIndex());
}
public function testTypeCheck(): void
{
$class = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CLASS, 'Foo\Bar', 'Baz', false, false, 1, 2);
$function = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_FUNCTION, 'Foo\Bar', 'Baz', false, false, 1, 2);
$constant = new NamespaceUseAnalysis(NamespaceUseAnalysis::TYPE_CONSTANT, 'Foo\Bar', 'Baz', false, false, 1, 2);
self::assertTrue($class->isClass());
self::assertFalse($class->isFunction());
self::assertFalse($class->isConstant());
self::assertSame(NamespaceUseAnalysis::TYPE_CLASS, $class->getType());
self::assertFalse($function->isClass());
self::assertTrue($function->isFunction());
self::assertFalse($function->isConstant());
self::assertSame(NamespaceUseAnalysis::TYPE_FUNCTION, $function->getType());
self::assertFalse($constant->isClass());
self::assertFalse($constant->isFunction());
self::assertTrue($constant->isConstant());
self::assertSame(NamespaceUseAnalysis::TYPE_CONSTANT, $constant->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/Tokenizer/Analyzer/Analysis/ArgumentAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/ArgumentAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
/**
* @author VeeWee <toonverwerft@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ArgumentAnalysisTest extends TestCase
{
public function testWithoutName(): void
{
$analysis = new ArgumentAnalysis(null, null, null, null);
self::assertNull($analysis->getName());
self::assertNull($analysis->getNameIndex());
}
public function testName(): void
{
$analysis = new ArgumentAnalysis('$name', 1, null, null);
self::assertSame('$name', $analysis->getName());
self::assertSame(1, $analysis->getNameIndex());
}
public function testDefault(): void
{
$analysis = new ArgumentAnalysis('$name', 1, 'default', null);
self::assertTrue($analysis->hasDefault());
self::assertSame('default', $analysis->getDefault());
}
public function testNoDefaultFound(): void
{
$analysis = new ArgumentAnalysis('$name', 1, null, null);
self::assertFalse($analysis->hasDefault());
self::assertNull($analysis->getDefault());
}
public function testType(): void
{
$analysis = new ArgumentAnalysis('$name', 1, null, new TypeAnalysis('string', 1, 4));
self::assertTrue($analysis->hasTypeAnalysis());
self::assertSame('string', $analysis->getTypeAnalysis()->getName());
self::assertSame(1, $analysis->getTypeAnalysis()->getStartIndex());
self::assertSame(4, $analysis->getTypeAnalysis()->getEndIndex());
}
public function testNoTypeFound(): void
{
$analysis = new ArgumentAnalysis('$name', 1, null, null);
self::assertFalse($analysis->hasTypeAnalysis());
self::assertNull($analysis->getTypeAnalysis());
}
}
| 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/Tokenizer/Analyzer/Analysis/AttributeAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/AttributeAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis;
/**
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class AttributeAnalysisTest extends TestCase
{
public function testAttribute(): void
{
$attributes = [
['start' => 3, 'end' => 12, 'name' => 'AB\Baz'],
['start' => 14, 'end' => 32, 'name' => '\A\B\Qux'],
];
$analysis = new AttributeAnalysis(2, 34, 3, 34, $attributes);
self::assertSame(2, $analysis->getStartIndex());
self::assertSame(34, $analysis->getEndIndex());
self::assertSame(3, $analysis->getOpeningBracketIndex());
self::assertSame(34, $analysis->getClosingBracketIndex());
self::assertSame($attributes, $analysis->getAttributes());
}
}
| 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/Tokenizer/Analyzer/Analysis/CaseAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/CaseAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis;
/**
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CaseAnalysisTest extends TestCase
{
public function testCase(): void
{
$analysis = new CaseAnalysis(12, 20);
self::assertSame(12, $analysis->getIndex());
self::assertSame(20, $analysis->getColonIndex());
}
}
| 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/Tokenizer/Analyzer/Analysis/DefaultAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/DefaultAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis;
/**
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DefaultAnalysisTest extends TestCase
{
public function testDefault(): void
{
$analysis = new DefaultAnalysis(15, 16);
self::assertSame(15, $analysis->getIndex());
self::assertSame(16, $analysis->getColonIndex());
}
}
| 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/Tokenizer/Analyzer/Analysis/NamespaceAnalysisTest.php | tests/Tokenizer/Analyzer/Analysis/NamespaceAnalysisTest.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\Tokenizer\Analyzer\Analysis;
use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
/**
* @author VeeWee <toonverwerft@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NamespaceAnalysisTest extends TestCase
{
public function testFullName(): void
{
$analysis = new NamespaceAnalysis('Full\NamespaceName', 'NamespaceName', 1, 2, 1, 10);
self::assertSame('Full\NamespaceName', $analysis->getFullName());
}
public function testShortName(): void
{
$analysis = new NamespaceAnalysis('Full\NamespaceName', 'NamespaceName', 1, 2, 1, 10);
self::assertSame('NamespaceName', $analysis->getShortName());
self::assertFalse($analysis->isGlobalNamespace());
}
public function testStartIndex(): void
{
$analysis = new NamespaceAnalysis('Full\NamespaceName', 'NamespaceName', 1, 2, 1, 10);
self::assertSame(1, $analysis->getStartIndex());
}
public function testEndIndex(): void
{
$analysis = new NamespaceAnalysis('Full\NamespaceName', 'NamespaceName', 1, 2, 1, 10);
self::assertSame(2, $analysis->getEndIndex());
}
public function testScopeStartIndex(): void
{
$analysis = new NamespaceAnalysis('Full\NamespaceName', 'NamespaceName', 1, 2, 1, 10);
self::assertSame(1, $analysis->getScopeStartIndex());
}
public function testScopeEndIndex(): void
{
$analysis = new NamespaceAnalysis('Full\NamespaceName', 'NamespaceName', 1, 2, 1, 10);
self::assertSame(10, $analysis->getScopeEndIndex());
}
public function testGlobal(): void
{
$analysis = new NamespaceAnalysis('', '', 1, 2, 1, 10);
self::assertTrue($analysis->isGlobalNamespace());
}
}
| 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/Tokenizer/Transformer/BraceClassInstantiationTransformerTest.php | tests/Tokenizer/Transformer/BraceClassInstantiationTransformerTest.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\Tokenizer\Transformer;
use PhpCsFixer\Tests\Test\AbstractTransformerTestCase;
use PhpCsFixer\Tokenizer\CT;
/**
* @author Sebastiaans Stok <s.stok@rollerscapes.net>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Transformer\BraceClassInstantiationTransformer
*
* @phpstan-import-type _TransformerTestExpectedKindsUnderIndex from AbstractTransformerTestCase
* @phpstan-import-type _TransformerTestObservedKinds from AbstractTransformerTestCase
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class BraceClassInstantiationTransformerTest extends AbstractTransformerTestCase
{
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
* @param _TransformerTestObservedKinds $observedKinds
*
* @dataProvider provideProcessCases
*/
public function testProcess(string $source, array $expectedTokens, array $observedKinds = []): void
{
$this->doTest(
$source,
$expectedTokens,
$observedKinds,
);
}
/**
* @return iterable<int, array{string, _TransformerTestExpectedKindsUnderIndex, _TransformerTestExpectedKindsUnderIndex}>
*/
public static function provideProcessCases(): iterable
{
yield [
'<?php echo (new Process())->getOutput();',
[
3 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
9 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
[
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php echo (new Process())::getOutput();',
[
3 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
9 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
[
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php return foo()->bar(new Foo())->bar();',
[
4 => '(',
5 => ')',
8 => '(',
12 => '(',
13 => ')',
14 => ')',
17 => '(',
18 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php $foo[0](new Foo())->bar();',
[
5 => '(',
9 => '(',
10 => ')',
11 => ')',
14 => '(',
15 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php $foo(new Foo())->bar();',
[
2 => '(',
6 => '(',
7 => ')',
8 => ')',
11 => '(',
12 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php $$foo(new Foo())->bar();',
[
3 => '(',
7 => '(',
8 => ')',
9 => ')',
12 => '(',
13 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php if ($foo){}(new Foo)->foo();',
[
8 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
12 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
[
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php echo (((new \stdClass()))->a);',
[
5 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
12 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
[
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php $foo = array(new Foo());',
[
6 => '(',
10 => '(',
11 => ')',
12 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php if (new Foo()) { } elseif (new Bar()) { } else if (new Baz()) { }',
[
3 => '(',
7 => '(',
8 => ')',
9 => ')',
17 => '(',
21 => '(',
22 => ')',
23 => ')',
33 => '(',
37 => '(',
38 => ')',
39 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php switch (new Foo()) { }',
[
3 => '(',
7 => '(',
8 => ')',
9 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php for (new Foo();;) { }',
[
3 => '(',
7 => '(',
8 => ')',
11 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php foreach (new Foo() as $foo) { }',
[
3 => '(',
7 => '(',
8 => ')',
13 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php while (new Foo()) { }',
[
3 => '(',
7 => '(',
8 => ')',
9 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php do { } while (new Foo());',
[
9 => '(',
13 => '(',
14 => ')',
15 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php $static = new static(new \SplFileInfo(__FILE__));',
[
8 => '(',
13 => '(',
15 => ')',
16 => ')',
],
[
'(',
')',
'(',
')',
],
];
yield [
'<?php $foo = new class(new \stdClass()) {};',
[
8 => '(',
13 => '(',
14 => ')',
15 => ')',
],
[
'(',
')',
],
];
yield [
'<?php $foo = (new class(new \stdClass()) {});',
[
5 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
20 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
[
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php $fn = fn() => null;',
[
6 => '(',
7 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php $result = ($function)(new Argument());',
[
5 => '(',
7 => ')',
8 => '(',
12 => '(',
13 => ')',
14 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
yield [
'<?php $result = (new Invokable())(new Argument1());',
[
5 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
9 => '(',
10 => ')',
11 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
12 => '(',
16 => '(',
17 => ')',
18 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
}
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
* @param _TransformerTestObservedKinds $observedKinds
*
* @dataProvider provideProcessPhp80Cases
*
* @requires PHP 8.0
*/
public function testProcessPhp80(array $expectedTokens, array $observedKinds, string $source): void
{
$this->doTest(
$source,
$expectedTokens,
$observedKinds,
);
}
/**
* @return iterable<int, array{_TransformerTestExpectedKindsUnderIndex, _TransformerTestExpectedKindsUnderIndex, string}>
*/
public static function provideProcessPhp80Cases(): iterable
{
yield [
[
5 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
8 => '(',
10 => '(',
11 => ')',
12 => ')',
13 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
'<?php $a = (new (foo()));',
];
yield [
[
5 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
15 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
[
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
'<?php $a = (new #[Foo]
class{}) ?>',
];
}
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
* @param _TransformerTestObservedKinds $observedKinds
*
* @dataProvider provideProcessPhp81Cases
*
* @requires PHP 8.1
*/
public function testProcessPhp81(array $expectedTokens, array $observedKinds, string $source): void
{
$this->doTest(
$source,
$expectedTokens,
$observedKinds,
);
}
/**
* @return iterable<int, array{_TransformerTestExpectedKindsUnderIndex, _TransformerTestExpectedKindsUnderIndex, string}>
*/
public static function provideProcessPhp81Cases(): iterable
{
yield [
[
20 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
24 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
43 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
47 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
54 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
64 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
107 => CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
111 => CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
[
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
'<?php
class Test {
public function __construct(
public $prop = (new Foo),
) {}
}
function test(
$foo = (new A),
$baz = (new C(x: 2)),
) {
}
static $x = new (Foo);
const C = new (Foo);
function test2($param = (new Foo)) {}
',
];
}
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
* @param _TransformerTestObservedKinds $observedKinds
*
* @dataProvider provideProcessPrePhp84Cases
*
* @requires PHP <8.4
*/
public function testProcessPrePhp84(string $source, array $expectedTokens, array $observedKinds = []): void
{
$this->doTest(
$source,
$expectedTokens,
$observedKinds,
);
}
/**
* @return iterable<int, array{string, _TransformerTestExpectedKindsUnderIndex, _TransformerTestObservedKinds}>
*/
public static function provideProcessPrePhp84Cases(): iterable
{
yield [
'<?php $foo{0}(new Foo())->bar();',
[
5 => '(',
9 => '(',
10 => ')',
11 => ')',
14 => '(',
15 => ')',
],
[
'(',
')',
CT::T_BRACE_CLASS_INSTANTIATION_OPEN,
CT::T_BRACE_CLASS_INSTANTIATION_CLOSE,
],
];
}
}
| 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/Tokenizer/Transformer/ConstructorPromotionTransformerTest.php | tests/Tokenizer/Transformer/ConstructorPromotionTransformerTest.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\Tokenizer\Transformer;
use PhpCsFixer\Tests\Test\AbstractTransformerTestCase;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Transformer\ConstructorPromotionTransformer
*
* @phpstan-import-type _TransformerTestExpectedKindsUnderIndex from AbstractTransformerTestCase
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ConstructorPromotionTransformerTest extends AbstractTransformerTestCase
{
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
*
* @dataProvider provideProcessCases
*
* @requires PHP 8.0
*/
public function testProcess(array $expectedTokens, string $source): void
{
$this->doTest(
$source,
$expectedTokens,
[
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC,
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED,
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE,
],
);
}
/**
* @return iterable<int, array{_TransformerTestExpectedKindsUnderIndex, string}>
*/
public static function provideProcessCases(): iterable
{
yield [
[
14 => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC,
25 => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED,
36 => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE,
],
'<?php
class Point {
public function __construct(
public float $x = 0.0,
protected float $y = 0.0,
private float $z = 0.0,
) {}
}
',
];
yield [
[
16 => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC,
22 => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED,
28 => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE,
],
'<?php $a = new class {function/* 1 */__CONSTRUCT/* 2 */(/* 3 */public float $x,protected float $y,private float $z) {}};',
];
}
public function testNotChange(): void
{
$code = '<?php
// class Foo1 {
// function __construct(
// private float $z = new class {
// public function __construct() {}
// }
// ) {}
// }
// class Foo2 {
// function __construct(
// private array $z = [new class {}],
// ) {}
// }
// class Foo3 {
// public function __construct(
// public float $x = 0.0,
// protected float $y = 0.0,
// private float $z = 0.0,
// ) {}
// }
function __construct(/* public */ $foo){}
class Foo4 {
public function construct(/* public */ $foo)
{}
}
class Foo5 {
public $foo1;
protected $foo2;
private $foo3;
public function __construct(/* public */ $foo){} public $foo4;
}
';
Tokens::clearCache();
foreach (Tokens::fromCode($code) as $token) {
self::assertFalse($token->isGivenKind([
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC,
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED,
CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE,
]));
}
}
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
*
* @dataProvider provideFix81Cases
*
* @requires PHP 8.1
*/
public function testFix81(array $expectedTokens, string $source): void
{
$this->doTest(
$source,
$expectedTokens,
[
CT::T_TYPE_ALTERNATION,
],
);
}
/**
* @return iterable<string, array{_TransformerTestExpectedKindsUnderIndex, string}>
*/
public static function provideFix81Cases(): iterable
{
yield 'readonly' => [
[
14 => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC,
23 => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE,
36 => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC,
52 => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC,
],
'<?php
class Test {
public function __construct(
public readonly float $f,
private readonly int $i = 0,
public readonly array $ary = [],
readonly public array $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/Tokenizer/Transformer/FirstClassCallableTransformerTest.php | tests/Tokenizer/Transformer/FirstClassCallableTransformerTest.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\Tokenizer\Transformer;
use PhpCsFixer\Tests\Test\AbstractTransformerTestCase;
use PhpCsFixer\Tokenizer\CT;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Transformer\FirstClassCallableTransformer
*
* @phpstan-import-type _TransformerTestExpectedKindsUnderIndex from AbstractTransformerTestCase
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FirstClassCallableTransformerTest extends AbstractTransformerTestCase
{
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
*
* @dataProvider provideProcessCases
*
* @requires PHP 8.1
*/
public function testProcess(array $expectedTokens, string $source): void
{
$this->doTest($source, $expectedTokens, [CT::T_FIRST_CLASS_CALLABLE]);
}
/**
* @return iterable<string, array{_TransformerTestExpectedKindsUnderIndex, string}>
*/
public static function provideProcessCases(): iterable
{
yield 'set' => [
[
3 => CT::T_FIRST_CLASS_CALLABLE,
9 => CT::T_FIRST_CLASS_CALLABLE,
15 => CT::T_FIRST_CLASS_CALLABLE,
23 => CT::T_FIRST_CLASS_CALLABLE,
31 => CT::T_FIRST_CLASS_CALLABLE,
41 => CT::T_FIRST_CLASS_CALLABLE,
49 => CT::T_FIRST_CLASS_CALLABLE,
57 => CT::T_FIRST_CLASS_CALLABLE,
71 => CT::T_FIRST_CLASS_CALLABLE,
77 => CT::T_FIRST_CLASS_CALLABLE,
88 => CT::T_FIRST_CLASS_CALLABLE,
101 => CT::T_FIRST_CLASS_CALLABLE,
],
'<?php
strlen(...);
$closure(...);
$invokableObject(...);
$obj->method(...);
$obj->$methodStr(...);
($obj->property)(...);
Foo::method(...);
$classStr::$methodStr(...);
self::{$complex . $expression}(...);
\'strlen\'(...);
[$obj, \'method\'](...);
[Foo::class, \'method\'](...) ?>',
];
yield 'comments and spacing' => [
[
4 => CT::T_FIRST_CLASS_CALLABLE,
12 => CT::T_FIRST_CLASS_CALLABLE,
18 => CT::T_FIRST_CLASS_CALLABLE,
28 => CT::T_FIRST_CLASS_CALLABLE,
40 => CT::T_FIRST_CLASS_CALLABLE,
],
'<?php
strlen(/* */.../* */);
$closure( ...);
$invokableObject(... );
$obj->method( ... );
$obj->$methodStr( /* */ ... /* */ );
',
];
yield 'not cases' => [
[],
'<?php
array_unshift($types, ...$nulls);
array_unshift(...$nulls, 1);
foo(...$args, named: $arg);
foo(named: $arg, ...$args);
foo(...$nulls);
$fruits = ["banana", "orange", ...$parts, "watermelon"];
$a = [...$array1, ...$array2];
',
];
}
}
| 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/Tokenizer/Transformer/NamedArgumentTransformerTest.php | tests/Tokenizer/Transformer/NamedArgumentTransformerTest.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\Tokenizer\Transformer;
use PhpCsFixer\Tests\Test\AbstractTransformerTestCase;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Transformer\NamedArgumentTransformer
*
* @phpstan-import-type _TransformerTestExpectedKindsUnderIndex from AbstractTransformerTestCase
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NamedArgumentTransformerTest extends AbstractTransformerTestCase
{
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
*
* @dataProvider provideProcessCases
*
* @requires PHP 8.0
*/
public function testProcess(string $source, array $expectedTokens): void
{
$this->doTest($source, $expectedTokens);
}
/**
* @return iterable<string, array{string, _TransformerTestExpectedKindsUnderIndex}>
*/
public static function provideProcessCases(): iterable
{
yield 'function call' => [
'<?php foo(test: 1);',
[
3 => CT::T_NAMED_ARGUMENT_NAME,
4 => CT::T_NAMED_ARGUMENT_COLON,
],
];
yield 'dynamic function 2x' => [
'<?php $foo(foo: 1, bar: 2, 3,);',
[
3 => CT::T_NAMED_ARGUMENT_NAME,
4 => CT::T_NAMED_ARGUMENT_COLON,
9 => CT::T_NAMED_ARGUMENT_NAME,
10 => CT::T_NAMED_ARGUMENT_COLON,
],
];
yield 'method' => [
'<?php
class Bar {
public function a($foo){}
}
$foo = new Bar();
$foo->a(foo: 1);
',
[
36 => CT::T_NAMED_ARGUMENT_NAME,
37 => CT::T_NAMED_ARGUMENT_COLON,
],
];
yield 'nested' => [
'<?php
foo(test: static function() {
bar(test: 1);
},);
',
[
4 => CT::T_NAMED_ARGUMENT_NAME,
5 => CT::T_NAMED_ARGUMENT_COLON,
17 => CT::T_NAMED_ARGUMENT_NAME,
18 => CT::T_NAMED_ARGUMENT_COLON,
],
];
}
/**
* @dataProvider provideDoNotChangeCases
*/
public function testDoNotChange(string $source): void
{
self::assertNotChange($source);
}
/**
* @return iterable<string, array{string}>
*/
public static function provideDoNotChangeCases(): iterable
{
yield 'switch/case/constants' => [
'<?php
define(\'FOO\', 123);
define(\'BAR\', 123);
$a = $guard = 123;
switch($a) {
case FOO:
echo 456;
break;
case 3 + FOO:
echo 789;
break;
case ($guard ? BAR : 2):
echo 456;
break;
}
foo(1 , $a3 ? BAR : 2);
$a1 = [1, BAR ? 1 : 2];
$a2 = [1, (BAR) ? 1 : 2];
',
];
yield 'goto' => [
'<?php
define(\'FOO\', 123);
$guard = 1;
{
beginning:
echo $guard ? 1 + FOO : 2;
echo $guard ? 1 : 2;
}
',
];
yield 'return type' => ['<?php function foo(): array { return []; }'];
}
private static function assertNotChange(string $source): void
{
Tokens::clearCache();
foreach (Tokens::fromCode($source) as $token) {
self::assertFalse($token->isGivenKind([
CT::T_NAMED_ARGUMENT_NAME,
CT::T_NAMED_ARGUMENT_COLON,
]));
}
}
}
| 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/Tokenizer/Transformer/ImportTransformerTest.php | tests/Tokenizer/Transformer/ImportTransformerTest.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\Tokenizer\Transformer;
use PhpCsFixer\Tests\Test\AbstractTransformerTestCase;
use PhpCsFixer\Tokenizer\CT;
/**
* @author Gregor Harlan <gharlan@web.de>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Transformer\ImportTransformer
*
* @phpstan-import-type _TransformerTestExpectedKindsUnderIndex from AbstractTransformerTestCase
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ImportTransformerTest extends AbstractTransformerTestCase
{
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
*
* @dataProvider provideProcessCases
*/
public function testProcess(string $source, array $expectedTokens = []): void
{
$this->doTest(
$source,
$expectedTokens,
[
\T_CONST,
CT::T_CONST_IMPORT,
\T_FUNCTION,
CT::T_FUNCTION_IMPORT,
],
);
}
/**
* @return iterable<int, array{string, _TransformerTestExpectedKindsUnderIndex}>
*/
public static function provideProcessCases(): iterable
{
yield [
'<?php const FOO = 1;',
[
1 => \T_CONST,
],
];
yield [
'<?php use Foo; const FOO = 1;',
[
6 => \T_CONST,
],
];
yield [
'<?php class Foo { const BAR = 1; }',
[
7 => \T_CONST,
],
];
yield [
'<?php use const Foo\BAR;',
[
3 => CT::T_CONST_IMPORT,
],
];
yield [
'<?php function foo() {}',
[
1 => \T_FUNCTION,
],
];
yield [
'<?php $a = function () {};',
[
5 => \T_FUNCTION,
],
];
yield [
'<?php class Foo { function foo() {} }',
[
7 => \T_FUNCTION,
],
];
yield [
'<?php function & foo() {}',
[
1 => \T_FUNCTION,
],
];
yield [
'<?php use function Foo\bar;',
[
3 => CT::T_FUNCTION_IMPORT,
],
];
yield [
'<?php use Foo\ { function Bar };',
[
8 => CT::T_FUNCTION_IMPORT,
],
];
yield [
'<?php use Foo\ {
function F1,
const Constants\C1,
function Functions\F2,
const C2,
function F3,
const C3,
};',
[
8 => CT::T_FUNCTION_IMPORT,
13 => CT::T_CONST_IMPORT,
20 => CT::T_FUNCTION_IMPORT,
27 => CT::T_CONST_IMPORT,
32 => CT::T_FUNCTION_IMPORT,
37 => CT::T_CONST_IMPORT,
],
];
}
}
| 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/Tokenizer/Transformer/ReturnRefTransformerTest.php | tests/Tokenizer/Transformer/ReturnRefTransformerTest.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\Tokenizer\Transformer;
use PhpCsFixer\Tests\Test\AbstractTransformerTestCase;
use PhpCsFixer\Tokenizer\CT;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Transformer\ReturnRefTransformer
*
* @phpstan-import-type _TransformerTestExpectedKindsUnderIndex from AbstractTransformerTestCase
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ReturnRefTransformerTest extends AbstractTransformerTestCase
{
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
*
* @dataProvider provideProcessCases
*/
public function testProcess(string $source, array $expectedTokens = []): void
{
$this->doTest(
$source,
$expectedTokens,
[
CT::T_RETURN_REF,
],
);
}
/**
* @return iterable<int, array{0: string, 1?: _TransformerTestExpectedKindsUnderIndex}>
*/
public static function provideProcessCases(): iterable
{
yield [
'<?php function & foo(): array { return []; }',
[
3 => CT::T_RETURN_REF,
],
];
yield [
'<?php $a = 1 & 2;',
];
yield [
'<?php function fnc(array & $arr) {}',
];
yield [
'<?php fn &(): array => [];',
[
3 => CT::T_RETURN_REF,
],
];
yield [
'<?php fn (array & $arr) => 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/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformerTest.php | tests/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformerTest.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\Tokenizer\Transformer;
use PhpCsFixer\Tests\Test\AbstractTransformerTestCase;
use PhpCsFixer\Tokenizer\CT;
/**
* @covers \PhpCsFixer\Tokenizer\Transformer\DisjunctiveNormalFormTypeParenthesisTransformer
*
* @internal
*
* @phpstan-import-type _TransformerTestExpectedKindsUnderIndex from AbstractTransformerTestCase
*
* @requires PHP 8.2
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DisjunctiveNormalFormTypeParenthesisTransformerTest extends AbstractTransformerTestCase
{
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
*
* @dataProvider provideProcessCases
*/
public function testProcess(string $source, array $expectedTokens): void
{
$this->doTest($source, $expectedTokens, [CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]);
}
/**
* @return iterable<string, array{string, _TransformerTestExpectedKindsUnderIndex}>
*/
public static function provideProcessCases(): iterable
{
yield 'lambda with lots of arguments and some others' => [
'<?php
$a = function(
(X&Y)|C $a,
$b = array(1,2),
(\X&\Y)|C $c,
array $d = [1,2],
(\X&\Y)|C $e,
$x, $y, $z, P|(H&J) $uu,
) {};
function foo (array $a = array(66,88, $d = [99,44],array()), $e = [99,44],(C&V)|G|array $f = array()){};
return new static();
',
[
8 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // $a
12 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
31 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // $c
37 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
57 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // $e
63 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
81 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // $uu
85 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
140 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // $f
144 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'one line function signatures with comments' => [
'<?php function Foo1 ((A&B)|C $x1, \C|(A&B) $x2,/* No (X&Y) ! */(A&B)|I $xxx): void {}',
[
6 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // $x1
10 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
20 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // $x2
24 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
29 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // $xxx
33 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'multiple functions and arguments' => [
'<?php
function Foo1 ((A&B)|C $x1): void {}
function Foo2 (C|(A&B) $x2): void {}
function Foo3 (C|(A&B)|D $x3): void {}
function Foo4 ((A&B)|(\C&E\B\D) $x4): void {}
function Foo5 ($x5): void {}
',
[
6 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // Foo1
10 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
30 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // Foo2
34 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
52 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // Foo3
56 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
74 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // Foo4
78 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
80 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
89 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'multiple functions including methods' => [
'<?php
function Foo():M|(A&B)|J {}
$a = function(): X|(A&B) {};
interface Bar {
function G():(A&C)|(A&B);
}
class G {
public function X():K|(Z&Y)|P{}
}
',
[
9 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
13 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
31 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
35 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
53 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
57 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
59 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
63 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
84 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
88 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'multiple functions including methods 2' => [
'<?php
function Foo():(A&B)|M {}
$a = function(): (A&B)|N {};
interface Bar {
function G():(A&C)|I;
}
class G {
public function X():(Z&Y)|P{}
}
',
[
7 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
11 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
27 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
31 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
51 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
55 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
76 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
80 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'DNF property, A|(C&D)' => [
'<?php
class Dnf
{
public A|(C&D) $a;
}
const E = 1;
const F = 2;
(E&F);
',
[
11 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
15 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'DNF property, (A&B)|C' => [
'<?php
class Dnf
{
public (A&B)|C $a;
}',
[
9 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
13 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'DNF property, two groups with string and namespace separator' => [
'<?php
class Dnf
{
public (A\BH&Z\SAD\I)|(G\J&F\G\AK) $a;
}
',
[
9 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
19 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
21 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
31 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'bigger set of multiple DNF properties' => [
'<?php
class Dnf
{
public /* A|(C&D) */ A|(C&D) $a;
protected (C&D)|B $b;
private (C&D)|(E&F)|(G&H) $c;
static (C&D)|Z $d;
public /** (C&D)|X */ (C&D)|X $e;
public function foo($a, $b) {
return
$z|($A&$B)|(A::z&B\A::x)
|| A::b|($A&$B)
;
}
}
',
[
13 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
17 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
24 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
28 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
37 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
41 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
43 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
47 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
49 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
53 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
60 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
64 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
75 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
79 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'constructor property promotion' => [
'<?php
class Dnf
{
public function __construct(
public Y|(A&B) $x,
protected (A&B)|X $u,
private (\A\C&B\A)|(\D\C&\E\D) $i,
) {}
}
',
[
18 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
22 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
29 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
33 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
42 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
51 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
53 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
63 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'more properties' => [
'<?php
class Dnf
{
public A|B|C|(E&D) $a;
public E/**/ | X\C\B | /** */ \C|(E1&D1) $v;
public F | B | C | (D&Y) | E | (F&O) $a;
static G|B|C|(E77&D88) $XYZ;
static public (H&S)|B $f;
public static I|(P&S11) $f2;
}
static $a = 1;
return new static();
',
[
15 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // E&D
19 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
44 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // E1&D1
48 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
67 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // D&Y
71 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
79 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // F&O
83 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
96 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // E77&D88
100 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
109 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // P&S
113 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
126 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, // f2
130 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'arrow functions' => [
'<?php
$f1 = fn (): A|(B&C) => new Foo();
$f2 = fn ((A&B)|C $x, A|(B&C) $y): (A&B&C)|D|(E&F) => new Bar();
',
[
14 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
18 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
36 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
40 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
49 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
53 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
59 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
65 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
69 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
73 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
yield 'invokable class' => [
'<?php
class A
{
public function __invoke((Foo&Bar)|string $a): string
{
return "A";
}
}
return (new A())(new class implements Foo, Bar {});
',
[
14 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
18 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
}
/**
* @param _TransformerTestExpectedKindsUnderIndex $expectedTokens
*
* @dataProvider provideProcess83Cases
*
* @requires PHP 8.3
*/
public function testProcess83(string $source, array $expectedTokens): void
{
$this->doTest($source, $expectedTokens);
}
/**
* @return iterable<string, array{string, _TransformerTestExpectedKindsUnderIndex}>
*/
public static function provideProcess83Cases(): iterable
{
yield 'typed const' => [
'<?php
class Foo {
const A|(B&C) Bar = 1;
const (B&C)|A Bar = 2;
const D|(B&C)|A Bar = 3;
}',
[
12 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
16 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
27 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
31 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
46 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
50 => CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
],
];
}
}
| 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/Tokenizer/Transformer/WhitespacyCommentTransformerTest.php | tests/Tokenizer/Transformer/WhitespacyCommentTransformerTest.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\Tokenizer\Transformer;
use PhpCsFixer\Tests\Test\AbstractTransformerTestCase;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-import-type _PhpTokenArray from Token
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @covers \PhpCsFixer\Tokenizer\Transformer\WhitespacyCommentTransformer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class WhitespacyCommentTransformerTest extends AbstractTransformerTestCase
{
/**
* @param array<int, _PhpTokenArray> $expectedTokens
*
* @dataProvider provideProcessCases
*/
public function testProcess(string $source, array $expectedTokens): void
{
$tokens = Tokens::fromCode($source);
foreach ($expectedTokens as $index => $expectedToken) {
$token = $tokens[$index];
self::assertSame($expectedToken[1], $token->getContent());
self::assertSame($expectedToken[0], $token->getId());
}
}
/**
* @return iterable<int, array{string, array<int, _PhpTokenArray>}>
*/
public static function provideProcessCases(): iterable
{
yield [
"<?php // foo\n \$a = 1;",
[
1 => [\T_COMMENT, '// foo'],
2 => [\T_WHITESPACE, "\n "],
],
];
yield [
"<?php // foo\n\n ",
[
1 => [\T_COMMENT, '// foo'],
2 => [\T_WHITESPACE, "\n\n "],
],
];
yield [
"<?php // foo \r\n ",
[
1 => [\T_COMMENT, '// foo'],
2 => [\T_WHITESPACE, " \r\n "],
],
];
yield [
'<?php /* foo1 */// foo2 ',
[
1 => [\T_COMMENT, '/* foo1 */'],
2 => [\T_COMMENT, '// foo2'],
],
];
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.