Skip to content

Commit

Permalink
PsrAutoloadingFixer - do not remove directory structure from the Clas…
Browse files Browse the repository at this point in the history
…s name
  • Loading branch information
kubawerlos authored and keradus committed Dec 24, 2020
1 parent 490faa6 commit 5d1856f
Show file tree
Hide file tree
Showing 21 changed files with 425 additions and 79 deletions.
23 changes: 21 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ jobs:
PHP_CS_FIXER_TEST_USE_LEGACY_TOKENIZER: 1
SYMFONY_DEPRECATIONS_HELPER: 'disabled'

- operating-system: 'ubuntu-20.04'
php-version: '7.4'
job-description: 'with calculating code coverage'
calculate-code-coverage: 'yes'
phpunit-flags: '--testsuite coverage --exclude-group covers-nothing --coverage-clover build/logs/clover.xml'

- operating-system: 'ubuntu-20.04'
php-version: '7.4'
job-description: 'with migration rules'
Expand Down Expand Up @@ -61,11 +67,18 @@ jobs:
- name: Checkout code
uses: actions/checkout@v2

- name: Get code coverage driver
uses: actions/[email protected]
id: code-coverage-driver
with:
script: 'return "${{ matrix.calculate-code-coverage }}" == "yes" ? "pcov" : "none"'
result-encoding: string

- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
coverage: none
coverage: ${{ steps.code-coverage-driver.outputs.result }}
tools: flex
env:
fail-fast: false # disabled as old PHP version cannot run flex
Expand Down Expand Up @@ -110,7 +123,13 @@ jobs:
FAST_LINT_TEST_CASES: ${{ matrix.FAST_LINT_TEST_CASES }}
PHP_CS_FIXER_TEST_USE_LEGACY_TOKENIZER: ${{ matrix.PHP_CS_FIXER_TEST_USE_LEGACY_TOKENIZER }}
SYMFONY_DEPRECATIONS_HELPER: ${{ matrix.SYMFONY_DEPRECATIONS_HELPER }}
run: vendor/bin/phpunit
run: vendor/bin/phpunit ${{ matrix.phpunit-flags }}

- name: Upload coverage results to Coveralls
if: matrix.calculate-code-coverage == 'yes'
env:
COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: php vendor/bin/php-coveralls --verbose

- name: Run PHP CS Fixer
env:
Expand Down
27 changes: 0 additions & 27 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,33 +22,6 @@ before_install:

jobs:
include:
-
stage: Test
php: 7.4
name: 7.4 | Collect coverage
before_install:
# for building a tag release we don't need to collect code coverage
- if [ $TRAVIS_TAG ]; then travis_terminate 0; fi

## regular `before_install`
# turn off XDebug
- phpenv config-rm xdebug.ini || return 0

# Require PHPUnit 8
- composer require --dev --no-update phpunit/phpunit:^8

# Install PCOV
- pecl install pcov
install:
- travis_retry composer update $DEFAULT_COMPOSER_FLAGS $COMPOSER_FLAGS
- composer info -D | sort
before_script:
# Make code compatible with PHPUnit 8
- PHP_CS_FIXER_FUTURE_MODE=1 php php-cs-fixer fix --rules=void_return -q tests || return 0
script:
- vendor/bin/phpunit --testsuite coverage --exclude-group covers-nothing --coverage-clover build/logs/clover.xml || travis_terminate 1
- php vendor/bin/php-coveralls -v

-
stage: Deployment
php: 7.4
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"justinrainbow/json-schema": "^5.0",
"keradus/cli-executor": "^1.4",
"mikey179/vfsstream": "^1.6",
"php-coveralls/php-coveralls": "^2.4.1",
"php-coveralls/php-coveralls": "^2.4.2",
"php-cs-fixer/accessible-object": "^1.0",
"php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.2",
"php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.2.1",
Expand Down
2 changes: 1 addition & 1 deletion doc/rules/phpdoc/phpdoc_order_by_value.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Configuration

List of annotations to order, e.g. ``["covers"]``.

Allowed values: a subset of ``['author', 'covers', 'coversNothing', 'dataProvider', 'depends', 'group', 'internal', 'requires', 'uses']``
Allowed values: a subset of ``['author', 'covers', 'coversNothing', 'dataProvider', 'depends', 'group', 'internal', 'requires', 'throws', 'uses']``

Default value: ``['covers']``

Expand Down
1 change: 1 addition & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
enforceTimeLimit="true"
failOnWarning="true"
processIsolation="false"
stopOnFailure="false"
timeoutForSmallTests="2"
Expand Down
73 changes: 68 additions & 5 deletions src/Fixer/Basic/PsrAutoloadingFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,7 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens)
return;
}

if (null === $namespace && null !== $this->configuration['dir']) {
$expectedClassyName = substr(str_replace('/', '_', $file->getRealPath()), -\strlen($classyName) - 4, -4);
} else {
$expectedClassyName = $file->getBasename('.php');
}
$expectedClassyName = $this->calculateClassyName($file, $namespace, $classyName);

if ($classyName !== $expectedClassyName) {
$tokens[$classyIndex] = new Token([T_STRING, $expectedClassyName]);
Expand Down Expand Up @@ -210,4 +206,71 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens)
$tokens->insertAt($namespaceStartIndex, $newNamespace);
}
}

/**
* @param null|string $namespace
* @param string $currentName
*
* @return string
*/
private function calculateClassyName(\SplFileInfo $file, $namespace, $currentName)
{
$name = $file->getBasename('.php');

$maxNamespace = $this->calculateMaxNamespace($file, $namespace);

if (null !== $this->configuration['dir']) {
return ('' !== $maxNamespace ? (str_replace('\\', '_', $maxNamespace).'_') : '').$name;
}

$namespaceParts = array_reverse(explode('\\', $maxNamespace));

foreach ($namespaceParts as $namespacePart) {
$nameCandidate = sprintf('%s_%s', $namespacePart, $name);
if (strtolower($nameCandidate) !== strtolower(substr($currentName, -\strlen($nameCandidate)))) {
break;
}
$name = $nameCandidate;
}

return $name;
}

/**
* @param null|string $namespace
*
* @return string
*/
private function calculateMaxNamespace(\SplFileInfo $file, $namespace)
{
if (null === $this->configuration['dir']) {
$root = \dirname($file->getRealPath());
while ($root !== \dirname($root)) {
$root = \dirname($root);
}
} else {
$root = realpath($this->configuration['dir']);
}

$namespaceAccordingToFileLocation = trim(str_replace(\DIRECTORY_SEPARATOR, '\\', substr(\dirname($file->getRealPath()), \strlen($root))), '\\');

if (null === $namespace) {
return $namespaceAccordingToFileLocation;
}

$namespaceAccordingToFileLocationPartsReversed = array_reverse(explode('\\', $namespaceAccordingToFileLocation));
$namespacePartsReversed = array_reverse(explode('\\', $namespace));

foreach ($namespacePartsReversed as $key => $namespaceParte) {
if (!isset($namespaceAccordingToFileLocationPartsReversed[$key])) {
break;
}
if (strtolower($namespaceParte) !== strtolower($namespaceAccordingToFileLocationPartsReversed[$key])) {
break;
}
unset($namespaceAccordingToFileLocationPartsReversed[$key]);
}

return implode('\\', array_reverse($namespaceAccordingToFileLocationPartsReversed));
}
}
10 changes: 10 additions & 0 deletions src/Fixer/Comment/SingleLineCommentStyleFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,16 @@ public function getDefinition()
);
}

/**
* {@inheritdoc}
*
* Must run after NoUselessReturnFixer.
*/
public function getPriority()
{
return -19;
}

/**
* {@inheritdoc}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens)
continue;
}

if ($token->isGivenKind(T_EXTENDS) && $this->isMultilineExtendsWithMoreThanOneAncestor($tokens, $index)) {
if ($token->isGivenKind([T_EXTENDS, T_IMPLEMENTS]) && $this->isMultilineExtendsOrImplementsWithMoreThanOneAncestor($tokens, $index)) {
continue;
}

Expand Down Expand Up @@ -298,7 +298,7 @@ private function isMultiLineReturn(Tokens $tokens, $index)
*
* @return bool
*/
private function isMultilineExtendsWithMoreThanOneAncestor(Tokens $tokens, $index)
private function isMultilineExtendsOrImplementsWithMoreThanOneAncestor(Tokens $tokens, $index)
{
$hasMoreThanOneAncestor = false;

Expand Down
2 changes: 1 addition & 1 deletion src/Fixer/Phpdoc/PhpdocNoAccessFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class Foo
/**
* {@inheritdoc}
*
* Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocOrderFixer, PhpdocSeparationFixer, PhpdocTrimFixer.
* Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer.
* Must run after CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer.
*/
public function getPriority()
Expand Down
2 changes: 1 addition & 1 deletion src/Fixer/Phpdoc/PhpdocNoPackageFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class Baz
/**
* {@inheritdoc}
*
* Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocOrderFixer, PhpdocSeparationFixer, PhpdocTrimFixer.
* Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer.
* Must run after CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer.
*/
public function getPriority()
Expand Down
1 change: 1 addition & 0 deletions src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ protected function createConfigurationDefinition()
'group',
'internal',
'requires',
'throws',
'uses',
];

Expand Down
2 changes: 1 addition & 1 deletion src/Fixer/Phpdoc/PhpdocOrderFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function getDefinition()
* {@inheritdoc}
*
* Must run before PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer.
* Must run after CommentToPhpdocFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocNoAccessFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer.
* Must run after CommentToPhpdocFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocNoEmptyReturnFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer.
*/
public function getPriority()
{
Expand Down
2 changes: 1 addition & 1 deletion src/Fixer/ReturnNotation/NoUselessReturnFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function example($b) {
/**
* {@inheritdoc}
*
* Must run before BlankLineBeforeReturnFixer, BlankLineBeforeStatementFixer, NoExtraBlankLinesFixer, NoWhitespaceInBlankLineFixer.
* Must run before BlankLineBeforeReturnFixer, BlankLineBeforeStatementFixer, NoExtraBlankLinesFixer, NoWhitespaceInBlankLineFixer, SingleLineCommentStyleFixer.
* Must run after NoEmptyStatementFixer, NoUnneededCurlyBracesFixer, NoUselessElseFixer, SimplifiedNullReturnFixer.
*/
public function getPriority()
Expand Down
15 changes: 1 addition & 14 deletions tests/AutoReview/FixerFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ public function provideFixersPriorityCases()
[$fixers['no_useless_return'], $fixers['blank_line_before_statement']],
[$fixers['no_useless_return'], $fixers['no_extra_blank_lines']],
[$fixers['no_useless_return'], $fixers['no_whitespace_in_blank_line']],
[$fixers['no_useless_return'], $fixers['single_line_comment_style']],
[$fixers['no_useless_sprintf'], $fixers['method_argument_space']],
[$fixers['no_useless_sprintf'], $fixers['native_function_casing']],
[$fixers['no_useless_sprintf'], $fixers['no_empty_statement']],
Expand Down Expand Up @@ -221,7 +222,6 @@ public function provideFixersPriorityCases()
[$fixers['phpdoc_annotation_without_dot'], $fixers['phpdoc_types']],
[$fixers['phpdoc_annotation_without_dot'], $fixers['phpdoc_types_order']],
[$fixers['phpdoc_no_access'], $fixers['no_empty_phpdoc']],
[$fixers['phpdoc_no_access'], $fixers['phpdoc_order']],
[$fixers['phpdoc_no_access'], $fixers['phpdoc_separation']],
[$fixers['phpdoc_no_access'], $fixers['phpdoc_trim']],
[$fixers['phpdoc_no_alias_tag'], $fixers['phpdoc_add_missing_param_annotation']],
Expand All @@ -231,7 +231,6 @@ public function provideFixersPriorityCases()
[$fixers['phpdoc_no_empty_return'], $fixers['phpdoc_separation']],
[$fixers['phpdoc_no_empty_return'], $fixers['phpdoc_trim']],
[$fixers['phpdoc_no_package'], $fixers['no_empty_phpdoc']],
[$fixers['phpdoc_no_package'], $fixers['phpdoc_order']],
[$fixers['phpdoc_no_package'], $fixers['phpdoc_separation']],
[$fixers['phpdoc_no_package'], $fixers['phpdoc_trim']],
[$fixers['phpdoc_no_useless_inheritdoc'], $fixers['no_empty_phpdoc']],
Expand Down Expand Up @@ -338,13 +337,6 @@ static function ($name) {
*/
public function testFixersPriorityPairsHaveIntegrationTest(FixerInterface $first, FixerInterface $second)
{
// This structure contains older cases that are not yet covered by tests.
// It may only shrink, never add anything to it.
$casesWithoutTests = [
'phpdoc_no_access,phpdoc_order.test',
'phpdoc_no_package,phpdoc_order.test',
];

$integrationTestName = $this->generateIntegrationTestName($first, $second);
$file = $this->getIntegrationPriorityDirectory().$integrationTestName;

Expand All @@ -357,11 +349,6 @@ public function testFixersPriorityPairsHaveIntegrationTest(FixerInterface $first
$integrationTestExists = is_file($file);
}

if (\in_array($integrationTestName, $casesWithoutTests, true)) {
static::assertFalse($integrationTestExists, sprintf('Case "%s" already has an integration test, so it should be removed from "$casesWithoutTests".', $integrationTestName));
static::markTestIncomplete(sprintf('Case "%s" has no integration test yet, please help and add it.', $integrationTestName));
}

static::assertTrue($integrationTestExists, sprintf('There shall be an integration test "%s". How do you know that priority set up is good, if there is no integration test to check it?', $integrationTestName));

$file = realpath($file);
Expand Down
2 changes: 1 addition & 1 deletion tests/Fixer/Basic/Psr0FixerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function testFixCase()
$fileProphecy->willExtend(\SplFileInfo::class);
$fileProphecy->getBasename('.php')->willReturn('Bar');
$fileProphecy->getExtension()->willReturn('php');
$fileProphecy->getRealPath()->willReturn(__DIR__.'/Psr0/Foo/Bar.php');
$fileProphecy->getRealPath()->willReturn(__DIR__.\DIRECTORY_SEPARATOR.'Psr0'.\DIRECTORY_SEPARATOR.'Foo'.\DIRECTORY_SEPARATOR.'Bar.php');
$file = $fileProphecy->reveal();

$expected = <<<'EOF'
Expand Down
4 changes: 2 additions & 2 deletions tests/Fixer/Basic/Psr4FixerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function testFixCase()
$fileProphecy->willExtend(\SplFileInfo::class);
$fileProphecy->getBasename('.php')->willReturn('Bar');
$fileProphecy->getExtension()->willReturn('php');
$fileProphecy->getRealPath()->willReturn(__DIR__.'/Psr4/Foo/Bar.php');
$fileProphecy->getRealPath()->willReturn(__DIR__.\DIRECTORY_SEPARATOR.'Psr4'.\DIRECTORY_SEPARATOR.'Foo'.\DIRECTORY_SEPARATOR.'Bar.php');
$file = $fileProphecy->reveal();

$expected = <<<'EOF'
Expand All @@ -47,7 +47,7 @@ class bar {}

$expected = <<<'EOF'
<?php
class Bar {}
class Psr4_Foo_Bar {}
EOF;
$input = <<<'EOF'
<?php
Expand Down
Loading

0 comments on commit 5d1856f

Please sign in to comment.