diff --git a/.docker/php-blackfire/Dockerfile b/.docker/php-blackfire/Dockerfile new file mode 100644 index 00000000000..77ffe71bb55 --- /dev/null +++ b/.docker/php-blackfire/Dockerfile @@ -0,0 +1,27 @@ +################################################ +## Docker image used for profiling Rector ## +################################################ + +ARG PHP_VERSION=8.0 + +FROM rector/rector:php${PHP_VERSION} + +# Install php extensions +RUN apt-get update && apt-get install -y \ + wget \ + gnupg2 + +# Setup blackfire repo +RUN wget -q -O - https://packages.blackfire.io/gpg.key | apt-key add - +RUN echo "deb http://packages.blackfire.io/debian any main" | tee /etc/apt/sources.list.d/blackfire.list + +# Install blackfire php extensions +RUN apt-get update && apt-get install -y \ + blackfire-php + +# Install blackfire cli tool +RUN mkdir -p /tmp/blackfire \ + && architecture=$(case $(uname -m) in i386 | i686 | x86) echo "i386" ;; x86_64 | amd64) echo "amd64" ;; aarch64 | arm64 | armv8) echo "arm64" ;; *) echo "amd64" ;; esac) \ + && curl -A "Docker" -L https://blackfire.io/api/v1/releases/client/linux/$architecture | tar zxp -C /tmp/blackfire \ + && mv /tmp/blackfire/blackfire /usr/bin/blackfire \ + && rm -Rf /tmp/blackfire diff --git a/.docker/php-blackfire/readme.md b/.docker/php-blackfire/readme.md new file mode 100644 index 00000000000..bdbb91fa1b0 --- /dev/null +++ b/.docker/php-blackfire/readme.md @@ -0,0 +1,34 @@ +## Docker image for Blackfire profiling + +### Build + +Builds image with `rector-blackfire` tag. + +``` +docker build . --tag rector-blackfire --file .docker/php-blackfire/Dockerfile +``` + +You can use `--build-arg PHP_VERSION=7.4` to build with specific PHP version. Supported versions are: 7.3, 7.4, 8.0 + + +### Prepare + +These variables must be set on host to pass them into container (obtain values at [blackfire.io](https://blackfire.io)): +``` +export BLACKFIRE_CLIENT_ID="" +export BLACKFIRE_CLIENT_TOKEN="" +``` + + +### Usage + +Get into container: + +``` +docker run --entrypoint="" -it --rm -e BLACKFIRE_CLIENT_ID -e BLACKFIRE_CLIENT_TOKEN -v $(pwd):/rector rector-blackfire bash +``` + +Once in container, you can start profiling: +``` +blackfire run php bin/rector +``` diff --git a/.docker/php-xdebug/Dockerfile b/.docker/php-xdebug/Dockerfile new file mode 100644 index 00000000000..0743f67154a --- /dev/null +++ b/.docker/php-xdebug/Dockerfile @@ -0,0 +1,11 @@ +################################################ +## Docker image used for debugging Rector ## +################################################ + +ARG PHP_VERSION=8.0 + +FROM rector/rector:php${PHP_VERSION} + +RUN pecl install xdebug + +COPY .docker/php-xdebug/xdebug.ini /usr/local/etc/php/conf.d/xdebug.ini diff --git a/.docker/php-xdebug/readme.md b/.docker/php-xdebug/readme.md new file mode 100644 index 00000000000..c1f4e9a5663 --- /dev/null +++ b/.docker/php-xdebug/readme.md @@ -0,0 +1,26 @@ +## Docker image for Xdebug debugging + +### Build + +Builds image with `rector-xdebug` tag. + +```shell +docker build . --tag rector-xdebug --file .docker/php-xdebug/Dockerfile +``` + +You can use `--build-arg PHP_VERSION=7.4` to build with specific PHP version. Supported versions are: 7.3, 7.4, 8.0 + +### Usage + +Get into container (change ip address): + +```shell +docker run -it --rm \ + --entrypoint="" \ + --volume $(pwd):/rector \ + --env XDEBUG_CONFIG="client_host=172.16.165.1" \ + --env PHP_IDE_CONFIG="serverName=rector" \ + rector-xdebug bash +``` + +**Do not forget to run rector binary with `--xdebug` option.** diff --git a/.docker/php-xdebug/xdebug.ini b/.docker/php-xdebug/xdebug.ini new file mode 100644 index 00000000000..058a8eab61e --- /dev/null +++ b/.docker/php-xdebug/xdebug.ini @@ -0,0 +1,5 @@ +[xdebug] +zend_extension = "/usr/local/lib/php/extensions/no-debug-non-zts-20200930/xdebug.so" +xdebug.mode = debug +xdebug.client_port = 9003 +xdebug.start_with_request = yes diff --git a/.docker/php/opcache.ini b/.docker/php/opcache.ini new file mode 100644 index 00000000000..52787e7bbf7 --- /dev/null +++ b/.docker/php/opcache.ini @@ -0,0 +1,10 @@ +[opcache] +opcache.memory_consumption=128 +opcache.interned_strings_buffer=8 +opcache.max_accelerated_files=4000 +opcache.revalidate_freq=60 +opcache.fast_shutdown=1 +opcache.enable_cli=1 +opcache.enable=1 +opcache.file_cache='/tmp/opcache' +opcache.file_update_protection=0 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000000..69ced33d8d7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,28 @@ +*~  +.DS_Store +.idea/ + +.env +.editorconfig +.phpstorm.meta.php + +phpstan.neon +rector.php +phpunit.xml +ecs.php + +LICENSE + +.gitattributes +.gitignore + +*.md + +.dockerignore +Dockerfile +docker-compose.yml +docker-compose.dist.yml + +/docs + +*.phar diff --git a/.github/ISSUE_TEMPLATE/1_Bug_report.md b/.github/ISSUE_TEMPLATE/1_Bug_report.md deleted file mode 100644 index 9713f45da7a..00000000000 --- a/.github/ISSUE_TEMPLATE/1_Bug_report.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -name: Bug Report -labels: bug -about: Report errors and problems ---- - -# Bug Report - - - -| Subject | Details | -| :------------- | :---------------------------------------------------------------| -| Rector version | e.g. v0.9.5 (invoke `vendor/bin/rector --version`) | -| Installed as | composer dependency / prefixed Rector | - - - -## Minimal PHP Code Causing Issue - - - -## Expected Behaviour - - diff --git a/.github/ISSUE_TEMPLATE/2_Feature_request.md b/.github/ISSUE_TEMPLATE/2_Feature_request.md deleted file mode 100644 index 9f5b7fb41da..00000000000 --- a/.github/ISSUE_TEMPLATE/2_Feature_request.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -name: Feature Request -labels: feature -about: RFC and ideas for new features and improvements ---- - -# Feature Request - - - -## Diff - - - -```diff --$value = $value + 5; -+$value += 5; -``` diff --git a/.github/ISSUE_TEMPLATE/3_Support_question.md b/.github/ISSUE_TEMPLATE/3_Support_question.md deleted file mode 100644 index 63db7c2d50f..00000000000 --- a/.github/ISSUE_TEMPLATE/3_Support_question.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -name: Support Question -labels: support -about: Questions about using this library ---- - -# Question diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml deleted file mode 100644 index 1078a37963f..00000000000 --- a/.github/dependabot.yaml +++ /dev/null @@ -1,16 +0,0 @@ -version: 2 - -updates: - - - package-ecosystem: composer - directory: "/" - open-pull-requests-limit: 5 - schedule: - interval: weekly - - - - package-ecosystem: github-actions - directory: "/" - open-pull-requests-limit: 5 - schedule: - interval: monthly diff --git a/.github/workflows/bare_run.yaml b/.github/workflows/bare_run.yaml new file mode 100644 index 00000000000..013e982c267 --- /dev/null +++ b/.github/workflows/bare_run.yaml @@ -0,0 +1,29 @@ +name: Bare Run + +on: + pull_request: null + push: + branches: + - main + +jobs: + bare_run: + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + php_version: ['7.1', '7.2', '7.3', '7.4', '8.0'] + + steps: + - uses: actions/checkout@v2 + + - + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php_version }} + coverage: none + + - run: php bin/rector --version --ansi + + - run: php bin/rector list --ansi diff --git a/.github/workflows/build_scoped_rector.yaml b/.github/workflows/build_scoped_rector.yaml deleted file mode 100644 index 08fbeea3ca8..00000000000 --- a/.github/workflows/build_scoped_rector.yaml +++ /dev/null @@ -1,108 +0,0 @@ -# builds the content of https://github.com/rectorphp/rector-prefixed -# inspiration from https://github.com/phpstan/phpstan-src/blob/master/.github/workflows/phar.yml -name: Build Scoped Rector - -on: - push: - branches: - - main - tags: - - '*' - -env: - # see https://github.com/composer/composer/issues/9368#issuecomment-718112361 - COMPOSER_ROOT_VERSION: "dev-main" - -jobs: - build_scoped_rector: - runs-on: ubuntu-latest - steps: - - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - - - uses: shivammathur/setup-php@v2 - with: - php-version: 8.0 - coverage: none - - # fixes https://github.com/rectorphp/rector/pull/4559/checks?check_run_id=1359814403, see https://github.com/shivammathur/setup-php#composer-github-oauth - env: - COMPOSER_TOKEN: ${{ secrets.ACCESS_TOKEN }} - - # install only prod dependencies - do not use ramsey, it uses cache including "dev", we want to avoid it here - - run: composer install --no-dev --ansi - - # 1. copy files to $NESTED_DIRECTORY directory Exclude the scoped/nested directories to prevent rsync from copying in a loop - - run: rsync --exclude rector-build -av * rector-build --quiet - - run: rm -rf rector-build/packages-tests rector-build/rules-tests rector-build/tests - - # 2. downgrade rector - - run: sh build/downgrade-rector.sh rector-build - - # 3. prefix classes - - run: sh build/build-rector-scoped.sh rector-build rector-prefixed-downgraded - - # 4. lint the code for PHP 7.1 - this must happen here, as setup-php allows only one PHP version switch: https://github.com/shivammathur/setup-php/issues/434 - - - uses: shivammathur/setup-php@v2 - with: - php-version: 7.1 - coverage: none - - run: composer create-project php-parallel-lint/php-parallel-lint php-parallel-lint --ansi - - run: php-parallel-lint/parallel-lint rector-prefixed-downgraded --exclude rector-prefixed-downgraded/stubs --exclude rector-prefixed-downgraded/vendor/symfony/error-handler/Resources --exclude rector-prefixed-downgraded/vendor/symfony/http-kernel/Resources --exclude rector-prefixed-downgraded/vendor/rector/rector-nette/tests --exclude rector-prefixed-downgraded/vendor/symfony/polyfill-mbstring/bootstrap80.php --exclude rector-prefixed-downgraded/vendor/tracy/tracy/examples - - # 5. copy repository meta files - - run: | - cp -R build/target-repository/. rector-prefixed-downgraded - cp -R templates rector-prefixed-downgraded/ - - # 6. clone remote repository, so we can push it - - - uses: "actions/checkout@v2" - with: - repository: rectorphp/rector-prefixed - path: remote-repository - token: ${{ secrets.ACCESS_TOKEN }} - - # remove remote files, to avoid piling up dead code in remote repository - - run: rm -rf remote-repository/.github remote-repository/config remote-repository/src remote-repository/rules remote-repository/packages remote-repository/upgrade remote-repository/vendor - - - run: cp -a rector-prefixed-downgraded/. remote-repository - - # 7. setup git - - - working-directory: remote-repository - run: | - git config user.email "tomas.vot@gmail.com" - git config user.name "Tomas Votruba" - - # commit metadata - - - name: "Get Git log" - id: git-log - run: echo ::set-output name=log::$(git log ${{ github.event.before }}..${{ github.event.after }} --reverse --pretty='%H %s' | sed -e 's/^/https:\/\/github.com\/rectorphp\/rector\/commit\//') - - # 8.A publish it to remote repository without tag - - - name: "Commit Prefixed - main" - working-directory: remote-repository - if: "!startsWith(github.ref, 'refs/tags/')" - run: | - git add --all - git commit -m "Updated Rector to commit ${{ github.event.after }}" -m "${{ steps.git-log.outputs.log }}" - git push --quiet origin main - - # 8.B publish it to remote repository with tag - - - name: "Commit Prefixed - tag" - working-directory: remote-repository - if: "startsWith(github.ref, 'refs/tags/')" - run: | - git add --all - git commit -m "Rector ${GITHUB_REF#refs/tags/}" -m "${{ steps.git-log.outputs.log }}" - git push --quiet origin main - git tag ${GITHUB_REF#refs/tags/} -m "${GITHUB_REF#refs/tags/}" - git push --quiet origin ${GITHUB_REF#refs/tags/} diff --git a/.github/workflows/build_scoped_rector_php70.yaml b/.github/workflows/build_scoped_rector_php70.yaml deleted file mode 100644 index dd078f27dbc..00000000000 --- a/.github/workflows/build_scoped_rector_php70.yaml +++ /dev/null @@ -1,130 +0,0 @@ -# builds the content of https://github.com/rectorphp/rector-prefixed-php70 -# inspiration from https://github.com/phpstan/phpstan-src/blob/master/.github/workflows/phar.yml -name: Build Scoped Rector PHP 7.0 - -on: - push: - branches: - - main - tags: - - '*' - -env: - # see https://github.com/composer/composer/issues/9368#issuecomment-718112361 - COMPOSER_ROOT_VERSION: "dev-main" - -jobs: - build_scoped_rector_php70: - runs-on: ubuntu-latest - steps: - - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - - - uses: shivammathur/setup-php@v2 - with: - php-version: 7.4 - coverage: none - - # fixes https://github.com/rectorphp/rector/pull/4559/checks?check_run_id=1359814403, see https://github.com/shivammathur/setup-php#composer-github-oauth - env: - COMPOSER_TOKEN: ${{ secrets.ACCESS_TOKEN }} - - # install only prod dependencies - do not use ramsey, it uses cache including "dev", we want to avoid it here - - run: composer install --no-dev --ansi - - - run: wget https://github.com/box-project/box/releases/download/3.12.2/box.phar -N --no-verbose - - # extra content of phpstan.phar to vendor/phpstan/phpstan-extracted - - run: php box.phar extract vendor/phpstan/phpstan/phpstan.phar vendor/phpstan/phpstan-extracted - - # "composer remove phpstan/phpstan" original phpstan/phpstan is now duplicated, we don't need it now -required by phpstan extensions, cannot be removed like this - - # to avoid double packing the same code - - run: rm -rf vendor/bin/phpstan vendor/phpstan/phpstan/bootstrap.php - # the vendor/phpstan/phpstan/bootstrap.php is statically included by composer, so better add empty file - - run: echo " vendor/phpstan/phpstan/bootstrap.php - - run: rm -rf vendor/phpstan/phpstan/phpstan.phar - - run: rm -rf phpstan-for-rector.neon - - # 1. copy files to $NESTED_DIRECTORY directory Exclude the scoped/nested directories to prevent rsync from copying in a loop - - run: rsync --exclude rector-build-php70 -av * rector-build-php70 --quiet - - run: rm -rf rector-build-php70/packages-tests rector-build-php70/rules-tests rector-build-php70/tests - - # this must run - - run: bin/rector list --debug - - # 2. downgrade rector - - run: sh build/downgrade-rector-php70.sh rector-build-php70 - - # 3. prefix classes - - run: sh build/build-rector-scoped-php70.sh rector-build-php70 rector-prefixed-downgraded-php70 - - # 4. lint the code for PHP 7.0 - this must happen here, as setup-php allows only one PHP version switch: https://github.com/shivammathur/setup-php/issues/434 - - - uses: shivammathur/setup-php@v2 - with: - php-version: 7.0 - coverage: none - - run: | - rm -rf vendor && mkdir -p vendor - cp -R rector-prefixed-downgraded-php70/vendor/* vendor/ - rm -rf php-parallel-lint - composer create-project php-parallel-lint/php-parallel-lint php-parallel-lint --ansi - - - run: php-parallel-lint/parallel-lint rector-prefixed-downgraded-php70 --exclude rector-prefixed-downgraded-php70/stubs --exclude rector-prefixed-downgraded-php70/vendor/symfony/error-handler/Resources --exclude rector-prefixed-downgraded-php70/vendor/symfony/http-kernel/Resources --exclude rector-prefixed-downgraded-php70/vendor/rector/rector-nette/tests --exclude rector-prefixed-downgraded-php70/vendor/symfony/polyfill-mbstring/bootstrap80.php --exclude rector-prefixed-downgraded-php70/vendor/tracy/tracy/examples --exclude rector-prefixed-downgraded-php70/vendor/rector/rector-installer/tests --exclude rector-prefixed-downgraded-php70/vendor/symplify/smart-file-system/tests --exclude rector-prefixed-downgraded-php70/vendor/symfony/http-foundation/Session --exclude rector-prefixed-downgraded-php70/vendor/symfony/var-dumper --exclude rector-prefixed-downgraded-php70/vendor/nette/caching --exclude rector-prefixed-downgraded-php70/vendor/rector/rector-nette/src/Rector/LNumber --exclude rector-prefixed-downgraded-php70/vendor/symfony/http-foundation/Test --exclude rector-prefixed-downgraded-php70/vendor/symplify/simple-php-doc-parser/tests --exclude rector-prefixed-downgraded-php70/vendor/tracy/tracy/src/Tracy/Bar/panels/info.panel.phtml --exclude rector-prefixed-downgraded-php70/vendor/symfony/string/Slugger/AsciiSlugger.php - - # 5. copy repository meta files - - run: | - cp -R build/target-repository-php70/. rector-prefixed-downgraded-php70 - cp -R templates rector-prefixed-downgraded-php70/ - - # 6. clone remote repository, so we can push it - - - uses: "actions/checkout@v2" - with: - repository: rectorphp/rector-prefixed-php70 - path: remote-repository-php70 - token: ${{ secrets.ACCESS_TOKEN }} - - # remove remote files, to avoid piling up dead code in remote repository - - run: rm -rf remote-repository-php70/config remote-repository-php70/src remote-repository-php70/rules remote-repository-php70/packages remote-repository-php70/upgrade remote-repository-php70/vendor - - - run: cp -a rector-prefixed-downgraded-php70/. remote-repository-php70 - - # 7. setup git - - - working-directory: remote-repository-php70 - run: | - git config user.email "tomas.vot@gmail.com" - git config user.name "Tomas Votruba" - - # commit metadata - - - name: "Get Git log" - id: git-log - run: echo ::set-output name=log::$(git log ${{ github.event.before }}..${{ github.event.after }} --reverse --pretty='%H %s' | sed -e 's/^/https:\/\/github.com\/rectorphp\/rector\/commit\//') - - # 8.A publish it to remote repository without tag - - - name: "Commit Prefixed - main" - working-directory: remote-repository-php70 - if: "!startsWith(github.ref, 'refs/tags/')" - run: | - git add --all - git commit -m "Updated Rector to commit ${{ github.event.after }}" -m "${{ steps.git-log.outputs.log }}" - git push --quiet origin main - - # 8.B publish it to remote repository with tag - - - name: "Commit Prefixed - tag" - working-directory: remote-repository-php70 - if: "startsWith(github.ref, 'refs/tags/')" - run: | - git add --all - git commit -m "Rector ${GITHUB_REF#refs/tags/}" -m "${{ steps.git-log.outputs.log }}" - git push --quiet origin main - git tag ${GITHUB_REF#refs/tags/} -m "${GITHUB_REF#refs/tags/}" - git push --quiet origin ${GITHUB_REF#refs/tags/} diff --git a/.github/workflows/code_analysis.yaml b/.github/workflows/code_analysis.yaml deleted file mode 100644 index 501f725c9a3..00000000000 --- a/.github/workflows/code_analysis.yaml +++ /dev/null @@ -1,54 +0,0 @@ -name: Code Analysis - -on: - pull_request: null - -env: - # see https://github.com/composer/composer/issues/9368#issuecomment-718112361 - COMPOSER_ROOT_VERSION: "dev-main" - -jobs: - code_analysis: - strategy: - fail-fast: false - matrix: - actions: - - - name: 'Composer Validate' - run: composer validate --ansi - - - - name: 'Validate Max File Length' - run: vendor/bin/easy-ci validate-file-length packages rules src tests - - - - name: 'PHPStan' - run: vendor/bin/phpstan analyse --ansi --error-format symplify - - - - name: 'PHPStan for config' - run: composer phpstan-config - - # see https://github.com/rectorphp/rector-generator - - - name: 'Rector Generate From Recipe' - run: | - bin/rector init-recipe --ansi - bin/rector generate --ansi - - name: ${{ matrix.actions.name }} - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - # see https://github.com/shivammathur/setup-php - - - uses: shivammathur/setup-php@v2 - with: - php-version: 8.0 - coverage: none - - - uses: "ramsey/composer-install@v1" - - - run: ${{ matrix.actions.run }} diff --git a/.github/workflows/code_analysis_no_dev.yaml b/.github/workflows/code_analysis_no_dev.yaml deleted file mode 100644 index c8cdfb59a58..00000000000 --- a/.github/workflows/code_analysis_no_dev.yaml +++ /dev/null @@ -1,40 +0,0 @@ -name: Code Analysis [no dev] - -on: - pull_request: null - -env: - # see https://github.com/composer/composer/issues/9368#issuecomment-718112361 - COMPOSER_ROOT_VERSION: "dev-main" - -jobs: - matrix: - strategy: - fail-fast: false - matrix: - actions: - - - name: 'Rector List' - run: bin/rector list - - - - name: 'Show command' - run: bin/rector show --ansi - - name: ${{ matrix.actions.name }} - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - # see https://github.com/shivammathur/setup-php - - uses: shivammathur/setup-php@v2 - with: - php-version: 7.4 - coverage: none - - # must be removed, as local config is missing dev dependencies - - run: rm phpstan-for-rector.neon - - - run: composer install --no-progress --ansi --no-dev - - - run: ${{ matrix.actions.run }} diff --git a/.github/workflows/packages_tests.yaml b/.github/workflows/packages_tests.yaml deleted file mode 100644 index 3ba08e6aaa4..00000000000 --- a/.github/workflows/packages_tests.yaml +++ /dev/null @@ -1,46 +0,0 @@ -# builds the content of https://github.com/rectorphp/rector-prefixed -# inspiration from https://github.com/phpstan/phpstan-src/blob/master/.github/workflows/phar.yml -name: Packages Tests - -on: - pull_request: null - push: - branches: - - main - -env: - # see https://github.com/composer/composer/issues/9368#issuecomment-718112361 - COMPOSER_ROOT_VERSION: "dev-main" - -jobs: - packages_tests: - runs-on: ubuntu-latest - - strategy: - fail-fast: false - matrix: - package_name: - - rector-nette - - rector-symfony - - rector-laravel - - rector-phpunit - - rector-cakephp - - rector-doctrine - - steps: - - - uses: "actions/checkout@v2" - with: - repository: rectorphp/${{ matrix.package_name }} - - - - uses: shivammathur/setup-php@v2 - with: - php-version: 8.0 - coverage: none - - - - run: composer install --ansi - - - - run: vendor/bin/phpunit diff --git a/.github/workflows/php8_attributes.yaml b/.github/workflows/php8_attributes.yaml new file mode 100644 index 00000000000..4132adfa0f0 --- /dev/null +++ b/.github/workflows/php8_attributes.yaml @@ -0,0 +1,21 @@ +name: PHP 8 Attributes + +on: + pull_request: null + push: + branches: + - main + +jobs: + php8_attributes: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.0' + coverage: none + + - run: bin/rector process tests/fixture-php8-attributes --config ci/rector-attributes.php --ansi diff --git a/.github/workflows/php_linter.yaml b/.github/workflows/php_linter.yaml deleted file mode 100644 index fec64d91122..00000000000 --- a/.github/workflows/php_linter.yaml +++ /dev/null @@ -1,25 +0,0 @@ -name: PHP Linter - -on: - pull_request: null - -env: - # see https://github.com/composer/composer/issues/9368#issuecomment-718112361 - COMPOSER_ROOT_VERSION: "dev-main" - -jobs: - php_linter: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - - - uses: shivammathur/setup-php@v2 - with: - php-version: 8.0 - coverage: none - - - run: composer create-project php-parallel-lint/php-parallel-lint php-parallel-lint - - - run: php-parallel-lint/parallel-lint src bin/rector config tests packages rules --colors --exclude rules/psr4/tests/Rector/Namespace_/MultipleClassFileToPsr4ClassesRector/Source --exclude rules/autodiscovery/tests/Rector/FileNode/MoveInterfacesToContractNamespaceDirectoryRector/Expected --exclude packages/node-type-resolver/tests/PerNodeTypeResolver/PropertyFetchTypeResolver/Source --exclude rules/nette-kdyby/tests/Rector/MethodCall/ReplaceEventManagerWithEventSubscriberRector/Source/ExpectedSomeClassCopyEvent.php --exclude rules/nette-kdyby/tests/Rector/MethodCall/ReplaceMagicPropertyEventWithEventClassRector/Source --exclude rules/type-declaration/tests/Rector/ClassMethod/ParamTypeFromStrictTypedPropertyRector/Source diff --git a/.github/workflows/php_parser_3.yaml b/.github/workflows/php_parser_3.yaml new file mode 100644 index 00000000000..58c20db43e1 --- /dev/null +++ b/.github/workflows/php_parser_3.yaml @@ -0,0 +1,25 @@ +name: PHP Parser 3 + +on: + pull_request: null + push: + branches: + - main + +jobs: + php_parser_3: + runs-on: ubuntu-latest + + steps: + - + uses: shivammathur/setup-php@v2 + with: + php-version: 7.1 + coverage: none + + # wait for deploy to packagist + - run: sleep 70 + + - run: composer require nikic/php-parser:^3.1 --ansi + - run: composer require rector/rector:dev-main --dev --ansi + - run: vendor/bin/rector list --ansi diff --git a/.github/workflows/publish_docker_images.yaml b/.github/workflows/publish_docker_images.yaml new file mode 100644 index 00000000000..d40be47eb91 --- /dev/null +++ b/.github/workflows/publish_docker_images.yaml @@ -0,0 +1,64 @@ +name: Build docker images +on: + push: + # Publish `main` as Docker `latest` image. + branches: + - main + + # Publish `v1.2.3` tags as releases. + tags: + - '*' + +env: + # see https://github.com/composer/composer/issues/9368#issuecomment-718112361 + COMPOSER_ROOT_VERSION: "dev-main" + +jobs: + publish_images: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v1 + + - name: Login to DockerHub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + - name: Build images + run: | + DOCKER_TAGS="" + + # Pull tag and branch from github.ref, which is either refs/heads/... or refs/tags/... + TAG=$(echo "${{ github.ref }}" | sed -e '/refs\/tags\//!d; s,refs/.*/v\?\(.*\),\1,') + BRANCH=$(echo "${{ github.ref }}" | sed -e '/refs\/heads\//!d; s,refs/.*/\(.*\),\1,') + + if [ "main" == "$BRANCH" ]; then + DOCKER_TAGS="$DOCKER_TAGS latest" + fi + + if [ ! -z "$TAG" ]; then + DOCKER_TAGS="$DOCKER_TAGS $TAG" + fi + + echo "Image will be tagged with: $DOCKER_TAGS" + + DOCKER_TAG_ARG="" + for ARG in $DOCKER_TAGS; do + DOCKER_TAG_ARG="$DOCKER_TAG_ARG --tag rector/rector:$ARG" + done + + docker buildx create --name builder-php8 --use + docker buildx build \ + --progress plain \ + --cache-from=rector/rector:build-cache-php8 \ + --cache-to=type=registry,ref=rector/rector:build-cache-php8,mode=max,push=true \ + --target rector \ + --push \ + $DOCKER_TAG_ARG \ + --platform linux/amd64,linux/arm64 \ + --build-arg PHP_VERSION=8 . diff --git a/.github/workflows/rector.yaml b/.github/workflows/rector.yaml deleted file mode 100644 index 971ce2a1cdf..00000000000 --- a/.github/workflows/rector.yaml +++ /dev/null @@ -1,74 +0,0 @@ -#### -# Due to some Github Actions limitations, we are running realtime fixes (commits) only for self-owned-pr -# -# Current limitations: -# - Secrets (ACCESS_TOKEN) are not available in PRs from forks -# - Github Token has Read-only access (can not commit), Personal Access Token must be used instead -# - Github Token does not trigger workflows after push -# -# So we basically have chicken-egg problem here -# -# https://help.github.com/en/actions/configuring-and-managing-workflows/authenticating-with-the-github_token#permissions-for-the-github_token -#### -name: Rector - -on: - pull_request: null - -env: - # see https://github.com/composer/composer/issues/9368#issuecomment-718112361 - COMPOSER_ROOT_VERSION: "dev-main" - -jobs: - rector: - strategy: - fail-fast: false - matrix: - directories: - - src tests rules-tests packages packages-tests - - rules - - runs-on: ubuntu-latest - steps: - # workaround for missing secret in fork PRs - see https://github.com/actions/checkout/issues/298 - # see https://github.com/rectorphp/rector/commit/d395e1c28b8e6a56711dcc2e10490a82965850e4 - - - if: github.event.pull_request.head.repo.full_name == github.repository - uses: actions/checkout@v2 - with: - # Must be used to trigger workflow after push - token: ${{ secrets.ACCESS_TOKEN }} - - # in forks, the token is not available - so we cannot us eit - - - if: github.event.pull_request.head.repo.full_name != github.repository - uses: actions/checkout@v2 - - - - uses: shivammathur/setup-php@v2 - with: - # PHP 7.3 is required, so Rector's code is PHP 7.3 compatible even after refactoring - php-version: 8.0 - coverage: none - - - run: composer install --no-progress --ansi - - ## First run Rector - here can't be --dry-run !!! it would stop the job with it and not commit anything in the future - - run: bin/rector process ${{ matrix.directories }} --ansi --no-progress-bar - - - run: vendor/bin/ecs check --match-git-diff --fix --ansi - - # see https://github.com/EndBug/add-and-commit - - - # commit only to core contributors who have repository access - if: github.event.pull_request.head.repo.full_name == github.repository - uses: EndBug/add-and-commit@v7.2.0 - with: - # The arguments for the `git add` command (see the paragraph below for more info) - add: . - message: "[ci-review] Rector Rectify" - author_name: "kaizen-ci" - author_email: "info@kaizen-ci.org" - env: - # to get push access - GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }} diff --git a/.github/workflows/rector_run.yaml b/.github/workflows/rector_run.yaml new file mode 100644 index 00000000000..e51c14183a2 --- /dev/null +++ b/.github/workflows/rector_run.yaml @@ -0,0 +1,60 @@ +name: Rector Run + +on: + pull_request: null + push: + branches: + - main + +jobs: + rector_run: + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + php_version: ['7.1', '7.2', '7.3', '7.4', '8.0'] + commands: + - + name: 'Finalize Entity' + install: composer require doctrine/orm + run: vendor/bin/rector process ../tests/fixture-finalize --config ../ci/rector-finalize.php --ansi + + - + name: 'Composer Dependency' + install: composer require symfony/console 2.8 + run: vendor/bin/rector list --debug --ansi + + - + name: 'Along PHPStan' + install: composer require phpstan/phpstan:0.12.85 --dev --ansi + run: | + vendor/bin/rector list --ansi + vendor/bin/phpstan -h --ansi + + name: "PHP ${{ matrix.php_version }}" + + steps: + - uses: actions/checkout@v2 + + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php_version }} + coverage: none + + - run: | + mkdir standalone + cd standalone + # wait for deploy to packagist + sleep 70 + + - run: | + cd standalone + # run + composer require rector/rector:dev-main --dev --ansi + ${{ matrix.commands.install }} + + - + run: | + cd standalone + ${{ matrix.commands.run }} diff --git a/.github/workflows/standalone_rule_test.yaml b/.github/workflows/standalone_rule_test.yaml new file mode 100644 index 00000000000..39107a91887 --- /dev/null +++ b/.github/workflows/standalone_rule_test.yaml @@ -0,0 +1,37 @@ +name: Standalone Rule Test + +on: + pull_request: null + push: + branches: + - main + +jobs: + standalone_rule_test: + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + actions: + - + name: 'Rector Prefixed' + run: composer require rector/rector:dev-main --dev + + steps: + # see https://github.com/rectorphp/rector-prefixed-rule-test + - + uses: actions/checkout@v2 + with: + repository: rectorphp/rector-prefixed-rule-test + + - uses: shivammathur/setup-php@v2 + with: + php-version: '7.3' + coverage: none + + - uses: "ramsey/composer-install@v1" + + - run: ${{ matrix.actions.run }} + + - run: vendor/bin/phpunit diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml deleted file mode 100644 index f501ea82b61..00000000000 --- a/.github/workflows/tests.yaml +++ /dev/null @@ -1,34 +0,0 @@ -name: Tests - -on: - pull_request: null - -env: - # see https://github.com/composer/composer/issues/9368#issuecomment-718112361 - COMPOSER_ROOT_VERSION: "dev-main" - -jobs: - tests: - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - php: ['7.3', '7.4', '8.0'] - path: - - tests - - rules-tests - - packages-tests - - name: PHP ${{ matrix.php }} tests for ${{ matrix.path }} - steps: - - uses: actions/checkout@v2 - - - - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ matrix.php }} - coverage: none - - - uses: "ramsey/composer-install@v1" - - - run: vendor/bin/phpunit ${{ matrix.path }} diff --git a/.github/workflows/weekly_pull_requests.yaml b/.github/workflows/weekly_pull_requests.yaml deleted file mode 100644 index cfb5f0df17d..00000000000 --- a/.github/workflows/weekly_pull_requests.yaml +++ /dev/null @@ -1,58 +0,0 @@ -name: Weekly Pull Requests - -on: - schedule: - # https://crontab.guru/once-a-week - - cron: "0 0 * * 0" - -env: - # see https://github.com/composer/composer/issues/9368#issuecomment-718112361 - COMPOSER_ROOT_VERSION: "dev-main" - -jobs: - weekly_pull_requests: - strategy: - fail-fast: false - matrix: - actions: - - - name: "Re-Generate Nodes/Rectors Documentation" - run: "composer docs" - branch: 'automated-regenerated-nodes-rectors-documentation' - - - - name: 'Apply Coding Standard' - run: "composer fix-cs" - branch: 'automated-apply-coding-standards' - - name: ${{ matrix.actions.name }} - runs-on: ubuntu-latest - - steps: - - - uses: actions/checkout@v2 - with: - token: ${{ secrets.ACCESS_TOKEN }} - - # see https://github.com/shivammathur/setup-php - - - uses: shivammathur/setup-php@v2 - with: - php-version: 7.4 - coverage: none - - - uses: "ramsey/composer-install@v1" - - - run: ${{ matrix.actions.run }} - - # see https://github.com/peter-evans/create-pull-request - - - name: Create pull-request - uses: peter-evans/create-pull-request@v3 - with: - token: ${{ secrets.GITHUB_TOKEN }} - commit-message: "[automated] ${{ matrix.actions.name }}" - base: 'main' - branch: ${{ matrix.actions.branch }} - title: '[automated] ${{ matrix.actions.name }}' - delete-branch: true diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000000..bea124eb186 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,58 @@ +ARG PHP_VERSION=8.0 +FROM php:${PHP_VERSION}-cli as base + +RUN apt-get update && apt-get install -y \ + libzip4 \ + libicu63 \ + && rm -rf /var/lib/apt/lists/* + +FROM base as build + +WORKDIR /rector + +# Install php extensions +RUN apt-get update && apt-get install -y \ + g++ \ + git \ + libicu-dev \ + libzip-dev \ + unzip \ + wget \ + zip \ + && pecl -q install \ + zip \ + && docker-php-ext-configure intl \ + && docker-php-ext-configure opcache --enable-opcache \ + && docker-php-ext-install \ + intl \ + opcache \ + zip + +# Add source +COPY . . + +# Build runtime image +FROM base as rector + +COPY --from=build /usr/local/lib/php /usr/local/lib/php +COPY --from=build /usr/local/etc/php /usr/local/etc/php +COPY .docker/php/opcache.ini /usr/local/etc/php/conf.d/opcache.ini + +ENV PATH /rector/bin:$PATH + +# Add source +COPY . /rector + +ENTRYPOINT [ "rector" ] + +VOLUME ["/project"] +WORKDIR "/project" + +RUN mkdir -p /tmp/opcache + +RUN chmod +x /rector/bin/rector +RUN /rector/bin/rector list + +RUN mkdir -p /tmp/opcache \ + && /rector/bin/rector list \ + && chmod 777 -R /tmp diff --git a/README.md b/README.md index c0294b2c3f2..aac868a0e44 100644 --- a/README.md +++ b/README.md @@ -1,88 +1,11 @@ -# Rector - Speedup Your PHP Development +# Prefixed Rector -[![Downloads](https://img.shields.io/packagist/dt/rector/rector.svg?style=flat-square)](https://packagist.org/packages/rector/rector) +[![Build Status Github Actions](https://img.shields.io/github/workflow/status/rectorphp/rector-prefixed/Code_Checks?style=flat-square)](https://github.com/rectorphp/rector-prefixed/actions) +[![Downloads](https://img.shields.io/packagist/dt/rector/rector.svg?style=flat-square)](https://packagist.org/packages/rector/rector-prefixed) -
+Do you have conflicts on Rector install? You're in the right place. Prefixed Rector can [be installed even on very old Symfony](https://getrector.org/blog/2020/01/20/how-to-install-rector-despite-composer-conflicts). -Rector helps you with 2 areas - major code changes and in daily work. - -- Do you have a legacy code base? Do you want to have that latest version of PHP or your favorite framework? - → **Rector gets you there with instant upgrade**. - -
- -- Do you have code quality you need, but struggle to keep it with new developers in your team? Do you wish to have code-reviews for each member of your team, but don't have time for it? -→ **Add Rector to you CI and let it fix your code for you. Get [instant feedback](https://tomasvotruba.com/blog/2020/01/13/why-is-first-instant-feedback-crucial-to-developers/) after each commit.** - -
- -It's a tool that [we develop](https://getrector.org/) and share for free, so anyone can automate their refactoring. - -[Hire us](https://getrector.org/contact) to speed up learning Rector, AST and nodes, to educate your team about Rectors benefits and to setup Rector in your project, so that you can enjoy the 300 % development speed :+1: - -
- -## Open-Source First - -Rector **instantly upgrades and refactors the PHP code of your application**. -It supports all versions of PHP from 5.3 and major open-source projects: - -
- -

- - - - - - - - Drupal Rector rules - -
- -
- - - - - -
- -

- -### What Can Rector Do for You? - -- [Complete 2800 `@var` types in 2 minutes](https://tomasvotruba.com/blog/2019/07/29/how-we-completed-thousands-of-missing-var-annotations-in-a-day/) -- [Upgrade 30 000 unit tests from PHPUnit 6 to 9](https://twitter.com/LBajsarowicz/status/1272947900016967683) -- [Complete PHP 7.4 Property Types](https://tomasvotruba.com/blog/2018/11/15/how-to-get-php-74-typed-properties-to-your-code-in-few-seconds/) -- [Migrate from Nette to Symfony](https://tomasvotruba.com/blog/2019/02/21/how-we-migrated-from-nette-to-symfony-in-3-weeks-part-1/) -- [Refactor Laravel Facades to Dependency Injection](https://tomasvotruba.com/blog/2019/03/04/how-to-turn-laravel-from-static-to-dependency-injection-in-one-day/) -- And much more... - -
- -## Documentation - -- [Explore 450+ Rector Rules](/docs/rector_rules_overview.md) -- [How Does Rector Work?](/docs/how_it_works.md) -- [PHP Parser Nodes](https://github.com/rectorphp/php-parser-nodes-docs/) - -### Advanced - -- [Auto Import Names](/docs/auto_import_names.md) -- [How to Ignore Rule or Paths](/docs/how_to_ignore_rule_or_paths.md) -- [Static Reflection and Autoload](/docs/static_reflection_and_autoload.md) -- [How to Configure Rule](/docs/how_to_configure_rules.md) -- [How to Generate Configuration file](/docs/init_command.md) - -### Contributing - -- [How to add Test for Rector Rule](/docs/how_to_add_test_for_rector_rule.md) -- [How to work with Doc Block and Comments](/docs/how_to_work_with_doc_block_and_comments.md) -- [How to Create New Rector Rule](/docs/create_own_rule.md) - -
+Do you have older PHP? Rector prefixed goes down to PHP 7.1, so you can install it even on older projects. ## Install @@ -90,131 +13,13 @@ It supports all versions of PHP from 5.3 and major open-source projects: composer require rector/rector --dev ``` -- Having conflicts during `composer require`? → Use the [Rector Prefixed](https://github.com/rectorphp/rector-prefixed) with PHP 7.1+ version -- Using a different PHP version than Rector supports? → Use the [Docker image](/docs/how_to_run_rector_in_docker.md) - -
- -## Running Rector - -There a 2 main ways to use Rector: - -- a *single rule*, to have the change under control -- or group of rules called *sets* - -To use them, create a `rector.php` in your root directory: - ```bash +# generate "rector.php" config vendor/bin/rector init -``` -And modify it: - -```php -// rector.php -use Rector\Php74\Rector\Property\TypedPropertyRector; -use Rector\Set\ValueObject\SetList; -use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; - -return static function (ContainerConfigurator $containerConfigurator): void { - // here we can define, what sets of rules will be applied - // tip: use "SetList" class to autocomplete sets - $containerConfigurator->import(SetList::CODE_QUALITY); - - // register single rule - $services = $containerConfigurator->services(); - $services->set(TypedPropertyRector::class); -}; -``` - -Then dry run Rector: - -```bash +# dry run vendor/bin/rector process src --dry-run -``` -Rector will show you diff of files that it *would* change. To *make* the changes, drop `--dry-run`: - -```bash +# changing run vendor/bin/rector process src ``` - -*Note: `rector.php` is loaded by default. For different location, use `--config` option.* - -
- -## Configuration - -```php -// rector.php -use Rector\Core\Configuration\Option; -use Rector\Core\ValueObject\PhpVersion; -use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; - -return static function (ContainerConfigurator $containerConfigurator): void { - $parameters = $containerConfigurator->parameters(); - - // paths to refactor; solid alternative to CLI arguments - $parameters->set(Option::PATHS, [__DIR__ . '/src', __DIR__ . '/tests']); - - // is your PHP version different from the one your refactor to? [default: your PHP version], uses PHP_VERSION_ID format - $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_72); - - // Run Rector only on changed files - $parameters->set(Option::ENABLE_CACHE, true); - - // Path to phpstan with extensions, that PHPSTan in Rector uses to determine types - $parameters->set(Option::PHPSTAN_FOR_RECTOR_PATH, getcwd() . '/phpstan-for-config.neon'); -}; -``` - -
- -## How to Contribute - -See [the contribution guide](/CONTRIBUTING.md). - -
- -### Debugging - -You can use `--debug` option, that will print nested exceptions output: - -```bash -vendor/bin/rector process src/Controller --dry-run --debug -``` - -Or with Xdebug: - -1. Make sure [Xdebug](https://xdebug.org/) is installed and configured -2. Add `--xdebug` option when running Rector - -```bash -vendor/bin/rector process src/Controller --dry-run --xdebug -``` - -To assist with simple debugging Rector provides a 2 helpers to pretty-print AST-nodes: - -```php -use PhpParser\Node\Scalar\String_; - -$node = new String_('hello world!'); - -// prints node to string, as PHP code displays it -print_node($node); - -// dump nested node object with nested properties -dump_node($node); -// 2nd argument is how deep the nesting is - this makes sure the dump is short and useful -dump_node($node, 1); -``` - -
- -## Known Drawbacks - -### How to Apply Coding Standards? - -Rector uses [nikic/php-parser](https://github.com/nikic/PHP-Parser/), built on technology called an *abstract syntax tree* (AST). An AST doesn't know about spaces and when written to a file it produces poorly formatted code in both PHP and docblock annotations. **That's why your project needs to have a coding standard tool** and a set of formatting rules, so it can make Rector's output code nice and shiny again. - -We're using [ECS](https://github.com/symplify/easy-coding-standard) with [this setup](ecs.php). diff --git a/bin/rector b/bin/rector index 5643eeebb3c..5274bbad961 100755 --- a/bin/rector +++ b/bin/rector @@ -1,4 +1,5 @@ #!/usr/bin/env php -includeDependencyOrRepositoryVendorAutoloadIfExists(); - - // load extracted PHPStan with its own preload.php $extractedPhpstanAutoload = __DIR__ . '/../vendor/phpstan/phpstan-extracted/vendor/autoload.php'; -if (file_exists($extractedPhpstanAutoload)) { +if (\file_exists($extractedPhpstanAutoload)) { require_once $extractedPhpstanAutoload; -} elseif (should_include_preload()) { +} elseif (\RectorPrefix20210509\should_include_preload()) { require_once __DIR__ . '/../preload.php'; } - require_once __DIR__ . '/../src/constants.php'; - $autoloadIncluder->loadIfExistsAndNotLoadedYet(__DIR__ . '/../vendor/scoper-autoload.php'); - $autoloadIncluder->autoloadProjectAutoloaderFile(); $autoloadIncluder->autoloadFromCommandLine(); - -$symfonyStyleFactory = new SymfonyStyleFactory(new PrivatesCaller()); +$symfonyStyleFactory = new \Rector\Core\Console\Style\SymfonyStyleFactory(new \RectorPrefix20210509\Symplify\PackageBuilder\Reflection\PrivatesCaller()); $symfonyStyle = $symfonyStyleFactory->create(); - -$rectorConfigsResolver = new RectorConfigsResolver(); - +$rectorConfigsResolver = new \Rector\Core\Bootstrap\RectorConfigsResolver(); try { $bootstrapConfigs = $rectorConfigsResolver->provide(); - $rectorContainerFactory = new RectorContainerFactory(); + $rectorContainerFactory = new \Rector\Core\DependencyInjection\RectorContainerFactory(); $container = $rectorContainerFactory->createFromBootstrapConfigs($bootstrapConfigs); -} catch (Throwable $throwable) { +} catch (\Throwable $throwable) { $symfonyStyle->error($throwable->getMessage()); - exit(ShellCode::ERROR); + exit(\RectorPrefix20210509\Symplify\PackageBuilder\Console\ShellCode::ERROR); } - - // preload local InstalledVersions.php - to fix incorrect version by same-named class in phpstan $currentlyInstalledVersions = __DIR__ . '/../../../../vendor/composer/InstalledVersions.php'; -if (file_exists($currentlyInstalledVersions)) { +if (\file_exists($currentlyInstalledVersions)) { require_once $currentlyInstalledVersions; } - - /** @var ConsoleApplication $application */ -$application = $container->get(ConsoleApplication::class); +$application = $container->get(\Rector\Core\Console\ConsoleApplication::class); exit($application->run()); - final class AutoloadIncluder { /** * @var string[] */ private $alreadyLoadedAutoloadFiles = []; - - public function includeDependencyOrRepositoryVendorAutoloadIfExists(): void + public function includeDependencyOrRepositoryVendorAutoloadIfExists() : void { // Rector's vendor is already loaded - if (class_exists(RectorKernel::class)) { + if (\class_exists(\Rector\Core\HttpKernel\RectorKernel::class)) { return; } - // in Rector develop repository $this->loadIfExistsAndNotLoadedYet(__DIR__ . '/../vendor/autoload.php'); } - /** * In case Rector is installed as vendor dependency, * this autoloads the project vendor/autoload.php, including Rector */ - public function autoloadProjectAutoloaderFile(): void + public function autoloadProjectAutoloaderFile() : void { $this->loadIfExistsAndNotLoadedYet(__DIR__ . '/../../../autoload.php'); } - - public function autoloadFromCommandLine(): void + public function autoloadFromCommandLine() : void { $cliArgs = $_SERVER['argv']; - - $autoloadOptionPosition = array_search('-a', $cliArgs, true) ?: array_search('--autoload-file', $cliArgs, true); - if (! $autoloadOptionPosition) { + $autoloadOptionPosition = \array_search('-a', $cliArgs, \true) ?: \array_search('--autoload-file', $cliArgs, \true); + if (!$autoloadOptionPosition) { return; } - $autoloadFileValuePosition = $autoloadOptionPosition + 1; $fileToAutoload = $cliArgs[$autoloadFileValuePosition] ?? null; if ($fileToAutoload === null) { return; } - $this->loadIfExistsAndNotLoadedYet($fileToAutoload); } - - public function loadIfExistsAndNotLoadedYet(string $filePath): void + public function loadIfExistsAndNotLoadedYet(string $filePath) : void { - if (! file_exists($filePath)) { + if (!\file_exists($filePath)) { return; } - - if (in_array($filePath, $this->alreadyLoadedAutoloadFiles, true)) { + if (\in_array($filePath, $this->alreadyLoadedAutoloadFiles, \true)) { return; } - - $this->alreadyLoadedAutoloadFiles[] = realpath($filePath); - + $this->alreadyLoadedAutoloadFiles[] = \realpath($filePath); require_once $filePath; } } - - +\class_alias('RectorPrefix20210509\\AutoloadIncluder', 'AutoloadIncluder', \false); // load local php-parser only in prefixed version or development repository -function should_include_preload(): bool +function should_include_preload() : bool { - if (file_exists(__DIR__ . '/../vendor/scoper-autoload.php')) { - return true; + if (\file_exists(__DIR__ . '/../vendor/scoper-autoload.php')) { + return \true; } - - if (! file_exists(getcwd() . '/composer.json')) { - return false; + if (!\file_exists(\getcwd() . '/composer.json')) { + return \false; } - - $composerJsonFileContent = file_get_contents(getcwd() . '/composer.json'); - return strpos($composerJsonFileContent, '"name": "rector/rector"') !== false; + $composerJsonFileContent = \file_get_contents(\getcwd() . '/composer.json'); + return \strpos($composerJsonFileContent, '"name": "rector/rector"') !== \false; } diff --git a/bootstrap.php b/bootstrap.php new file mode 100644 index 00000000000..daf0ed94c96 --- /dev/null +++ b/bootstrap.php @@ -0,0 +1,31 @@ +loadClass($class); + } + + // aliased by php-scoper, that's why its missing + if ($class === 'Symplify\SmartFileSystem\SmartFileInfo') { + $filePath = __DIR__ . '/vendor/symplify/smart-file-system/src/SmartFileInfo.php'; + if (file_exists($filePath)) { + require $filePath; + } + } +}); diff --git a/ci/rector-attributes.php b/ci/rector-attributes.php new file mode 100644 index 00000000000..908c41af6b5 --- /dev/null +++ b/ci/rector-attributes.php @@ -0,0 +1,18 @@ +import(SymfonySetList::SYMFONY_52); + + $parameters = $containerConfigurator->parameters(); + $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_80); +}; diff --git a/ci/rector-finalize.php b/ci/rector-finalize.php new file mode 100644 index 00000000000..a61198407c6 --- /dev/null +++ b/ci/rector-finalize.php @@ -0,0 +1,12 @@ +services(); + $services->set(FinalizeClassesWithoutChildrenRector::class); +}; diff --git a/composer.json b/composer.json index a316f78842e..8565f482c27 100644 --- a/composer.json +++ b/composer.json @@ -1,138 +1,26 @@ { "name": "rector/rector", - "description": "Instant upgrade and refactoring of your PHP code", + "description": "Prefixed and PHP 7.1 downgraded version of rector/rector", + "license": "MIT", "bin": [ "bin/rector" ], - "license": "MIT", - "homepage": "https://getrector.org", "require": { - "php": "^7.3|^8.0", - "ext-dom": "*", - "ext-json": "*", - "composer/semver": "^3.2", - "composer/xdebug-handler": "^1.3|^2.0", - "danielstjules/stringy": "^3.1", - "doctrine/inflector": "^2.0", - "ergebnis/json-printer": "^3.1", - "idiosyncratic/editorconfig": "^0.1.0", - "jean85/pretty-package-versions": "^1.6", - "nette/caching": "^3.1", - "nette/utils": "^3.2", - "nikic/php-parser": "4.10.4", - "phpstan/phpdoc-parser": "^0.5.4", - "phpstan/phpstan": "0.12.85", - "phpstan/phpstan-phpunit": "^0.12.18", - "rector/rector-cakephp": "^0.10.4", - "rector/rector-doctrine": "^0.10.6", - "rector/extension-installer": "^0.10.2", - "rector/rector-laravel": "^0.10.2", - "rector/rector-nette": "^0.10.9", - "rector/rector-nette-to-symfony": "^0.10.0", - "rector/rector-phpunit": "^0.10.8", - "rector/rector-symfony": "^0.10.5", - "sebastian/diff": "^4.0.4", - "shanethehat/pretty-xml": "^1.0", - "symfony/console": "^4.4.8|^5.1", - "symfony/dependency-injection": "^5.1", - "symfony/finder": "^4.4.8|^5.1", - "symfony/http-kernel": "^4.4.8|^5.1", - "symplify/astral": "^9.3", - "symplify/autowire-array-parameter": "^9.3", - "symplify/console-color-diff": "^9.3", - "symplify/package-builder": "^9.3", - "symplify/rule-doc-generator-contracts": "^9.3", - "symplify/set-config-resolver": "^9.3", - "symplify/simple-php-doc-parser": "^9.3", - "symplify/skipper": "^9.3", - "symplify/smart-file-system": "^9.3", - "symplify/symfony-php-config": "^9.3", - "tracy/tracy": "^2.8", - "webmozart/assert": "^1.10" - }, - "require-dev": { - "phpstan/extension-installer": "^1.1", - "phpstan/phpstan-nette": "^0.12.16", - "phpunit/phpunit": "^9.5", - "rector/rector-generator": "^0.1.7", - "rector/rector-phpstan-rules": "^0.1", - "symplify/coding-standard": "^9.3", - "symplify/easy-ci": "^9.3", - "symplify/easy-coding-standard": "^9.3", - "symplify/easy-testing": "^9.3", - "symplify/phpstan-extensions": "^9.3", - "symplify/phpstan-rules": "^9.3", - "symplify/rule-doc-generator": "^9.3" - }, - "replace": { - "rector/rector-prefixed": "self.version" + "php": "^7.1|^8.0", + "phpstan/phpstan": "0.12.85" }, "autoload": { - "psr-4": { - "Rector\\": ["packages", "rules"], - "Rector\\Core\\": "src", - "Rector\\Compiler\\": "utils/compiler/src" - }, "files": [ - "src/functions/node_helper.php", - "src/constants.php" + "bootstrap.php" ] }, - "autoload-dev": { - "psr-4": { - "Rector\\Tests\\": ["packages-tests", "rules-tests"], - "Rector\\Core\\Tests\\": "tests", - "Rector\\RuleDocGenerator\\": "utils/rule-doc-generator/src" - }, - "classmap": [ - "stubs/Annotations", - "stubs/Nette", - "rules-tests/Autodiscovery/Rector/Class_/MoveServicesBySuffixToDirectoryRector/Expected", - "rules-tests/Autodiscovery/Rector/Interface_/MoveInterfacesToContractNamespaceDirectoryRector/Expected", - "rules-tests/CodingStyle/Rector/Namespace_/ImportFullyQualifiedNamesRector/Source", - "rules-tests/Renaming/Rector/Name/RenameClassRector/Source", - "rules-tests/Renaming/Rector/FileWithoutNamespace/PseudoNamespaceToNamespaceRector/Source", - "rules-tests/CodingStyle/Rector/Namespace_/ImportFullyQualifiedNamesRector/Source", - "rules-tests/Renaming/Rector/Name/RenameClassRector/Source" - ], - "files": [ - "stubs/Doctrine/Persistence/ObjectManager.php", - "stubs/Doctrine/Common/Persistence/ObjectManager.php", - "rules-tests/Transform/Rector/FuncCall/FuncCallToMethodCallRector/Source/some_view_function.php", - "rules-tests/TypeDeclaration/Rector/FunctionLike/ReturnTypeDeclarationRector/Source/MyBar.php", - "rules-tests/TypeDeclaration/Rector/Property/CompleteVarDocTypePropertyRector/Source/EventDispatcher.php" - ] - }, - "scripts": { - "complete-check": [ - "@check-cs", - "@phpstan", - "@docs", - "phpunit" - ], - "check-cs": [ - "vendor/bin/ecs check --ansi", - "vendor/bin/ecs check-markdown README.md --ansi" - ], - "fix-cs": [ - "vendor/bin/ecs check --fix --ansi", - "vendor/bin/ecs check-markdown README.md --fix --ansi" - ], - "phpstan": "vendor/bin/phpstan analyse --ansi --error-format symplify", - "phpstan-config": "vendor/bin/phpstan analyse config --ansi --error-format symplify", - "docs": [ - "vendor/bin/rule-doc-generator generate packages rules --output-file docs/rector_rules_overview.md --ansi --categorize", - "vendor/bin/ecs check-markdown docs/rector_rules_overview.md --ansi --fix" - ], - "rector": "bin/rector process --ansi" - }, "extra": { "branch-alias": { "dev-main": "0.10-dev" } }, - "config": { - "sort-packages": true, - "platform-check": false + "conflict": { + "phpstan/phpdoc-parser": "<=0.5.3", + "phpstan/phpstan": "<=0.12.82" } } diff --git a/config/config.php b/config/config.php index e60c55f3578..268f778caa9 100644 --- a/config/config.php +++ b/config/config.php @@ -1,27 +1,24 @@ import(__DIR__ . '/services.php'); $containerConfigurator->import(__DIR__ . '/services-rules.php'); $containerConfigurator->import(__DIR__ . '/services-packages.php'); $containerConfigurator->import(__DIR__ . '/parameters.php'); - - $extensionConfigResolver = new ExtensionConfigResolver(); + $extensionConfigResolver = new \Rector\Core\Bootstrap\ExtensionConfigResolver(); $extensionConfigFiles = $extensionConfigResolver->provide(); foreach ($extensionConfigFiles as $extensionConfigFile) { $containerConfigurator->import($extensionConfigFile->getRealPath()); } - // require only in dev $containerConfigurator->import(__DIR__ . '/../utils/compiler/config/config.php', null, 'not_found'); - // to override extension-loaded config $parameters = $containerConfigurator->parameters(); - $parameters->set(Option::PHPSTAN_FOR_RECTOR_PATH, getcwd() . '/phpstan-for-rector.neon'); + $parameters->set(\Rector\Core\Configuration\Option::PHPSTAN_FOR_RECTOR_PATH, \getcwd() . '/phpstan-for-rector.neon'); }; diff --git a/config/parameters.php b/config/parameters.php index 7c3fdc75163..f241670ac69 100644 --- a/config/parameters.php +++ b/config/parameters.php @@ -1,33 +1,28 @@ parameters(); - // paths and extensions - $parameters->set(Option::PATHS, []); - $parameters->set(Option::FILE_EXTENSIONS, ['php']); - $parameters->set(Option::AUTOLOAD_PATHS, []); - + $parameters->set(\Rector\Core\Configuration\Option::PATHS, []); + $parameters->set(\Rector\Core\Configuration\Option::FILE_EXTENSIONS, ['php']); + $parameters->set(\Rector\Core\Configuration\Option::AUTOLOAD_PATHS, []); // these files will be executed, useful e.g. for constant definitions - $parameters->set(Option::BOOTSTRAP_FILES, []); - + $parameters->set(\Rector\Core\Configuration\Option::BOOTSTRAP_FILES, []); // FQN class importing - $parameters->set(Option::AUTO_IMPORT_NAMES, false); - $parameters->set(Option::IMPORT_SHORT_CLASSES, true); - $parameters->set(Option::IMPORT_DOC_BLOCKS, true); - - $parameters->set(Option::PHP_VERSION_FEATURES, null); - $parameters->set(Option::PROJECT_TYPE, ProjectType::PROPRIETARY); - $parameters->set(Option::NESTED_CHAIN_METHOD_CALL_LIMIT, 30); - $parameters->set(Option::SKIP, []); - + $parameters->set(\Rector\Core\Configuration\Option::AUTO_IMPORT_NAMES, \false); + $parameters->set(\Rector\Core\Configuration\Option::IMPORT_SHORT_CLASSES, \true); + $parameters->set(\Rector\Core\Configuration\Option::IMPORT_DOC_BLOCKS, \true); + $parameters->set(\Rector\Core\Configuration\Option::PHP_VERSION_FEATURES, null); + $parameters->set(\Rector\Core\Configuration\Option::PROJECT_TYPE, \Rector\Core\ValueObject\ProjectType::PROPRIETARY); + $parameters->set(\Rector\Core\Configuration\Option::NESTED_CHAIN_METHOD_CALL_LIMIT, 30); + $parameters->set(\Rector\Core\Configuration\Option::SKIP, []); // cache - $parameters->set(Option::ENABLE_CACHE, false); - $parameters->set(Option::CACHE_DIR, sys_get_temp_dir() . '/rector_cached_files'); + $parameters->set(\Rector\Core\Configuration\Option::ENABLE_CACHE, \false); + $parameters->set(\Rector\Core\Configuration\Option::CACHE_DIR, \sys_get_temp_dir() . '/rector_cached_files'); }; diff --git a/config/services-packages.php b/config/services-packages.php index 6e20301b6b3..58e10b01e4d 100644 --- a/config/services-packages.php +++ b/config/services-packages.php @@ -1,27 +1,20 @@ services(); - - $services->defaults() - ->public() - ->autowire() - ->autoconfigure(); - - $services->load('Rector\\', __DIR__ . '/../packages') - ->exclude([ - __DIR__ . '/../packages/*/{ValueObject,Contract,Exception}', - __DIR__ . '/../packages/BetterPhpDocParser/PhpDocInfo/PhpDocInfo.php', - __DIR__ . '/../packages/Testing/PHPUnit', - __DIR__ . '/../packages/BetterPhpDocParser/PhpDoc', - __DIR__ . '/../packages/NodeTypeResolver/NodeVisitor/FileNodeVisitor.php', - - // used in PHPStan - __DIR__ . '/../packages/NodeTypeResolver/Reflection/BetterReflection/RectorBetterReflectionSourceLocatorFactory.php', - __DIR__ . '/../packages/NodeTypeResolver/Reflection/BetterReflection/SourceLocatorProvider/DynamicSourceLocatorProvider.php', - ]); + $services->defaults()->public()->autowire()->autoconfigure(); + $services->load('Rector\\', __DIR__ . '/../packages')->exclude([ + __DIR__ . '/../packages/*/{ValueObject,Contract,Exception}', + __DIR__ . '/../packages/BetterPhpDocParser/PhpDocInfo/PhpDocInfo.php', + __DIR__ . '/../packages/Testing/PHPUnit', + __DIR__ . '/../packages/BetterPhpDocParser/PhpDoc', + __DIR__ . '/../packages/NodeTypeResolver/NodeVisitor/FileNodeVisitor.php', + // used in PHPStan + __DIR__ . '/../packages/NodeTypeResolver/Reflection/BetterReflection/RectorBetterReflectionSourceLocatorFactory.php', + __DIR__ . '/../packages/NodeTypeResolver/Reflection/BetterReflection/SourceLocatorProvider/DynamicSourceLocatorProvider.php', + ]); }; diff --git a/config/services-rules.php b/config/services-rules.php index 380df98add7..3a7c40cebbc 100644 --- a/config/services-rules.php +++ b/config/services-rules.php @@ -1,26 +1,18 @@ parameters(); - $parameters->set(Option::TYPES_TO_REMOVE_STATIC_FROM, []); - + $parameters->set(\Rector\Core\Configuration\Option::TYPES_TO_REMOVE_STATIC_FROM, []); $services = $containerConfigurator->services(); - - $services->defaults() - ->public() - ->autowire() - ->autoconfigure(); - + $services->defaults()->public()->autowire()->autoconfigure(); // psr-4 - $services->alias(PSR4AutoloadNamespaceMatcherInterface::class, PSR4NamespaceMatcher::class); - - $services->load('Rector\\', __DIR__ . '/../rules') - ->exclude([__DIR__ . '/../rules/*/{ValueObject,Rector,Contract,Exception}']); + $services->alias(\Rector\PSR4\Contract\PSR4AutoloadNamespaceMatcherInterface::class, \Rector\PSR4\Composer\PSR4NamespaceMatcher::class); + $services->load('Rector\\', __DIR__ . '/../rules')->exclude([__DIR__ . '/../rules/*/{ValueObject,Rector,Contract,Exception}']); }; diff --git a/config/services.php b/config/services.php index cdff9644df1..4ed8af9af27 100644 --- a/config/services.php +++ b/config/services.php @@ -1,14 +1,15 @@ services(); - - $services->defaults() - ->public() - ->autowire() - ->autoconfigure(); - - $services->load('Rector\Core\\', __DIR__ . '/../src') - ->exclude([ - __DIR__ . '/../src/Rector', - __DIR__ . '/../src/Exception', - __DIR__ . '/../src/DependencyInjection/CompilerPass', - __DIR__ . '/../src/DependencyInjection/Loader', - __DIR__ . '/../src/HttpKernel', - __DIR__ . '/../src/ValueObject', - __DIR__ . '/../src/Bootstrap', - __DIR__ . '/../src/PhpParser/Node/CustomNode', - __DIR__ . '/../src/functions', - __DIR__ . '/../src/constants.php', - ]); - - $services->alias(SymfonyApplication::class, ConsoleApplication::class); - - $services->set(FileSystemGuard::class); - - $services->set(SimpleCallableNodeTraverser::class); - - $services->set(ParserFactory::class); - $services->set(BuilderFactory::class); - $services->set(CloningVisitor::class); - $services->set(NodeFinder::class); - - $services->set(Parser::class) - ->factory([service(NikicPhpParserFactory::class), 'create']); - $services->set(Lexer::class) - ->factory([service(PhpParserLexerFactory::class), 'create']); - + $services->defaults()->public()->autowire()->autoconfigure(); + $services->load('Rector\\Core\\', __DIR__ . '/../src')->exclude([__DIR__ . '/../src/Rector', __DIR__ . '/../src/Exception', __DIR__ . '/../src/DependencyInjection/CompilerPass', __DIR__ . '/../src/DependencyInjection/Loader', __DIR__ . '/../src/HttpKernel', __DIR__ . '/../src/ValueObject', __DIR__ . '/../src/Bootstrap', __DIR__ . '/../src/PhpParser/Node/CustomNode', __DIR__ . '/../src/functions', __DIR__ . '/../src/constants.php']); + $services->alias(\RectorPrefix20210509\Symfony\Component\Console\Application::class, \Rector\Core\Console\ConsoleApplication::class); + $services->set(\RectorPrefix20210509\Symplify\SmartFileSystem\FileSystemGuard::class); + $services->set(\RectorPrefix20210509\Symplify\Astral\NodeTraverser\SimpleCallableNodeTraverser::class); + $services->set(\PhpParser\ParserFactory::class); + $services->set(\PhpParser\BuilderFactory::class); + $services->set(\PhpParser\NodeVisitor\CloningVisitor::class); + $services->set(\PhpParser\NodeFinder::class); + $services->set(\PhpParser\Parser::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\Rector\Core\PhpParser\Parser\NikicPhpParserFactory::class), 'create']); + $services->set(\PhpParser\Lexer::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\Rector\Core\PhpParser\Parser\PhpParserLexerFactory::class), 'create']); // symplify/package-builder - $services->set(PrivatesAccessor::class); - $services->set(PrivatesCaller::class); - $services->set(FinderSanitizer::class); - $services->set(FileSystemFilter::class); - - $services->set(ParameterProvider::class) - ->arg('$container', service('service_container')); - - $services->set(CommandNaming::class); - $services->set(SmartFileSystem::class); - - $services->set(StringFormatConverter::class); - - $services->set(SymfonyStyleFactory::class); - $services->set(SymfonyStyle::class) - ->factory([service(SymfonyStyleFactory::class), 'create']); - - $services->set(JsonFileSystem::class); - $services->set(NodeConnectingVisitor::class); - - $services->set(InflectorFactory::class); - $services->set(Inflector::class) - ->factory([service(InflectorFactory::class), 'build']); - - $services->set(VersionParser::class); - $services->set(TypeChecker::class); - + $services->set(\RectorPrefix20210509\Symplify\PackageBuilder\Reflection\PrivatesAccessor::class); + $services->set(\RectorPrefix20210509\Symplify\PackageBuilder\Reflection\PrivatesCaller::class); + $services->set(\RectorPrefix20210509\Symplify\SmartFileSystem\Finder\FinderSanitizer::class); + $services->set(\RectorPrefix20210509\Symplify\SmartFileSystem\FileSystemFilter::class); + $services->set(\RectorPrefix20210509\Symplify\PackageBuilder\Parameter\ParameterProvider::class)->arg('$container', \RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service('service_container')); + $services->set(\RectorPrefix20210509\Symplify\PackageBuilder\Console\Command\CommandNaming::class); + $services->set(\RectorPrefix20210509\Symplify\SmartFileSystem\SmartFileSystem::class); + $services->set(\RectorPrefix20210509\Symplify\PackageBuilder\Strings\StringFormatConverter::class); + $services->set(\RectorPrefix20210509\Symplify\PackageBuilder\Console\Style\SymfonyStyleFactory::class); + $services->set(\RectorPrefix20210509\Symfony\Component\Console\Style\SymfonyStyle::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\RectorPrefix20210509\Symplify\PackageBuilder\Console\Style\SymfonyStyleFactory::class), 'create']); + $services->set(\RectorPrefix20210509\Symplify\SmartFileSystem\Json\JsonFileSystem::class); + $services->set(\PhpParser\NodeVisitor\NodeConnectingVisitor::class); + $services->set(\RectorPrefix20210509\Doctrine\Inflector\Rules\English\InflectorFactory::class); + $services->set(\RectorPrefix20210509\Doctrine\Inflector\Inflector::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\RectorPrefix20210509\Doctrine\Inflector\Rules\English\InflectorFactory::class), 'build']); + $services->set(\RectorPrefix20210509\Composer\Semver\VersionParser::class); + $services->set(\RectorPrefix20210509\Symplify\PackageBuilder\Php\TypeChecker::class); // phpdoc parser $services->set(\PHPStan\PhpDocParser\Lexer\Lexer::class); - $services->alias(PhpDocParser::class, BetterPhpDocParser::class); - + $services->alias(\PHPStan\PhpDocParser\Parser\PhpDocParser::class, \Rector\BetterPhpDocParser\PhpDocParser\BetterPhpDocParser::class); // cache - $services->set(DependencyResolver::class) - ->factory([service(PHPStanServicesFactory::class), 'createDependencyResolver']); - $services->set(FileHelper::class) - ->factory([service(PHPStanServicesFactory::class), 'createFileHelper']); - - $services->set(Cache::class) - ->factory([service(NetteCacheFactory::class), 'create']); - + $services->set(\PHPStan\Dependency\DependencyResolver::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\Rector\NodeTypeResolver\DependencyInjection\PHPStanServicesFactory::class), 'createDependencyResolver']); + $services->set(\PHPStan\File\FileHelper::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\Rector\NodeTypeResolver\DependencyInjection\PHPStanServicesFactory::class), 'createFileHelper']); + $services->set(\RectorPrefix20210509\Nette\Caching\Cache::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\Rector\Caching\Cache\NetteCacheFactory::class), 'create']); // type resolving - $services->set(IntermediateSourceLocator::class); - $services->alias(TypeParser::class, BetterTypeParser::class); - + $services->set(\Rector\NodeTypeResolver\Reflection\BetterReflection\SourceLocator\IntermediateSourceLocator::class); + $services->alias(\PHPStan\PhpDocParser\Parser\TypeParser::class, \Rector\BetterPhpDocParser\PhpDocParser\BetterTypeParser::class); // PHPStan services - $services->set(ReflectionProvider::class) - ->factory([service(PHPStanServicesFactory::class), 'createReflectionProvider']); - $services->set(NodeScopeResolver::class) - ->factory([service(PHPStanServicesFactory::class), 'createNodeScopeResolver']); - $services->set(ScopeFactory::class) - ->factory([service(PHPStanServicesFactory::class), 'createScopeFactory']); - $services->set(TypeNodeResolver::class) - ->factory([service(PHPStanServicesFactory::class), 'createTypeNodeResolver']); - $services->set(DynamicSourceLocatorProvider::class) - ->factory([service(PHPStanServicesFactory::class), 'createDynamicSourceLocatorProvider']); - - $services->set(Printer::class); - $services->alias(PrinterInterface::class, Printer::class); - - $services->set(Formatter::class); - - $services->set(EditorConfig::class); - - $services->alias(EditorConfigParserInterface::class, EditorConfigIdiosyncraticParser::class); + $services->set(\PHPStan\Reflection\ReflectionProvider::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\Rector\NodeTypeResolver\DependencyInjection\PHPStanServicesFactory::class), 'createReflectionProvider']); + $services->set(\PHPStan\Analyser\NodeScopeResolver::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\Rector\NodeTypeResolver\DependencyInjection\PHPStanServicesFactory::class), 'createNodeScopeResolver']); + $services->set(\PHPStan\Analyser\ScopeFactory::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\Rector\NodeTypeResolver\DependencyInjection\PHPStanServicesFactory::class), 'createScopeFactory']); + $services->set(\PHPStan\PhpDoc\TypeNodeResolver::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\Rector\NodeTypeResolver\DependencyInjection\PHPStanServicesFactory::class), 'createTypeNodeResolver']); + $services->set(\Rector\NodeTypeResolver\Reflection\BetterReflection\SourceLocatorProvider\DynamicSourceLocatorProvider::class)->factory([\RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\Configurator\service(\Rector\NodeTypeResolver\DependencyInjection\PHPStanServicesFactory::class), 'createDynamicSourceLocatorProvider']); + $services->set(\RectorPrefix20210509\Ergebnis\Json\Printer\Printer::class); + $services->alias(\RectorPrefix20210509\Ergebnis\Json\Printer\PrinterInterface::class, \RectorPrefix20210509\Ergebnis\Json\Printer\Printer::class); + $services->set(\RectorPrefix20210509\PrettyXml\Formatter::class); + $services->set(\RectorPrefix20210509\Idiosyncratic\EditorConfig\EditorConfig::class); + $services->alias(\Rector\FileFormatter\Contract\EditorConfig\EditorConfigParserInterface::class, \Rector\FileFormatter\EditorConfig\EditorConfigIdiosyncraticParser::class); }; diff --git a/config/set/action-injection-to-constructor-injection.php b/config/set/action-injection-to-constructor-injection.php index 7f3f39ac464..743df3c0511 100644 --- a/config/set/action-injection-to-constructor-injection.php +++ b/config/set/action-injection-to-constructor-injection.php @@ -1,13 +1,13 @@ services(); - $services->set(ActionInjectionToConstructorInjectionRector::class); - $services->set(ReplaceVariableByPropertyFetchRector::class); + $services->set(\Rector\DependencyInjection\Rector\Class_\ActionInjectionToConstructorInjectionRector::class); + $services->set(\Rector\DependencyInjection\Rector\Variable\ReplaceVariableByPropertyFetchRector::class); }; diff --git a/config/set/carbon-2.php b/config/set/carbon-2.php index b3bf448f534..82514d033fb 100644 --- a/config/set/carbon-2.php +++ b/config/set/carbon-2.php @@ -1,14 +1,14 @@ services(); - $services->set(ChangeDiffForHumansArgsRector::class); - $services->set(ChangeCarbonSingularMethodCallToPluralRector::class); + $services->set(\Rector\Carbon\Rector\MethodCall\ChangeDiffForHumansArgsRector::class); + $services->set(\Rector\Carbon\Rector\MethodCall\ChangeCarbonSingularMethodCallToPluralRector::class); }; diff --git a/config/set/code-quality-strict.php b/config/set/code-quality-strict.php index e23e152633a..eaba83b7c3b 100644 --- a/config/set/code-quality-strict.php +++ b/config/set/code-quality-strict.php @@ -1,19 +1,19 @@ services(); - $services->set(MoveOutMethodCallInsideIfConditionRector::class); - $services->set(CountArrayToEmptyArrayComparisonRector::class); - $services->set(MoveVariableDeclarationNearReferenceRector::class); - $services->set(UseMessageVariableForSprintfInSymfonyStyleRector::class); - $services->set(FlipTypeControlToUseExclusiveTypeRector::class); + $services->set(\Rector\CodeQualityStrict\Rector\If_\MoveOutMethodCallInsideIfConditionRector::class); + $services->set(\Rector\CodingStyle\Rector\FuncCall\CountArrayToEmptyArrayComparisonRector::class); + $services->set(\Rector\CodeQualityStrict\Rector\Variable\MoveVariableDeclarationNearReferenceRector::class); + $services->set(\Rector\CodingStyle\Rector\MethodCall\UseMessageVariableForSprintfInSymfonyStyleRector::class); + $services->set(\Rector\CodeQuality\Rector\Identical\FlipTypeControlToUseExclusiveTypeRector::class); }; diff --git a/config/set/code-quality.php b/config/set/code-quality.php index dde1de80892..792eeb614c9 100644 --- a/config/set/code-quality.php +++ b/config/set/code-quality.php @@ -1,6 +1,7 @@ services(); - $services->set(CombinedAssignRector::class); - $services->set(SimplifyEmptyArrayCheckRector::class); - $services->set(ForeachToInArrayRector::class); - $services->set(SimplifyForeachToCoalescingRector::class); - $services->set(InArrayAndArrayKeysToArrayKeyExistsRector::class); - $services->set(SimplifyFuncGetArgsCountRector::class); - $services->set(SimplifyInArrayValuesRector::class); - $services->set(SimplifyStrposLowerRector::class); - $services->set(GetClassToInstanceOfRector::class); - $services->set(SimplifyArraySearchRector::class); - $services->set(SimplifyConditionsRector::class); - $services->set(SimplifyIfNotNullReturnRector::class); - $services->set(SimplifyIfReturnBoolRector::class); - $services->set(SimplifyUselessVariableRector::class); - $services->set(UnnecessaryTernaryExpressionRector::class); - $services->set(RemoveExtraParametersRector::class); - $services->set(SimplifyDeMorganBinaryRector::class); - $services->set(SimplifyTautologyTernaryRector::class); - $services->set(SimplifyForeachToArrayFilterRector::class); - $services->set(SingleInArrayToCompareRector::class); - $services->set(SimplifyIfElseToTernaryRector::class); - $services->set(JoinStringConcatRector::class); - $services->set(ConsecutiveNullCompareReturnsToNullCoalesceQueueRector::class); - $services->set(SimplifyIfIssetToNullCoalescingRector::class); - $services->set(ExplicitBoolCompareRector::class); - $services->set(CombineIfRector::class); - $services->set(UseIdenticalOverEqualWithSameTypeRector::class); - $services->set(SimplifyDuplicatedTernaryRector::class); - $services->set(SimplifyBoolIdenticalTrueRector::class); - $services->set(SimplifyRegexPatternRector::class); - $services->set(BooleanNotIdenticalToNotIdenticalRector::class); - $services->set(CallableThisArrayToAnonymousFunctionRector::class); - $services->set(AndAssignsToSeparateLinesRector::class); - $services->set(ForToForeachRector::class); - $services->set(CompactToVariablesRector::class); - $services->set(CompleteDynamicPropertiesRector::class); - $services->set(IsAWithStringWithThirdArgumentRector::class); - $services->set(StrlenZeroToIdenticalEmptyStringRector::class); - $services->set(RemoveAlwaysTrueConditionSetInConstructorRector::class); - $services->set(ThrowWithPreviousExceptionRector::class); - $services->set(RemoveSoleValueSprintfRector::class); - $services->set(ShortenElseIfRector::class); - $services->set(AddPregQuoteDelimiterRector::class); - $services->set(ArrayMergeOfNonArraysToSimpleArrayRector::class); - $services->set(IntvalToTypeCastRector::class); - $services->set(ArrayKeyExistsTernaryThenValueToCoalescingRector::class); - $services->set(AbsolutizeRequireAndIncludePathRector::class); - $services->set(ChangeArrayPushToArrayAssignRector::class); - $services->set(ForRepeatedCountToOwnVariableRector::class); - $services->set(ForeachItemsAssignToEmptyArrayToAssignRector::class); - $services->set(InlineIfToExplicitIfRector::class); - $services->set(ArrayKeysAndInArrayToArrayKeyExistsRector::class); - $services->set(SplitListAssignToSeparateLineRector::class); - $services->set(UnusedForeachValueToArrayKeysRector::class); - $services->set(ArrayThisCallToThisMethodCallRector::class); - $services->set(CommonNotEqualRector::class); - $services->set(RenameFunctionRector::class) - ->call('configure', [[ - RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ - 'split' => 'explode', - 'join' => 'implode', - 'sizeof' => 'count', - # https://www.php.net/manual/en/aliases.php - 'chop' => 'rtrim', - 'doubleval' => 'floatval', - 'gzputs' => 'gzwrites', - 'fputs' => 'fwrite', - 'ini_alter' => 'ini_set', - 'is_double' => 'is_float', - 'is_integer' => 'is_int', - 'is_long' => 'is_int', - 'is_real' => 'is_float', - 'is_writeable' => 'is_writable', - 'key_exists' => 'array_key_exists', - 'pos' => 'current', - 'strchr' => 'strstr', - # mb - 'mbstrcut' => 'mb_strcut', - 'mbstrlen' => 'mb_strlen', - 'mbstrpos' => 'mb_strpos', - 'mbstrrpos' => 'mb_strrpos', - 'mbsubstr' => 'mb_substr', - ], - ]]); - $services->set(SetTypeToCastRector::class); - $services->set(LogicalToBooleanRector::class); - $services->set(VarToPublicPropertyRector::class); - $services->set(FixClassCaseSensitivityNameRector::class); - $services->set(IssetOnPropertyObjectToPropertyExistsRector::class); - $services->set(NewStaticToNewSelfRector::class); - $services->set(DateTimeToDateTimeInterfaceRector::class); - $services->set(UnwrapSprintfOneArgumentRector::class); - $services->set(SwitchNegatedTernaryRector::class); - $services->set(SingularSwitchToIfRector::class); - $services->set(SimplifyIfNullableReturnRector::class); - $services->set(NarrowUnionTypeDocRector::class); - $services->set(FuncGetArgsToVariadicParamRector::class); - $services->set(CallUserFuncToMethodCallRector::class); - $services->set(CallUserFuncWithArrowFunctionToInlineRector::class); + $services->set(\Rector\CodeQuality\Rector\Assign\CombinedAssignRector::class); + $services->set(\Rector\CodeQuality\Rector\BooleanAnd\SimplifyEmptyArrayCheckRector::class); + $services->set(\Rector\CodeQuality\Rector\Foreach_\ForeachToInArrayRector::class); + $services->set(\Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToCoalescingRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\InArrayAndArrayKeysToArrayKeyExistsRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\SimplifyFuncGetArgsCountRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\SimplifyInArrayValuesRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\SimplifyStrposLowerRector::class); + $services->set(\Rector\CodeQuality\Rector\Identical\GetClassToInstanceOfRector::class); + $services->set(\Rector\CodeQuality\Rector\Identical\SimplifyArraySearchRector::class); + $services->set(\Rector\CodeQuality\Rector\Identical\SimplifyConditionsRector::class); + $services->set(\Rector\CodeQuality\Rector\If_\SimplifyIfNotNullReturnRector::class); + $services->set(\Rector\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector::class); + $services->set(\Rector\CodeQuality\Rector\Return_\SimplifyUselessVariableRector::class); + $services->set(\Rector\CodeQuality\Rector\Ternary\UnnecessaryTernaryExpressionRector::class); + $services->set(\Rector\Php71\Rector\FuncCall\RemoveExtraParametersRector::class); + $services->set(\Rector\CodeQuality\Rector\BooleanNot\SimplifyDeMorganBinaryRector::class); + $services->set(\Rector\CodeQuality\Rector\Ternary\SimplifyTautologyTernaryRector::class); + $services->set(\Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToArrayFilterRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\SingleInArrayToCompareRector::class); + $services->set(\Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector::class); + $services->set(\Rector\CodeQuality\Rector\Concat\JoinStringConcatRector::class); + $services->set(\Rector\CodeQuality\Rector\If_\ConsecutiveNullCompareReturnsToNullCoalesceQueueRector::class); + $services->set(\Rector\CodeQuality\Rector\If_\SimplifyIfIssetToNullCoalescingRector::class); + $services->set(\Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector::class); + $services->set(\Rector\CodeQuality\Rector\If_\CombineIfRector::class); + $services->set(\Rector\CodeQuality\Rector\Equal\UseIdenticalOverEqualWithSameTypeRector::class); + $services->set(\Rector\CodeQuality\Rector\Ternary\SimplifyDuplicatedTernaryRector::class); + $services->set(\Rector\CodeQuality\Rector\Identical\SimplifyBoolIdenticalTrueRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\SimplifyRegexPatternRector::class); + $services->set(\Rector\CodeQuality\Rector\Identical\BooleanNotIdenticalToNotIdenticalRector::class); + $services->set(\Rector\CodeQuality\Rector\Array_\CallableThisArrayToAnonymousFunctionRector::class); + $services->set(\Rector\CodeQuality\Rector\LogicalAnd\AndAssignsToSeparateLinesRector::class); + $services->set(\Rector\CodeQuality\Rector\For_\ForToForeachRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\CompactToVariablesRector::class); + $services->set(\Rector\CodeQuality\Rector\Class_\CompleteDynamicPropertiesRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\IsAWithStringWithThirdArgumentRector::class); + $services->set(\Rector\CodeQuality\Rector\Identical\StrlenZeroToIdenticalEmptyStringRector::class); + $services->set(\Rector\CodeQuality\Rector\FunctionLike\RemoveAlwaysTrueConditionSetInConstructorRector::class); + $services->set(\Rector\CodeQuality\Rector\Catch_\ThrowWithPreviousExceptionRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\RemoveSoleValueSprintfRector::class); + $services->set(\Rector\CodeQuality\Rector\If_\ShortenElseIfRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\AddPregQuoteDelimiterRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\ArrayMergeOfNonArraysToSimpleArrayRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\IntvalToTypeCastRector::class); + $services->set(\Rector\CodeQuality\Rector\Ternary\ArrayKeyExistsTernaryThenValueToCoalescingRector::class); + $services->set(\Rector\CodeQuality\Rector\Include_\AbsolutizeRequireAndIncludePathRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\ChangeArrayPushToArrayAssignRector::class); + $services->set(\Rector\CodeQuality\Rector\For_\ForRepeatedCountToOwnVariableRector::class); + $services->set(\Rector\CodeQuality\Rector\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector::class); + $services->set(\Rector\CodeQuality\Rector\Expression\InlineIfToExplicitIfRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\ArrayKeysAndInArrayToArrayKeyExistsRector::class); + $services->set(\Rector\CodeQuality\Rector\Assign\SplitListAssignToSeparateLineRector::class); + $services->set(\Rector\CodeQuality\Rector\Foreach_\UnusedForeachValueToArrayKeysRector::class); + $services->set(\Rector\CodeQuality\Rector\Array_\ArrayThisCallToThisMethodCallRector::class); + $services->set(\Rector\CodeQuality\Rector\NotEqual\CommonNotEqualRector::class); + $services->set(\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::class)->call('configure', [[\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ + 'split' => 'explode', + 'join' => 'implode', + 'sizeof' => 'count', + # https://www.php.net/manual/en/aliases.php + 'chop' => 'rtrim', + 'doubleval' => 'floatval', + 'gzputs' => 'gzwrites', + 'fputs' => 'fwrite', + 'ini_alter' => 'ini_set', + 'is_double' => 'is_float', + 'is_integer' => 'is_int', + 'is_long' => 'is_int', + 'is_real' => 'is_float', + 'is_writeable' => 'is_writable', + 'key_exists' => 'array_key_exists', + 'pos' => 'current', + 'strchr' => 'strstr', + # mb + 'mbstrcut' => 'mb_strcut', + 'mbstrlen' => 'mb_strlen', + 'mbstrpos' => 'mb_strpos', + 'mbstrrpos' => 'mb_strrpos', + 'mbsubstr' => 'mb_substr', + ]]]); + $services->set(\Rector\CodeQuality\Rector\FuncCall\SetTypeToCastRector::class); + $services->set(\Rector\CodeQuality\Rector\LogicalAnd\LogicalToBooleanRector::class); + $services->set(\Rector\Php52\Rector\Property\VarToPublicPropertyRector::class); + $services->set(\Rector\CodeQuality\Rector\Name\FixClassCaseSensitivityNameRector::class); + $services->set(\Rector\CodeQuality\Rector\Isset_\IssetOnPropertyObjectToPropertyExistsRector::class); + $services->set(\Rector\CodeQuality\Rector\New_\NewStaticToNewSelfRector::class); + $services->set(\Rector\CodeQuality\Rector\ClassMethod\DateTimeToDateTimeInterfaceRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\UnwrapSprintfOneArgumentRector::class); + $services->set(\Rector\CodeQuality\Rector\Ternary\SwitchNegatedTernaryRector::class); + $services->set(\Rector\CodeQuality\Rector\Switch_\SingularSwitchToIfRector::class); + $services->set(\Rector\CodeQuality\Rector\If_\SimplifyIfNullableReturnRector::class); + $services->set(\Rector\CodeQuality\Rector\ClassMethod\NarrowUnionTypeDocRector::class); + $services->set(\Rector\CodingStyle\Rector\ClassMethod\FuncGetArgsToVariadicParamRector::class); + $services->set(\Rector\CodingStyle\Rector\FuncCall\CallUserFuncToMethodCallRector::class); + $services->set(\Rector\CodeQuality\Rector\FuncCall\CallUserFuncWithArrowFunctionToInlineRector::class); }; diff --git a/config/set/coding-style-advanced.php b/config/set/coding-style-advanced.php index bf2cae8b74b..2acf0d2f0d3 100644 --- a/config/set/coding-style-advanced.php +++ b/config/set/coding-style-advanced.php @@ -1,11 +1,11 @@ services(); - $services->set(UseMessageVariableForSprintfInSymfonyStyleRector::class); + $services->set(\Rector\CodingStyle\Rector\MethodCall\UseMessageVariableForSprintfInSymfonyStyleRector::class); }; diff --git a/config/set/coding-style.php b/config/set/coding-style.php index 58b47727daa..3e6db968e0d 100644 --- a/config/set/coding-style.php +++ b/config/set/coding-style.php @@ -1,6 +1,7 @@ services(); - $services->set(PHPStormVarAnnotationRector::class); - $services->set(NullableCompareToNullRector::class); - $services->set(BinarySwitchToIfElseRector::class); - $services->set(ConsistentImplodeRector::class); - $services->set(TernaryConditionVariableAssignmentRector::class); - $services->set(RemoveUnusedAliasRector::class); - $services->set(SymplifyQuoteEscapeRector::class); - $services->set(SplitGroupedConstantsAndPropertiesRector::class); - $services->set(SplitStringClassConstantToClassConstFetchRector::class); - $services->set(StringClassNameToClassConstantRector::class); - $services->set(ConsistentPregDelimiterRector::class); - $services->set(FollowRequireByDirRector::class); - $services->set(CatchExceptionNameMatchingTypeRector::class); - $services->set(UseIncrementAssignRector::class); - $services->set(SplitDoubleAssignRector::class); - $services->set(VarConstantCommentRector::class); - $services->set(EncapsedStringsToSprintfRector::class); - $services->set(WrapEncapsedVariableInCurlyBracesRector::class); - $services->set(NewlineBeforeNewAssignSetRector::class); - $services->set(ManualJsonStringToJsonEncodeArrayRector::class); - $services->set(AddArrayDefaultToArrayPropertyRector::class); - $services->set(AddFalseDefaultToBoolPropertyRector::class); - $services->set(MakeInheritedMethodVisibilitySameAsParentRector::class); - $services->set(CallUserFuncArrayToVariadicRector::class); - $services->set(VersionCompareFuncCallToConstantRector::class); - $services->set(UseMessageVariableForSprintfInSymfonyStyleRector::class); - - $services->set(FuncCallToConstFetchRector::class) - ->call('configure', [[ - FuncCallToConstFetchRector::FUNCTIONS_TO_CONSTANTS => [ - 'php_sapi_name' => 'PHP_SAPI', - 'pi' => 'M_PI', - ], - ]]); - - $services->set(SeparateMultiUseImportsRector::class); - $services->set(RemoveDoubleUnderscoreInMethodNameRector::class); - $services->set(PostIncDecToPreIncDecRector::class); - $services->set(UnSpreadOperatorRector::class); + $services->set(\Rector\CodingStyle\Rector\Assign\PHPStormVarAnnotationRector::class); + $services->set(\Rector\CodingStyle\Rector\If_\NullableCompareToNullRector::class); + $services->set(\Rector\CodingStyle\Rector\Switch_\BinarySwitchToIfElseRector::class); + $services->set(\Rector\CodingStyle\Rector\FuncCall\ConsistentImplodeRector::class); + $services->set(\Rector\CodingStyle\Rector\Ternary\TernaryConditionVariableAssignmentRector::class); + $services->set(\Rector\CodingStyle\Rector\Use_\RemoveUnusedAliasRector::class); + $services->set(\Rector\CodingStyle\Rector\String_\SymplifyQuoteEscapeRector::class); + $services->set(\Rector\CodingStyle\Rector\ClassConst\SplitGroupedConstantsAndPropertiesRector::class); + $services->set(\Rector\CodingStyle\Rector\String_\SplitStringClassConstantToClassConstFetchRector::class); + $services->set(\Rector\Php55\Rector\String_\StringClassNameToClassConstantRector::class); + $services->set(\Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector::class); + $services->set(\Rector\CodingStyle\Rector\Include_\FollowRequireByDirRector::class); + $services->set(\Rector\CodingStyle\Rector\Catch_\CatchExceptionNameMatchingTypeRector::class); + $services->set(\Rector\CodingStyle\Rector\Plus\UseIncrementAssignRector::class); + $services->set(\Rector\CodingStyle\Rector\Assign\SplitDoubleAssignRector::class); + $services->set(\Rector\CodingStyle\Rector\ClassConst\VarConstantCommentRector::class); + $services->set(\Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector::class); + $services->set(\Rector\CodingStyle\Rector\Encapsed\WrapEncapsedVariableInCurlyBracesRector::class); + $services->set(\Rector\CodingStyle\Rector\ClassMethod\NewlineBeforeNewAssignSetRector::class); + $services->set(\Rector\CodingStyle\Rector\Assign\ManualJsonStringToJsonEncodeArrayRector::class); + $services->set(\Rector\CodingStyle\Rector\Class_\AddArrayDefaultToArrayPropertyRector::class); + $services->set(\Rector\CodingStyle\Rector\Property\AddFalseDefaultToBoolPropertyRector::class); + $services->set(\Rector\CodingStyle\Rector\ClassMethod\MakeInheritedMethodVisibilitySameAsParentRector::class); + $services->set(\Rector\CodingStyle\Rector\FuncCall\CallUserFuncArrayToVariadicRector::class); + $services->set(\Rector\CodingStyle\Rector\FuncCall\VersionCompareFuncCallToConstantRector::class); + $services->set(\Rector\CodingStyle\Rector\MethodCall\UseMessageVariableForSprintfInSymfonyStyleRector::class); + $services->set(\Rector\Transform\Rector\FuncCall\FuncCallToConstFetchRector::class)->call('configure', [[\Rector\Transform\Rector\FuncCall\FuncCallToConstFetchRector::FUNCTIONS_TO_CONSTANTS => ['php_sapi_name' => 'PHP_SAPI', 'pi' => 'M_PI']]]); + $services->set(\Rector\CodingStyle\Rector\Use_\SeparateMultiUseImportsRector::class); + $services->set(\Rector\CodingStyle\Rector\ClassMethod\RemoveDoubleUnderscoreInMethodNameRector::class); + $services->set(\Rector\CodingStyle\Rector\PostInc\PostIncDecToPreIncDecRector::class); + $services->set(\Rector\CodingStyle\Rector\ClassMethod\UnSpreadOperatorRector::class); }; diff --git a/config/set/dead-code.php b/config/set/dead-code.php index dc32399fb96..1d5f47f54cf 100644 --- a/config/set/dead-code.php +++ b/config/set/dead-code.php @@ -1,6 +1,7 @@ services(); - $services->set(UnwrapFutureCompatibleIfFunctionExistsRector::class); - $services->set(UnwrapFutureCompatibleIfPhpVersionRector::class); - $services->set(RecastingRemovalRector::class); - $services->set(RemoveDeadStmtRector::class); - $services->set(RemoveDuplicatedArrayKeyRector::class); - $services->set(RemoveUnusedForeachKeyRector::class); - $services->set(RemoveParentCallWithoutParentRector::class); - $services->set(RemoveEmptyClassMethodRector::class); - $services->set(RemoveDoubleAssignRector::class); - $services->set(SimplifyMirrorAssignRector::class); - $services->set(RemoveOverriddenValuesRector::class); - $services->set(RemoveUnusedPrivatePropertyRector::class); - $services->set(RemoveUnusedPrivateClassConstantRector::class); - $services->set(RemoveUnusedPrivateMethodRector::class); - $services->set(RemoveCodeAfterReturnRector::class); - $services->set(RemoveDeadConstructorRector::class); - $services->set(RemoveDeadReturnRector::class); - $services->set(RemoveDeadIfForeachForRector::class); - $services->set(RemoveAndTrueRector::class); - $services->set(RemoveConcatAutocastRector::class); - $services->set(SimplifyUselessVariableRector::class); - $services->set(RemoveDelegatingParentCallRector::class); - $services->set(RemoveDuplicatedInstanceOfRector::class); - $services->set(RemoveDuplicatedCaseInSwitchRector::class); - $services->set(RemoveSetterOnlyPropertyAndMethodCallRector::class); - $services->set(RemoveNullPropertyInitializationRector::class); - $services->set(RemoveUnreachableStatementRector::class); - $services->set(SimplifyIfElseWithSameContentRector::class); - $services->set(TernaryToBooleanOrFalseToBooleanAndRector::class); - $services->set(RemoveEmptyTestMethodRector::class); - $services->set(RemoveDeadTryCatchRector::class); - $services->set(RemoveUnusedVariableAssignRector::class); - $services->set(RemoveDuplicatedIfReturnRector::class); - $services->set(RemoveUnusedNonEmptyArrayBeforeForeachRector::class); - $services->set(RemoveAssignOfVoidReturnFunctionRector::class); - $services->set(RemoveEmptyMethodCallRector::class); - $services->set(RemoveDeadConditionAboveReturnRector::class); - $services->set(RemoveUnusedConstructorParamRector::class); - $services->set(RemoveDeadInstanceOfRector::class); - $services->set(RemoveDeadLoopRector::class); - $services->set(RemoveUnusedPrivateMethodParameterRector::class); - + $services->set(\Rector\DeadCode\Rector\If_\UnwrapFutureCompatibleIfFunctionExistsRector::class); + $services->set(\Rector\DeadCode\Rector\If_\UnwrapFutureCompatibleIfPhpVersionRector::class); + $services->set(\Rector\DeadCode\Rector\Cast\RecastingRemovalRector::class); + $services->set(\Rector\DeadCode\Rector\Expression\RemoveDeadStmtRector::class); + $services->set(\Rector\DeadCode\Rector\Array_\RemoveDuplicatedArrayKeyRector::class); + $services->set(\Rector\DeadCode\Rector\Foreach_\RemoveUnusedForeachKeyRector::class); + $services->set(\Rector\DeadCode\Rector\StaticCall\RemoveParentCallWithoutParentRector::class); + $services->set(\Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector::class); + $services->set(\Rector\DeadCode\Rector\Assign\RemoveDoubleAssignRector::class); + $services->set(\Rector\DeadCode\Rector\Expression\SimplifyMirrorAssignRector::class); + $services->set(\Rector\DeadCode\Rector\FunctionLike\RemoveOverriddenValuesRector::class); + $services->set(\Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector::class); + $services->set(\Rector\DeadCode\Rector\ClassConst\RemoveUnusedPrivateClassConstantRector::class); + $services->set(\Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodRector::class); + $services->set(\Rector\DeadCode\Rector\FunctionLike\RemoveCodeAfterReturnRector::class); + $services->set(\Rector\DeadCode\Rector\ClassMethod\RemoveDeadConstructorRector::class); + $services->set(\Rector\DeadCode\Rector\FunctionLike\RemoveDeadReturnRector::class); + $services->set(\Rector\DeadCode\Rector\For_\RemoveDeadIfForeachForRector::class); + $services->set(\Rector\DeadCode\Rector\BooleanAnd\RemoveAndTrueRector::class); + $services->set(\Rector\DeadCode\Rector\Concat\RemoveConcatAutocastRector::class); + $services->set(\Rector\CodeQuality\Rector\Return_\SimplifyUselessVariableRector::class); + $services->set(\Rector\DeadCode\Rector\ClassMethod\RemoveDelegatingParentCallRector::class); + $services->set(\Rector\DeadCode\Rector\BinaryOp\RemoveDuplicatedInstanceOfRector::class); + $services->set(\Rector\DeadCode\Rector\Switch_\RemoveDuplicatedCaseInSwitchRector::class); + $services->set(\Rector\DeadCode\Rector\Property\RemoveSetterOnlyPropertyAndMethodCallRector::class); + $services->set(\Rector\DeadCode\Rector\PropertyProperty\RemoveNullPropertyInitializationRector::class); + $services->set(\Rector\DeadCode\Rector\Stmt\RemoveUnreachableStatementRector::class); + $services->set(\Rector\DeadCode\Rector\If_\SimplifyIfElseWithSameContentRector::class); + $services->set(\Rector\DeadCode\Rector\Ternary\TernaryToBooleanOrFalseToBooleanAndRector::class); + $services->set(\Rector\PHPUnit\Rector\ClassMethod\RemoveEmptyTestMethodRector::class); + $services->set(\Rector\DeadCode\Rector\TryCatch\RemoveDeadTryCatchRector::class); + $services->set(\Rector\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector::class); + $services->set(\Rector\DeadCode\Rector\FunctionLike\RemoveDuplicatedIfReturnRector::class); + $services->set(\Rector\DeadCode\Rector\If_\RemoveUnusedNonEmptyArrayBeforeForeachRector::class); + $services->set(\Rector\DeadCode\Rector\Assign\RemoveAssignOfVoidReturnFunctionRector::class); + $services->set(\Rector\DeadCode\Rector\MethodCall\RemoveEmptyMethodCallRector::class); + $services->set(\Rector\DeadCode\Rector\Return_\RemoveDeadConditionAboveReturnRector::class); + $services->set(\Rector\DeadCode\Rector\ClassMethod\RemoveUnusedConstructorParamRector::class); + $services->set(\Rector\DeadCode\Rector\If_\RemoveDeadInstanceOfRector::class); + $services->set(\Rector\DeadCode\Rector\For_\RemoveDeadLoopRector::class); + $services->set(\Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodParameterRector::class); // docblock - $services->set(RemoveUselessParamTagRector::class); - $services->set(RemoveUselessReturnTagRector::class); - $services->set(RemoveNonExistingVarAnnotationRector::class); + $services->set(\Rector\DeadCode\Rector\ClassMethod\RemoveUselessParamTagRector::class); + $services->set(\Rector\DeadCode\Rector\ClassMethod\RemoveUselessReturnTagRector::class); + $services->set(\Rector\DeadCode\Rector\Node\RemoveNonExistingVarAnnotationRector::class); }; diff --git a/config/set/defluent.php b/config/set/defluent.php index 16ce9b8e2a6..978260d9c98 100644 --- a/config/set/defluent.php +++ b/config/set/defluent.php @@ -1,6 +1,7 @@ services(); - // variable/property - $services->set(FluentChainMethodCallToNormalMethodCallRector::class); - $services->set(ReturnFluentChainMethodCallToNormalMethodCallRector::class); - + $services->set(\Rector\Defluent\Rector\MethodCall\FluentChainMethodCallToNormalMethodCallRector::class); + $services->set(\Rector\Defluent\Rector\Return_\ReturnFluentChainMethodCallToNormalMethodCallRector::class); // new - $services->set(NewFluentChainMethodCallToNonFluentRector::class); - $services->set(ReturnNewFluentChainMethodCallToNonFluentRector::class); - - $services->set(ReturnThisRemoveRector::class); - $services->set(DefluentReturnMethodCallRector::class); - $services->set(MethodCallOnSetterMethodCallToStandaloneAssignRector::class); - $services->set(InArgFluentChainMethodCallToStandaloneMethodCallRector::class); + $services->set(\Rector\Defluent\Rector\MethodCall\NewFluentChainMethodCallToNonFluentRector::class); + $services->set(\Rector\Defluent\Rector\Return_\ReturnNewFluentChainMethodCallToNonFluentRector::class); + $services->set(\Rector\Defluent\Rector\ClassMethod\ReturnThisRemoveRector::class); + $services->set(\Rector\Defluent\Rector\Return_\DefluentReturnMethodCallRector::class); + $services->set(\Rector\Defluent\Rector\MethodCall\MethodCallOnSetterMethodCallToStandaloneAssignRector::class); + $services->set(\Rector\Defluent\Rector\MethodCall\InArgFluentChainMethodCallToStandaloneMethodCallRector::class); }; diff --git a/config/set/downgrade-php53.php b/config/set/downgrade-php53.php index 403fc5f414a..85df6f595fe 100644 --- a/config/set/downgrade-php53.php +++ b/config/set/downgrade-php53.php @@ -1,16 +1,15 @@ parameters(); - $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_53); - + $parameters->set(\Rector\Core\Configuration\Option::PHP_VERSION_FEATURES, \Rector\Core\ValueObject\PhpVersion::PHP_53); $services = $containerConfigurator->services(); - $services->set(DirConstToFileConstRector::class); + $services->set(\Rector\DowngradePhp53\Rector\Dir\DirConstToFileConstRector::class); }; diff --git a/config/set/downgrade-php70.php b/config/set/downgrade-php70.php index d47c7c12632..f112ae885d9 100644 --- a/config/set/downgrade-php70.php +++ b/config/set/downgrade-php70.php @@ -1,6 +1,7 @@ parameters(); - $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_56); - + $parameters->set(\Rector\Core\Configuration\Option::PHP_VERSION_FEATURES, \Rector\Core\ValueObject\PhpVersion::PHP_56); $services = $containerConfigurator->services(); - $services->set(DowngradeScalarTypeDeclarationRector::class); - $services->set(DowngradeStrictTypeDeclarationRector::class); - $services->set(DowngradeAnonymousClassRector::class); - $services->set(DowngradeNullCoalesceRector::class); - $services->set(DowngradeSpaceshipRector::class); - $services->set(DowngradeDefineArrayConstantRector::class); - $services->set(DowngradeSessionStartArrayOptionsRector::class); - $services->set(SplitGroupedUseImportsRector::class); - $services->set(DowngradeGeneratedScalarTypesRector::class); + $services->set(\Rector\DowngradePhp70\Rector\FunctionLike\DowngradeScalarTypeDeclarationRector::class); + $services->set(\Rector\DowngradePhp70\Rector\Declare_\DowngradeStrictTypeDeclarationRector::class); + $services->set(\Rector\DowngradePhp70\Rector\New_\DowngradeAnonymousClassRector::class); + $services->set(\Rector\DowngradePhp70\Rector\Coalesce\DowngradeNullCoalesceRector::class); + $services->set(\Rector\DowngradePhp70\Rector\Spaceship\DowngradeSpaceshipRector::class); + $services->set(\Rector\DowngradePhp70\Rector\Expression\DowngradeDefineArrayConstantRector::class); + $services->set(\Rector\DowngradePhp70\Rector\FuncCall\DowngradeSessionStartArrayOptionsRector::class); + $services->set(\Rector\DowngradePhp70\Rector\GroupUse\SplitGroupedUseImportsRector::class); + $services->set(\Rector\DowngradePhp70\Rector\String_\DowngradeGeneratedScalarTypesRector::class); }; diff --git a/config/set/downgrade-php71.php b/config/set/downgrade-php71.php index 69e3a236131..7b7c4ebc97a 100644 --- a/config/set/downgrade-php71.php +++ b/config/set/downgrade-php71.php @@ -1,6 +1,7 @@ parameters(); - $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_70); - + $parameters->set(\Rector\Core\Configuration\Option::PHP_VERSION_FEATURES, \Rector\Core\ValueObject\PhpVersion::PHP_70); $services = $containerConfigurator->services(); - $services->set(DowngradeNullableTypeDeclarationRector::class); - $services->set(DowngradeVoidTypeDeclarationRector::class); - $services->set(DowngradeClassConstantVisibilityRector::class); - $services->set(DowngradePipeToMultiCatchExceptionRector::class); - $services->set(SymmetricArrayDestructuringToListRector::class); - $services->set(DowngradeNegativeStringOffsetToStrlenRector::class); - $services->set(DowngradeKeysInListRector::class); - $services->set(DowngradeIterablePseudoTypeDeclarationRector::class); - $services->set(DowngradeIsIterableRector::class); + $services->set(\Rector\DowngradePhp71\Rector\FunctionLike\DowngradeNullableTypeDeclarationRector::class); + $services->set(\Rector\DowngradePhp71\Rector\FunctionLike\DowngradeVoidTypeDeclarationRector::class); + $services->set(\Rector\DowngradePhp71\Rector\ClassConst\DowngradeClassConstantVisibilityRector::class); + $services->set(\Rector\DowngradePhp71\Rector\TryCatch\DowngradePipeToMultiCatchExceptionRector::class); + $services->set(\Rector\DowngradePhp71\Rector\Array_\SymmetricArrayDestructuringToListRector::class); + $services->set(\Rector\DowngradePhp71\Rector\String_\DowngradeNegativeStringOffsetToStrlenRector::class); + $services->set(\Rector\DowngradePhp71\Rector\List_\DowngradeKeysInListRector::class); + $services->set(\Rector\DowngradePhp71\Rector\FunctionLike\DowngradeIterablePseudoTypeDeclarationRector::class); + $services->set(\Rector\DowngradePhp71\Rector\FuncCall\DowngradeIsIterableRector::class); }; diff --git a/config/set/downgrade-php72.php b/config/set/downgrade-php72.php index 7044dca1087..85d9092f88d 100644 --- a/config/set/downgrade-php72.php +++ b/config/set/downgrade-php72.php @@ -1,6 +1,7 @@ parameters(); - $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_71); - + $parameters->set(\Rector\Core\Configuration\Option::PHP_VERSION_FEATURES, \Rector\Core\ValueObject\PhpVersion::PHP_71); $services = $containerConfigurator->services(); - $services->set(DowngradeObjectTypeDeclarationRector::class); - $services->set(DowngradeParameterTypeWideningRector::class); - $services->set(DowngradePregUnmatchedAsNullConstantRector::class); - $services->set(DowngradeStreamIsattyRector::class); + $services->set(\Rector\DowngradePhp72\Rector\FunctionLike\DowngradeObjectTypeDeclarationRector::class); + $services->set(\Rector\DowngradePhp72\Rector\Class_\DowngradeParameterTypeWideningRector::class); + $services->set(\Rector\DowngradePhp72\Rector\FuncCall\DowngradePregUnmatchedAsNullConstantRector::class); + $services->set(\Rector\DowngradePhp72\Rector\FuncCall\DowngradeStreamIsattyRector::class); }; diff --git a/config/set/downgrade-php73.php b/config/set/downgrade-php73.php index 2be3ec5a92e..8ff0ed25ea2 100644 --- a/config/set/downgrade-php73.php +++ b/config/set/downgrade-php73.php @@ -1,6 +1,7 @@ parameters(); - $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_72); - + $parameters->set(\Rector\Core\Configuration\Option::PHP_VERSION_FEATURES, \Rector\Core\ValueObject\PhpVersion::PHP_72); $services = $containerConfigurator->services(); - $services->set(DowngradeFlexibleHeredocSyntaxRector::class); - $services->set(DowngradeListReferenceAssignmentRector::class); - $services->set(DowngradeTrailingCommasInFunctionCallsRector::class); - $services->set(DowngradeArrayKeyFirstLastRector::class); - $services->set(SetCookieOptionsArrayToArgumentsRector::class); + $services->set(\Rector\DowngradePhp73\Rector\String_\DowngradeFlexibleHeredocSyntaxRector::class); + $services->set(\Rector\DowngradePhp73\Rector\List_\DowngradeListReferenceAssignmentRector::class); + $services->set(\Rector\DowngradePhp73\Rector\FuncCall\DowngradeTrailingCommasInFunctionCallsRector::class); + $services->set(\Rector\DowngradePhp73\Rector\FuncCall\DowngradeArrayKeyFirstLastRector::class); + $services->set(\Rector\DowngradePhp73\Rector\FuncCall\SetCookieOptionsArrayToArgumentsRector::class); }; diff --git a/config/set/downgrade-php74.php b/config/set/downgrade-php74.php index 9bfdc4f042b..0ceb65f00f0 100644 --- a/config/set/downgrade-php74.php +++ b/config/set/downgrade-php74.php @@ -1,6 +1,7 @@ parameters(); - $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_73); - + $parameters->set(\Rector\Core\Configuration\Option::PHP_VERSION_FEATURES, \Rector\Core\ValueObject\PhpVersion::PHP_73); $services = $containerConfigurator->services(); - $services->set(DowngradeTypedPropertyRector::class); - $services->set(ArrowFunctionToAnonymousFunctionRector::class); - $services->set(DowngradeCovariantReturnTypeRector::class); - $services->set(DowngradeContravariantArgumentTypeRector::class); - $services->set(DowngradeNullCoalescingOperatorRector::class); - $services->set(DowngradeNumericLiteralSeparatorRector::class); - $services->set(DowngradeStripTagsCallWithArrayRector::class); - $services->set(DowngradeArraySpreadRector::class); - $services->set(DowngradeArrayMergeCallWithoutArgumentsRector::class); - $services->set(DowngradeFreadFwriteFalsyToNegationRector::class); - $services->set(DowngradeSelfTypeDeclarationRector::class); + $services->set(\Rector\DowngradePhp74\Rector\Property\DowngradeTypedPropertyRector::class); + $services->set(\Rector\DowngradePhp74\Rector\ArrowFunction\ArrowFunctionToAnonymousFunctionRector::class); + $services->set(\Rector\DowngradePhp74\Rector\ClassMethod\DowngradeCovariantReturnTypeRector::class); + $services->set(\Rector\DowngradePhp74\Rector\ClassMethod\DowngradeContravariantArgumentTypeRector::class); + $services->set(\Rector\DowngradePhp74\Rector\Coalesce\DowngradeNullCoalescingOperatorRector::class); + $services->set(\Rector\DowngradePhp74\Rector\LNumber\DowngradeNumericLiteralSeparatorRector::class); + $services->set(\Rector\DowngradePhp74\Rector\FuncCall\DowngradeStripTagsCallWithArrayRector::class); + $services->set(\Rector\DowngradePhp74\Rector\Array_\DowngradeArraySpreadRector::class); + $services->set(\Rector\DowngradePhp74\Rector\FuncCall\DowngradeArrayMergeCallWithoutArgumentsRector::class); + $services->set(\Rector\DowngradePhp74\Rector\Identical\DowngradeFreadFwriteFalsyToNegationRector::class); + $services->set(\Rector\DowngradePhp74\Rector\ClassMethod\DowngradeSelfTypeDeclarationRector::class); }; diff --git a/config/set/downgrade-php80.php b/config/set/downgrade-php80.php index 24c40dbaba0..b0e56d58226 100644 --- a/config/set/downgrade-php80.php +++ b/config/set/downgrade-php80.php @@ -1,6 +1,7 @@ parameters(); - $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_74); - + $parameters->set(\Rector\Core\Configuration\Option::PHP_VERSION_FEATURES, \Rector\Core\ValueObject\PhpVersion::PHP_74); $services = $containerConfigurator->services(); - $services->set(DowngradeUnionTypeTypedPropertyRector::class); - $services->set(DowngradeUnionTypeDeclarationRector::class); - $services->set(DowngradeMixedTypeDeclarationRector::class); - $services->set(DowngradeStaticTypeDeclarationRector::class); - $services->set(DowngradePropertyPromotionRector::class); - $services->set(DowngradeNonCapturingCatchesRector::class); - $services->set(DowngradeMatchToSwitchRector::class); - $services->set(DowngradeClassOnObjectToGetClassRector::class); - $services->set(DowngradeNullsafeToTernaryOperatorRector::class); - $services->set(DowngradeTrailingCommasInParamUseRector::class); + $services->set(\Rector\DowngradePhp80\Rector\Property\DowngradeUnionTypeTypedPropertyRector::class); + $services->set(\Rector\DowngradePhp80\Rector\FunctionLike\DowngradeUnionTypeDeclarationRector::class); + $services->set(\Rector\DowngradePhp80\Rector\FunctionLike\DowngradeMixedTypeDeclarationRector::class); + $services->set(\Rector\DowngradePhp80\Rector\ClassMethod\DowngradeStaticTypeDeclarationRector::class); + $services->set(\Rector\DowngradePhp80\Rector\Class_\DowngradePropertyPromotionRector::class); + $services->set(\Rector\DowngradePhp80\Rector\Catch_\DowngradeNonCapturingCatchesRector::class); + $services->set(\Rector\DowngradePhp80\Rector\Expression\DowngradeMatchToSwitchRector::class); + $services->set(\Rector\DowngradePhp80\Rector\ClassConstFetch\DowngradeClassOnObjectToGetClassRector::class); + $services->set(\Rector\DowngradePhp80\Rector\NullsafeMethodCall\DowngradeNullsafeToTernaryOperatorRector::class); + $services->set(\Rector\DowngradePhp80\Rector\ClassMethod\DowngradeTrailingCommasInParamUseRector::class); }; diff --git a/config/set/early-return.php b/config/set/early-return.php index 70be964cbe5..7f026c199cf 100644 --- a/config/set/early-return.php +++ b/config/set/early-return.php @@ -1,6 +1,7 @@ services(); - $services->set(ChangeNestedForeachIfsToEarlyContinueRector::class); - $services->set(ChangeAndIfToEarlyReturnRector::class); - $services->set(ChangeIfElseValueAssignToEarlyReturnRector::class); - $services->set(ChangeNestedIfsToEarlyReturnRector::class); - $services->set(RemoveAlwaysElseRector::class); - $services->set(ReturnBinaryAndToEarlyReturnRector::class); - $services->set(ChangeOrIfReturnToEarlyReturnRector::class); - $services->set(ChangeOrIfContinueToMultiContinueRector::class); - $services->set(ReturnAfterToEarlyOnBreakRector::class); - $services->set(PreparedValueToEarlyReturnRector::class); - $services->set(ReturnBinaryOrToEarlyReturnRector::class); + $services->set(\Rector\EarlyReturn\Rector\Foreach_\ChangeNestedForeachIfsToEarlyContinueRector::class); + $services->set(\Rector\EarlyReturn\Rector\If_\ChangeAndIfToEarlyReturnRector::class); + $services->set(\Rector\EarlyReturn\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector::class); + $services->set(\Rector\EarlyReturn\Rector\If_\ChangeNestedIfsToEarlyReturnRector::class); + $services->set(\Rector\EarlyReturn\Rector\If_\RemoveAlwaysElseRector::class); + $services->set(\Rector\EarlyReturn\Rector\Return_\ReturnBinaryAndToEarlyReturnRector::class); + $services->set(\Rector\EarlyReturn\Rector\If_\ChangeOrIfReturnToEarlyReturnRector::class); + $services->set(\Rector\EarlyReturn\Rector\If_\ChangeOrIfContinueToMultiContinueRector::class); + $services->set(\Rector\EarlyReturn\Rector\Foreach_\ReturnAfterToEarlyOnBreakRector::class); + $services->set(\Rector\EarlyReturn\Rector\Return_\PreparedValueToEarlyReturnRector::class); + $services->set(\Rector\EarlyReturn\Rector\Return_\ReturnBinaryOrToEarlyReturnRector::class); }; diff --git a/config/set/flysystem-20.php b/config/set/flysystem-20.php index 53c18417811..5d4eb11aec8 100644 --- a/config/set/flysystem-20.php +++ b/config/set/flysystem-20.php @@ -1,35 +1,29 @@ services(); - $services->set(RenameMethodRector::class) - ->call('configure', [[ - RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([ - // Rename is now move, specific for files. - new MethodCallRename('League\Flysystem\Filesystem', 'rename', 'move'), - - // No arbitrary abbreviations - new MethodCallRename('League\Flysystem\Filesystem', 'createDir', 'createDirectory'), - - // Writes are now deterministic - new MethodCallRename('League\Flysystem\Filesystem', 'update', 'write'), - new MethodCallRename('League\Flysystem\Filesystem', 'updateStream', 'writeStream'), - new MethodCallRename('League\Flysystem\Filesystem', 'put', 'write'), - new MethodCallRename('League\Flysystem\Filesystem', 'putStream', 'writeStream'), - - // Metadata getters are renamed - new MethodCallRename('League\Flysystem\Filesystem', 'getTimestamp', 'lastModified'), - new MethodCallRename('League\Flysystem\Filesystem', 'has', 'fileExists'), - new MethodCallRename('League\Flysystem\Filesystem', 'getMimetype', 'mimeType'), - new MethodCallRename('League\Flysystem\Filesystem', 'getSize', 'fileSize'), - new MethodCallRename('League\Flysystem\Filesystem', 'getVisibility', 'visibility'), - ]), - ]]); + $services->set(\Rector\Renaming\Rector\MethodCall\RenameMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\MethodCall\RenameMethodRector::METHOD_CALL_RENAMES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([ + // Rename is now move, specific for files. + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'rename', 'move'), + // No arbitrary abbreviations + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'createDir', 'createDirectory'), + // Writes are now deterministic + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'update', 'write'), + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'updateStream', 'writeStream'), + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'put', 'write'), + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'putStream', 'writeStream'), + // Metadata getters are renamed + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'getTimestamp', 'lastModified'), + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'has', 'fileExists'), + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'getMimetype', 'mimeType'), + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'getSize', 'fileSize'), + new \Rector\Renaming\ValueObject\MethodCallRename('League\\Flysystem\\Filesystem', 'getVisibility', 'visibility'), + ])]]); }; diff --git a/config/set/framework-extra-bundle-40.php b/config/set/framework-extra-bundle-40.php index 370ad991e02..35603562649 100644 --- a/config/set/framework-extra-bundle-40.php +++ b/config/set/framework-extra-bundle-40.php @@ -1,14 +1,13 @@ services(); - $services->set(ReplaceSensioRouteAnnotationWithSymfonyRector::class); - - $services->set(RemoveServiceFromSensioRouteRector::class); + $services->set(\Rector\Symfony\Rector\ClassMethod\ReplaceSensioRouteAnnotationWithSymfonyRector::class); + $services->set(\Rector\Symfony\Rector\ClassMethod\RemoveServiceFromSensioRouteRector::class); }; diff --git a/config/set/framework-extra-bundle-50.php b/config/set/framework-extra-bundle-50.php index c1e4fb90e73..5e92595d85c 100644 --- a/config/set/framework-extra-bundle-50.php +++ b/config/set/framework-extra-bundle-50.php @@ -1,11 +1,11 @@ services(); - $services->set(TemplateAnnotationToThisRenderRector::class); + $services->set(\Rector\Symfony\Rector\ClassMethod\TemplateAnnotationToThisRenderRector::class); }; diff --git a/config/set/gmagick_to_imagick.php b/config/set/gmagick_to_imagick.php index 0b599b7421c..f2bc16ad6b1 100644 --- a/config/set/gmagick_to_imagick.php +++ b/config/set/gmagick_to_imagick.php @@ -1,167 +1,16 @@ services(); - $services->set(RenameClassRector::class) - ->call('configure', [[ - RenameClassRector::OLD_TO_NEW_CLASSES => [ - 'Gmagick' => 'Imagick', - 'GmagickPixel' => 'ImagickPixel', - ], - ]]); - - $services->set(RenameMethodRector::class) - ->call('configure', [[ - RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([ - new MethodCallRename('Gmagick', 'addimage', 'addImage'), - new MethodCallRename('Gmagick', 'addnoiseimage', 'addNoiseImage'), - new MethodCallRename('Gmagick', 'annotateimage', 'annotateImage'), - new MethodCallRename('Gmagick', 'blurimage', 'blurImage'), - new MethodCallRename('Gmagick', 'borderimage', 'borderImage'), - new MethodCallRename('Gmagick', 'charcoalimage', 'charcoalImage'), - new MethodCallRename('Gmagick', 'chopimage', 'chopImage'), - new MethodCallRename('Gmagick', 'commentimage', 'commentImage'), - new MethodCallRename('Gmagick', 'compositeimage', 'compositeImage'), - new MethodCallRename('Gmagick', 'cropimage', 'cropImage'), - new MethodCallRename('Gmagick', 'cropthumbnailimage', 'cropThumbnailImage'), - new MethodCallRename('Gmagick', 'cyclecolormapimage', 'cycleColormapImage'), - new MethodCallRename('Gmagick', 'deconstructimages', 'deconstructImages'), - new MethodCallRename('Gmagick', 'despeckleimage', 'despeckleImage'), - new MethodCallRename('Gmagick', 'drawimage', 'drawImage'), - new MethodCallRename('Gmagick', 'edgeimage', 'edgeImage'), - new MethodCallRename('Gmagick', 'embossimage', 'embossImage'), - new MethodCallRename('Gmagick', 'enhanceimage', 'enhanceImage'), - new MethodCallRename('Gmagick', 'equalizeimage', 'equalizeImage'), - new MethodCallRename('Gmagick', 'flipimage', 'flipImage'), - new MethodCallRename('Gmagick', 'flopimage', 'flopImage'), - new MethodCallRename('Gmagick', 'frameimage', 'frameImage'), - new MethodCallRename('Gmagick', 'gammaimage', 'gammaImage'), - new MethodCallRename('Gmagick', 'getcopyright', 'getCopyright'), - new MethodCallRename('Gmagick', 'getfilename', 'getFilename'), - new MethodCallRename('Gmagick', 'getimagebackgroundcolor', 'getImageBackgroundColor'), - new MethodCallRename('Gmagick', 'getimageblueprimary', 'getImageBluePrimary'), - new MethodCallRename('Gmagick', 'getimagebordercolor', 'getImageBorderColor'), - new MethodCallRename('Gmagick', 'getimagechanneldepth', 'getImageChannelDepth'), - new MethodCallRename('Gmagick', 'getimagecolors', 'getImageColors'), - new MethodCallRename('Gmagick', 'getimagecolorspace', 'getImageColorspace'), - new MethodCallRename('Gmagick', 'getimagecompose', 'getImageCompose'), - new MethodCallRename('Gmagick', 'getimagedelay', 'getImageDelay'), - new MethodCallRename('Gmagick', 'getimagedepth', 'getImageDepth'), - new MethodCallRename('Gmagick', 'getimagedispose', 'getImageDispose'), - new MethodCallRename('Gmagick', 'getimageextrema', 'getImageExtrema'), - new MethodCallRename('Gmagick', 'getimagefilename', 'getImageFilename'), - new MethodCallRename('Gmagick', 'getimageformat', 'getImageFormat'), - new MethodCallRename('Gmagick', 'getimagegamma', 'getImageGamma'), - new MethodCallRename('Gmagick', 'getimagegreenprimary', 'getImageGreenPrimary'), - new MethodCallRename('Gmagick', 'getimageheight', 'getImageHeight'), - new MethodCallRename('Gmagick', 'getimagehistogram', 'getImageHistogram'), - new MethodCallRename('Gmagick', 'getimageindex', 'getImageIndex'), - new MethodCallRename('Gmagick', 'getimageinterlacescheme', 'getImageInterlaceScheme'), - new MethodCallRename('Gmagick', 'getimageiterations', 'getImageIterations'), - new MethodCallRename('Gmagick', 'getimagematte', 'getImageMatte'), - new MethodCallRename('Gmagick', 'getimagemattecolor', 'getImageMatteColor'), - new MethodCallRename('Gmagick', 'getimageprofile', 'getImageProfile'), - new MethodCallRename('Gmagick', 'getimageredprimary', 'getImageRedPrimary'), - new MethodCallRename('Gmagick', 'getimagerenderingintent', 'getImageRenderingIntent'), - new MethodCallRename('Gmagick', 'getimageresolution', 'getImageResolution'), - new MethodCallRename('Gmagick', 'getimagescene', 'getImageScene'), - new MethodCallRename('Gmagick', 'getimagesignature', 'getImageSignature'), - new MethodCallRename('Gmagick', 'getimagetype', 'getImageType'), - new MethodCallRename('Gmagick', 'getimageunits', 'getImageUnits'), - new MethodCallRename('Gmagick', 'getimagewhitepoint', 'getImageWhitePoint'), - new MethodCallRename('Gmagick', 'getimagewidth', 'getImageWidth'), - new MethodCallRename('Gmagick', 'getpackagename', 'getPackageName'), - new MethodCallRename('Gmagick', 'getquantumdepth', 'getQuantumDepth'), - new MethodCallRename('Gmagick', 'getreleasedate', 'getReleaseDate'), - new MethodCallRename('Gmagick', 'getsamplingfactors', 'getSamplingFactors'), - new MethodCallRename('Gmagick', 'getsize', 'getSize'), - new MethodCallRename('Gmagick', 'getversion', 'getVersion'), - new MethodCallRename('Gmagick', 'hasnextimage', 'hasNextImage'), - new MethodCallRename('Gmagick', 'haspreviousimage', 'hasPreviousImage'), - new MethodCallRename('Gmagick', 'implodeimage', 'implodeImage'), - new MethodCallRename('Gmagick', 'labelimage', 'labelImage'), - new MethodCallRename('Gmagick', 'levelimage', 'levelImage'), - new MethodCallRename('Gmagick', 'magnifyimage', 'magnifyImage'), - new MethodCallRename('Gmagick', 'mapimage', 'mapImage'), - new MethodCallRename('Gmagick', 'medianfilterimage', 'medianFilterImage'), - new MethodCallRename('Gmagick', 'minifyimage', 'minifyImage'), - new MethodCallRename('Gmagick', 'modulateimage', 'modulateImage'), - new MethodCallRename('Gmagick', 'motionblurimage', 'motionBlurImage'), - new MethodCallRename('Gmagick', 'newimage', 'newImage'), - new MethodCallRename('Gmagick', 'nextimage', 'nextImage'), - new MethodCallRename('Gmagick', 'normalizeimage', 'normalizeImage'), - new MethodCallRename('Gmagick', 'oilpaintimage', 'oilPaintImage'), - new MethodCallRename('Gmagick', 'previousimage', 'previousImage'), - new MethodCallRename('Gmagick', 'profileimage', 'profileImage'), - new MethodCallRename('Gmagick', 'quantizeimage', 'quantizeImage'), - new MethodCallRename('Gmagick', 'quantizeimages', 'quantizeImages'), - new MethodCallRename('Gmagick', 'queryfontmetrics', 'queryFontMetrics'), - new MethodCallRename('Gmagick', 'queryfonts', 'queryFonts'), - new MethodCallRename('Gmagick', 'queryformats', 'queryFormats'), - new MethodCallRename('Gmagick', 'radialblurimage', 'radialBlurImage'), - new MethodCallRename('Gmagick', 'raiseimage', 'raiseImage'), - new MethodCallRename('Gmagick', 'readimage', 'readimages'), - new MethodCallRename('Gmagick', 'readimageblob', 'readImageBlob'), - new MethodCallRename('Gmagick', 'readimagefile', 'readImageFile'), - new MethodCallRename('Gmagick', 'reducenoiseimage', 'reduceNoiseImage'), - new MethodCallRename('Gmagick', 'removeimage', 'removeImage'), - new MethodCallRename('Gmagick', 'removeimageprofile', 'removeImageProfile'), - new MethodCallRename('Gmagick', 'resampleimage', 'resampleImage'), - new MethodCallRename('Gmagick', 'resizeimage', 'resizeImage'), - new MethodCallRename('Gmagick', 'rollimage', 'rollImage'), - new MethodCallRename('Gmagick', 'rotateimage', 'rotateImage'), - new MethodCallRename('Gmagick', 'scaleimage', 'scaleImage'), - new MethodCallRename('Gmagick', 'separateimagechannel', 'separateImageChannel'), - new MethodCallRename('Gmagick', 'setCompressionQuality', 'getCompressionQuality'), - new MethodCallRename('Gmagick', 'setfilename', 'setFilename'), - new MethodCallRename('Gmagick', 'setimagebackgroundcolor', 'setImageBackgroundColor'), - new MethodCallRename('Gmagick', 'setimageblueprimary', 'setImageBluePrimary'), - new MethodCallRename('Gmagick', 'setimagebordercolor', 'setImageBorderColor'), - new MethodCallRename('Gmagick', 'setimagechanneldepth', 'setImageChannelDepth'), - new MethodCallRename('Gmagick', 'setimagecolorspace', 'setImageColorspace'), - new MethodCallRename('Gmagick', 'setimagecompose', 'setImageCompose'), - new MethodCallRename('Gmagick', 'setimagedelay', 'setImageDelay'), - new MethodCallRename('Gmagick', 'setimagedepth', 'setImageDepth'), - new MethodCallRename('Gmagick', 'setimagedispose', 'setImageDispose'), - new MethodCallRename('Gmagick', 'setimagefilename', 'setImageFilename'), - new MethodCallRename('Gmagick', 'setimageformat', 'setImageFormat'), - new MethodCallRename('Gmagick', 'setimagegamma', 'setImageGamma'), - new MethodCallRename('Gmagick', 'setimagegreenprimary', 'setImageGreenPrimary'), - new MethodCallRename('Gmagick', 'setimageindex', 'setImageIndex'), - new MethodCallRename('Gmagick', 'setimageinterlacescheme', 'setImageInterlaceScheme'), - new MethodCallRename('Gmagick', 'setimageiterations', 'setImageIterations'), - new MethodCallRename('Gmagick', 'setimageprofile', 'setImageProfile'), - new MethodCallRename('Gmagick', 'setimageredprimary', 'setImageRedPrimary'), - new MethodCallRename('Gmagick', 'setimagerenderingintent', 'setImageRenderingIntent'), - new MethodCallRename('Gmagick', 'setimageresolution', 'setImageResolution'), - new MethodCallRename('Gmagick', 'setimagescene', 'setImageScene'), - new MethodCallRename('Gmagick', 'setimagetype', 'setImageType'), - new MethodCallRename('Gmagick', 'setimageunits', 'setImageUnits'), - new MethodCallRename('Gmagick', 'setimagewhitepoint', 'setImageWhitePoint'), - new MethodCallRename('Gmagick', 'setsamplingfactors', 'setSamplingFactors'), - new MethodCallRename('Gmagick', 'setsize', 'setSize'), - new MethodCallRename('Gmagick', 'shearimage', 'shearImage'), - new MethodCallRename('Gmagick', 'solarizeimage', 'solarizeImage'), - new MethodCallRename('Gmagick', 'spreadimage', 'spreadImage'), - new MethodCallRename('Gmagick', 'stripimage', 'stripImage'), - new MethodCallRename('Gmagick', 'swirlimage', 'swirlImage'), - new MethodCallRename('Gmagick', 'thumbnailimage', 'thumbnailImage'), - new MethodCallRename('Gmagick', 'trimimage', 'trimImage'), - new MethodCallRename('Gmagick', 'writeimage', 'writeImage'), - new MethodCallRename('GmagickPixel', 'getcolor', 'getColor'), - new MethodCallRename('GmagickPixel', 'getcolorcount', 'getColorCount'), - new MethodCallRename('GmagickPixel', 'getcolorvalue', 'getColorValue'), - new MethodCallRename('GmagickPixel', 'setcolor', 'setColor'), - new MethodCallRename('GmagickPixel', 'setcolorvalue', 'setColorValue'), - ]), - ]]); + $services->set(\Rector\Renaming\Rector\Name\RenameClassRector::class)->call('configure', [[\Rector\Renaming\Rector\Name\RenameClassRector::OLD_TO_NEW_CLASSES => ['Gmagick' => 'Imagick', 'GmagickPixel' => 'ImagickPixel']]]); + $services->set(\Rector\Renaming\Rector\MethodCall\RenameMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\MethodCall\RenameMethodRector::METHOD_CALL_RENAMES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'addimage', 'addImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'addnoiseimage', 'addNoiseImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'annotateimage', 'annotateImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'blurimage', 'blurImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'borderimage', 'borderImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'charcoalimage', 'charcoalImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'chopimage', 'chopImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'commentimage', 'commentImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'compositeimage', 'compositeImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'cropimage', 'cropImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'cropthumbnailimage', 'cropThumbnailImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'cyclecolormapimage', 'cycleColormapImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'deconstructimages', 'deconstructImages'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'despeckleimage', 'despeckleImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'drawimage', 'drawImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'edgeimage', 'edgeImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'embossimage', 'embossImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'enhanceimage', 'enhanceImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'equalizeimage', 'equalizeImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'flipimage', 'flipImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'flopimage', 'flopImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'frameimage', 'frameImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'gammaimage', 'gammaImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getcopyright', 'getCopyright'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getfilename', 'getFilename'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagebackgroundcolor', 'getImageBackgroundColor'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageblueprimary', 'getImageBluePrimary'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagebordercolor', 'getImageBorderColor'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagechanneldepth', 'getImageChannelDepth'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagecolors', 'getImageColors'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagecolorspace', 'getImageColorspace'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagecompose', 'getImageCompose'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagedelay', 'getImageDelay'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagedepth', 'getImageDepth'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagedispose', 'getImageDispose'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageextrema', 'getImageExtrema'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagefilename', 'getImageFilename'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageformat', 'getImageFormat'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagegamma', 'getImageGamma'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagegreenprimary', 'getImageGreenPrimary'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageheight', 'getImageHeight'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagehistogram', 'getImageHistogram'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageindex', 'getImageIndex'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageinterlacescheme', 'getImageInterlaceScheme'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageiterations', 'getImageIterations'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagematte', 'getImageMatte'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagemattecolor', 'getImageMatteColor'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageprofile', 'getImageProfile'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageredprimary', 'getImageRedPrimary'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagerenderingintent', 'getImageRenderingIntent'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageresolution', 'getImageResolution'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagescene', 'getImageScene'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagesignature', 'getImageSignature'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagetype', 'getImageType'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimageunits', 'getImageUnits'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagewhitepoint', 'getImageWhitePoint'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getimagewidth', 'getImageWidth'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getpackagename', 'getPackageName'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getquantumdepth', 'getQuantumDepth'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getreleasedate', 'getReleaseDate'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getsamplingfactors', 'getSamplingFactors'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getsize', 'getSize'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'getversion', 'getVersion'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'hasnextimage', 'hasNextImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'haspreviousimage', 'hasPreviousImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'implodeimage', 'implodeImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'labelimage', 'labelImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'levelimage', 'levelImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'magnifyimage', 'magnifyImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'mapimage', 'mapImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'medianfilterimage', 'medianFilterImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'minifyimage', 'minifyImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'modulateimage', 'modulateImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'motionblurimage', 'motionBlurImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'newimage', 'newImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'nextimage', 'nextImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'normalizeimage', 'normalizeImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'oilpaintimage', 'oilPaintImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'previousimage', 'previousImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'profileimage', 'profileImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'quantizeimage', 'quantizeImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'quantizeimages', 'quantizeImages'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'queryfontmetrics', 'queryFontMetrics'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'queryfonts', 'queryFonts'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'queryformats', 'queryFormats'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'radialblurimage', 'radialBlurImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'raiseimage', 'raiseImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'readimage', 'readimages'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'readimageblob', 'readImageBlob'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'readimagefile', 'readImageFile'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'reducenoiseimage', 'reduceNoiseImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'removeimage', 'removeImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'removeimageprofile', 'removeImageProfile'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'resampleimage', 'resampleImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'resizeimage', 'resizeImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'rollimage', 'rollImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'rotateimage', 'rotateImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'scaleimage', 'scaleImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'separateimagechannel', 'separateImageChannel'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setCompressionQuality', 'getCompressionQuality'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setfilename', 'setFilename'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagebackgroundcolor', 'setImageBackgroundColor'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimageblueprimary', 'setImageBluePrimary'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagebordercolor', 'setImageBorderColor'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagechanneldepth', 'setImageChannelDepth'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagecolorspace', 'setImageColorspace'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagecompose', 'setImageCompose'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagedelay', 'setImageDelay'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagedepth', 'setImageDepth'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagedispose', 'setImageDispose'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagefilename', 'setImageFilename'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimageformat', 'setImageFormat'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagegamma', 'setImageGamma'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagegreenprimary', 'setImageGreenPrimary'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimageindex', 'setImageIndex'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimageinterlacescheme', 'setImageInterlaceScheme'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimageiterations', 'setImageIterations'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimageprofile', 'setImageProfile'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimageredprimary', 'setImageRedPrimary'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagerenderingintent', 'setImageRenderingIntent'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimageresolution', 'setImageResolution'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagescene', 'setImageScene'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagetype', 'setImageType'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimageunits', 'setImageUnits'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setimagewhitepoint', 'setImageWhitePoint'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setsamplingfactors', 'setSamplingFactors'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'setsize', 'setSize'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'shearimage', 'shearImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'solarizeimage', 'solarizeImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'spreadimage', 'spreadImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'stripimage', 'stripImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'swirlimage', 'swirlImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'thumbnailimage', 'thumbnailImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'trimimage', 'trimImage'), new \Rector\Renaming\ValueObject\MethodCallRename('Gmagick', 'writeimage', 'writeImage'), new \Rector\Renaming\ValueObject\MethodCallRename('GmagickPixel', 'getcolor', 'getColor'), new \Rector\Renaming\ValueObject\MethodCallRename('GmagickPixel', 'getcolorcount', 'getColorCount'), new \Rector\Renaming\ValueObject\MethodCallRename('GmagickPixel', 'getcolorvalue', 'getColorValue'), new \Rector\Renaming\ValueObject\MethodCallRename('GmagickPixel', 'setcolor', 'setColor'), new \Rector\Renaming\ValueObject\MethodCallRename('GmagickPixel', 'setcolorvalue', 'setColorValue')])]]); }; diff --git a/config/set/guzzle50.php b/config/set/guzzle50.php index 938d87aaf45..b73ba35a0a6 100644 --- a/config/set/guzzle50.php +++ b/config/set/guzzle50.php @@ -1,6 +1,7 @@ services(); - # both uses "%classes_to_defluent% - $services->set(FluentChainMethodCallToNormalMethodCallRector::class); - - $configuration = [ - new FuncCallToMethodCall('GuzzleHttp\json_decode', 'GuzzleHttp\Utils', 'jsonDecode'), - new FuncCallToMethodCall('GuzzleHttp\get_path', 'GuzzleHttp\Utils', 'getPath'), - ]; - - $services->set(FuncCallToMethodCallRector::class) - ->call('configure', [[ - FuncCallToMethodCallRector::FUNC_CALL_TO_CLASS_METHOD_CALL => ValueObjectInliner::inline($configuration), - ]]); - - $services->set(StaticCallToFuncCallRector::class) - ->call('configure', [[ - StaticCallToFuncCallRector::STATIC_CALLS_TO_FUNCTIONS => ValueObjectInliner::inline([ - new StaticCallToFuncCall('GuzzleHttp\Utils', 'setPath', 'GuzzleHttp\set_path'), - new StaticCallToFuncCall('GuzzleHttp\Pool', 'batch', 'GuzzleHttp\Pool\batch'), - ]), - ]]); - - $services->set(RenameMethodRector::class) - ->call('configure', [[ - RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([ - new MethodCallRename('GuzzleHttp\Message\MessageInterface', 'getHeaderLines', 'getHeaderAsArray'), - ]), - ]]); + $services->set(\Rector\Defluent\Rector\MethodCall\FluentChainMethodCallToNormalMethodCallRector::class); + $configuration = [new \Rector\Transform\ValueObject\FuncCallToMethodCall('GuzzleHttp\\json_decode', 'GuzzleHttp\\Utils', 'jsonDecode'), new \Rector\Transform\ValueObject\FuncCallToMethodCall('GuzzleHttp\\get_path', 'GuzzleHttp\\Utils', 'getPath')]; + $services->set(\Rector\Transform\Rector\FuncCall\FuncCallToMethodCallRector::class)->call('configure', [[\Rector\Transform\Rector\FuncCall\FuncCallToMethodCallRector::FUNC_CALL_TO_CLASS_METHOD_CALL => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline($configuration)]]); + $services->set(\Rector\Transform\Rector\StaticCall\StaticCallToFuncCallRector::class)->call('configure', [[\Rector\Transform\Rector\StaticCall\StaticCallToFuncCallRector::STATIC_CALLS_TO_FUNCTIONS => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Transform\ValueObject\StaticCallToFuncCall('GuzzleHttp\\Utils', 'setPath', 'GuzzleHttp\\set_path'), new \Rector\Transform\ValueObject\StaticCallToFuncCall('GuzzleHttp\\Pool', 'batch', 'GuzzleHttp\\Pool\\batch')])]]); + $services->set(\Rector\Renaming\Rector\MethodCall\RenameMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\MethodCall\RenameMethodRector::METHOD_CALL_RENAMES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Renaming\ValueObject\MethodCallRename('GuzzleHttp\\Message\\MessageInterface', 'getHeaderLines', 'getHeaderAsArray')])]]); }; diff --git a/config/set/kdyby-to-symfony.php b/config/set/kdyby-to-symfony.php index 32edea5c00e..22fe699887b 100644 --- a/config/set/kdyby-to-symfony.php +++ b/config/set/kdyby-to-symfony.php @@ -1,6 +1,7 @@ services(); - $services->set(ChangeMethodVisibilityRector::class) - ->call('configure', [[ - ChangeMethodVisibilityRector::METHOD_VISIBILITIES => ValueObjectInliner::inline([ - new ChangeMethodVisibility('Kdyby\Events\Subscriber', 'getSubscribedEvents', Visibility::STATIC), - ]), - ]]); - - $services->set(RenameMethodRector::class) - ->call('configure', [[ - RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([ - new MethodCallRename('Kdyby\Translation\Translator', 'translate', 'trans'), - new MethodCallRename('Kdyby\RabbitMq\IConsumer', 'process', 'execute'), - ]), - ]]); - - $services->set(RenameClassRector::class) - ->call('configure', [[ - RenameClassRector::OLD_TO_NEW_CLASSES => [ - 'Kdyby\RabbitMq\IConsumer' => 'OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface', - 'Kdyby\RabbitMq\IProducer' => 'OldSound\RabbitMqBundle\RabbitMq\ProducerInterface', - 'Kdyby\Monolog\Logger' => 'Psr\Log\LoggerInterface', - 'Kdyby\Events\Subscriber' => 'Symfony\Component\EventDispatcher\EventSubscriberInterface', - 'Kdyby\Translation\Translator' => 'Symfony\Contracts\Translation\TranslatorInterface', - ], - ]]); - - $services->set(WrapTransParameterNameRector::class); + $services->set(\Rector\Visibility\Rector\ClassMethod\ChangeMethodVisibilityRector::class)->call('configure', [[\Rector\Visibility\Rector\ClassMethod\ChangeMethodVisibilityRector::METHOD_VISIBILITIES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Visibility\ValueObject\ChangeMethodVisibility('Kdyby\\Events\\Subscriber', 'getSubscribedEvents', \Rector\Core\ValueObject\Visibility::STATIC)])]]); + $services->set(\Rector\Renaming\Rector\MethodCall\RenameMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\MethodCall\RenameMethodRector::METHOD_CALL_RENAMES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Renaming\ValueObject\MethodCallRename('Kdyby\\Translation\\Translator', 'translate', 'trans'), new \Rector\Renaming\ValueObject\MethodCallRename('Kdyby\\RabbitMq\\IConsumer', 'process', 'execute')])]]); + $services->set(\Rector\Renaming\Rector\Name\RenameClassRector::class)->call('configure', [[\Rector\Renaming\Rector\Name\RenameClassRector::OLD_TO_NEW_CLASSES => ['Kdyby\\RabbitMq\\IConsumer' => 'OldSound\\RabbitMqBundle\\RabbitMq\\ConsumerInterface', 'Kdyby\\RabbitMq\\IProducer' => 'OldSound\\RabbitMqBundle\\RabbitMq\\ProducerInterface', 'Kdyby\\Monolog\\Logger' => 'Psr\\Log\\LoggerInterface', 'Kdyby\\Events\\Subscriber' => 'Symfony\\Component\\EventDispatcher\\EventSubscriberInterface', 'Kdyby\\Translation\\Translator' => 'Symfony\\Contracts\\Translation\\TranslatorInterface']]]); + $services->set(\Rector\NetteToSymfony\Rector\MethodCall\WrapTransParameterNameRector::class); }; diff --git a/config/set/league-event-30.php b/config/set/league-event-30.php index fe3db7ac0d9..170681dda51 100644 --- a/config/set/league-event-30.php +++ b/config/set/league-event-30.php @@ -1,6 +1,7 @@ parameters(); - $parameters->set(Option::AUTO_IMPORT_NAMES, true); - + $parameters->set(\Rector\Core\Configuration\Option::AUTO_IMPORT_NAMES, \true); $services = $containerConfigurator->services(); - $services->set(ChangePackageVersionComposerRector::class) - ->call('configure', [[ - ChangePackageVersionComposerRector::PACKAGES_AND_VERSIONS => ValueObjectInliner::inline([ - new PackageAndVersion('league/event', '^3.0'), - ]), - ]]); - - $services->set(RenameMethodRector::class) - ->call('configure', [[ - RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([ - new MethodCallRename('League\Event\EventInterface', 'getName', 'eventName'), - new MethodCallRename('League\Event\EmitterInterface', 'emit', 'dispatch'), - new MethodCallRename('League\Event\EmitterInterface', 'addListener', 'subscribeTo'), - new MethodCallRename('League\Event\EmitterInterface', 'addOneTimeListener', 'subscribeOneTo'), - new MethodCallRename('League\Event\EmitterInterface', 'useListenerProvider', 'subscribeListenersFrom'), - new MethodCallRename('League\Event\ListenerInterface', 'handle', '__invoke'), - ]), - ]]); - - $services->set(AddParamTypeDeclarationRector::class) - ->call('configure', [[ - AddParamTypeDeclarationRector::PARAMETER_TYPEHINTS => ValueObjectInliner::inline([ - new AddParamTypeDeclaration( - 'League\Event\ListenerInterface', - '__invoke', - 0, - new ObjectWithoutClassType() - ), - ]), - ]]); - - $services->set(AddReturnTypeDeclarationRector::class) - ->call('configure', [[ - AddReturnTypeDeclarationRector::METHOD_RETURN_TYPES => ValueObjectInliner::inline([ - new AddReturnTypeDeclaration('League\Event\EventInterface', 'eventName', new StringType()), - new AddReturnTypeDeclaration('League\Event\ListenerInterface', '__invoke', new VoidType()), - ]), - ]]); - - $services->set(RenameClassRector::class) - ->call('configure', [[ - RenameClassRector::OLD_TO_NEW_CLASSES => [ - 'League\Event\Emitter' => 'League\Event\EventDispatcher', - 'League\Event\ListenerInterface' => 'League\Event\Listener', - 'League\Event\GeneratorInterface' => 'League\Event\EventGenerator', - 'League\Event\ListenerProviderInterface' => 'League\Event\ListenerSubscriber', - 'League\Event\ListenerAcceptorInterface' => 'League\Event\ListenerRegistry', - ], - ]]); - - $services->set(AddInterfaceByParentRector::class) - ->call('configure', [[ - AddInterfaceByParentRector::INTERFACE_BY_PARENT => [ - 'League\Event\Event' => 'League\Event\HasEventName', - 'League\Event\AbstractListener' => 'League\Event\Listener', - ], - ]]); - - $services->set(RemoveInterfacesRector::class) - ->call('configure', [[ - RemoveInterfacesRector::INTERFACES_TO_REMOVE => ['League\Event\EventInterface'], - ]]); - - $services->set(RemoveParentRector::class) - ->call('configure', [[ - RemoveParentRector::PARENT_TYPES_TO_REMOVE => [ - 'League\Event\AbstractEvent', - 'League\Event\Event', - 'League\Event\AbstractListener', - ], - ]]); - - $services->set(DispatchStringToObjectRector::class); + $services->set(\Rector\Composer\Rector\ChangePackageVersionComposerRector::class)->call('configure', [[\Rector\Composer\Rector\ChangePackageVersionComposerRector::PACKAGES_AND_VERSIONS => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Composer\ValueObject\PackageAndVersion('league/event', '^3.0')])]]); + $services->set(\Rector\Renaming\Rector\MethodCall\RenameMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\MethodCall\RenameMethodRector::METHOD_CALL_RENAMES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Renaming\ValueObject\MethodCallRename('League\\Event\\EventInterface', 'getName', 'eventName'), new \Rector\Renaming\ValueObject\MethodCallRename('League\\Event\\EmitterInterface', 'emit', 'dispatch'), new \Rector\Renaming\ValueObject\MethodCallRename('League\\Event\\EmitterInterface', 'addListener', 'subscribeTo'), new \Rector\Renaming\ValueObject\MethodCallRename('League\\Event\\EmitterInterface', 'addOneTimeListener', 'subscribeOneTo'), new \Rector\Renaming\ValueObject\MethodCallRename('League\\Event\\EmitterInterface', 'useListenerProvider', 'subscribeListenersFrom'), new \Rector\Renaming\ValueObject\MethodCallRename('League\\Event\\ListenerInterface', 'handle', '__invoke')])]]); + $services->set(\Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector::class)->call('configure', [[\Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector::PARAMETER_TYPEHINTS => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\TypeDeclaration\ValueObject\AddParamTypeDeclaration('League\\Event\\ListenerInterface', '__invoke', 0, new \PHPStan\Type\ObjectWithoutClassType())])]]); + $services->set(\Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationRector::class)->call('configure', [[\Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationRector::METHOD_RETURN_TYPES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\TypeDeclaration\ValueObject\AddReturnTypeDeclaration('League\\Event\\EventInterface', 'eventName', new \PHPStan\Type\StringType()), new \Rector\TypeDeclaration\ValueObject\AddReturnTypeDeclaration('League\\Event\\ListenerInterface', '__invoke', new \PHPStan\Type\VoidType())])]]); + $services->set(\Rector\Renaming\Rector\Name\RenameClassRector::class)->call('configure', [[\Rector\Renaming\Rector\Name\RenameClassRector::OLD_TO_NEW_CLASSES => ['League\\Event\\Emitter' => 'League\\Event\\EventDispatcher', 'League\\Event\\ListenerInterface' => 'League\\Event\\Listener', 'League\\Event\\GeneratorInterface' => 'League\\Event\\EventGenerator', 'League\\Event\\ListenerProviderInterface' => 'League\\Event\\ListenerSubscriber', 'League\\Event\\ListenerAcceptorInterface' => 'League\\Event\\ListenerRegistry']]]); + $services->set(\Rector\Transform\Rector\Class_\AddInterfaceByParentRector::class)->call('configure', [[\Rector\Transform\Rector\Class_\AddInterfaceByParentRector::INTERFACE_BY_PARENT => ['League\\Event\\Event' => 'League\\Event\\HasEventName', 'League\\Event\\AbstractListener' => 'League\\Event\\Listener']]]); + $services->set(\Rector\Removing\Rector\Class_\RemoveInterfacesRector::class)->call('configure', [[\Rector\Removing\Rector\Class_\RemoveInterfacesRector::INTERFACES_TO_REMOVE => ['League\\Event\\EventInterface']]]); + $services->set(\Rector\Removing\Rector\Class_\RemoveParentRector::class)->call('configure', [[\Rector\Removing\Rector\Class_\RemoveParentRector::PARENT_TYPES_TO_REMOVE => ['League\\Event\\AbstractEvent', 'League\\Event\\Event', 'League\\Event\\AbstractListener']]]); + $services->set(\Rector\LeagueEvent\Rector\MethodCall\DispatchStringToObjectRector::class); }; diff --git a/config/set/monolog20.php b/config/set/monolog20.php index 2088db9f9c2..960c0611539 100644 --- a/config/set/monolog20.php +++ b/config/set/monolog20.php @@ -1,30 +1,14 @@ services(); - $services->set(RenameMethodRector::class) - ->call('configure', [[ - RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([ - new MethodCallRename('Monolog\Logger', 'addDebug', 'debug'), - new MethodCallRename('Monolog\Logger', 'addInfo', 'info'), - new MethodCallRename('Monolog\Logger', 'addNotice', 'notice'), - new MethodCallRename('Monolog\Logger', 'addWarning', 'warning'), - new MethodCallRename('Monolog\Logger', 'addError', 'error'), - new MethodCallRename('Monolog\Logger', 'addCritical', 'critical'), - new MethodCallRename('Monolog\Logger', 'addAlert', 'alert'), - new MethodCallRename('Monolog\Logger', 'addEmergency', 'emergency'), - new MethodCallRename('Monolog\Logger', 'warn', 'warning'), - new MethodCallRename('Monolog\Logger', 'err', 'error'), - new MethodCallRename('Monolog\Logger', 'crit', 'critical'), - new MethodCallRename('Monolog\Logger', 'emerg', 'emergency'), - ]), - ]]); + $services->set(\Rector\Renaming\Rector\MethodCall\RenameMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\MethodCall\RenameMethodRector::METHOD_CALL_RENAMES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'addDebug', 'debug'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'addInfo', 'info'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'addNotice', 'notice'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'addWarning', 'warning'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'addError', 'error'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'addCritical', 'critical'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'addAlert', 'alert'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'addEmergency', 'emergency'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'warn', 'warning'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'err', 'error'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'crit', 'critical'), new \Rector\Renaming\ValueObject\MethodCallRename('Monolog\\Logger', 'emerg', 'emergency')])]]); }; diff --git a/config/set/mysql-to-mysqli.php b/config/set/mysql-to-mysqli.php index 46b178086bf..e2a93acc9cd 100644 --- a/config/set/mysql-to-mysqli.php +++ b/config/set/mysql-to-mysqli.php @@ -1,6 +1,7 @@ services(); - # https://stackoverflow.com/a/1390625/1348344 # https://github.com/philip/MySQLConverterTool/blob/master/Converter.php # https://www.phpclasses.org/blog/package/9199/post/3-Smoothly-Migrate-your-PHP-Code-using-the-Old-MySQL-extension-to-MySQLi.html - $services->set(MysqlAssignToMysqliRector::class); - - $services->set(MysqlFuncCallToMysqliRector::class); - - $services->set(RemoveFuncCallArgRector::class) - ->call('configure', [[ - RemoveFuncCallArgRector::REMOVED_FUNCTION_ARGUMENTS => ValueObjectInliner::inline([ - new RemoveFuncCallArg('mysql_pconnect', 3), - new RemoveFuncCallArg('mysql_connect', 3), - new RemoveFuncCallArg('mysql_connect', 4), - ]), - ]]); - - $services->set(MysqlPConnectToMysqliConnectRector::class); - + $services->set(\Rector\MysqlToMysqli\Rector\Assign\MysqlAssignToMysqliRector::class); + $services->set(\Rector\MysqlToMysqli\Rector\FuncCall\MysqlFuncCallToMysqliRector::class); + $services->set(\Rector\Removing\Rector\FuncCall\RemoveFuncCallArgRector::class)->call('configure', [[\Rector\Removing\Rector\FuncCall\RemoveFuncCallArgRector::REMOVED_FUNCTION_ARGUMENTS => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Removing\ValueObject\RemoveFuncCallArg('mysql_pconnect', 3), new \Rector\Removing\ValueObject\RemoveFuncCallArg('mysql_connect', 3), new \Rector\Removing\ValueObject\RemoveFuncCallArg('mysql_connect', 4)])]]); + $services->set(\Rector\MysqlToMysqli\Rector\FuncCall\MysqlPConnectToMysqliConnectRector::class); # first swap arguments, then rename - $services->set(SwapFuncCallArgumentsRector::class) - ->call('configure', [[ - SwapFuncCallArgumentsRector::FUNCTION_ARGUMENT_SWAPS => ValueObjectInliner::inline([ - new SwapFuncCallArguments('mysql_query', [1, 0]), - new SwapFuncCallArguments('mysql_real_escape_string', [1, 0]), - new SwapFuncCallArguments('mysql_select_db', [1, 0]), - new SwapFuncCallArguments('mysql_set_charset', [1, 0]), - ]), - ]]); - - $services->set(RenameFunctionRector::class) - ->call('configure', [[ - RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ - 'mysql_connect' => 'mysqli_connect', - 'mysql_data_seek' => 'mysqli_data_seek', - 'mysql_fetch_array' => 'mysqli_fetch_array', - 'mysql_fetch_assoc' => 'mysqli_fetch_assoc', - 'mysql_fetch_lengths' => 'mysqli_fetch_lengths', - 'mysql_fetch_object' => 'mysqli_fetch_object', - 'mysql_fetch_row' => 'mysqli_fetch_row', - 'mysql_field_seek' => 'mysqli_field_seek', - 'mysql_free_result' => 'mysqli_free_result', - 'mysql_get_client_info' => 'mysqli_get_client_info', - 'mysql_num_fields' => 'mysqli_num_fields', - 'mysql_numfields' => 'mysqli_num_fields', - 'mysql_num_rows' => 'mysqli_num_rows', - 'mysql_numrows' => 'mysqli_num_rows', - ], - ]]); - + $services->set(\Rector\Arguments\Rector\FuncCall\SwapFuncCallArgumentsRector::class)->call('configure', [[\Rector\Arguments\Rector\FuncCall\SwapFuncCallArgumentsRector::FUNCTION_ARGUMENT_SWAPS => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Arguments\ValueObject\SwapFuncCallArguments('mysql_query', [1, 0]), new \Rector\Arguments\ValueObject\SwapFuncCallArguments('mysql_real_escape_string', [1, 0]), new \Rector\Arguments\ValueObject\SwapFuncCallArguments('mysql_select_db', [1, 0]), new \Rector\Arguments\ValueObject\SwapFuncCallArguments('mysql_set_charset', [1, 0])])]]); + $services->set(\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::class)->call('configure', [[\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => ['mysql_connect' => 'mysqli_connect', 'mysql_data_seek' => 'mysqli_data_seek', 'mysql_fetch_array' => 'mysqli_fetch_array', 'mysql_fetch_assoc' => 'mysqli_fetch_assoc', 'mysql_fetch_lengths' => 'mysqli_fetch_lengths', 'mysql_fetch_object' => 'mysqli_fetch_object', 'mysql_fetch_row' => 'mysqli_fetch_row', 'mysql_field_seek' => 'mysqli_field_seek', 'mysql_free_result' => 'mysqli_free_result', 'mysql_get_client_info' => 'mysqli_get_client_info', 'mysql_num_fields' => 'mysqli_num_fields', 'mysql_numfields' => 'mysqli_num_fields', 'mysql_num_rows' => 'mysqli_num_rows', 'mysql_numrows' => 'mysqli_num_rows']]]); # http://php.net/manual/en/mysql.constants.php → http://php.net/manual/en/mysqli.constants.php - $services->set(RenameConstantRector::class) - ->call('configure', [[ - RenameConstantRector::OLD_TO_NEW_CONSTANTS => [ - 'MYSQL_ASSOC' => 'MYSQLI_ASSOC', - 'MYSQL_BOTH' => 'MYSQLI_BOTH', - 'MYSQL_CLIENT_COMPRESS' => 'MYSQLI_CLIENT_COMPRESS', - 'MYSQL_CLIENT_IGNORE_SPACE' => 'MYSQLI_CLIENT_IGNORE_SPACE', - 'MYSQL_CLIENT_INTERACTIVE' => 'MYSQLI_CLIENT_INTERACTIVE', - 'MYSQL_CLIENT_SSL' => 'MYSQLI_CLIENT_SSL', - 'MYSQL_NUM' => 'MYSQLI_NUM', - 'MYSQL_PRIMARY_KEY_FLAG' => 'MYSQLI_PRI_KEY_FLAG', - ], - ]]); - - $services->set(MysqlQueryMysqlErrorWithLinkRector::class); + $services->set(\Rector\Renaming\Rector\ConstFetch\RenameConstantRector::class)->call('configure', [[\Rector\Renaming\Rector\ConstFetch\RenameConstantRector::OLD_TO_NEW_CONSTANTS => ['MYSQL_ASSOC' => 'MYSQLI_ASSOC', 'MYSQL_BOTH' => 'MYSQLI_BOTH', 'MYSQL_CLIENT_COMPRESS' => 'MYSQLI_CLIENT_COMPRESS', 'MYSQL_CLIENT_IGNORE_SPACE' => 'MYSQLI_CLIENT_IGNORE_SPACE', 'MYSQL_CLIENT_INTERACTIVE' => 'MYSQLI_CLIENT_INTERACTIVE', 'MYSQL_CLIENT_SSL' => 'MYSQLI_CLIENT_SSL', 'MYSQL_NUM' => 'MYSQLI_NUM', 'MYSQL_PRIMARY_KEY_FLAG' => 'MYSQLI_PRI_KEY_FLAG']]]); + $services->set(\Rector\MysqlToMysqli\Rector\FuncCall\MysqlQueryMysqlErrorWithLinkRector::class); }; diff --git a/config/set/naming.php b/config/set/naming.php index 5bb94d52f84..f56c3286229 100644 --- a/config/set/naming.php +++ b/config/set/naming.php @@ -1,6 +1,7 @@ services(); - $services->set(RenameParamToMatchTypeRector::class); - $services->set(RenamePropertyToMatchTypeRector::class); - $services->set(RenameVariableToMatchNewTypeRector::class); - $services->set(RenameVariableToMatchMethodCallReturnTypeRector::class); - $services->set(MakeGetterClassMethodNameStartWithGetRector::class); - $services->set(MakeIsserClassMethodNameStartWithIsRector::class); - $services->set(RenameForeachValueVariableToMatchMethodCallReturnTypeRector::class); - $services->set(MakeBoolPropertyRespectIsHasWasMethodNamingRector::class); - $services->set(RenameForeachValueVariableToMatchExprVariableRector::class); + $services->set(\Rector\Naming\Rector\ClassMethod\RenameParamToMatchTypeRector::class); + $services->set(\Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector::class); + $services->set(\Rector\Naming\Rector\ClassMethod\RenameVariableToMatchNewTypeRector::class); + $services->set(\Rector\Naming\Rector\Assign\RenameVariableToMatchMethodCallReturnTypeRector::class); + $services->set(\Rector\Naming\Rector\ClassMethod\MakeGetterClassMethodNameStartWithGetRector::class); + $services->set(\Rector\Naming\Rector\ClassMethod\MakeIsserClassMethodNameStartWithIsRector::class); + $services->set(\Rector\Naming\Rector\Foreach_\RenameForeachValueVariableToMatchMethodCallReturnTypeRector::class); + $services->set(\Rector\Naming\Rector\Property\MakeBoolPropertyRespectIsHasWasMethodNamingRector::class); + $services->set(\Rector\Naming\Rector\Foreach_\RenameForeachValueVariableToMatchExprVariableRector::class); }; diff --git a/config/set/order.php b/config/set/order.php index 819be93c6e1..d04774bd0da 100644 --- a/config/set/order.php +++ b/config/set/order.php @@ -1,19 +1,19 @@ services(); - $services->set(OrderPrivateMethodsByUseRector::class); - $services->set(OrderClassConstantsByIntegerValueRector::class); - $services->set(OrderMethodsByVisibilityRector::class); - $services->set(OrderPropertiesByVisibilityRector::class); - $services->set(OrderConstantsByVisibilityRector::class); + $services->set(\Rector\Order\Rector\Class_\OrderPrivateMethodsByUseRector::class); + $services->set(\Rector\Order\Rector\Class_\OrderClassConstantsByIntegerValueRector::class); + $services->set(\Rector\Order\Rector\Class_\OrderMethodsByVisibilityRector::class); + $services->set(\Rector\Order\Rector\Class_\OrderPropertiesByVisibilityRector::class); + $services->set(\Rector\Order\Rector\Class_\OrderConstantsByVisibilityRector::class); }; diff --git a/config/set/phalcon40.php b/config/set/phalcon40.php index a89373243e8..d9d53d64228 100644 --- a/config/set/phalcon40.php +++ b/config/set/phalcon40.php @@ -1,127 +1,19 @@ services(); - # for class renames is better - https://docs.phalcon.io/4.0/en/upgrade#cheat-sheet - $services->set(RenameClassRector::class) - ->call('configure', [[ - RenameClassRector::OLD_TO_NEW_CLASSES => [ - 'Phalcon\Acl\Adapter' => 'Phalcon\Acl\Adapter\AbstractAdapter', - 'Phalcon\Acl\Resource' => 'Phalcon\Acl\Component', - 'Phalcon\Acl\ResourceInterface' => 'Phalcon\Acl\ComponentInterface', - 'Phalcon\Acl\ResourceAware' => 'Phalcon\Acl\ComponentAware', - 'Phalcon\Assets\ResourceInterface' => 'Phalcon\Assets\AssetInterface', - 'Phalcon\Validation\MessageInterface' => 'Phalcon\Messages\MessageInterface', - 'Phalcon\Mvc\Model\MessageInterface' => 'Phalcon\Messages\MessageInterface', - 'Phalcon\Annotations\Adapter' => 'Phalcon\Annotations\Adapter\AbstractAdapter', - 'Phalcon\Annotations\Factory' => 'Phalcon\Annotations\AnnotationsFactory', - 'Phalcon\Application' => 'Phalcon\Application\AbstractApplication', - 'Phalcon\Assets\Resource' => 'Phalcon\Assets\Asset', - 'Phalcon\Assets\Resource\Css' => 'Phalcon\Assets\Asset\Css', - 'Phalcon\Assets\Resource\Js' => 'Phalcon\Assets\Asset\Js', - 'Phalcon\Cache\Backend' => 'Phalcon\Cache', - 'Phalcon\Cache\Backend\Factory' => 'Phalcon\Cache\AdapterFactory', - 'Phalcon\Cache\Backend\Apcu' => 'Phalcon\Cache\Adapter\Apcu', - 'Phalcon\Cache\Backend\File' => 'Phalcon\Cache\Adapter\Stream', - 'Phalcon\Cache\Backend\Libmemcached' => 'Phalcon\Cache\Adapter\Libmemcached', - 'Phalcon\Cache\Backend\Memory' => 'Phalcon\Cache\Adapter\Memory', - 'Phalcon\Cache\Backend\Redis' => 'Phalcon\Cache\Adapter\Redis', - 'Phalcon\Cache\Exception' => 'Phalcon\Cache\Exception\Exception', - 'Phalcon\Config\Factory' => 'Phalcon\Config\ConfigFactory', - 'Phalcon\Db' => 'Phalcon\Db\AbstractDb', - 'Phalcon\Db\Adapter' => 'Phalcon\Db\Adapter\AbstractAdapter', - 'Phalcon\Db\Adapter\Pdo' => 'Phalcon\Db\Adapter\Pdo\AbstractPdo', - 'Phalcon\Db\Adapter\Pdo\Factory' => 'Phalcon\Db\Adapter\PdoFactory', - 'Phalcon\Dispatcher' => 'Phalcon\Dispatcher\AbstractDispatcher', - 'Phalcon\Factory' => 'Phalcon\Factory\AbstractFactory', - 'Phalcon\Flash' => 'Phalcon\Flash\AbstractFlash', - 'Phalcon\Forms\Element' => 'Phalcon\Forms\Element\AbstractElement', - 'Phalcon\Image\Adapter' => 'Phalcon\Image\Adapter\AbstractAdapter', - 'Phalcon\Image\Factory' => 'Phalcon\Image\ImageFactory', - 'Phalcon\Logger\Adapter' => 'Phalcon\Logger\Adapter\AbstractAdapter', - 'Phalcon\Logger\Adapter\Blackhole' => 'Phalcon\Logger\Adapter\Noop', - 'Phalcon\Logger\Adapter\File' => 'Phalcon\Logger\Adapter\Stream', - 'Phalcon\Logger\Factory' => 'Phalcon\Logger\LoggerFactory', - 'Phalcon\Logger\Formatter' => 'Phalcon\Logger\Formatter\AbstractFormatter', - 'Phalcon\Mvc\Collection' => 'Phalcon\Collection', - 'Phalcon\Mvc\Collection\Exception' => 'Phalcon\Collection\Exception', - 'Phalcon\Mvc\Model\Message' => 'Phalcon\Messages\Message', - 'Phalcon\Mvc\Model\MetaData\Files' => 'Phalcon\Mvc\Model\MetaData\Stream', - 'Phalcon\Mvc\Model\Validator' => 'Phalcon\Validation\Validator', - 'Phalcon\Mvc\Model\Validator\Email' => 'Phalcon\Validation\Validator\Email', - 'Phalcon\Mvc\Model\Validator\Exclusionin' => 'Phalcon\Validation\Validator\ExclusionIn', - 'Phalcon\Mvc\Model\Validator\Inclusionin' => 'Phalcon\Validation\Validator\InclusionIn', - 'Phalcon\Mvc\Model\Validator\Ip' => 'Phalcon\Validation\Validator\Ip', - 'Phalcon\Mvc\Model\Validator\Numericality' => 'Phalcon\Validation\Validator\Numericality', - 'Phalcon\Mvc\Model\Validator\PresenceOf' => 'Phalcon\Validation\Validator\PresenceOf', - 'Phalcon\Mvc\Model\Validator\Regex' => 'Phalcon\Validation\Validator\Regex', - 'Phalcon\Mvc\Model\Validator\StringLength' => 'Phalcon\Validation\Validator\StringLength', - 'Phalcon\Mvc\Model\Validator\Uniqueness' => 'Phalcon\Validation\Validator\Uniqueness', - 'Phalcon\Mvc\Model\Validator\Url' => 'Phalcon\Validation\Validator\Url', - 'Phalcon\Mvc\Url' => 'Phalcon\Url', - 'Phalcon\Mvc\Url\Exception' => 'Phalcon\Url\Exception', - 'Phalcon\Mvc\User\Component' => 'Phalcon\Di\Injectable', - 'Phalcon\Mvc\User\Module' => 'Phalcon\Di\Injectable', - 'Phalcon\Mvc\User\Plugin' => 'Phalcon\Di\Injectable', - 'Phalcon\Mvc\View\Engine' => 'Phalcon\Mvc\View\Engine\AbstractEngine', - 'Phalcon\Paginator\Adapter' => 'Phalcon\Paginator\Adapter\AbstractAdapter', - 'Phalcon\Paginator\Factory' => 'Phalcon\Paginator\PaginatorFactory', - 'Phalcon\Session\Adapter' => 'Phalcon\Session\Adapter\AbstractAdapter', - 'Phalcon\Session\Adapter\Files' => 'Phalcon\Session\Adapter\Stream', - 'Phalcon\Session\Factory' => 'Phalcon\Session\Manager', - 'Phalcon\Translate\Adapter' => 'Phalcon\Translate\Adapter\AbstractAdapter', - 'Phalcon\Translate\Factory' => 'Phalcon\Translate\TranslateFactory', - 'Phalcon\Validation\CombinedFieldsValidator' => 'Phalcon\Validation\AbstractCombinedFieldsValidator', - 'Phalcon\Validation\Message' => 'Phalcon\Messages\Message', - 'Phalcon\Validation\Message\Group' => 'Phalcon\Messages\Messages', - 'Phalcon\Validation\Validator' => 'Phalcon\Validation\AbstractValidator', - 'Phalcon\Text' => 'Phalcon\Helper\Str', - 'Phalcon\Session\AdapterInterface' => 'SessionHandlerInterface', - ], - ]]); - - $services->set(RenameMethodRector::class) - ->call('configure', [[ - RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([ - new MethodCallRename('Phalcon\Acl\AdapterInterface', 'isResource', 'isComponent'), - new MethodCallRename('Phalcon\Acl\AdapterInterface', 'addResource', 'addComponent'), - new MethodCallRename('Phalcon\Acl\AdapterInterface', 'addResourceAccess', 'addComponentAccess'), - new MethodCallRename('Phalcon\Acl\AdapterInterface', 'dropResourceAccess', 'dropComponentAccess'), - new MethodCallRename('Phalcon\Acl\AdapterInterface', 'getActiveResource', 'getActiveComponent'), - new MethodCallRename('Phalcon\Acl\AdapterInterface', 'getResources', 'getComponents'), - new MethodCallRename('Phalcon\Acl\Adapter\Memory', 'isResource', 'isComponent'), - new MethodCallRename('Phalcon\Acl\Adapter\Memory', 'addResource', 'addComponent'), - new MethodCallRename('Phalcon\Acl\Adapter\Memory', 'addResourceAccess', 'addComponentAccess'), - new MethodCallRename('Phalcon\Acl\Adapter\Memory', 'dropResourceAccess', 'dropComponentAccess'), - new MethodCallRename('Phalcon\Acl\Adapter\Memory', 'getResources', 'getComponents'), - new MethodCallRename('Phalcon\Cli\Console', 'addModules', 'registerModules'), - new MethodCallRename('Phalcon\Dispatcher', 'setModelBinding', 'setModelBinder'), - new MethodCallRename('Phalcon\Assets\Manager', 'addResource', 'addAsset'), - new MethodCallRename('Phalcon\Assets\Manager', 'addResourceByType', 'addAssetByType'), - new MethodCallRename('Phalcon\Assets\Manager', 'collectionResourcesByType', 'collectionAssetsByType'), - new MethodCallRename('Phalcon\Http\RequestInterface', 'isSecureRequest', 'isSecure'), - new MethodCallRename('Phalcon\Http\RequestInterface', 'isSoapRequested', 'isSoap'), - new MethodCallRename('Phalcon\Paginator', 'getPaginate', 'paginate'), - new MethodCallRename('Phalcon\Mvc\Model\Criteria', 'order', 'orderBy'), - ]), - ]]); - - $services->set(RenameConstantRector::class) - ->call('configure', [[ - RenameConstantRector::OLD_TO_NEW_CONSTANTS => [ - 'FILTER_SPECIAL_CHARS' => 'FILTER_SPECIAL', - 'FILTER_ALPHANUM' => 'FILTER_ALNUM', - ], - ]]); + $services->set(\Rector\Renaming\Rector\Name\RenameClassRector::class)->call('configure', [[\Rector\Renaming\Rector\Name\RenameClassRector::OLD_TO_NEW_CLASSES => ['Phalcon\\Acl\\Adapter' => 'Phalcon\\Acl\\Adapter\\AbstractAdapter', 'Phalcon\\Acl\\Resource' => 'Phalcon\\Acl\\Component', 'Phalcon\\Acl\\ResourceInterface' => 'Phalcon\\Acl\\ComponentInterface', 'Phalcon\\Acl\\ResourceAware' => 'Phalcon\\Acl\\ComponentAware', 'Phalcon\\Assets\\ResourceInterface' => 'Phalcon\\Assets\\AssetInterface', 'Phalcon\\Validation\\MessageInterface' => 'Phalcon\\Messages\\MessageInterface', 'Phalcon\\Mvc\\Model\\MessageInterface' => 'Phalcon\\Messages\\MessageInterface', 'Phalcon\\Annotations\\Adapter' => 'Phalcon\\Annotations\\Adapter\\AbstractAdapter', 'Phalcon\\Annotations\\Factory' => 'Phalcon\\Annotations\\AnnotationsFactory', 'Phalcon\\Application' => 'Phalcon\\Application\\AbstractApplication', 'Phalcon\\Assets\\Resource' => 'Phalcon\\Assets\\Asset', 'Phalcon\\Assets\\Resource\\Css' => 'Phalcon\\Assets\\Asset\\Css', 'Phalcon\\Assets\\Resource\\Js' => 'Phalcon\\Assets\\Asset\\Js', 'Phalcon\\Cache\\Backend' => 'Phalcon\\Cache', 'Phalcon\\Cache\\Backend\\Factory' => 'Phalcon\\Cache\\AdapterFactory', 'Phalcon\\Cache\\Backend\\Apcu' => 'Phalcon\\Cache\\Adapter\\Apcu', 'Phalcon\\Cache\\Backend\\File' => 'Phalcon\\Cache\\Adapter\\Stream', 'Phalcon\\Cache\\Backend\\Libmemcached' => 'Phalcon\\Cache\\Adapter\\Libmemcached', 'Phalcon\\Cache\\Backend\\Memory' => 'Phalcon\\Cache\\Adapter\\Memory', 'Phalcon\\Cache\\Backend\\Redis' => 'Phalcon\\Cache\\Adapter\\Redis', 'Phalcon\\Cache\\Exception' => 'Phalcon\\Cache\\Exception\\Exception', 'Phalcon\\Config\\Factory' => 'Phalcon\\Config\\ConfigFactory', 'Phalcon\\Db' => 'Phalcon\\Db\\AbstractDb', 'Phalcon\\Db\\Adapter' => 'Phalcon\\Db\\Adapter\\AbstractAdapter', 'Phalcon\\Db\\Adapter\\Pdo' => 'Phalcon\\Db\\Adapter\\Pdo\\AbstractPdo', 'Phalcon\\Db\\Adapter\\Pdo\\Factory' => 'Phalcon\\Db\\Adapter\\PdoFactory', 'Phalcon\\Dispatcher' => 'Phalcon\\Dispatcher\\AbstractDispatcher', 'Phalcon\\Factory' => 'Phalcon\\Factory\\AbstractFactory', 'Phalcon\\Flash' => 'Phalcon\\Flash\\AbstractFlash', 'Phalcon\\Forms\\Element' => 'Phalcon\\Forms\\Element\\AbstractElement', 'Phalcon\\Image\\Adapter' => 'Phalcon\\Image\\Adapter\\AbstractAdapter', 'Phalcon\\Image\\Factory' => 'Phalcon\\Image\\ImageFactory', 'Phalcon\\Logger\\Adapter' => 'Phalcon\\Logger\\Adapter\\AbstractAdapter', 'Phalcon\\Logger\\Adapter\\Blackhole' => 'Phalcon\\Logger\\Adapter\\Noop', 'Phalcon\\Logger\\Adapter\\File' => 'Phalcon\\Logger\\Adapter\\Stream', 'Phalcon\\Logger\\Factory' => 'Phalcon\\Logger\\LoggerFactory', 'Phalcon\\Logger\\Formatter' => 'Phalcon\\Logger\\Formatter\\AbstractFormatter', 'Phalcon\\Mvc\\Collection' => 'Phalcon\\Collection', 'Phalcon\\Mvc\\Collection\\Exception' => 'Phalcon\\Collection\\Exception', 'Phalcon\\Mvc\\Model\\Message' => 'Phalcon\\Messages\\Message', 'Phalcon\\Mvc\\Model\\MetaData\\Files' => 'Phalcon\\Mvc\\Model\\MetaData\\Stream', 'Phalcon\\Mvc\\Model\\Validator' => 'Phalcon\\Validation\\Validator', 'Phalcon\\Mvc\\Model\\Validator\\Email' => 'Phalcon\\Validation\\Validator\\Email', 'Phalcon\\Mvc\\Model\\Validator\\Exclusionin' => 'Phalcon\\Validation\\Validator\\ExclusionIn', 'Phalcon\\Mvc\\Model\\Validator\\Inclusionin' => 'Phalcon\\Validation\\Validator\\InclusionIn', 'Phalcon\\Mvc\\Model\\Validator\\Ip' => 'Phalcon\\Validation\\Validator\\Ip', 'Phalcon\\Mvc\\Model\\Validator\\Numericality' => 'Phalcon\\Validation\\Validator\\Numericality', 'Phalcon\\Mvc\\Model\\Validator\\PresenceOf' => 'Phalcon\\Validation\\Validator\\PresenceOf', 'Phalcon\\Mvc\\Model\\Validator\\Regex' => 'Phalcon\\Validation\\Validator\\Regex', 'Phalcon\\Mvc\\Model\\Validator\\StringLength' => 'Phalcon\\Validation\\Validator\\StringLength', 'Phalcon\\Mvc\\Model\\Validator\\Uniqueness' => 'Phalcon\\Validation\\Validator\\Uniqueness', 'Phalcon\\Mvc\\Model\\Validator\\Url' => 'Phalcon\\Validation\\Validator\\Url', 'Phalcon\\Mvc\\Url' => 'Phalcon\\Url', 'Phalcon\\Mvc\\Url\\Exception' => 'Phalcon\\Url\\Exception', 'Phalcon\\Mvc\\User\\Component' => 'Phalcon\\Di\\Injectable', 'Phalcon\\Mvc\\User\\Module' => 'Phalcon\\Di\\Injectable', 'Phalcon\\Mvc\\User\\Plugin' => 'Phalcon\\Di\\Injectable', 'Phalcon\\Mvc\\View\\Engine' => 'Phalcon\\Mvc\\View\\Engine\\AbstractEngine', 'Phalcon\\Paginator\\Adapter' => 'Phalcon\\Paginator\\Adapter\\AbstractAdapter', 'Phalcon\\Paginator\\Factory' => 'Phalcon\\Paginator\\PaginatorFactory', 'Phalcon\\Session\\Adapter' => 'Phalcon\\Session\\Adapter\\AbstractAdapter', 'Phalcon\\Session\\Adapter\\Files' => 'Phalcon\\Session\\Adapter\\Stream', 'Phalcon\\Session\\Factory' => 'Phalcon\\Session\\Manager', 'Phalcon\\Translate\\Adapter' => 'Phalcon\\Translate\\Adapter\\AbstractAdapter', 'Phalcon\\Translate\\Factory' => 'Phalcon\\Translate\\TranslateFactory', 'Phalcon\\Validation\\CombinedFieldsValidator' => 'Phalcon\\Validation\\AbstractCombinedFieldsValidator', 'Phalcon\\Validation\\Message' => 'Phalcon\\Messages\\Message', 'Phalcon\\Validation\\Message\\Group' => 'Phalcon\\Messages\\Messages', 'Phalcon\\Validation\\Validator' => 'Phalcon\\Validation\\AbstractValidator', 'Phalcon\\Text' => 'Phalcon\\Helper\\Str', 'Phalcon\\Session\\AdapterInterface' => 'SessionHandlerInterface']]]); + $services->set(\Rector\Renaming\Rector\MethodCall\RenameMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\MethodCall\RenameMethodRector::METHOD_CALL_RENAMES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\AdapterInterface', 'isResource', 'isComponent'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\AdapterInterface', 'addResource', 'addComponent'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\AdapterInterface', 'addResourceAccess', 'addComponentAccess'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\AdapterInterface', 'dropResourceAccess', 'dropComponentAccess'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\AdapterInterface', 'getActiveResource', 'getActiveComponent'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\AdapterInterface', 'getResources', 'getComponents'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\Adapter\\Memory', 'isResource', 'isComponent'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\Adapter\\Memory', 'addResource', 'addComponent'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\Adapter\\Memory', 'addResourceAccess', 'addComponentAccess'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\Adapter\\Memory', 'dropResourceAccess', 'dropComponentAccess'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Acl\\Adapter\\Memory', 'getResources', 'getComponents'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Cli\\Console', 'addModules', 'registerModules'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Dispatcher', 'setModelBinding', 'setModelBinder'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Assets\\Manager', 'addResource', 'addAsset'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Assets\\Manager', 'addResourceByType', 'addAssetByType'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Assets\\Manager', 'collectionResourcesByType', 'collectionAssetsByType'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Http\\RequestInterface', 'isSecureRequest', 'isSecure'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Http\\RequestInterface', 'isSoapRequested', 'isSoap'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Paginator', 'getPaginate', 'paginate'), new \Rector\Renaming\ValueObject\MethodCallRename('Phalcon\\Mvc\\Model\\Criteria', 'order', 'orderBy')])]]); + $services->set(\Rector\Renaming\Rector\ConstFetch\RenameConstantRector::class)->call('configure', [[\Rector\Renaming\Rector\ConstFetch\RenameConstantRector::OLD_TO_NEW_CONSTANTS => ['FILTER_SPECIAL_CHARS' => 'FILTER_SPECIAL', 'FILTER_ALPHANUM' => 'FILTER_ALNUM']]]); }; diff --git a/config/set/php52.php b/config/set/php52.php index 813caae4970..e6850c585f3 100644 --- a/config/set/php52.php +++ b/config/set/php52.php @@ -1,24 +1,20 @@ services(); - $services->set(VarToPublicPropertyRector::class); - $services->set(ContinueToBreakInSwitchRector::class); - - $services->set(RemoveFuncCallArgRector::class) - ->call('configure', [[ - RemoveFuncCallArgRector::REMOVED_FUNCTION_ARGUMENTS => ValueObjectInliner::inline([ - // see https://www.php.net/manual/en/function.ldap-first-attribute.php - new RemoveFuncCallArg('ldap_first_attribute', 2), - ]), - ]]); + $services->set(\Rector\Php52\Rector\Property\VarToPublicPropertyRector::class); + $services->set(\Rector\Php52\Rector\Switch_\ContinueToBreakInSwitchRector::class); + $services->set(\Rector\Removing\Rector\FuncCall\RemoveFuncCallArgRector::class)->call('configure', [[\Rector\Removing\Rector\FuncCall\RemoveFuncCallArgRector::REMOVED_FUNCTION_ARGUMENTS => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([ + // see https://www.php.net/manual/en/function.ldap-first-attribute.php + new \Rector\Removing\ValueObject\RemoveFuncCallArg('ldap_first_attribute', 2), + ])]]); }; diff --git a/config/set/php53.php b/config/set/php53.php index e34f32ffc64..3a05b0ca032 100644 --- a/config/set/php53.php +++ b/config/set/php53.php @@ -1,20 +1,17 @@ services(); - $services->set(TernaryToElvisRector::class); - - $services->set(DirNameFileConstantToDirConstantRector::class); - - $services->set(ClearReturnNewByReferenceRector::class); - - $services->set(ReplaceHttpServerVarsByServerRector::class); + $services->set(\Rector\Php53\Rector\Ternary\TernaryToElvisRector::class); + $services->set(\Rector\Php53\Rector\FuncCall\DirNameFileConstantToDirConstantRector::class); + $services->set(\Rector\Php53\Rector\AssignRef\ClearReturnNewByReferenceRector::class); + $services->set(\Rector\Php53\Rector\Variable\ReplaceHttpServerVarsByServerRector::class); }; diff --git a/config/set/php54.php b/config/set/php54.php index ad658792681..e239e2ee9c6 100644 --- a/config/set/php54.php +++ b/config/set/php54.php @@ -1,22 +1,15 @@ services(); - $services->set(RenameFunctionRector::class) - ->call('configure', [[ - RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ - 'mysqli_param_count' => 'mysqli_stmt_param_count', - ], - ]]); - - $services->set(RemoveReferenceFromCallRector::class); - - $services->set(RemoveZeroBreakContinueRector::class); + $services->set(\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::class)->call('configure', [[\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => ['mysqli_param_count' => 'mysqli_stmt_param_count']]]); + $services->set(\Rector\Php54\Rector\FuncCall\RemoveReferenceFromCallRector::class); + $services->set(\Rector\Php54\Rector\Break_\RemoveZeroBreakContinueRector::class); }; diff --git a/config/set/php55.php b/config/set/php55.php index a92ed2619e3..aeffa097ac0 100644 --- a/config/set/php55.php +++ b/config/set/php55.php @@ -1,13 +1,13 @@ services(); - $services->set(StringClassNameToClassConstantRector::class); - $services->set(ClassConstantToSelfClassRector::class); + $services->set(\Rector\Php55\Rector\String_\StringClassNameToClassConstantRector::class); + $services->set(\Rector\Php55\Rector\Class_\ClassConstantToSelfClassRector::class); }; diff --git a/config/set/php56.php b/config/set/php56.php index b8fc941986a..0205ab877b8 100644 --- a/config/set/php56.php +++ b/config/set/php56.php @@ -1,57 +1,16 @@ services(); - $services->set(PowToExpRector::class); - - $services->set(RenameFunctionRector::class) - ->call('configure', [[ - RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ - 'mcrypt_generic_end' => 'mcrypt_generic_deinit', - 'set_socket_blocking' => 'stream_set_blocking', - 'ocibindbyname' => 'oci_bind_by_name', - 'ocicancel' => 'oci_cancel', - 'ocicolumnisnull' => 'oci_field_is_null', - 'ocicolumnname' => 'oci_field_name', - 'ocicolumnprecision' => 'oci_field_precision', - 'ocicolumnscale' => 'oci_field_scale', - 'ocicolumnsize' => 'oci_field_size', - 'ocicolumntype' => 'oci_field_type', - 'ocicolumntyperaw' => 'oci_field_type_raw', - 'ocicommit' => 'oci_commit', - 'ocidefinebyname' => 'oci_define_by_name', - 'ocierror' => 'oci_error', - 'ociexecute' => 'oci_execute', - 'ocifetch' => 'oci_fetch', - 'ocifetchstatement' => 'oci_fetch_all', - 'ocifreecursor' => 'oci_free_statement', - 'ocifreestatement' => 'oci_free_statement', - 'ociinternaldebug' => 'oci_internal_debug', - 'ocilogoff' => 'oci_close', - 'ocilogon' => 'oci_connect', - 'ocinewcollection' => 'oci_new_collection', - 'ocinewcursor' => 'oci_new_cursor', - 'ocinewdescriptor' => 'oci_new_descriptor', - 'ocinlogon' => 'oci_new_connect', - 'ocinumcols' => 'oci_num_fields', - 'ociparse' => 'oci_parse', - 'ociplogon' => 'oci_pconnect', - 'ociresult' => 'oci_result', - 'ocirollback' => 'oci_rollback', - 'ocirowcount' => 'oci_num_rows', - 'ociserverversion' => 'oci_server_version', - 'ocisetprefetch' => 'oci_set_prefetch', - 'ocistatementtype' => 'oci_statement_type', - ], - ]]); - + $services->set(\Rector\Php56\Rector\FuncCall\PowToExpRector::class); + $services->set(\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::class)->call('configure', [[\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => ['mcrypt_generic_end' => 'mcrypt_generic_deinit', 'set_socket_blocking' => 'stream_set_blocking', 'ocibindbyname' => 'oci_bind_by_name', 'ocicancel' => 'oci_cancel', 'ocicolumnisnull' => 'oci_field_is_null', 'ocicolumnname' => 'oci_field_name', 'ocicolumnprecision' => 'oci_field_precision', 'ocicolumnscale' => 'oci_field_scale', 'ocicolumnsize' => 'oci_field_size', 'ocicolumntype' => 'oci_field_type', 'ocicolumntyperaw' => 'oci_field_type_raw', 'ocicommit' => 'oci_commit', 'ocidefinebyname' => 'oci_define_by_name', 'ocierror' => 'oci_error', 'ociexecute' => 'oci_execute', 'ocifetch' => 'oci_fetch', 'ocifetchstatement' => 'oci_fetch_all', 'ocifreecursor' => 'oci_free_statement', 'ocifreestatement' => 'oci_free_statement', 'ociinternaldebug' => 'oci_internal_debug', 'ocilogoff' => 'oci_close', 'ocilogon' => 'oci_connect', 'ocinewcollection' => 'oci_new_collection', 'ocinewcursor' => 'oci_new_cursor', 'ocinewdescriptor' => 'oci_new_descriptor', 'ocinlogon' => 'oci_new_connect', 'ocinumcols' => 'oci_num_fields', 'ociparse' => 'oci_parse', 'ociplogon' => 'oci_pconnect', 'ociresult' => 'oci_result', 'ocirollback' => 'oci_rollback', 'ocirowcount' => 'oci_num_rows', 'ociserverversion' => 'oci_server_version', 'ocisetprefetch' => 'oci_set_prefetch', 'ocistatementtype' => 'oci_statement_type']]]); # inspired by level in psalm - https://github.com/vimeo/psalm/blob/82e0bcafac723fdf5007a31a7ae74af1736c9f6f/tests/FileManipulationTest.php#L1063 - $services->set(AddDefaultValueForUndefinedVariableRector::class); + $services->set(\Rector\Php56\Rector\FunctionLike\AddDefaultValueForUndefinedVariableRector::class); }; diff --git a/config/set/php70.php b/config/set/php70.php index 8657511ced3..e2e69adbed4 100644 --- a/config/set/php70.php +++ b/config/set/php70.php @@ -1,6 +1,7 @@ import(__DIR__ . '/mysql-to-mysqli.php'); - $services = $containerConfigurator->services(); - $services->set(Php4ConstructorRector::class); - - $services->set(TernaryToNullCoalescingRector::class); - - $services->set(RandomFunctionRector::class); - - $services->set(ExceptionHandlerTypehintRector::class); - - $services->set(MultiDirnameRector::class); - - $services->set(ListSplitStringRector::class); - - $services->set(EmptyListRector::class); - + $services->set(\Rector\Php70\Rector\ClassMethod\Php4ConstructorRector::class); + $services->set(\Rector\Php70\Rector\Ternary\TernaryToNullCoalescingRector::class); + $services->set(\Rector\Php70\Rector\FuncCall\RandomFunctionRector::class); + $services->set(\Rector\Php70\Rector\FunctionLike\ExceptionHandlerTypehintRector::class); + $services->set(\Rector\Php70\Rector\FuncCall\MultiDirnameRector::class); + $services->set(\Rector\Php70\Rector\Assign\ListSplitStringRector::class); + $services->set(\Rector\Php70\Rector\List_\EmptyListRector::class); # be careful, run this just once, since it can keep swapping order back and forth - $services->set(ListSwapArrayOrderRector::class); - - $services->set(CallUserMethodRector::class); - - $services->set(EregToPregMatchRector::class); - - $services->set(ReduceMultipleDefaultSwitchRector::class); - - $services->set(TernaryToSpaceshipRector::class); - - $services->set(WrapVariableVariableNameInCurlyBracesRector::class); - - $services->set(IfToSpaceshipRector::class); - - $services->set(StaticCallOnNonStaticToInstanceCallRector::class); - - $services->set(ThisCallOnStaticMethodToStaticCallRector::class); - - $services->set(BreakNotInLoopOrSwitchToReturnRector::class); - - $services->set(RenameMktimeWithoutArgsToTimeRector::class); - - $services->set(NonVariableToVariableOnFunctionCallRector::class); + $services->set(\Rector\Php70\Rector\Assign\ListSwapArrayOrderRector::class); + $services->set(\Rector\Php70\Rector\FuncCall\CallUserMethodRector::class); + $services->set(\Rector\Php70\Rector\FuncCall\EregToPregMatchRector::class); + $services->set(\Rector\Php70\Rector\Switch_\ReduceMultipleDefaultSwitchRector::class); + $services->set(\Rector\Php70\Rector\Ternary\TernaryToSpaceshipRector::class); + $services->set(\Rector\Php70\Rector\Variable\WrapVariableVariableNameInCurlyBracesRector::class); + $services->set(\Rector\Php70\Rector\If_\IfToSpaceshipRector::class); + $services->set(\Rector\Php70\Rector\StaticCall\StaticCallOnNonStaticToInstanceCallRector::class); + $services->set(\Rector\Php70\Rector\MethodCall\ThisCallOnStaticMethodToStaticCallRector::class); + $services->set(\Rector\Php70\Rector\Break_\BreakNotInLoopOrSwitchToReturnRector::class); + $services->set(\Rector\Php70\Rector\FuncCall\RenameMktimeWithoutArgsToTimeRector::class); + $services->set(\Rector\Php70\Rector\FuncCall\NonVariableToVariableOnFunctionCallRector::class); }; diff --git a/config/set/php71.php b/config/set/php71.php index 9103be0dac3..4430166bd77 100644 --- a/config/set/php71.php +++ b/config/set/php71.php @@ -1,6 +1,7 @@ services(); - $services->set(IsIterableRector::class); - $services->set(MultiExceptionCatchRector::class); - $services->set(AssignArrayToStringRector::class); - $services->set(CountOnNullRector::class); - $services->set(RemoveExtraParametersRector::class); - $services->set(BinaryOpBetweenNumberAndStringRector::class); - $services->set(ListToArrayDestructRector::class); + $services->set(\Rector\Php71\Rector\BooleanOr\IsIterableRector::class); + $services->set(\Rector\Php71\Rector\TryCatch\MultiExceptionCatchRector::class); + $services->set(\Rector\Php71\Rector\Assign\AssignArrayToStringRector::class); + $services->set(\Rector\Php71\Rector\FuncCall\CountOnNullRector::class); + $services->set(\Rector\Php71\Rector\FuncCall\RemoveExtraParametersRector::class); + $services->set(\Rector\Php71\Rector\BinaryOp\BinaryOpBetweenNumberAndStringRector::class); + $services->set(\Rector\Php71\Rector\List_\ListToArrayDestructRector::class); }; diff --git a/config/set/php72.php b/config/set/php72.php index 1fed4b14fcd..0c5c0b018d1 100644 --- a/config/set/php72.php +++ b/config/set/php72.php @@ -1,6 +1,7 @@ services(); - $services->set(WhileEachToForeachRector::class); - - $services->set(ListEachRector::class); - - $services->set(ReplaceEachAssignmentWithKeyCurrentRector::class); - - $services->set(UnsetCastRector::class); - - $services->set(RenameFunctionRector::class) - ->call('configure', [[ - RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ - # and imagewbmp - 'jpeg2wbmp' => 'imagecreatefromjpeg', - # or imagewbmp - 'png2wbmp' => 'imagecreatefrompng', - #migration72.deprecated.gmp_random-function - # http://php.net/manual/en/migration72.deprecated.php - # or gmp_random_range - 'gmp_random' => 'gmp_random_bits', - 'read_exif_data' => 'exif_read_data', - ], - ]]); - - $services->set(GetClassOnNullRector::class); - - $services->set(IsObjectOnIncompleteClassRector::class); - - $services->set(ParseStrWithResultArgumentRector::class); - - $services->set(StringsAssertNakedRector::class); - - $services->set(CreateFunctionToAnonymousFunctionRector::class); - - $services->set(StringifyDefineRector::class); + $services->set(\Rector\Php72\Rector\While_\WhileEachToForeachRector::class); + $services->set(\Rector\Php72\Rector\Assign\ListEachRector::class); + $services->set(\Rector\Php72\Rector\Assign\ReplaceEachAssignmentWithKeyCurrentRector::class); + $services->set(\Rector\Php72\Rector\Unset_\UnsetCastRector::class); + $services->set(\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::class)->call('configure', [[\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ + # and imagewbmp + 'jpeg2wbmp' => 'imagecreatefromjpeg', + # or imagewbmp + 'png2wbmp' => 'imagecreatefrompng', + #migration72.deprecated.gmp_random-function + # http://php.net/manual/en/migration72.deprecated.php + # or gmp_random_range + 'gmp_random' => 'gmp_random_bits', + 'read_exif_data' => 'exif_read_data', + ]]]); + $services->set(\Rector\Php72\Rector\FuncCall\GetClassOnNullRector::class); + $services->set(\Rector\Php72\Rector\FuncCall\IsObjectOnIncompleteClassRector::class); + $services->set(\Rector\Php72\Rector\FuncCall\ParseStrWithResultArgumentRector::class); + $services->set(\Rector\Php72\Rector\FuncCall\StringsAssertNakedRector::class); + $services->set(\Rector\Php72\Rector\FuncCall\CreateFunctionToAnonymousFunctionRector::class); + $services->set(\Rector\Php72\Rector\FuncCall\StringifyDefineRector::class); }; diff --git a/config/set/php73.php b/config/set/php73.php index 763e646ef15..541fcba429b 100644 --- a/config/set/php73.php +++ b/config/set/php73.php @@ -1,6 +1,7 @@ services(); - $services->set(IsCountableRector::class); - $services->set(ArrayKeyFirstLastRector::class); - $services->set(SensitiveDefineRector::class); - $services->set(SensitiveConstantNameRector::class); - $services->set(SensitiveHereNowDocRector::class); - - $services->set(RenameFunctionRector::class) - ->call('configure', [[ - RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ - # https://wiki.php.net/rfc/deprecations_php_7_3 - 'image2wbmp' => 'imagewbmp', - 'mbregex_encoding' => 'mb_regex_encoding', - 'mbereg' => 'mb_ereg', - 'mberegi' => 'mb_eregi', - 'mbereg_replace' => 'mb_ereg_replace', - 'mberegi_replace' => 'mb_eregi_replace', - 'mbsplit' => 'mb_split', - 'mbereg_match' => 'mb_ereg_match', - 'mbereg_search' => 'mb_ereg_search', - 'mbereg_search_pos' => 'mb_ereg_search_pos', - 'mbereg_search_regs' => 'mb_ereg_search_regs', - 'mbereg_search_init' => 'mb_ereg_search_init', - 'mbereg_search_getregs' => 'mb_ereg_search_getregs', - 'mbereg_search_getpos' => 'mb_ereg_search_getpos', - ], - ]]); - - $services->set(StringifyStrNeedlesRector::class); - $services->set(JsonThrowOnErrorRector::class); - $services->set(RegexDashEscapeRector::class); - $services->set(ContinueToBreakInSwitchRector::class); + $services->set(\Rector\Php73\Rector\BooleanOr\IsCountableRector::class); + $services->set(\Rector\Php73\Rector\FuncCall\ArrayKeyFirstLastRector::class); + $services->set(\Rector\Php73\Rector\FuncCall\SensitiveDefineRector::class); + $services->set(\Rector\Php73\Rector\ConstFetch\SensitiveConstantNameRector::class); + $services->set(\Rector\Php73\Rector\String_\SensitiveHereNowDocRector::class); + $services->set(\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::class)->call('configure', [[\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ + # https://wiki.php.net/rfc/deprecations_php_7_3 + 'image2wbmp' => 'imagewbmp', + 'mbregex_encoding' => 'mb_regex_encoding', + 'mbereg' => 'mb_ereg', + 'mberegi' => 'mb_eregi', + 'mbereg_replace' => 'mb_ereg_replace', + 'mberegi_replace' => 'mb_eregi_replace', + 'mbsplit' => 'mb_split', + 'mbereg_match' => 'mb_ereg_match', + 'mbereg_search' => 'mb_ereg_search', + 'mbereg_search_pos' => 'mb_ereg_search_pos', + 'mbereg_search_regs' => 'mb_ereg_search_regs', + 'mbereg_search_init' => 'mb_ereg_search_init', + 'mbereg_search_getregs' => 'mb_ereg_search_getregs', + 'mbereg_search_getpos' => 'mb_ereg_search_getpos', + ]]]); + $services->set(\Rector\Php73\Rector\FuncCall\StringifyStrNeedlesRector::class); + $services->set(\Rector\Php73\Rector\FuncCall\JsonThrowOnErrorRector::class); + $services->set(\Rector\Php73\Rector\FuncCall\RegexDashEscapeRector::class); + $services->set(\Rector\Php52\Rector\Switch_\ContinueToBreakInSwitchRector::class); }; diff --git a/config/set/php74.php b/config/set/php74.php index fef44e0a074..117ec23231e 100644 --- a/config/set/php74.php +++ b/config/set/php74.php @@ -1,6 +1,7 @@ services(); - $services->set(TypedPropertyRector::class); - - $services->set(RenameFunctionRector::class) - ->call('configure', [[ - RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ - #the_real_type - # https://wiki.php.net/rfc/deprecations_php_7_4 - 'is_real' => 'is_float', - #apache_request_headers_function - # https://wiki.php.net/rfc/deprecations_php_7_4 - 'apache_request_headers' => 'getallheaders', - //'hebrevc' => ['nl2br', 'hebrev'], - ], - ]]); - - $services->set(ArrayKeyExistsOnPropertyRector::class); - - $services->set(FilterVarToAddSlashesRector::class); - - $services->set(ExportToReflectionFunctionRector::class); - - $services->set(GetCalledClassToStaticClassRector::class); - - $services->set(MbStrrposEncodingArgumentPositionRector::class); - - $services->set(RealToFloatTypeCastRector::class); - - $services->set(NullCoalescingOperatorRector::class); - - $services->set(ReservedFnFunctionRector::class); - - $services->set(ClosureToArrowFunctionRector::class); - - $services->set(ArraySpreadInsteadOfArrayMergeRector::class); - - $services->set(AddLiteralSeparatorToNumberRector::class); - - $services->set(ChangeReflectionTypeToStringToGetNameRector::class); - - $services->set(RestoreDefaultNullToNullableTypePropertyRector::class); + $services->set(\Rector\Php74\Rector\Property\TypedPropertyRector::class); + $services->set(\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::class)->call('configure', [[\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ + #the_real_type + # https://wiki.php.net/rfc/deprecations_php_7_4 + 'is_real' => 'is_float', + #apache_request_headers_function + # https://wiki.php.net/rfc/deprecations_php_7_4 + 'apache_request_headers' => 'getallheaders', + ]]]); + $services->set(\Rector\Php74\Rector\FuncCall\ArrayKeyExistsOnPropertyRector::class); + $services->set(\Rector\Php74\Rector\FuncCall\FilterVarToAddSlashesRector::class); + $services->set(\Rector\Php74\Rector\StaticCall\ExportToReflectionFunctionRector::class); + $services->set(\Rector\Php74\Rector\FuncCall\GetCalledClassToStaticClassRector::class); + $services->set(\Rector\Php74\Rector\FuncCall\MbStrrposEncodingArgumentPositionRector::class); + $services->set(\Rector\Php74\Rector\Double\RealToFloatTypeCastRector::class); + $services->set(\Rector\Php74\Rector\Assign\NullCoalescingOperatorRector::class); + $services->set(\Rector\Php74\Rector\Function_\ReservedFnFunctionRector::class); + $services->set(\Rector\Php74\Rector\Closure\ClosureToArrowFunctionRector::class); + $services->set(\Rector\Php74\Rector\FuncCall\ArraySpreadInsteadOfArrayMergeRector::class); + $services->set(\Rector\Php74\Rector\LNumber\AddLiteralSeparatorToNumberRector::class); + $services->set(\Rector\Php74\Rector\MethodCall\ChangeReflectionTypeToStringToGetNameRector::class); + $services->set(\Rector\Php74\Rector\Property\RestoreDefaultNullToNullableTypePropertyRector::class); }; diff --git a/config/set/php80.php b/config/set/php80.php index faa6a4f3902..77dfb8b9244 100644 --- a/config/set/php80.php +++ b/config/set/php80.php @@ -1,6 +1,7 @@ services(); - $services->set(UnionTypesRector::class); - $services->set(StrContainsRector::class); - $services->set(StrStartsWithRector::class); - $services->set(StrEndsWithRector::class); - $services->set(StringableForToStringRector::class); - $services->set(AnnotationToAttributeRector::class); - $services->set(ClassOnObjectRector::class); - $services->set(GetDebugTypeRector::class); - $services->set(TokenGetAllToObjectRector::class); - $services->set(RemoveUnusedVariableInCatchRector::class); - $services->set(ClassPropertyAssignToConstructorPromotionRector::class); - $services->set(ChangeSwitchToMatchRector::class); - + $services->set(\Rector\Php80\Rector\FunctionLike\UnionTypesRector::class); + $services->set(\Rector\Php80\Rector\NotIdentical\StrContainsRector::class); + $services->set(\Rector\Php80\Rector\Identical\StrStartsWithRector::class); + $services->set(\Rector\Php80\Rector\Identical\StrEndsWithRector::class); + $services->set(\Rector\Php80\Rector\Class_\StringableForToStringRector::class); + $services->set(\Rector\Php80\Rector\Class_\AnnotationToAttributeRector::class); + $services->set(\Rector\Php80\Rector\FuncCall\ClassOnObjectRector::class); + $services->set(\Rector\Php80\Rector\Ternary\GetDebugTypeRector::class); + $services->set(\Rector\Php80\Rector\FuncCall\TokenGetAllToObjectRector::class); + $services->set(\Rector\Php80\Rector\Catch_\RemoveUnusedVariableInCatchRector::class); + $services->set(\Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector::class); + $services->set(\Rector\Php80\Rector\Switch_\ChangeSwitchToMatchRector::class); // nette\utils and Strings::replace() - $services->set(ArgumentAdderRector::class) - ->call('configure', [[ - ArgumentAdderRector::ADDED_ARGUMENTS => ValueObjectInliner::inline([ - new ArgumentAdder('Nette\Utils\Strings', 'replace', 2, 'replacement', ''), - ]), - ]]); - $services->set(RemoveParentCallWithoutParentRector::class); - $services->set(SetStateToStaticRector::class); - $services->set(FinalPrivateToPrivateVisibilityRector::class); + $services->set(\Rector\Arguments\Rector\ClassMethod\ArgumentAdderRector::class)->call('configure', [[\Rector\Arguments\Rector\ClassMethod\ArgumentAdderRector::ADDED_ARGUMENTS => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Arguments\ValueObject\ArgumentAdder('Nette\\Utils\\Strings', 'replace', 2, 'replacement', '')])]]); + $services->set(\Rector\DeadCode\Rector\StaticCall\RemoveParentCallWithoutParentRector::class); + $services->set(\Rector\Php80\Rector\ClassMethod\SetStateToStaticRector::class); + $services->set(\Rector\Php80\Rector\ClassMethod\FinalPrivateToPrivateVisibilityRector::class); // @see https://php.watch/versions/8.0/pgsql-aliases-deprecated - $services->set(RenameFunctionRector::class) - ->call('configure', [[ - RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ - 'pg_clientencoding' => 'pg_client_encoding', - 'pg_cmdtuples' => 'pg_affected_rows', - 'pg_errormessage' => 'pg_last_error', - 'pg_fieldisnull' => 'pg_field_is_null', - 'pg_fieldname' => 'pg_field_name', - 'pg_fieldnum' => 'pg_field_num', - 'pg_fieldprtlen' => 'pg_field_prtlen', - 'pg_fieldsize' => 'pg_field_size', - 'pg_fieldtype' => 'pg_field_type', - 'pg_freeresult' => 'pg_free_result', - 'pg_getlastoid' => 'pg_last_oid', - 'pg_loclose' => 'pg_lo_close', - 'pg_locreate' => 'pg_lo_create', - 'pg_loexport' => 'pg_lo_export', - 'pg_loimport' => 'pg_lo_import', - 'pg_loopen' => 'pg_lo_open', - 'pg_loread' => 'pg_lo_read', - 'pg_loreadall' => 'pg_lo_read_all', - 'pg_lounlink' => 'pg_lo_unlink', - 'pg_lowrite' => 'pg_lo_write', - 'pg_numfields' => 'pg_num_fields', - 'pg_numrows' => 'pg_num_rows', - 'pg_result' => 'pg_fetch_result', - 'pg_setclientencoding' => 'pg_set_client_encoding', - ], - ]]); - $services->set(OptionalParametersAfterRequiredRector::class); + $services->set(\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::class)->call('configure', [[\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => ['pg_clientencoding' => 'pg_client_encoding', 'pg_cmdtuples' => 'pg_affected_rows', 'pg_errormessage' => 'pg_last_error', 'pg_fieldisnull' => 'pg_field_is_null', 'pg_fieldname' => 'pg_field_name', 'pg_fieldnum' => 'pg_field_num', 'pg_fieldprtlen' => 'pg_field_prtlen', 'pg_fieldsize' => 'pg_field_size', 'pg_fieldtype' => 'pg_field_type', 'pg_freeresult' => 'pg_free_result', 'pg_getlastoid' => 'pg_last_oid', 'pg_loclose' => 'pg_lo_close', 'pg_locreate' => 'pg_lo_create', 'pg_loexport' => 'pg_lo_export', 'pg_loimport' => 'pg_lo_import', 'pg_loopen' => 'pg_lo_open', 'pg_loread' => 'pg_lo_read', 'pg_loreadall' => 'pg_lo_read_all', 'pg_lounlink' => 'pg_lo_unlink', 'pg_lowrite' => 'pg_lo_write', 'pg_numfields' => 'pg_num_fields', 'pg_numrows' => 'pg_num_rows', 'pg_result' => 'pg_fetch_result', 'pg_setclientencoding' => 'pg_set_client_encoding']]]); + $services->set(\Rector\Php80\Rector\ClassMethod\OptionalParametersAfterRequiredRector::class); }; diff --git a/config/set/php81.php b/config/set/php81.php index 48ad736ba8d..60e1370d6b7 100644 --- a/config/set/php81.php +++ b/config/set/php81.php @@ -1,11 +1,11 @@ services(); - $services->set(ReturnNeverTypeRector::class); + $services->set(\Rector\TypeDeclaration\Rector\ClassMethod\ReturnNeverTypeRector::class); }; diff --git a/config/set/phpexcel-to-phpspreadsheet.php b/config/set/phpexcel-to-phpspreadsheet.php index a5ce0d050f7..6e49af66b46 100644 --- a/config/set/phpexcel-to-phpspreadsheet.php +++ b/config/set/phpexcel-to-phpspreadsheet.php @@ -1,6 +1,7 @@ services(); - $services->set(ChangeIOFactoryArgumentRector::class); - - $services->set(ChangeSearchLocationToRegisterReaderRector::class); - - $services->set(CellStaticToCoordinateRector::class); - - $services->set(ChangeDataTypeForValueRector::class); - - $services->set(ChangePdfWriterRector::class); - - $services->set(ChangeChartRendererRector::class); - - $services->set(AddRemovedDefaultValuesRector::class); - - $services->set(ChangeConditionalReturnedCellRector::class); - - $services->set(ChangeConditionalGetConditionRector::class); - - $services->set(ChangeConditionalSetConditionRector::class); - - $services->set(RemoveSetTempDirOnExcelWriterRector::class); - - $services->set(ChangeDuplicateStyleArrayToApplyFromArrayRector::class); - - $services->set(GetDefaultStyleToGetParentRector::class); - - $services->set(IncreaseColumnIndexRector::class); - + $services->set(\Rector\PHPOffice\Rector\StaticCall\ChangeIOFactoryArgumentRector::class); + $services->set(\Rector\PHPOffice\Rector\StaticCall\ChangeSearchLocationToRegisterReaderRector::class); + $services->set(\Rector\PHPOffice\Rector\StaticCall\CellStaticToCoordinateRector::class); + $services->set(\Rector\PHPOffice\Rector\StaticCall\ChangeDataTypeForValueRector::class); + $services->set(\Rector\PHPOffice\Rector\StaticCall\ChangePdfWriterRector::class); + $services->set(\Rector\PHPOffice\Rector\StaticCall\ChangeChartRendererRector::class); + $services->set(\Rector\PHPOffice\Rector\StaticCall\AddRemovedDefaultValuesRector::class); + $services->set(\Rector\PHPOffice\Rector\MethodCall\ChangeConditionalReturnedCellRector::class); + $services->set(\Rector\PHPOffice\Rector\MethodCall\ChangeConditionalGetConditionRector::class); + $services->set(\Rector\PHPOffice\Rector\MethodCall\ChangeConditionalSetConditionRector::class); + $services->set(\Rector\PHPOffice\Rector\MethodCall\RemoveSetTempDirOnExcelWriterRector::class); + $services->set(\Rector\PHPOffice\Rector\MethodCall\ChangeDuplicateStyleArrayToApplyFromArrayRector::class); + $services->set(\Rector\PHPOffice\Rector\MethodCall\GetDefaultStyleToGetParentRector::class); + $services->set(\Rector\PHPOffice\Rector\MethodCall\IncreaseColumnIndexRector::class); # beware! this can be run only once, since its circular change - $services->set(RenameMethodRector::class) - ->call('configure', [[ - RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([ - // https://github.com/PHPOffice/PhpSpreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md#worksheetsetsharedstyle - new MethodCallRename('PHPExcel_Worksheet', 'setSharedStyle', 'duplicateStyle'), - // https://github.com/PHPOffice/PhpSpreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md#worksheetgetselectedcell - new MethodCallRename('PHPExcel_Worksheet', 'getSelectedCell', 'getSelectedCells'), - // https://github.com/PHPOffice/PhpSpreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md#cell-caching - new MethodCallRename('PHPExcel_Worksheet', 'getCellCacheController', 'getCellCollection'), - new MethodCallRename('PHPExcel_Worksheet', 'getCellCollection', 'getCoordinates'), - ]), - ]]); - - $configuration = [ - new RenameStaticMethod('PHPExcel_Shared_Date', 'ExcelToPHP', 'PHPExcel_Shared_Date', 'excelToTimestamp'), - new RenameStaticMethod( - 'PHPExcel_Shared_Date', - 'ExcelToPHPObject', - 'PHPExcel_Shared_Date', - 'excelToDateTimeObject' - ), - new RenameStaticMethod( - 'PHPExcel_Shared_Date', - 'FormattedPHPToExcel', - 'PHPExcel_Shared_Date', - 'formattedPHPToExcel' - ), - new RenameStaticMethod( - 'PHPExcel_Calculation_DateTime', - 'DAYOFWEEK', - 'PHPExcel_Calculation_DateTime', - 'WEEKDAY' - ), - new RenameStaticMethod( - 'PHPExcel_Calculation_DateTime', - 'WEEKOFYEAR', - 'PHPExcel_Calculation_DateTime', - 'WEEKNUCM' - ), - new RenameStaticMethod( - 'PHPExcel_Calculation_DateTime', - 'SECONDOFMINUTE', - 'PHPExcel_Calculation_DateTime', - 'SECOND' - ), - new RenameStaticMethod( - 'PHPExcel_Calculation_DateTime', - 'MINUTEOFHOUR', - 'PHPExcel_Calculation_DateTime', - 'MINUTE' - ), - ]; - - $services->set(RenameStaticMethodRector::class) - ->call('configure', [[ - RenameStaticMethodRector::OLD_TO_NEW_METHODS_BY_CLASSES => ValueObjectInliner::inline($configuration), - ]]); - - $services->set(RenameClassRector::class) - ->call('configure', [[ - RenameClassRector::OLD_TO_NEW_CLASSES => [ - 'PHPExcel' => 'PhpOffice\PhpSpreadsheet\Spreadsheet', - 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip' => 'PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip', - 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer' => 'PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer', - 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE' => 'PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE', - 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer' => 'PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer', - 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer' => 'PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer', - 'PHPExcel_Shared_OLE_PPS_File' => 'PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\File', - 'PHPExcel_Shared_OLE_PPS_Root' => 'PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root', - 'PHPExcel_Worksheet_AutoFilter_Column_Rule' => 'PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule', - 'PHPExcel_Writer_OpenDocument_Cell_Comment' => 'PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Comment', - 'PHPExcel_Calculation_Token_Stack' => 'PhpOffice\PhpSpreadsheet\Calculation\Token\Stack', - 'PHPExcel_Chart_Renderer_jpgraph' => 'PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph', - 'PHPExcel_Reader_Excel5_Escher' => 'PhpOffice\PhpSpreadsheet\Reader\Xls\Escher', - 'PHPExcel_Reader_Excel5_MD5' => 'PhpOffice\PhpSpreadsheet\Reader\Xls\MD5', - 'PHPExcel_Reader_Excel5_RC4' => 'PhpOffice\PhpSpreadsheet\Reader\Xls\RC4', - 'PHPExcel_Reader_Excel2007_Chart' => 'PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart', - 'PHPExcel_Reader_Excel2007_Theme' => 'PhpOffice\PhpSpreadsheet\Reader\Xlsx\Theme', - 'PHPExcel_Shared_Escher_DgContainer' => 'PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer', - 'PHPExcel_Shared_Escher_DggContainer' => 'PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer', - 'CholeskyDecomposition' => 'PhpOffice\PhpSpreadsheet\Shared\JAMA\CholeskyDecomposition', - 'EigenvalueDecomposition' => 'PhpOffice\PhpSpreadsheet\Shared\JAMA\EigenvalueDecomposition', - 'PHPExcel_Shared_JAMA_LUDecomposition' => 'PhpOffice\PhpSpreadsheet\Shared\JAMA\LUDecomposition', - 'PHPExcel_Shared_JAMA_Matrix' => 'PhpOffice\PhpSpreadsheet\Shared\JAMA\Matrix', - 'QRDecomposition' => 'PhpOffice\PhpSpreadsheet\Shared\JAMA\QRDecomposition', - 'PHPExcel_Shared_JAMA_QRDecomposition' => 'PhpOffice\PhpSpreadsheet\Shared\JAMA\QRDecomposition', - 'SingularValueDecomposition' => 'PhpOffice\PhpSpreadsheet\Shared\JAMA\SingularValueDecomposition', - 'PHPExcel_Shared_OLE_ChainedBlockStream' => 'PhpOffice\PhpSpreadsheet\Shared\OLE\ChainedBlockStream', - 'PHPExcel_Shared_OLE_PPS' => 'PhpOffice\PhpSpreadsheet\Shared\OLE\PPS', - 'PHPExcel_Best_Fit' => 'PhpOffice\PhpSpreadsheet\Shared\Trend\BestFit', - 'PHPExcel_Exponential_Best_Fit' => 'PhpOffice\PhpSpreadsheet\Shared\Trend\ExponentialBestFit', - 'PHPExcel_Linear_Best_Fit' => 'PhpOffice\PhpSpreadsheet\Shared\Trend\LinearBestFit', - 'PHPExcel_Logarithmic_Best_Fit' => 'PhpOffice\PhpSpreadsheet\Shared\Trend\LogarithmicBestFit', - 'polynomialBestFit' => 'PhpOffice\PhpSpreadsheet\Shared\Trend\PolynomialBestFit', - 'PHPExcel_Polynomial_Best_Fit' => 'PhpOffice\PhpSpreadsheet\Shared\Trend\PolynomialBestFit', - 'powerBestFit' => 'PhpOffice\PhpSpreadsheet\Shared\Trend\PowerBestFit', - 'PHPExcel_Power_Best_Fit' => 'PhpOffice\PhpSpreadsheet\Shared\Trend\PowerBestFit', - 'trendClass' => 'PhpOffice\PhpSpreadsheet\Shared\Trend\Trend', - 'PHPExcel_Worksheet_AutoFilter_Column' => 'PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column', - 'PHPExcel_Worksheet_Drawing_Shadow' => 'PhpOffice\PhpSpreadsheet\Worksheet\Drawing\Shadow', - 'PHPExcel_Writer_OpenDocument_Content' => 'PhpOffice\PhpSpreadsheet\Writer\Ods\Content', - 'PHPExcel_Writer_OpenDocument_Meta' => 'PhpOffice\PhpSpreadsheet\Writer\Ods\Meta', - 'PHPExcel_Writer_OpenDocument_MetaInf' => 'PhpOffice\PhpSpreadsheet\Writer\Ods\MetaInf', - 'PHPExcel_Writer_OpenDocument_Mimetype' => 'PhpOffice\PhpSpreadsheet\Writer\Ods\Mimetype', - 'PHPExcel_Writer_OpenDocument_Settings' => 'PhpOffice\PhpSpreadsheet\Writer\Ods\Settings', - 'PHPExcel_Writer_OpenDocument_Styles' => 'PhpOffice\PhpSpreadsheet\Writer\Ods\Styles', - 'PHPExcel_Writer_OpenDocument_Thumbnails' => 'PhpOffice\PhpSpreadsheet\Writer\Ods\Thumbnails', - 'PHPExcel_Writer_OpenDocument_WriterPart' => 'PhpOffice\PhpSpreadsheet\Writer\Ods\WriterPart', - 'PHPExcel_Writer_PDF_Core' => 'PhpOffice\PhpSpreadsheet\Writer\Pdf', - 'PHPExcel_Writer_PDF_DomPDF' => 'PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf', - 'PHPExcel_Writer_PDF_mPDF' => 'PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf', - 'PHPExcel_Writer_PDF_tcPDF' => 'PhpOffice\PhpSpreadsheet\Writer\Pdf\Tcpdf', - 'PHPExcel_Writer_Excel5_BIFFwriter' => 'PhpOffice\PhpSpreadsheet\Writer\Xls\BIFFwriter', - 'PHPExcel_Writer_Excel5_Escher' => 'PhpOffice\PhpSpreadsheet\Writer\Xls\Escher', - 'PHPExcel_Writer_Excel5_Font' => 'PhpOffice\PhpSpreadsheet\Writer\Xls\Font', - 'PHPExcel_Writer_Excel5_Parser' => 'PhpOffice\PhpSpreadsheet\Writer\Xls\Parser', - 'PHPExcel_Writer_Excel5_Workbook' => 'PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook', - 'PHPExcel_Writer_Excel5_Worksheet' => 'PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet', - 'PHPExcel_Writer_Excel5_Xf' => 'PhpOffice\PhpSpreadsheet\Writer\Xls\Xf', - 'PHPExcel_Writer_Excel2007_Chart' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\Chart', - 'PHPExcel_Writer_Excel2007_Comments' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\Comments', - 'PHPExcel_Writer_Excel2007_ContentTypes' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\ContentTypes', - 'PHPExcel_Writer_Excel2007_DocProps' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\DocProps', - 'PHPExcel_Writer_Excel2007_Drawing' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\Drawing', - 'PHPExcel_Writer_Excel2007_Rels' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels', - 'PHPExcel_Writer_Excel2007_RelsRibbon' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsRibbon', - 'PHPExcel_Writer_Excel2007_RelsVBA' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsVBA', - 'PHPExcel_Writer_Excel2007_StringTable' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\StringTable', - 'PHPExcel_Writer_Excel2007_Style' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\Style', - 'PHPExcel_Writer_Excel2007_Theme' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\Theme', - 'PHPExcel_Writer_Excel2007_Workbook' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\Workbook', - 'PHPExcel_Writer_Excel2007_Worksheet' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet', - 'PHPExcel_Writer_Excel2007_WriterPart' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx\WriterPart', - 'PHPExcel_CachedObjectStorage_CacheBase' => 'PhpOffice\PhpSpreadsheet\Collection\Cells', - 'PHPExcel_CalcEngine_CyclicReferenceStack' => 'PhpOffice\PhpSpreadsheet\Calculation\Engine\CyclicReferenceStack', - 'PHPExcel_CalcEngine_Logger' => 'PhpOffice\PhpSpreadsheet\Calculation\Engine\Logger', - 'PHPExcel_Calculation_Functions' => 'PhpOffice\PhpSpreadsheet\Calculation\Functions', - 'PHPExcel_Calculation_Function' => 'PhpOffice\PhpSpreadsheet\Calculation\Category', - 'PHPExcel_Calculation_Database' => 'PhpOffice\PhpSpreadsheet\Calculation\Database', - 'PHPExcel_Calculation_DateTime' => 'PhpOffice\PhpSpreadsheet\Calculation\DateTime', - 'PHPExcel_Calculation_Engineering' => 'PhpOffice\PhpSpreadsheet\Calculation\Engineering', - 'PHPExcel_Calculation_Exception' => 'PhpOffice\PhpSpreadsheet\Calculation\Exception', - 'PHPExcel_Calculation_ExceptionHandler' => 'PhpOffice\PhpSpreadsheet\Calculation\ExceptionHandler', - 'PHPExcel_Calculation_Financial' => 'PhpOffice\PhpSpreadsheet\Calculation\Financial', - 'PHPExcel_Calculation_FormulaParser' => 'PhpOffice\PhpSpreadsheet\Calculation\FormulaParser', - 'PHPExcel_Calculation_FormulaToken' => 'PhpOffice\PhpSpreadsheet\Calculation\FormulaToken', - 'PHPExcel_Calculation_Logical' => 'PhpOffice\PhpSpreadsheet\Calculation\Logical', - 'PHPExcel_Calculation_LookupRef' => 'PhpOffice\PhpSpreadsheet\Calculation\LookupRef', - 'PHPExcel_Calculation_MathTrig' => 'PhpOffice\PhpSpreadsheet\Calculation\MathTrig', - 'PHPExcel_Calculation_Statistical' => 'PhpOffice\PhpSpreadsheet\Calculation\Statistical', - 'PHPExcel_Calculation_TextData' => 'PhpOffice\PhpSpreadsheet\Calculation\TextData', - 'PHPExcel_Cell_AdvancedValueBinder' => 'PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder', - 'PHPExcel_Cell_DataType' => 'PhpOffice\PhpSpreadsheet\Cell\DataType', - 'PHPExcel_Cell_DataValidation' => 'PhpOffice\PhpSpreadsheet\Cell\DataValidation', - 'PHPExcel_Cell_DefaultValueBinder' => 'PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder', - 'PHPExcel_Cell_Hyperlink' => 'PhpOffice\PhpSpreadsheet\Cell\Hyperlink', - 'PHPExcel_Cell_IValueBinder' => 'PhpOffice\PhpSpreadsheet\Cell\IValueBinder', - 'PHPExcel_Chart_Axis' => 'PhpOffice\PhpSpreadsheet\Chart\Axis', - 'PHPExcel_Chart_DataSeries' => 'PhpOffice\PhpSpreadsheet\Chart\DataSeries', - 'PHPExcel_Chart_DataSeriesValues' => 'PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues', - 'PHPExcel_Chart_Exception' => 'PhpOffice\PhpSpreadsheet\Chart\Exception', - 'PHPExcel_Chart_GridLines' => 'PhpOffice\PhpSpreadsheet\Chart\GridLines', - 'PHPExcel_Chart_Layout' => 'PhpOffice\PhpSpreadsheet\Chart\Layout', - 'PHPExcel_Chart_Legend' => 'PhpOffice\PhpSpreadsheet\Chart\Legend', - 'PHPExcel_Chart_PlotArea' => 'PhpOffice\PhpSpreadsheet\Chart\PlotArea', - 'PHPExcel_Properties' => 'PhpOffice\PhpSpreadsheet\Chart\Properties', - 'PHPExcel_Chart_Title' => 'PhpOffice\PhpSpreadsheet\Chart\Title', - 'PHPExcel_DocumentProperties' => 'PhpOffice\PhpSpreadsheet\Document\Properties', - 'PHPExcel_DocumentSecurity' => 'PhpOffice\PhpSpreadsheet\Document\Security', - 'PHPExcel_Helper_HTML' => 'PhpOffice\PhpSpreadsheet\Helper\Html', - 'PHPExcel_Reader_Abstract' => 'PhpOffice\PhpSpreadsheet\Reader\BaseReader', - 'PHPExcel_Reader_CSV' => 'PhpOffice\PhpSpreadsheet\Reader\Csv', - 'PHPExcel_Reader_DefaultReadFilter' => 'PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter', - 'PHPExcel_Reader_Excel2003XML' => 'PhpOffice\PhpSpreadsheet\Reader\Xml', - 'PHPExcel_Reader_Exception' => 'PhpOffice\PhpSpreadsheet\Reader\Exception', - 'PHPExcel_Reader_Gnumeric' => 'PhpOffice\PhpSpreadsheet\Reader\Gnumeric', - 'PHPExcel_Reader_HTML' => 'PhpOffice\PhpSpreadsheet\Reader\Html', - 'PHPExcel_Reader_IReadFilter' => 'PhpOffice\PhpSpreadsheet\Reader\IReadFilter', - 'PHPExcel_Reader_IReader' => 'PhpOffice\PhpSpreadsheet\Reader\IReader', - 'PHPExcel_Reader_OOCalc' => 'PhpOffice\PhpSpreadsheet\Reader\Ods', - 'PHPExcel_Reader_SYLK' => 'PhpOffice\PhpSpreadsheet\Reader\Slk', - 'PHPExcel_Reader_Excel5' => 'PhpOffice\PhpSpreadsheet\Reader\Xls', - 'PHPExcel_Reader_Excel2007' => 'PhpOffice\PhpSpreadsheet\Reader\Xlsx', - 'PHPExcel_RichText_ITextElement' => 'PhpOffice\PhpSpreadsheet\RichText\ITextElement', - 'PHPExcel_RichText_Run' => 'PhpOffice\PhpSpreadsheet\RichText\Run', - 'PHPExcel_RichText_TextElement' => 'PhpOffice\PhpSpreadsheet\RichText\TextElement', - 'PHPExcel_Shared_CodePage' => 'PhpOffice\PhpSpreadsheet\Shared\CodePage', - 'PHPExcel_Shared_Date' => 'PhpOffice\PhpSpreadsheet\Shared\Date', - 'PHPExcel_Shared_Drawing' => 'PhpOffice\PhpSpreadsheet\Shared\Drawing', - 'PHPExcel_Shared_Escher' => 'PhpOffice\PhpSpreadsheet\Shared\Escher', - 'PHPExcel_Shared_File' => 'PhpOffice\PhpSpreadsheet\Shared\File', - 'PHPExcel_Shared_Font' => 'PhpOffice\PhpSpreadsheet\Shared\Font', - 'PHPExcel_Shared_OLE' => 'PhpOffice\PhpSpreadsheet\Shared\OLE', - 'PHPExcel_Shared_OLERead' => 'PhpOffice\PhpSpreadsheet\Shared\OLERead', - 'PHPExcel_Shared_PasswordHasher' => 'PhpOffice\PhpSpreadsheet\Shared\PasswordHasher', - 'PHPExcel_Shared_String' => 'PhpOffice\PhpSpreadsheet\Shared\StringHelper', - 'PHPExcel_Shared_TimeZone' => 'PhpOffice\PhpSpreadsheet\Shared\TimeZone', - 'PHPExcel_Shared_XMLWriter' => 'PhpOffice\PhpSpreadsheet\Shared\XMLWriter', - 'PHPExcel_Shared_Excel5' => 'PhpOffice\PhpSpreadsheet\Shared\Xls', - 'PHPExcel_Style_Alignment' => 'PhpOffice\PhpSpreadsheet\Style\Alignment', - 'PHPExcel_Style_Border' => 'PhpOffice\PhpSpreadsheet\Style\Border', - 'PHPExcel_Style_Borders' => 'PhpOffice\PhpSpreadsheet\Style\Borders', - 'PHPExcel_Style_Color' => 'PhpOffice\PhpSpreadsheet\Style\Color', - 'PHPExcel_Style_Conditional' => 'PhpOffice\PhpSpreadsheet\Style\Conditional', - 'PHPExcel_Style_Fill' => 'PhpOffice\PhpSpreadsheet\Style\Fill', - 'PHPExcel_Style_Font' => 'PhpOffice\PhpSpreadsheet\Style\Font', - 'PHPExcel_Style_NumberFormat' => 'PhpOffice\PhpSpreadsheet\Style\NumberFormat', - 'PHPExcel_Style_Protection' => 'PhpOffice\PhpSpreadsheet\Style\Protection', - 'PHPExcel_Style_Supervisor' => 'PhpOffice\PhpSpreadsheet\Style\Supervisor', - 'PHPExcel_Worksheet_AutoFilter' => 'PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter', - 'PHPExcel_Worksheet_BaseDrawing' => 'PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing', - 'PHPExcel_Worksheet_CellIterator' => 'PhpOffice\PhpSpreadsheet\Worksheet\CellIterator', - 'PHPExcel_Worksheet_Column' => 'PhpOffice\PhpSpreadsheet\Worksheet\Column', - 'PHPExcel_Worksheet_ColumnCellIterator' => 'PhpOffice\PhpSpreadsheet\Worksheet\ColumnCellIterator', - 'PHPExcel_Worksheet_ColumnDimension' => 'PhpOffice\PhpSpreadsheet\Worksheet\ColumnDimension', - 'PHPExcel_Worksheet_ColumnIterator' => 'PhpOffice\PhpSpreadsheet\Worksheet\ColumnIterator', - 'PHPExcel_Worksheet_Drawing' => 'PhpOffice\PhpSpreadsheet\Worksheet\Drawing', - 'PHPExcel_Worksheet_HeaderFooter' => 'PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter', - 'PHPExcel_Worksheet_HeaderFooterDrawing' => 'PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing', - 'PHPExcel_WorksheetIterator' => 'PhpOffice\PhpSpreadsheet\Worksheet\Iterator', - 'PHPExcel_Worksheet_MemoryDrawing' => 'PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing', - 'PHPExcel_Worksheet_PageMargins' => 'PhpOffice\PhpSpreadsheet\Worksheet\PageMargins', - 'PHPExcel_Worksheet_PageSetup' => 'PhpOffice\PhpSpreadsheet\Worksheet\PageSetup', - 'PHPExcel_Worksheet_Protection' => 'PhpOffice\PhpSpreadsheet\Worksheet\Protection', - 'PHPExcel_Worksheet_Row' => 'PhpOffice\PhpSpreadsheet\Worksheet\Row', - 'PHPExcel_Worksheet_RowCellIterator' => 'PhpOffice\PhpSpreadsheet\Worksheet\RowCellIterator', - 'PHPExcel_Worksheet_RowDimension' => 'PhpOffice\PhpSpreadsheet\Worksheet\RowDimension', - 'PHPExcel_Worksheet_RowIterator' => 'PhpOffice\PhpSpreadsheet\Worksheet\RowIterator', - 'PHPExcel_Worksheet_SheetView' => 'PhpOffice\PhpSpreadsheet\Worksheet\SheetView', - 'PHPExcel_Writer_Abstract' => 'PhpOffice\PhpSpreadsheet\Writer\BaseWriter', - 'PHPExcel_Writer_CSV' => 'PhpOffice\PhpSpreadsheet\Writer\Csv', - 'PHPExcel_Writer_Exception' => 'PhpOffice\PhpSpreadsheet\Writer\Exception', - 'PHPExcel_Writer_HTML' => 'PhpOffice\PhpSpreadsheet\Writer\Html', - 'PHPExcel_Writer_IWriter' => 'PhpOffice\PhpSpreadsheet\Writer\IWriter', - 'PHPExcel_Writer_OpenDocument' => 'PhpOffice\PhpSpreadsheet\Writer\Ods', - 'PHPExcel_Writer_PDF' => 'PhpOffice\PhpSpreadsheet\Writer\Pdf', - 'PHPExcel_Writer_Excel5' => 'PhpOffice\PhpSpreadsheet\Writer\Xls', - 'PHPExcel_Writer_Excel2007' => 'PhpOffice\PhpSpreadsheet\Writer\Xlsx', - 'PHPExcel_CachedObjectStorageFactory' => 'PhpOffice\PhpSpreadsheet\Collection\CellsFactory', - 'PHPExcel_Calculation' => 'PhpOffice\PhpSpreadsheet\Calculation\Calculation', - 'PHPExcel_Cell' => 'PhpOffice\PhpSpreadsheet\Cell\Cell', - 'PHPExcel_Chart' => 'PhpOffice\PhpSpreadsheet\Chart\Chart', - 'PHPExcel_Comment' => 'PhpOffice\PhpSpreadsheet\Comment', - 'PHPExcel_Exception' => 'PhpOffice\PhpSpreadsheet\Exception', - 'PHPExcel_HashTable' => 'PhpOffice\PhpSpreadsheet\HashTable', - 'PHPExcel_IComparable' => 'PhpOffice\PhpSpreadsheet\IComparable', - 'PHPExcel_IOFactory' => 'PhpOffice\PhpSpreadsheet\IOFactory', - 'PHPExcel_NamedRange' => 'PhpOffice\PhpSpreadsheet\NamedRange', - 'PHPExcel_ReferenceHelper' => 'PhpOffice\PhpSpreadsheet\ReferenceHelper', - 'PHPExcel_RichText' => 'PhpOffice\PhpSpreadsheet\RichText\RichText', - 'PHPExcel_Settings' => 'PhpOffice\PhpSpreadsheet\Settings', - 'PHPExcel_Style' => 'PhpOffice\PhpSpreadsheet\Style\Style', - 'PHPExcel_Worksheet' => 'PhpOffice\PhpSpreadsheet\Worksheet\Worksheet', - ], - ]]); + $services->set(\Rector\Renaming\Rector\MethodCall\RenameMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\MethodCall\RenameMethodRector::METHOD_CALL_RENAMES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([ + // https://github.com/PHPOffice/PhpSpreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md#worksheetsetsharedstyle + new \Rector\Renaming\ValueObject\MethodCallRename('PHPExcel_Worksheet', 'setSharedStyle', 'duplicateStyle'), + // https://github.com/PHPOffice/PhpSpreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md#worksheetgetselectedcell + new \Rector\Renaming\ValueObject\MethodCallRename('PHPExcel_Worksheet', 'getSelectedCell', 'getSelectedCells'), + // https://github.com/PHPOffice/PhpSpreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md#cell-caching + new \Rector\Renaming\ValueObject\MethodCallRename('PHPExcel_Worksheet', 'getCellCacheController', 'getCellCollection'), + new \Rector\Renaming\ValueObject\MethodCallRename('PHPExcel_Worksheet', 'getCellCollection', 'getCoordinates'), + ])]]); + $configuration = [new \Rector\Renaming\ValueObject\RenameStaticMethod('PHPExcel_Shared_Date', 'ExcelToPHP', 'PHPExcel_Shared_Date', 'excelToTimestamp'), new \Rector\Renaming\ValueObject\RenameStaticMethod('PHPExcel_Shared_Date', 'ExcelToPHPObject', 'PHPExcel_Shared_Date', 'excelToDateTimeObject'), new \Rector\Renaming\ValueObject\RenameStaticMethod('PHPExcel_Shared_Date', 'FormattedPHPToExcel', 'PHPExcel_Shared_Date', 'formattedPHPToExcel'), new \Rector\Renaming\ValueObject\RenameStaticMethod('PHPExcel_Calculation_DateTime', 'DAYOFWEEK', 'PHPExcel_Calculation_DateTime', 'WEEKDAY'), new \Rector\Renaming\ValueObject\RenameStaticMethod('PHPExcel_Calculation_DateTime', 'WEEKOFYEAR', 'PHPExcel_Calculation_DateTime', 'WEEKNUCM'), new \Rector\Renaming\ValueObject\RenameStaticMethod('PHPExcel_Calculation_DateTime', 'SECONDOFMINUTE', 'PHPExcel_Calculation_DateTime', 'SECOND'), new \Rector\Renaming\ValueObject\RenameStaticMethod('PHPExcel_Calculation_DateTime', 'MINUTEOFHOUR', 'PHPExcel_Calculation_DateTime', 'MINUTE')]; + $services->set(\Rector\Renaming\Rector\StaticCall\RenameStaticMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\StaticCall\RenameStaticMethodRector::OLD_TO_NEW_METHODS_BY_CLASSES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline($configuration)]]); + $services->set(\Rector\Renaming\Rector\Name\RenameClassRector::class)->call('configure', [[\Rector\Renaming\Rector\Name\RenameClassRector::OLD_TO_NEW_CLASSES => ['PHPExcel' => 'PhpOffice\\PhpSpreadsheet\\Spreadsheet', 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Escher\\DggContainer\\BstoreContainer\\BSE\\Blip', 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Escher\\DgContainer\\SpgrContainer\\SpContainer', 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Escher\\DggContainer\\BstoreContainer\\BSE', 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Escher\\DgContainer\\SpgrContainer', 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Escher\\DggContainer\\BstoreContainer', 'PHPExcel_Shared_OLE_PPS_File' => 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPS\\File', 'PHPExcel_Shared_OLE_PPS_Root' => 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPS\\Root', 'PHPExcel_Worksheet_AutoFilter_Column_Rule' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\AutoFilter\\Column\\Rule', 'PHPExcel_Writer_OpenDocument_Cell_Comment' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Ods\\Cell\\Comment', 'PHPExcel_Calculation_Token_Stack' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Token\\Stack', 'PHPExcel_Chart_Renderer_jpgraph' => 'PhpOffice\\PhpSpreadsheet\\Chart\\Renderer\\JpGraph', 'PHPExcel_Reader_Excel5_Escher' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Xls\\Escher', 'PHPExcel_Reader_Excel5_MD5' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Xls\\MD5', 'PHPExcel_Reader_Excel5_RC4' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Xls\\RC4', 'PHPExcel_Reader_Excel2007_Chart' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Xlsx\\Chart', 'PHPExcel_Reader_Excel2007_Theme' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Xlsx\\Theme', 'PHPExcel_Shared_Escher_DgContainer' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Escher\\DgContainer', 'PHPExcel_Shared_Escher_DggContainer' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Escher\\DggContainer', 'CholeskyDecomposition' => 'PhpOffice\\PhpSpreadsheet\\Shared\\JAMA\\CholeskyDecomposition', 'EigenvalueDecomposition' => 'PhpOffice\\PhpSpreadsheet\\Shared\\JAMA\\EigenvalueDecomposition', 'PHPExcel_Shared_JAMA_LUDecomposition' => 'PhpOffice\\PhpSpreadsheet\\Shared\\JAMA\\LUDecomposition', 'PHPExcel_Shared_JAMA_Matrix' => 'PhpOffice\\PhpSpreadsheet\\Shared\\JAMA\\Matrix', 'QRDecomposition' => 'PhpOffice\\PhpSpreadsheet\\Shared\\JAMA\\QRDecomposition', 'PHPExcel_Shared_JAMA_QRDecomposition' => 'PhpOffice\\PhpSpreadsheet\\Shared\\JAMA\\QRDecomposition', 'SingularValueDecomposition' => 'PhpOffice\\PhpSpreadsheet\\Shared\\JAMA\\SingularValueDecomposition', 'PHPExcel_Shared_OLE_ChainedBlockStream' => 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\ChainedBlockStream', 'PHPExcel_Shared_OLE_PPS' => 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPS', 'PHPExcel_Best_Fit' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Trend\\BestFit', 'PHPExcel_Exponential_Best_Fit' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Trend\\ExponentialBestFit', 'PHPExcel_Linear_Best_Fit' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Trend\\LinearBestFit', 'PHPExcel_Logarithmic_Best_Fit' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Trend\\LogarithmicBestFit', 'polynomialBestFit' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Trend\\PolynomialBestFit', 'PHPExcel_Polynomial_Best_Fit' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Trend\\PolynomialBestFit', 'powerBestFit' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Trend\\PowerBestFit', 'PHPExcel_Power_Best_Fit' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Trend\\PowerBestFit', 'trendClass' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Trend\\Trend', 'PHPExcel_Worksheet_AutoFilter_Column' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\AutoFilter\\Column', 'PHPExcel_Worksheet_Drawing_Shadow' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Drawing\\Shadow', 'PHPExcel_Writer_OpenDocument_Content' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Ods\\Content', 'PHPExcel_Writer_OpenDocument_Meta' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Ods\\Meta', 'PHPExcel_Writer_OpenDocument_MetaInf' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Ods\\MetaInf', 'PHPExcel_Writer_OpenDocument_Mimetype' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Ods\\Mimetype', 'PHPExcel_Writer_OpenDocument_Settings' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Ods\\Settings', 'PHPExcel_Writer_OpenDocument_Styles' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Ods\\Styles', 'PHPExcel_Writer_OpenDocument_Thumbnails' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Ods\\Thumbnails', 'PHPExcel_Writer_OpenDocument_WriterPart' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Ods\\WriterPart', 'PHPExcel_Writer_PDF_Core' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Pdf', 'PHPExcel_Writer_PDF_DomPDF' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Pdf\\Dompdf', 'PHPExcel_Writer_PDF_mPDF' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Pdf\\Mpdf', 'PHPExcel_Writer_PDF_tcPDF' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Pdf\\Tcpdf', 'PHPExcel_Writer_Excel5_BIFFwriter' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xls\\BIFFwriter', 'PHPExcel_Writer_Excel5_Escher' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xls\\Escher', 'PHPExcel_Writer_Excel5_Font' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xls\\Font', 'PHPExcel_Writer_Excel5_Parser' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xls\\Parser', 'PHPExcel_Writer_Excel5_Workbook' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xls\\Workbook', 'PHPExcel_Writer_Excel5_Worksheet' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xls\\Worksheet', 'PHPExcel_Writer_Excel5_Xf' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xls\\Xf', 'PHPExcel_Writer_Excel2007_Chart' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\Chart', 'PHPExcel_Writer_Excel2007_Comments' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\Comments', 'PHPExcel_Writer_Excel2007_ContentTypes' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\ContentTypes', 'PHPExcel_Writer_Excel2007_DocProps' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\DocProps', 'PHPExcel_Writer_Excel2007_Drawing' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\Drawing', 'PHPExcel_Writer_Excel2007_Rels' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\Rels', 'PHPExcel_Writer_Excel2007_RelsRibbon' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\RelsRibbon', 'PHPExcel_Writer_Excel2007_RelsVBA' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\RelsVBA', 'PHPExcel_Writer_Excel2007_StringTable' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\StringTable', 'PHPExcel_Writer_Excel2007_Style' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\Style', 'PHPExcel_Writer_Excel2007_Theme' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\Theme', 'PHPExcel_Writer_Excel2007_Workbook' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\Workbook', 'PHPExcel_Writer_Excel2007_Worksheet' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\Worksheet', 'PHPExcel_Writer_Excel2007_WriterPart' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx\\WriterPart', 'PHPExcel_CachedObjectStorage_CacheBase' => 'PhpOffice\\PhpSpreadsheet\\Collection\\Cells', 'PHPExcel_CalcEngine_CyclicReferenceStack' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Engine\\CyclicReferenceStack', 'PHPExcel_CalcEngine_Logger' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Engine\\Logger', 'PHPExcel_Calculation_Functions' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Functions', 'PHPExcel_Calculation_Function' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Category', 'PHPExcel_Calculation_Database' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Database', 'PHPExcel_Calculation_DateTime' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\DateTime', 'PHPExcel_Calculation_Engineering' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Engineering', 'PHPExcel_Calculation_Exception' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Exception', 'PHPExcel_Calculation_ExceptionHandler' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\ExceptionHandler', 'PHPExcel_Calculation_Financial' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Financial', 'PHPExcel_Calculation_FormulaParser' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\FormulaParser', 'PHPExcel_Calculation_FormulaToken' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\FormulaToken', 'PHPExcel_Calculation_Logical' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Logical', 'PHPExcel_Calculation_LookupRef' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\LookupRef', 'PHPExcel_Calculation_MathTrig' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\MathTrig', 'PHPExcel_Calculation_Statistical' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Statistical', 'PHPExcel_Calculation_TextData' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\TextData', 'PHPExcel_Cell_AdvancedValueBinder' => 'PhpOffice\\PhpSpreadsheet\\Cell\\AdvancedValueBinder', 'PHPExcel_Cell_DataType' => 'PhpOffice\\PhpSpreadsheet\\Cell\\DataType', 'PHPExcel_Cell_DataValidation' => 'PhpOffice\\PhpSpreadsheet\\Cell\\DataValidation', 'PHPExcel_Cell_DefaultValueBinder' => 'PhpOffice\\PhpSpreadsheet\\Cell\\DefaultValueBinder', 'PHPExcel_Cell_Hyperlink' => 'PhpOffice\\PhpSpreadsheet\\Cell\\Hyperlink', 'PHPExcel_Cell_IValueBinder' => 'PhpOffice\\PhpSpreadsheet\\Cell\\IValueBinder', 'PHPExcel_Chart_Axis' => 'PhpOffice\\PhpSpreadsheet\\Chart\\Axis', 'PHPExcel_Chart_DataSeries' => 'PhpOffice\\PhpSpreadsheet\\Chart\\DataSeries', 'PHPExcel_Chart_DataSeriesValues' => 'PhpOffice\\PhpSpreadsheet\\Chart\\DataSeriesValues', 'PHPExcel_Chart_Exception' => 'PhpOffice\\PhpSpreadsheet\\Chart\\Exception', 'PHPExcel_Chart_GridLines' => 'PhpOffice\\PhpSpreadsheet\\Chart\\GridLines', 'PHPExcel_Chart_Layout' => 'PhpOffice\\PhpSpreadsheet\\Chart\\Layout', 'PHPExcel_Chart_Legend' => 'PhpOffice\\PhpSpreadsheet\\Chart\\Legend', 'PHPExcel_Chart_PlotArea' => 'PhpOffice\\PhpSpreadsheet\\Chart\\PlotArea', 'PHPExcel_Properties' => 'PhpOffice\\PhpSpreadsheet\\Chart\\Properties', 'PHPExcel_Chart_Title' => 'PhpOffice\\PhpSpreadsheet\\Chart\\Title', 'PHPExcel_DocumentProperties' => 'PhpOffice\\PhpSpreadsheet\\Document\\Properties', 'PHPExcel_DocumentSecurity' => 'PhpOffice\\PhpSpreadsheet\\Document\\Security', 'PHPExcel_Helper_HTML' => 'PhpOffice\\PhpSpreadsheet\\Helper\\Html', 'PHPExcel_Reader_Abstract' => 'PhpOffice\\PhpSpreadsheet\\Reader\\BaseReader', 'PHPExcel_Reader_CSV' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Csv', 'PHPExcel_Reader_DefaultReadFilter' => 'PhpOffice\\PhpSpreadsheet\\Reader\\DefaultReadFilter', 'PHPExcel_Reader_Excel2003XML' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Xml', 'PHPExcel_Reader_Exception' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Exception', 'PHPExcel_Reader_Gnumeric' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Gnumeric', 'PHPExcel_Reader_HTML' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Html', 'PHPExcel_Reader_IReadFilter' => 'PhpOffice\\PhpSpreadsheet\\Reader\\IReadFilter', 'PHPExcel_Reader_IReader' => 'PhpOffice\\PhpSpreadsheet\\Reader\\IReader', 'PHPExcel_Reader_OOCalc' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Ods', 'PHPExcel_Reader_SYLK' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Slk', 'PHPExcel_Reader_Excel5' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Xls', 'PHPExcel_Reader_Excel2007' => 'PhpOffice\\PhpSpreadsheet\\Reader\\Xlsx', 'PHPExcel_RichText_ITextElement' => 'PhpOffice\\PhpSpreadsheet\\RichText\\ITextElement', 'PHPExcel_RichText_Run' => 'PhpOffice\\PhpSpreadsheet\\RichText\\Run', 'PHPExcel_RichText_TextElement' => 'PhpOffice\\PhpSpreadsheet\\RichText\\TextElement', 'PHPExcel_Shared_CodePage' => 'PhpOffice\\PhpSpreadsheet\\Shared\\CodePage', 'PHPExcel_Shared_Date' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Date', 'PHPExcel_Shared_Drawing' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Drawing', 'PHPExcel_Shared_Escher' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Escher', 'PHPExcel_Shared_File' => 'PhpOffice\\PhpSpreadsheet\\Shared\\File', 'PHPExcel_Shared_Font' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Font', 'PHPExcel_Shared_OLE' => 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE', 'PHPExcel_Shared_OLERead' => 'PhpOffice\\PhpSpreadsheet\\Shared\\OLERead', 'PHPExcel_Shared_PasswordHasher' => 'PhpOffice\\PhpSpreadsheet\\Shared\\PasswordHasher', 'PHPExcel_Shared_String' => 'PhpOffice\\PhpSpreadsheet\\Shared\\StringHelper', 'PHPExcel_Shared_TimeZone' => 'PhpOffice\\PhpSpreadsheet\\Shared\\TimeZone', 'PHPExcel_Shared_XMLWriter' => 'PhpOffice\\PhpSpreadsheet\\Shared\\XMLWriter', 'PHPExcel_Shared_Excel5' => 'PhpOffice\\PhpSpreadsheet\\Shared\\Xls', 'PHPExcel_Style_Alignment' => 'PhpOffice\\PhpSpreadsheet\\Style\\Alignment', 'PHPExcel_Style_Border' => 'PhpOffice\\PhpSpreadsheet\\Style\\Border', 'PHPExcel_Style_Borders' => 'PhpOffice\\PhpSpreadsheet\\Style\\Borders', 'PHPExcel_Style_Color' => 'PhpOffice\\PhpSpreadsheet\\Style\\Color', 'PHPExcel_Style_Conditional' => 'PhpOffice\\PhpSpreadsheet\\Style\\Conditional', 'PHPExcel_Style_Fill' => 'PhpOffice\\PhpSpreadsheet\\Style\\Fill', 'PHPExcel_Style_Font' => 'PhpOffice\\PhpSpreadsheet\\Style\\Font', 'PHPExcel_Style_NumberFormat' => 'PhpOffice\\PhpSpreadsheet\\Style\\NumberFormat', 'PHPExcel_Style_Protection' => 'PhpOffice\\PhpSpreadsheet\\Style\\Protection', 'PHPExcel_Style_Supervisor' => 'PhpOffice\\PhpSpreadsheet\\Style\\Supervisor', 'PHPExcel_Worksheet_AutoFilter' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\AutoFilter', 'PHPExcel_Worksheet_BaseDrawing' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\BaseDrawing', 'PHPExcel_Worksheet_CellIterator' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\CellIterator', 'PHPExcel_Worksheet_Column' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Column', 'PHPExcel_Worksheet_ColumnCellIterator' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\ColumnCellIterator', 'PHPExcel_Worksheet_ColumnDimension' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\ColumnDimension', 'PHPExcel_Worksheet_ColumnIterator' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\ColumnIterator', 'PHPExcel_Worksheet_Drawing' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Drawing', 'PHPExcel_Worksheet_HeaderFooter' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\HeaderFooter', 'PHPExcel_Worksheet_HeaderFooterDrawing' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\HeaderFooterDrawing', 'PHPExcel_WorksheetIterator' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Iterator', 'PHPExcel_Worksheet_MemoryDrawing' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\MemoryDrawing', 'PHPExcel_Worksheet_PageMargins' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\PageMargins', 'PHPExcel_Worksheet_PageSetup' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\PageSetup', 'PHPExcel_Worksheet_Protection' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Protection', 'PHPExcel_Worksheet_Row' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Row', 'PHPExcel_Worksheet_RowCellIterator' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\RowCellIterator', 'PHPExcel_Worksheet_RowDimension' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\RowDimension', 'PHPExcel_Worksheet_RowIterator' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\RowIterator', 'PHPExcel_Worksheet_SheetView' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\SheetView', 'PHPExcel_Writer_Abstract' => 'PhpOffice\\PhpSpreadsheet\\Writer\\BaseWriter', 'PHPExcel_Writer_CSV' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Csv', 'PHPExcel_Writer_Exception' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Exception', 'PHPExcel_Writer_HTML' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Html', 'PHPExcel_Writer_IWriter' => 'PhpOffice\\PhpSpreadsheet\\Writer\\IWriter', 'PHPExcel_Writer_OpenDocument' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Ods', 'PHPExcel_Writer_PDF' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Pdf', 'PHPExcel_Writer_Excel5' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xls', 'PHPExcel_Writer_Excel2007' => 'PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx', 'PHPExcel_CachedObjectStorageFactory' => 'PhpOffice\\PhpSpreadsheet\\Collection\\CellsFactory', 'PHPExcel_Calculation' => 'PhpOffice\\PhpSpreadsheet\\Calculation\\Calculation', 'PHPExcel_Cell' => 'PhpOffice\\PhpSpreadsheet\\Cell\\Cell', 'PHPExcel_Chart' => 'PhpOffice\\PhpSpreadsheet\\Chart\\Chart', 'PHPExcel_Comment' => 'PhpOffice\\PhpSpreadsheet\\Comment', 'PHPExcel_Exception' => 'PhpOffice\\PhpSpreadsheet\\Exception', 'PHPExcel_HashTable' => 'PhpOffice\\PhpSpreadsheet\\HashTable', 'PHPExcel_IComparable' => 'PhpOffice\\PhpSpreadsheet\\IComparable', 'PHPExcel_IOFactory' => 'PhpOffice\\PhpSpreadsheet\\IOFactory', 'PHPExcel_NamedRange' => 'PhpOffice\\PhpSpreadsheet\\NamedRange', 'PHPExcel_ReferenceHelper' => 'PhpOffice\\PhpSpreadsheet\\ReferenceHelper', 'PHPExcel_RichText' => 'PhpOffice\\PhpSpreadsheet\\RichText\\RichText', 'PHPExcel_Settings' => 'PhpOffice\\PhpSpreadsheet\\Settings', 'PHPExcel_Style' => 'PhpOffice\\PhpSpreadsheet\\Style\\Style', 'PHPExcel_Worksheet' => 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Worksheet']]]); }; diff --git a/config/set/phpspec-to-phpunit.php b/config/set/phpspec-to-phpunit.php index b593dc18deb..163257b0b91 100644 --- a/config/set/phpspec-to-phpunit.php +++ b/config/set/phpspec-to-phpunit.php @@ -1,6 +1,7 @@ services(); - # 1. first convert mocks - $services->set(PhpSpecMocksToPHPUnitMocksRector::class); - - $services->set(PhpSpecPromisesToPHPUnitAssertRector::class); - + $services->set(\Rector\PhpSpecToPHPUnit\Rector\MethodCall\PhpSpecMocksToPHPUnitMocksRector::class); + $services->set(\Rector\PhpSpecToPHPUnit\Rector\MethodCall\PhpSpecPromisesToPHPUnitAssertRector::class); # 2. then methods - $services->set(PhpSpecMethodToPHPUnitMethodRector::class); - + $services->set(\Rector\PhpSpecToPHPUnit\Rector\ClassMethod\PhpSpecMethodToPHPUnitMethodRector::class); # 3. then the class itself - $services->set(PhpSpecClassToPHPUnitClassRector::class); - - $services->set(AddMockPropertiesRector::class); - $services->set(MockVariableToPropertyFetchRector::class); - $services->set(RenameSpecFileToTestFileRector::class); + $services->set(\Rector\PhpSpecToPHPUnit\Rector\Class_\PhpSpecClassToPHPUnitClassRector::class); + $services->set(\Rector\PhpSpecToPHPUnit\Rector\Class_\AddMockPropertiesRector::class); + $services->set(\Rector\PhpSpecToPHPUnit\Rector\Variable\MockVariableToPropertyFetchRector::class); + $services->set(\Rector\PhpSpecToPHPUnit\Rector\Class_\RenameSpecFileToTestFileRector::class); }; diff --git a/config/set/phpspec30.php b/config/set/phpspec30.php index d3dd7dffb89..76c51b59f49 100644 --- a/config/set/phpspec30.php +++ b/config/set/phpspec30.php @@ -1,41 +1,19 @@ services(); - $services->set(RenameMethodRector::class) - ->call('configure', [[ - RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([ - // @see http://www.phpspec.net/en/stable/manual/upgrading-to-phpspec-3.html - new MethodCallRename('PhpSpec\ServiceContainer', 'set', 'define'), - new MethodCallRename('PhpSpec\ServiceContainer', 'setShared', 'define'), - ]), - ]]); - - $services->set(RenameClassRector::class) - ->call('configure', [[ - RenameClassRector::OLD_TO_NEW_CLASSES => [ - 'PhpSpec\Console\IO' => 'PhpSpec\Console\ConsoleIO', - 'PhpSpec\IO\IOInterface' => 'PhpSpec\IO\IO', - 'PhpSpec\Locator\ResourceInterface' => 'PhpSpec\Locator\Resource', - 'PhpSpec\Locator\ResourceLocatorInterface' => 'PhpSpec\Locator\ResourceLocator', - 'PhpSpec\Formatter\Presenter\PresenterInterface' => 'PhpSpec\Formatter\Presenter\Presenter', - 'PhpSpec\CodeGenerator\Generator\GeneratorInterface' => 'PhpSpec\CodeGenerator\Generator\Generator', - 'PhpSpec\Extension\ExtensionInterface' => 'PhpSpec\Extension', - 'Phpspec\CodeAnalysis\AccessInspectorInterface' => 'Phpspec\CodeAnalysis\AccessInspector', - 'Phpspec\Event\EventInterface' => 'Phpspec\Event\PhpSpecEvent', - 'PhpSpec\Formatter\Presenter\Differ\EngineInterface' => 'PhpSpec\Formatter\Presenter\Differ\DifferEngine', - 'PhpSpec\Matcher\MatcherInterface' => 'PhpSpec\Matcher\Matcher', - 'PhpSpec\Matcher\MatchersProviderInterface' => 'PhpSpec\Matcher\MatchersProvider', - 'PhpSpec\SpecificationInterface' => 'PhpSpec\Specification', - 'PhpSpec\Runner\Maintainer\MaintainerInterface' => 'PhpSpec\Runner\Maintainer\Maintainer', - ], - ]]); + $services->set(\Rector\Renaming\Rector\MethodCall\RenameMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\MethodCall\RenameMethodRector::METHOD_CALL_RENAMES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([ + // @see http://www.phpspec.net/en/stable/manual/upgrading-to-phpspec-3.html + new \Rector\Renaming\ValueObject\MethodCallRename('PhpSpec\\ServiceContainer', 'set', 'define'), + new \Rector\Renaming\ValueObject\MethodCallRename('PhpSpec\\ServiceContainer', 'setShared', 'define'), + ])]]); + $services->set(\Rector\Renaming\Rector\Name\RenameClassRector::class)->call('configure', [[\Rector\Renaming\Rector\Name\RenameClassRector::OLD_TO_NEW_CLASSES => ['PhpSpec\\Console\\IO' => 'PhpSpec\\Console\\ConsoleIO', 'PhpSpec\\IO\\IOInterface' => 'PhpSpec\\IO\\IO', 'PhpSpec\\Locator\\ResourceInterface' => 'PhpSpec\\Locator\\Resource', 'PhpSpec\\Locator\\ResourceLocatorInterface' => 'PhpSpec\\Locator\\ResourceLocator', 'PhpSpec\\Formatter\\Presenter\\PresenterInterface' => 'PhpSpec\\Formatter\\Presenter\\Presenter', 'PhpSpec\\CodeGenerator\\Generator\\GeneratorInterface' => 'PhpSpec\\CodeGenerator\\Generator\\Generator', 'PhpSpec\\Extension\\ExtensionInterface' => 'PhpSpec\\Extension', 'Phpspec\\CodeAnalysis\\AccessInspectorInterface' => 'Phpspec\\CodeAnalysis\\AccessInspector', 'Phpspec\\Event\\EventInterface' => 'Phpspec\\Event\\PhpSpecEvent', 'PhpSpec\\Formatter\\Presenter\\Differ\\EngineInterface' => 'PhpSpec\\Formatter\\Presenter\\Differ\\DifferEngine', 'PhpSpec\\Matcher\\MatcherInterface' => 'PhpSpec\\Matcher\\Matcher', 'PhpSpec\\Matcher\\MatchersProviderInterface' => 'PhpSpec\\Matcher\\MatchersProvider', 'PhpSpec\\SpecificationInterface' => 'PhpSpec\\Specification', 'PhpSpec\\Runner\\Maintainer\\MaintainerInterface' => 'PhpSpec\\Runner\\Maintainer\\Maintainer']]]); }; diff --git a/config/set/phpspec40.php b/config/set/phpspec40.php index 43b710fe4c0..aa658d93272 100644 --- a/config/set/phpspec40.php +++ b/config/set/phpspec40.php @@ -1,23 +1,16 @@ services(); - - $arrayType = new ArrayType(new MixedType(), new MixedType()); - - $services->set(AddReturnTypeDeclarationRector::class) - ->call('configure', [[ - AddReturnTypeDeclarationRector::METHOD_RETURN_TYPES => ValueObjectInliner::inline([ - new AddReturnTypeDeclaration('PhpSpec\ObjectBehavior', 'getMatchers', $arrayType), - ]), - ]]); + $arrayType = new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); + $services->set(\Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationRector::class)->call('configure', [[\Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationRector::METHOD_RETURN_TYPES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\TypeDeclaration\ValueObject\AddReturnTypeDeclaration('PhpSpec\\ObjectBehavior', 'getMatchers', $arrayType)])]]); }; diff --git a/config/set/privatization.php b/config/set/privatization.php index 12ffa80dcb3..cf04b60edd5 100644 --- a/config/set/privatization.php +++ b/config/set/privatization.php @@ -1,6 +1,7 @@ services(); - $services->set(FinalizeClassesWithoutChildrenRector::class); - $services->set(ChangeGlobalVariablesToPropertiesRector::class); - $services->set(ChangeReadOnlyPropertyWithDefaultValueToConstantRector::class); - $services->set(ChangeReadOnlyVariableWithDefaultValueToConstantRector::class); - $services->set(RepeatedLiteralToClassConstantRector::class); - $services->set(PrivatizeLocalGetterToPropertyRector::class); - $services->set(PrivatizeLocalPropertyToPrivatePropertyRector::class); - $services->set(PrivatizeFinalClassPropertyRector::class); - $services->set(PrivatizeFinalClassMethodRector::class); - + $services->set(\Rector\Privatization\Rector\Class_\FinalizeClassesWithoutChildrenRector::class); + $services->set(\Rector\Privatization\Rector\ClassMethod\ChangeGlobalVariablesToPropertiesRector::class); + $services->set(\Rector\Privatization\Rector\Property\ChangeReadOnlyPropertyWithDefaultValueToConstantRector::class); + $services->set(\Rector\Privatization\Rector\Class_\ChangeReadOnlyVariableWithDefaultValueToConstantRector::class); + $services->set(\Rector\Privatization\Rector\Class_\RepeatedLiteralToClassConstantRector::class); + $services->set(\Rector\Privatization\Rector\MethodCall\PrivatizeLocalGetterToPropertyRector::class); + $services->set(\Rector\Privatization\Rector\Property\PrivatizeLocalPropertyToPrivatePropertyRector::class); + $services->set(\Rector\Privatization\Rector\Property\PrivatizeFinalClassPropertyRector::class); + $services->set(\Rector\Privatization\Rector\ClassMethod\PrivatizeFinalClassMethodRector::class); // buggy, requires more work // $services->set(ChangeLocalPropertyToVariableRector::class); }; diff --git a/config/set/psr-4.php b/config/set/psr-4.php index 943ba4c8e2b..eb9bc768292 100644 --- a/config/set/psr-4.php +++ b/config/set/psr-4.php @@ -1,13 +1,13 @@ services(); - $services->set(NormalizeNamespaceByPSR4ComposerAutoloadRector::class); - $services->set(MultipleClassFileToPsr4ClassesRector::class); + $services->set(\Rector\PSR4\Rector\FileWithoutNamespace\NormalizeNamespaceByPSR4ComposerAutoloadRector::class); + $services->set(\Rector\PSR4\Rector\Namespace_\MultipleClassFileToPsr4ClassesRector::class); }; diff --git a/config/set/safe07.php b/config/set/safe07.php index dd39cd9604e..6460a85ac09 100644 --- a/config/set/safe07.php +++ b/config/set/safe07.php @@ -1,1124 +1,12 @@ services(); - $services->set(RenameFunctionRector::class) - ->call('configure', [[ - RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ - 'apache_getenv' => 'Safe\apache_getenv', - 'apache_get_version' => 'Safe\apache_get_version', - 'apache_request_headers' => 'Safe\apache_request_headers', - 'apache_reset_timeout' => 'Safe\apache_reset_timeout', - 'apache_response_headers' => 'Safe\apache_response_headers', - 'apache_setenv' => 'Safe\apache_setenv', - 'apcu_cache_info' => 'Safe\apcu_cache_info', - 'apcu_cas' => 'Safe\apcu_cas', - 'apcu_dec' => 'Safe\apcu_dec', - 'apcu_fetch' => 'Safe\apcu_fetch', - 'apcu_inc' => 'Safe\apcu_inc', - 'apcu_sma_info' => 'Safe\apcu_sma_info', - 'apc_cache_info' => 'Safe\apc_cache_info', - 'apc_cas' => 'Safe\apc_cas', - 'apc_compile_file' => 'Safe\apc_compile_file', - 'apc_dec' => 'Safe\apc_dec', - 'apc_define_constants' => 'Safe\apc_define_constants', - 'apc_delete' => 'Safe\apc_delete', - 'apc_delete_file' => 'Safe\apc_delete_file', - 'apc_fetch' => 'Safe\apc_fetch', - 'apc_inc' => 'Safe\apc_inc', - 'apc_load_constants' => 'Safe\apc_load_constants', - 'apc_sma_info' => 'Safe\apc_sma_info', - 'array_combine' => 'Safe\array_combine', - 'array_flip' => 'Safe\array_flip', - 'array_replace' => 'Safe\array_replace', - 'array_replace_recursive' => 'Safe\array_replace_recursive', - 'array_walk_recursive' => 'Safe\array_walk_recursive', - 'arsort' => 'Safe\arsort', - 'asort' => 'Safe\asort', - 'base64_decode' => 'Safe\base64_decode', - 'bzclose' => 'Safe\bzclose', - 'bzflush' => 'Safe\bzflush', - 'bzread' => 'Safe\bzread', - 'bzwrite' => 'Safe\bzwrite', - 'chdir' => 'Safe\chdir', - 'chgrp' => 'Safe\chgrp', - 'chmod' => 'Safe\chmod', - 'chown' => 'Safe\chown', - 'chroot' => 'Safe\chroot', - 'class_alias' => 'Safe\class_alias', - 'class_implements' => 'Safe\class_implements', - 'class_parents' => 'Safe\class_parents', - 'class_uses' => 'Safe\class_uses', - 'cli_set_process_title' => 'Safe\cli_set_process_title', - 'closelog' => 'Safe\closelog', - 'com_event_sink' => 'Safe\com_event_sink', - 'com_load_typelib' => 'Safe\com_load_typelib', - 'com_print_typeinfo' => 'Safe\com_print_typeinfo', - 'convert_uudecode' => 'Safe\convert_uudecode', - 'convert_uuencode' => 'Safe\convert_uuencode', - 'copy' => 'Safe\copy', - 'create_function' => 'Safe\create_function', - 'cubrid_free_result' => 'Safe\cubrid_free_result', - 'cubrid_get_charset' => 'Safe\cubrid_get_charset', - 'cubrid_get_client_info' => 'Safe\cubrid_get_client_info', - 'cubrid_get_db_parameter' => 'Safe\cubrid_get_db_parameter', - 'cubrid_get_server_info' => 'Safe\cubrid_get_server_info', - 'cubrid_insert_id' => 'Safe\cubrid_insert_id', - 'cubrid_lob2_new' => 'Safe\cubrid_lob2_new', - 'cubrid_lob2_size' => 'Safe\cubrid_lob2_size', - 'cubrid_lob2_size64' => 'Safe\cubrid_lob2_size64', - 'cubrid_lob2_tell' => 'Safe\cubrid_lob2_tell', - 'cubrid_lob2_tell64' => 'Safe\cubrid_lob2_tell64', - 'cubrid_set_db_parameter' => 'Safe\cubrid_set_db_parameter', - 'curl_escape' => 'Safe\curl_escape', - 'curl_exec' => 'Safe\curl_exec', - 'curl_getinfo' => 'Safe\curl_getinfo', - 'curl_init' => 'Safe\curl_init', - 'curl_multi_errno' => 'Safe\curl_multi_errno', - 'curl_multi_info_read' => 'Safe\curl_multi_info_read', - 'curl_multi_init' => 'Safe\curl_multi_init', - 'curl_setopt' => 'Safe\curl_setopt', - 'curl_share_errno' => 'Safe\curl_share_errno', - 'curl_share_setopt' => 'Safe\curl_share_setopt', - 'curl_unescape' => 'Safe\curl_unescape', - 'date_parse' => 'Safe\date_parse', - 'date_parse_from_format' => 'Safe\date_parse_from_format', - 'date_sunrise' => 'Safe\date_sunrise', - 'date_sunset' => 'Safe\date_sunset', - 'date_sun_info' => 'Safe\date_sun_info', - 'db2_autocommit' => 'Safe\db2_autocommit', - 'db2_bind_param' => 'Safe\db2_bind_param', - 'db2_client_info' => 'Safe\db2_client_info', - 'db2_close' => 'Safe\db2_close', - 'db2_commit' => 'Safe\db2_commit', - 'db2_execute' => 'Safe\db2_execute', - 'db2_free_result' => 'Safe\db2_free_result', - 'db2_free_stmt' => 'Safe\db2_free_stmt', - 'db2_get_option' => 'Safe\db2_get_option', - 'db2_pclose' => 'Safe\db2_pclose', - 'db2_rollback' => 'Safe\db2_rollback', - 'db2_server_info' => 'Safe\db2_server_info', - 'db2_set_option' => 'Safe\db2_set_option', - 'define' => 'Safe\define', - 'deflate_add' => 'Safe\deflate_add', - 'deflate_init' => 'Safe\deflate_init', - 'disk_free_space' => 'Safe\disk_free_space', - 'disk_total_space' => 'Safe\disk_total_space', - 'dl' => 'Safe\dl', - 'dns_get_record' => 'Safe\dns_get_record', - 'eio_busy' => 'Safe\eio_busy', - 'eio_chmod' => 'Safe\eio_chmod', - 'eio_chown' => 'Safe\eio_chown', - 'eio_close' => 'Safe\eio_close', - 'eio_custom' => 'Safe\eio_custom', - 'eio_dup2' => 'Safe\eio_dup2', - 'eio_event_loop' => 'Safe\eio_event_loop', - 'eio_fallocate' => 'Safe\eio_fallocate', - 'eio_fchmod' => 'Safe\eio_fchmod', - 'eio_fdatasync' => 'Safe\eio_fdatasync', - 'eio_fstat' => 'Safe\eio_fstat', - 'eio_fstatvfs' => 'Safe\eio_fstatvfs', - 'eio_fsync' => 'Safe\eio_fsync', - 'eio_ftruncate' => 'Safe\eio_ftruncate', - 'eio_futime' => 'Safe\eio_futime', - 'eio_grp' => 'Safe\eio_grp', - 'eio_lstat' => 'Safe\eio_lstat', - 'eio_mkdir' => 'Safe\eio_mkdir', - 'eio_mknod' => 'Safe\eio_mknod', - 'eio_nop' => 'Safe\eio_nop', - 'eio_readahead' => 'Safe\eio_readahead', - 'eio_readdir' => 'Safe\eio_readdir', - 'eio_readlink' => 'Safe\eio_readlink', - 'eio_rename' => 'Safe\eio_rename', - 'eio_rmdir' => 'Safe\eio_rmdir', - 'eio_seek' => 'Safe\eio_seek', - 'eio_sendfile' => 'Safe\eio_sendfile', - 'eio_stat' => 'Safe\eio_stat', - 'eio_statvfs' => 'Safe\eio_statvfs', - 'eio_symlink' => 'Safe\eio_symlink', - 'eio_sync' => 'Safe\eio_sync', - 'eio_syncfs' => 'Safe\eio_syncfs', - 'eio_sync_file_range' => 'Safe\eio_sync_file_range', - 'eio_truncate' => 'Safe\eio_truncate', - 'eio_unlink' => 'Safe\eio_unlink', - 'eio_utime' => 'Safe\eio_utime', - 'eio_write' => 'Safe\eio_write', - 'error_log' => 'Safe\error_log', - 'event_add' => 'Safe\event_add', - 'event_base_loopbreak' => 'Safe\event_base_loopbreak', - 'event_base_loopexit' => 'Safe\event_base_loopexit', - 'event_base_new' => 'Safe\event_base_new', - 'event_base_priority_init' => 'Safe\event_base_priority_init', - 'event_base_reinit' => 'Safe\event_base_reinit', - 'event_base_set' => 'Safe\event_base_set', - 'event_buffer_base_set' => 'Safe\event_buffer_base_set', - 'event_buffer_disable' => 'Safe\event_buffer_disable', - 'event_buffer_enable' => 'Safe\event_buffer_enable', - 'event_buffer_new' => 'Safe\event_buffer_new', - 'event_buffer_priority_set' => 'Safe\event_buffer_priority_set', - 'event_buffer_set_callback' => 'Safe\event_buffer_set_callback', - 'event_buffer_write' => 'Safe\event_buffer_write', - 'event_del' => 'Safe\event_del', - 'event_new' => 'Safe\event_new', - 'event_priority_set' => 'Safe\event_priority_set', - 'event_set' => 'Safe\event_set', - 'event_timer_set' => 'Safe\event_timer_set', - 'fastcgi_finish_request' => 'Safe\fastcgi_finish_request', - 'fbird_blob_cancel' => 'Safe\fbird_blob_cancel', - 'fclose' => 'Safe\fclose', - 'fflush' => 'Safe\fflush', - 'file' => 'Safe\file', - 'fileatime' => 'Safe\fileatime', - 'filectime' => 'Safe\filectime', - 'fileinode' => 'Safe\fileinode', - 'filemtime' => 'Safe\filemtime', - 'fileowner' => 'Safe\fileowner', - 'filesize' => 'Safe\filesize', - 'file_get_contents' => 'Safe\file_get_contents', - 'file_put_contents' => 'Safe\file_put_contents', - 'filter_input_array' => 'Safe\filter_input_array', - 'filter_var_array' => 'Safe\filter_var_array', - 'finfo_close' => 'Safe\finfo_close', - 'finfo_open' => 'Safe\finfo_open', - 'flock' => 'Safe\flock', - 'fopen' => 'Safe\fopen', - 'fputcsv' => 'Safe\fputcsv', - 'fread' => 'Safe\fread', - 'fsockopen' => 'Safe\fsockopen', - 'ftp_alloc' => 'Safe\ftp_alloc', - 'ftp_append' => 'Safe\ftp_append', - 'ftp_cdup' => 'Safe\ftp_cdup', - 'ftp_chdir' => 'Safe\ftp_chdir', - 'ftp_chmod' => 'Safe\ftp_chmod', - 'ftp_close' => 'Safe\ftp_close', - 'ftp_connect' => 'Safe\ftp_connect', - 'ftp_delete' => 'Safe\ftp_delete', - 'ftp_fget' => 'Safe\ftp_fget', - 'ftp_fput' => 'Safe\ftp_fput', - 'ftp_get' => 'Safe\ftp_get', - 'ftp_login' => 'Safe\ftp_login', - 'ftp_mkdir' => 'Safe\ftp_mkdir', - 'ftp_mlsd' => 'Safe\ftp_mlsd', - 'ftp_nlist' => 'Safe\ftp_nlist', - 'ftp_pasv' => 'Safe\ftp_pasv', - 'ftp_put' => 'Safe\ftp_put', - 'ftp_pwd' => 'Safe\ftp_pwd', - 'ftp_rename' => 'Safe\ftp_rename', - 'ftp_rmdir' => 'Safe\ftp_rmdir', - 'ftp_site' => 'Safe\ftp_site', - 'ftp_ssl_connect' => 'Safe\ftp_ssl_connect', - 'ftp_systype' => 'Safe\ftp_systype', - 'ftruncate' => 'Safe\ftruncate', - 'fwrite' => 'Safe\fwrite', - 'getallheaders' => 'Safe\getallheaders', - 'getcwd' => 'Safe\getcwd', - 'gethostname' => 'Safe\gethostname', - 'getimagesize' => 'Safe\getimagesize', - 'getlastmod' => 'Safe\getlastmod', - 'getmygid' => 'Safe\getmygid', - 'getmyinode' => 'Safe\getmyinode', - 'getmypid' => 'Safe\getmypid', - 'getmyuid' => 'Safe\getmyuid', - 'getopt' => 'Safe\getopt', - 'getprotobyname' => 'Safe\getprotobyname', - 'getprotobynumber' => 'Safe\getprotobynumber', - 'get_headers' => 'Safe\get_headers', - 'glob' => 'Safe\glob', - 'gmp_binomial' => 'Safe\gmp_binomial', - 'gmp_export' => 'Safe\gmp_export', - 'gmp_import' => 'Safe\gmp_import', - 'gmp_random_seed' => 'Safe\gmp_random_seed', - 'gnupg_adddecryptkey' => 'Safe\gnupg_adddecryptkey', - 'gnupg_addencryptkey' => 'Safe\gnupg_addencryptkey', - 'gnupg_addsignkey' => 'Safe\gnupg_addsignkey', - 'gnupg_cleardecryptkeys' => 'Safe\gnupg_cleardecryptkeys', - 'gnupg_clearencryptkeys' => 'Safe\gnupg_clearencryptkeys', - 'gnupg_clearsignkeys' => 'Safe\gnupg_clearsignkeys', - 'gnupg_setarmor' => 'Safe\gnupg_setarmor', - 'gnupg_setsignmode' => 'Safe\gnupg_setsignmode', - 'gzclose' => 'Safe\gzclose', - 'gzcompress' => 'Safe\gzcompress', - 'gzdecode' => 'Safe\gzdecode', - 'gzdeflate' => 'Safe\gzdeflate', - 'gzencode' => 'Safe\gzencode', - 'gzgets' => 'Safe\gzgets', - 'gzgetss' => 'Safe\gzgetss', - 'gzinflate' => 'Safe\gzinflate', - 'gzpassthru' => 'Safe\gzpassthru', - 'gzrewind' => 'Safe\gzrewind', - 'gzuncompress' => 'Safe\gzuncompress', - 'hash_hkdf' => 'Safe\hash_hkdf', - 'hash_update_file' => 'Safe\hash_update_file', - 'header_register_callback' => 'Safe\header_register_callback', - 'hex2bin' => 'Safe\hex2bin', - 'highlight_file' => 'Safe\highlight_file', - 'highlight_string' => 'Safe\highlight_string', - 'ibase_add_user' => 'Safe\ibase_add_user', - 'ibase_backup' => 'Safe\ibase_backup', - 'ibase_blob_cancel' => 'Safe\ibase_blob_cancel', - 'ibase_blob_create' => 'Safe\ibase_blob_create', - 'ibase_blob_get' => 'Safe\ibase_blob_get', - 'ibase_close' => 'Safe\ibase_close', - 'ibase_commit' => 'Safe\ibase_commit', - 'ibase_commit_ret' => 'Safe\ibase_commit_ret', - 'ibase_connect' => 'Safe\ibase_connect', - 'ibase_delete_user' => 'Safe\ibase_delete_user', - 'ibase_drop_db' => 'Safe\ibase_drop_db', - 'ibase_free_event_handler' => 'Safe\ibase_free_event_handler', - 'ibase_free_query' => 'Safe\ibase_free_query', - 'ibase_free_result' => 'Safe\ibase_free_result', - 'ibase_maintain_db' => 'Safe\ibase_maintain_db', - 'ibase_modify_user' => 'Safe\ibase_modify_user', - 'ibase_name_result' => 'Safe\ibase_name_result', - 'ibase_pconnect' => 'Safe\ibase_pconnect', - 'ibase_restore' => 'Safe\ibase_restore', - 'ibase_rollback' => 'Safe\ibase_rollback', - 'ibase_rollback_ret' => 'Safe\ibase_rollback_ret', - 'ibase_service_attach' => 'Safe\ibase_service_attach', - 'ibase_service_detach' => 'Safe\ibase_service_detach', - 'iconv' => 'Safe\iconv', - 'iconv_get_encoding' => 'Safe\iconv_get_encoding', - 'iconv_set_encoding' => 'Safe\iconv_set_encoding', - 'image2wbmp' => 'Safe\image2wbmp', - 'imageaffine' => 'Safe\imageaffine', - 'imageaffinematrixconcat' => 'Safe\imageaffinematrixconcat', - 'imageaffinematrixget' => 'Safe\imageaffinematrixget', - 'imagealphablending' => 'Safe\imagealphablending', - 'imageantialias' => 'Safe\imageantialias', - 'imagearc' => 'Safe\imagearc', - 'imagebmp' => 'Safe\imagebmp', - 'imagechar' => 'Safe\imagechar', - 'imagecharup' => 'Safe\imagecharup', - 'imagecolorat' => 'Safe\imagecolorat', - 'imagecolordeallocate' => 'Safe\imagecolordeallocate', - 'imagecolormatch' => 'Safe\imagecolormatch', - 'imageconvolution' => 'Safe\imageconvolution', - 'imagecopy' => 'Safe\imagecopy', - 'imagecopymerge' => 'Safe\imagecopymerge', - 'imagecopymergegray' => 'Safe\imagecopymergegray', - 'imagecopyresampled' => 'Safe\imagecopyresampled', - 'imagecopyresized' => 'Safe\imagecopyresized', - 'imagecreate' => 'Safe\imagecreate', - 'imagecreatefrombmp' => 'Safe\imagecreatefrombmp', - 'imagecreatefromgd' => 'Safe\imagecreatefromgd', - 'imagecreatefromgd2' => 'Safe\imagecreatefromgd2', - 'imagecreatefromgd2part' => 'Safe\imagecreatefromgd2part', - 'imagecreatefromgif' => 'Safe\imagecreatefromgif', - 'imagecreatefromjpeg' => 'Safe\imagecreatefromjpeg', - 'imagecreatefrompng' => 'Safe\imagecreatefrompng', - 'imagecreatefromwbmp' => 'Safe\imagecreatefromwbmp', - 'imagecreatefromwebp' => 'Safe\imagecreatefromwebp', - 'imagecreatefromxbm' => 'Safe\imagecreatefromxbm', - 'imagecreatefromxpm' => 'Safe\imagecreatefromxpm', - 'imagecreatetruecolor' => 'Safe\imagecreatetruecolor', - 'imagecrop' => 'Safe\imagecrop', - 'imagecropauto' => 'Safe\imagecropauto', - 'imagedashedline' => 'Safe\imagedashedline', - 'imagedestroy' => 'Safe\imagedestroy', - 'imageellipse' => 'Safe\imageellipse', - 'imagefill' => 'Safe\imagefill', - 'imagefilledarc' => 'Safe\imagefilledarc', - 'imagefilledellipse' => 'Safe\imagefilledellipse', - 'imagefilledpolygon' => 'Safe\imagefilledpolygon', - 'imagefilledrectangle' => 'Safe\imagefilledrectangle', - 'imagefilltoborder' => 'Safe\imagefilltoborder', - 'imagefilter' => 'Safe\imagefilter', - 'imageflip' => 'Safe\imageflip', - 'imagegammacorrect' => 'Safe\imagegammacorrect', - 'imagegd' => 'Safe\imagegd', - 'imagegd2' => 'Safe\imagegd2', - 'imagegif' => 'Safe\imagegif', - 'imagegrabscreen' => 'Safe\imagegrabscreen', - 'imagegrabwindow' => 'Safe\imagegrabwindow', - 'imagejpeg' => 'Safe\imagejpeg', - 'imagelayereffect' => 'Safe\imagelayereffect', - 'imageline' => 'Safe\imageline', - 'imageloadfont' => 'Safe\imageloadfont', - 'imageopenpolygon' => 'Safe\imageopenpolygon', - 'imagepng' => 'Safe\imagepng', - 'imagepolygon' => 'Safe\imagepolygon', - 'imagepsencodefont' => 'Safe\imagepsencodefont', - 'imagepsextendfont' => 'Safe\imagepsextendfont', - 'imagepsfreefont' => 'Safe\imagepsfreefont', - 'imagepsslantfont' => 'Safe\imagepsslantfont', - 'imagerectangle' => 'Safe\imagerectangle', - 'imagerotate' => 'Safe\imagerotate', - 'imagesavealpha' => 'Safe\imagesavealpha', - 'imagescale' => 'Safe\imagescale', - 'imagesetbrush' => 'Safe\imagesetbrush', - 'imagesetclip' => 'Safe\imagesetclip', - 'imagesetinterpolation' => 'Safe\imagesetinterpolation', - 'imagesetpixel' => 'Safe\imagesetpixel', - 'imagesetstyle' => 'Safe\imagesetstyle', - 'imagesetthickness' => 'Safe\imagesetthickness', - 'imagesettile' => 'Safe\imagesettile', - 'imagestring' => 'Safe\imagestring', - 'imagestringup' => 'Safe\imagestringup', - 'imagesx' => 'Safe\imagesx', - 'imagesy' => 'Safe\imagesy', - 'imagetruecolortopalette' => 'Safe\imagetruecolortopalette', - 'imagettfbbox' => 'Safe\imagettfbbox', - 'imagettftext' => 'Safe\imagettftext', - 'imagewbmp' => 'Safe\imagewbmp', - 'imagewebp' => 'Safe\imagewebp', - 'imagexbm' => 'Safe\imagexbm', - 'imap_append' => 'Safe\imap_append', - 'imap_check' => 'Safe\imap_check', - 'imap_clearflag_full' => 'Safe\imap_clearflag_full', - 'imap_close' => 'Safe\imap_close', - 'imap_createmailbox' => 'Safe\imap_createmailbox', - 'imap_deletemailbox' => 'Safe\imap_deletemailbox', - 'imap_gc' => 'Safe\imap_gc', - 'imap_headerinfo' => 'Safe\imap_headerinfo', - 'imap_mail' => 'Safe\imap_mail', - 'imap_mailboxmsginfo' => 'Safe\imap_mailboxmsginfo', - 'imap_mail_copy' => 'Safe\imap_mail_copy', - 'imap_mail_move' => 'Safe\imap_mail_move', - 'imap_mutf7_to_utf8' => 'Safe\imap_mutf7_to_utf8', - 'imap_num_msg' => 'Safe\imap_num_msg', - 'imap_open' => 'Safe\imap_open', - 'imap_renamemailbox' => 'Safe\imap_renamemailbox', - 'imap_savebody' => 'Safe\imap_savebody', - 'imap_setacl' => 'Safe\imap_setacl', - 'imap_setflag_full' => 'Safe\imap_setflag_full', - 'imap_set_quota' => 'Safe\imap_set_quota', - 'imap_subscribe' => 'Safe\imap_subscribe', - 'imap_thread' => 'Safe\imap_thread', - 'imap_timeout' => 'Safe\imap_timeout', - 'imap_undelete' => 'Safe\imap_undelete', - 'imap_unsubscribe' => 'Safe\imap_unsubscribe', - 'imap_utf8_to_mutf7' => 'Safe\imap_utf8_to_mutf7', - 'inet_ntop' => 'Safe\inet_ntop', - 'inflate_add' => 'Safe\inflate_add', - 'inflate_get_read_len' => 'Safe\inflate_get_read_len', - 'inflate_get_status' => 'Safe\inflate_get_status', - 'inflate_init' => 'Safe\inflate_init', - 'ingres_autocommit' => 'Safe\ingres_autocommit', - 'ingres_close' => 'Safe\ingres_close', - 'ingres_commit' => 'Safe\ingres_commit', - 'ingres_connect' => 'Safe\ingres_connect', - 'ingres_execute' => 'Safe\ingres_execute', - 'ingres_field_name' => 'Safe\ingres_field_name', - 'ingres_field_type' => 'Safe\ingres_field_type', - 'ingres_free_result' => 'Safe\ingres_free_result', - 'ingres_pconnect' => 'Safe\ingres_pconnect', - 'ingres_result_seek' => 'Safe\ingres_result_seek', - 'ingres_rollback' => 'Safe\ingres_rollback', - 'ingres_set_environment' => 'Safe\ingres_set_environment', - 'ini_get' => 'Safe\ini_get', - 'ini_set' => 'Safe\ini_set', - 'inotify_init' => 'Safe\inotify_init', - 'inotify_rm_watch' => 'Safe\inotify_rm_watch', - 'iptcembed' => 'Safe\iptcembed', - 'iptcparse' => 'Safe\iptcparse', - 'jpeg2wbmp' => 'Safe\jpeg2wbmp', - 'json_decode' => 'Safe\json_decode', - 'json_encode' => 'Safe\json_encode', - 'json_last_error_msg' => 'Safe\json_last_error_msg', - 'krsort' => 'Safe\krsort', - 'ksort' => 'Safe\ksort', - 'lchgrp' => 'Safe\lchgrp', - 'lchown' => 'Safe\lchown', - 'ldap_add' => 'Safe\ldap_add', - 'ldap_add_ext' => 'Safe\ldap_add_ext', - 'ldap_bind' => 'Safe\ldap_bind', - 'ldap_bind_ext' => 'Safe\ldap_bind_ext', - 'ldap_control_paged_result' => 'Safe\ldap_control_paged_result', - 'ldap_control_paged_result_response' => 'Safe\ldap_control_paged_result_response', - 'ldap_count_entries' => 'Safe\ldap_count_entries', - 'ldap_delete' => 'Safe\ldap_delete', - 'ldap_delete_ext' => 'Safe\ldap_delete_ext', - 'ldap_exop' => 'Safe\ldap_exop', - 'ldap_exop_passwd' => 'Safe\ldap_exop_passwd', - 'ldap_exop_whoami' => 'Safe\ldap_exop_whoami', - 'ldap_explode_dn' => 'Safe\ldap_explode_dn', - 'ldap_first_attribute' => 'Safe\ldap_first_attribute', - 'ldap_first_entry' => 'Safe\ldap_first_entry', - 'ldap_free_result' => 'Safe\ldap_free_result', - 'ldap_get_attributes' => 'Safe\ldap_get_attributes', - 'ldap_get_dn' => 'Safe\ldap_get_dn', - 'ldap_get_entries' => 'Safe\ldap_get_entries', - 'ldap_get_option' => 'Safe\ldap_get_option', - 'ldap_get_values' => 'Safe\ldap_get_values', - 'ldap_get_values_len' => 'Safe\ldap_get_values_len', - 'ldap_list' => 'Safe\ldap_list', - 'ldap_modify_batch' => 'Safe\ldap_modify_batch', - 'ldap_mod_add' => 'Safe\ldap_mod_add', - 'ldap_mod_add_ext' => 'Safe\ldap_mod_add_ext', - 'ldap_mod_del' => 'Safe\ldap_mod_del', - 'ldap_mod_del_ext' => 'Safe\ldap_mod_del_ext', - 'ldap_mod_replace' => 'Safe\ldap_mod_replace', - 'ldap_mod_replace_ext' => 'Safe\ldap_mod_replace_ext', - 'ldap_next_attribute' => 'Safe\ldap_next_attribute', - 'ldap_parse_exop' => 'Safe\ldap_parse_exop', - 'ldap_parse_result' => 'Safe\ldap_parse_result', - 'ldap_read' => 'Safe\ldap_read', - 'ldap_rename' => 'Safe\ldap_rename', - 'ldap_rename_ext' => 'Safe\ldap_rename_ext', - 'ldap_sasl_bind' => 'Safe\ldap_sasl_bind', - 'ldap_search' => 'Safe\ldap_search', - 'ldap_set_option' => 'Safe\ldap_set_option', - 'ldap_unbind' => 'Safe\ldap_unbind', - 'libxml_get_last_error' => 'Safe\libxml_get_last_error', - 'libxml_set_external_entity_loader' => 'Safe\libxml_set_external_entity_loader', - 'link' => 'Safe\link', - 'lzf_compress' => 'Safe\lzf_compress', - 'lzf_decompress' => 'Safe\lzf_decompress', - 'mailparse_msg_extract_part_file' => 'Safe\mailparse_msg_extract_part_file', - 'mailparse_msg_free' => 'Safe\mailparse_msg_free', - 'mailparse_msg_parse' => 'Safe\mailparse_msg_parse', - 'mailparse_msg_parse_file' => 'Safe\mailparse_msg_parse_file', - 'mailparse_stream_encode' => 'Safe\mailparse_stream_encode', - 'mb_chr' => 'Safe\mb_chr', - 'mb_detect_order' => 'Safe\mb_detect_order', - 'mb_encoding_aliases' => 'Safe\mb_encoding_aliases', - 'mb_eregi_replace' => 'Safe\mb_eregi_replace', - 'mb_ereg_replace' => 'Safe\mb_ereg_replace', - 'mb_ereg_replace_callback' => 'Safe\mb_ereg_replace_callback', - 'mb_ereg_search_getregs' => 'Safe\mb_ereg_search_getregs', - 'mb_ereg_search_init' => 'Safe\mb_ereg_search_init', - 'mb_ereg_search_regs' => 'Safe\mb_ereg_search_regs', - 'mb_ereg_search_setpos' => 'Safe\mb_ereg_search_setpos', - 'mb_http_output' => 'Safe\mb_http_output', - 'mb_internal_encoding' => 'Safe\mb_internal_encoding', - 'mb_ord' => 'Safe\mb_ord', - 'mb_parse_str' => 'Safe\mb_parse_str', - 'mb_regex_encoding' => 'Safe\mb_regex_encoding', - 'mb_send_mail' => 'Safe\mb_send_mail', - 'mb_split' => 'Safe\mb_split', - 'md5_file' => 'Safe\md5_file', - 'metaphone' => 'Safe\metaphone', - 'mime_content_type' => 'Safe\mime_content_type', - 'mkdir' => 'Safe\mkdir', - 'mktime' => 'Safe\mktime', - 'msg_queue_exists' => 'Safe\msg_queue_exists', - 'msg_receive' => 'Safe\msg_receive', - 'msg_remove_queue' => 'Safe\msg_remove_queue', - 'msg_send' => 'Safe\msg_send', - 'msg_set_queue' => 'Safe\msg_set_queue', - 'msql_affected_rows' => 'Safe\msql_affected_rows', - 'msql_close' => 'Safe\msql_close', - 'msql_connect' => 'Safe\msql_connect', - 'msql_create_db' => 'Safe\msql_create_db', - 'msql_data_seek' => 'Safe\msql_data_seek', - 'msql_db_query' => 'Safe\msql_db_query', - 'msql_drop_db' => 'Safe\msql_drop_db', - 'msql_field_len' => 'Safe\msql_field_len', - 'msql_field_name' => 'Safe\msql_field_name', - 'msql_field_seek' => 'Safe\msql_field_seek', - 'msql_field_table' => 'Safe\msql_field_table', - 'msql_field_type' => 'Safe\msql_field_type', - 'msql_free_result' => 'Safe\msql_free_result', - 'msql_pconnect' => 'Safe\msql_pconnect', - 'msql_query' => 'Safe\msql_query', - 'msql_select_db' => 'Safe\msql_select_db', - 'mssql_bind' => 'Safe\mssql_bind', - 'mssql_close' => 'Safe\mssql_close', - 'mssql_connect' => 'Safe\mssql_connect', - 'mssql_data_seek' => 'Safe\mssql_data_seek', - 'mssql_field_length' => 'Safe\mssql_field_length', - 'mssql_field_name' => 'Safe\mssql_field_name', - 'mssql_field_seek' => 'Safe\mssql_field_seek', - 'mssql_field_type' => 'Safe\mssql_field_type', - 'mssql_free_result' => 'Safe\mssql_free_result', - 'mssql_free_statement' => 'Safe\mssql_free_statement', - 'mssql_init' => 'Safe\mssql_init', - 'mssql_pconnect' => 'Safe\mssql_pconnect', - 'mssql_query' => 'Safe\mssql_query', - 'mssql_select_db' => 'Safe\mssql_select_db', - 'mysqli_get_cache_stats' => 'Safe\mysqli_get_cache_stats', - 'mysqli_get_client_stats' => 'Safe\mysqli_get_client_stats', - 'mysqlnd_ms_dump_servers' => 'Safe\mysqlnd_ms_dump_servers', - 'mysqlnd_ms_fabric_select_global' => 'Safe\mysqlnd_ms_fabric_select_global', - 'mysqlnd_ms_fabric_select_shard' => 'Safe\mysqlnd_ms_fabric_select_shard', - 'mysqlnd_ms_get_last_used_connection' => 'Safe\mysqlnd_ms_get_last_used_connection', - 'mysqlnd_qc_clear_cache' => 'Safe\mysqlnd_qc_clear_cache', - 'mysqlnd_qc_set_is_select' => 'Safe\mysqlnd_qc_set_is_select', - 'mysqlnd_qc_set_storage_handler' => 'Safe\mysqlnd_qc_set_storage_handler', - 'mysql_close' => 'Safe\mysql_close', - 'mysql_connect' => 'Safe\mysql_connect', - 'mysql_create_db' => 'Safe\mysql_create_db', - 'mysql_data_seek' => 'Safe\mysql_data_seek', - 'mysql_db_name' => 'Safe\mysql_db_name', - 'mysql_db_query' => 'Safe\mysql_db_query', - 'mysql_drop_db' => 'Safe\mysql_drop_db', - 'mysql_fetch_lengths' => 'Safe\mysql_fetch_lengths', - 'mysql_field_flags' => 'Safe\mysql_field_flags', - 'mysql_field_len' => 'Safe\mysql_field_len', - 'mysql_field_name' => 'Safe\mysql_field_name', - 'mysql_field_seek' => 'Safe\mysql_field_seek', - 'mysql_free_result' => 'Safe\mysql_free_result', - 'mysql_get_host_info' => 'Safe\mysql_get_host_info', - 'mysql_get_proto_info' => 'Safe\mysql_get_proto_info', - 'mysql_get_server_info' => 'Safe\mysql_get_server_info', - 'mysql_info' => 'Safe\mysql_info', - 'mysql_list_dbs' => 'Safe\mysql_list_dbs', - 'mysql_list_fields' => 'Safe\mysql_list_fields', - 'mysql_list_processes' => 'Safe\mysql_list_processes', - 'mysql_list_tables' => 'Safe\mysql_list_tables', - 'mysql_num_fields' => 'Safe\mysql_num_fields', - 'mysql_num_rows' => 'Safe\mysql_num_rows', - 'mysql_query' => 'Safe\mysql_query', - 'mysql_real_escape_string' => 'Safe\mysql_real_escape_string', - 'mysql_result' => 'Safe\mysql_result', - 'mysql_select_db' => 'Safe\mysql_select_db', - 'mysql_set_charset' => 'Safe\mysql_set_charset', - 'mysql_tablename' => 'Safe\mysql_tablename', - 'mysql_thread_id' => 'Safe\mysql_thread_id', - 'mysql_unbuffered_query' => 'Safe\mysql_unbuffered_query', - 'natcasesort' => 'Safe\natcasesort', - 'natsort' => 'Safe\natsort', - 'ob_end_clean' => 'Safe\ob_end_clean', - 'ob_end_flush' => 'Safe\ob_end_flush', - 'oci_bind_array_by_name' => 'Safe\oci_bind_array_by_name', - 'oci_bind_by_name' => 'Safe\oci_bind_by_name', - 'oci_cancel' => 'Safe\oci_cancel', - 'oci_close' => 'Safe\oci_close', - 'oci_commit' => 'Safe\oci_commit', - 'oci_connect' => 'Safe\oci_connect', - 'oci_define_by_name' => 'Safe\oci_define_by_name', - 'oci_execute' => 'Safe\oci_execute', - 'oci_fetch_all' => 'Safe\oci_fetch_all', - 'oci_field_name' => 'Safe\oci_field_name', - 'oci_field_precision' => 'Safe\oci_field_precision', - 'oci_field_scale' => 'Safe\oci_field_scale', - 'oci_field_size' => 'Safe\oci_field_size', - 'oci_field_type' => 'Safe\oci_field_type', - 'oci_field_type_raw' => 'Safe\oci_field_type_raw', - 'oci_free_descriptor' => 'Safe\oci_free_descriptor', - 'oci_free_statement' => 'Safe\oci_free_statement', - 'oci_new_collection' => 'Safe\oci_new_collection', - 'oci_new_connect' => 'Safe\oci_new_connect', - 'oci_new_cursor' => 'Safe\oci_new_cursor', - 'oci_new_descriptor' => 'Safe\oci_new_descriptor', - 'oci_num_fields' => 'Safe\oci_num_fields', - 'oci_num_rows' => 'Safe\oci_num_rows', - 'oci_parse' => 'Safe\oci_parse', - 'oci_pconnect' => 'Safe\oci_pconnect', - 'oci_result' => 'Safe\oci_result', - 'oci_rollback' => 'Safe\oci_rollback', - 'oci_server_version' => 'Safe\oci_server_version', - 'oci_set_action' => 'Safe\oci_set_action', - 'oci_set_call_timeout' => 'Safe\oci_set_call_timeout', - 'oci_set_client_identifier' => 'Safe\oci_set_client_identifier', - 'oci_set_client_info' => 'Safe\oci_set_client_info', - 'oci_set_db_operation' => 'Safe\oci_set_db_operation', - 'oci_set_edition' => 'Safe\oci_set_edition', - 'oci_set_module_name' => 'Safe\oci_set_module_name', - 'oci_set_prefetch' => 'Safe\oci_set_prefetch', - 'oci_statement_type' => 'Safe\oci_statement_type', - 'oci_unregister_taf_callback' => 'Safe\oci_unregister_taf_callback', - 'odbc_autocommit' => 'Safe\odbc_autocommit', - 'odbc_binmode' => 'Safe\odbc_binmode', - 'odbc_columnprivileges' => 'Safe\odbc_columnprivileges', - 'odbc_columns' => 'Safe\odbc_columns', - 'odbc_commit' => 'Safe\odbc_commit', - 'odbc_data_source' => 'Safe\odbc_data_source', - 'odbc_exec' => 'Safe\odbc_exec', - 'odbc_execute' => 'Safe\odbc_execute', - 'odbc_fetch_into' => 'Safe\odbc_fetch_into', - 'odbc_field_len' => 'Safe\odbc_field_len', - 'odbc_field_name' => 'Safe\odbc_field_name', - 'odbc_field_num' => 'Safe\odbc_field_num', - 'odbc_field_scale' => 'Safe\odbc_field_scale', - 'odbc_field_type' => 'Safe\odbc_field_type', - 'odbc_foreignkeys' => 'Safe\odbc_foreignkeys', - 'odbc_gettypeinfo' => 'Safe\odbc_gettypeinfo', - 'odbc_longreadlen' => 'Safe\odbc_longreadlen', - 'odbc_prepare' => 'Safe\odbc_prepare', - 'odbc_primarykeys' => 'Safe\odbc_primarykeys', - 'odbc_result' => 'Safe\odbc_result', - 'odbc_result_all' => 'Safe\odbc_result_all', - 'odbc_rollback' => 'Safe\odbc_rollback', - 'odbc_setoption' => 'Safe\odbc_setoption', - 'odbc_specialcolumns' => 'Safe\odbc_specialcolumns', - 'odbc_statistics' => 'Safe\odbc_statistics', - 'odbc_tableprivileges' => 'Safe\odbc_tableprivileges', - 'odbc_tables' => 'Safe\odbc_tables', - 'opcache_compile_file' => 'Safe\opcache_compile_file', - 'opcache_get_status' => 'Safe\opcache_get_status', - 'opendir' => 'Safe\opendir', - 'openlog' => 'Safe\openlog', - 'openssl_cipher_iv_length' => 'Safe\openssl_cipher_iv_length', - 'openssl_csr_export' => 'Safe\openssl_csr_export', - 'openssl_csr_export_to_file' => 'Safe\openssl_csr_export_to_file', - 'openssl_csr_get_subject' => 'Safe\openssl_csr_get_subject', - 'openssl_csr_new' => 'Safe\openssl_csr_new', - 'openssl_csr_sign' => 'Safe\openssl_csr_sign', - 'openssl_decrypt' => 'Safe\openssl_decrypt', - 'openssl_dh_compute_key' => 'Safe\openssl_dh_compute_key', - 'openssl_digest' => 'Safe\openssl_digest', - 'openssl_encrypt' => 'Safe\openssl_encrypt', - 'openssl_open' => 'Safe\openssl_open', - 'openssl_pbkdf2' => 'Safe\openssl_pbkdf2', - 'openssl_pkcs7_decrypt' => 'Safe\openssl_pkcs7_decrypt', - 'openssl_pkcs7_encrypt' => 'Safe\openssl_pkcs7_encrypt', - 'openssl_pkcs7_read' => 'Safe\openssl_pkcs7_read', - 'openssl_pkcs7_sign' => 'Safe\openssl_pkcs7_sign', - 'openssl_pkcs12_export' => 'Safe\openssl_pkcs12_export', - 'openssl_pkcs12_export_to_file' => 'Safe\openssl_pkcs12_export_to_file', - 'openssl_pkcs12_read' => 'Safe\openssl_pkcs12_read', - 'openssl_pkey_export' => 'Safe\openssl_pkey_export', - 'openssl_pkey_export_to_file' => 'Safe\openssl_pkey_export_to_file', - 'openssl_pkey_get_private' => 'Safe\openssl_pkey_get_private', - 'openssl_pkey_get_public' => 'Safe\openssl_pkey_get_public', - 'openssl_pkey_new' => 'Safe\openssl_pkey_new', - 'openssl_private_decrypt' => 'Safe\openssl_private_decrypt', - 'openssl_private_encrypt' => 'Safe\openssl_private_encrypt', - 'openssl_public_decrypt' => 'Safe\openssl_public_decrypt', - 'openssl_public_encrypt' => 'Safe\openssl_public_encrypt', - 'openssl_random_pseudo_bytes' => 'Safe\openssl_random_pseudo_bytes', - 'openssl_seal' => 'Safe\openssl_seal', - 'openssl_sign' => 'Safe\openssl_sign', - 'openssl_x509_export' => 'Safe\openssl_x509_export', - 'openssl_x509_export_to_file' => 'Safe\openssl_x509_export_to_file', - 'openssl_x509_fingerprint' => 'Safe\openssl_x509_fingerprint', - 'openssl_x509_read' => 'Safe\openssl_x509_read', - 'output_add_rewrite_var' => 'Safe\output_add_rewrite_var', - 'output_reset_rewrite_vars' => 'Safe\output_reset_rewrite_vars', - 'parse_ini_file' => 'Safe\parse_ini_file', - 'parse_ini_string' => 'Safe\parse_ini_string', - 'parse_url' => 'Safe\parse_url', - 'password_hash' => 'Safe\password_hash', - 'pcntl_exec' => 'Safe\pcntl_exec', - 'pcntl_getpriority' => 'Safe\pcntl_getpriority', - 'pcntl_setpriority' => 'Safe\pcntl_setpriority', - 'pcntl_signal_dispatch' => 'Safe\pcntl_signal_dispatch', - 'pcntl_sigprocmask' => 'Safe\pcntl_sigprocmask', - 'pcntl_strerror' => 'Safe\pcntl_strerror', - 'PDF_activate_item' => 'Safe\PDF_activate_item', - 'PDF_add_locallink' => 'Safe\PDF_add_locallink', - 'PDF_add_nameddest' => 'Safe\PDF_add_nameddest', - 'PDF_add_note' => 'Safe\PDF_add_note', - 'PDF_add_pdflink' => 'Safe\PDF_add_pdflink', - 'PDF_add_thumbnail' => 'Safe\PDF_add_thumbnail', - 'PDF_add_weblink' => 'Safe\PDF_add_weblink', - 'PDF_attach_file' => 'Safe\PDF_attach_file', - 'PDF_begin_layer' => 'Safe\PDF_begin_layer', - 'PDF_begin_page' => 'Safe\PDF_begin_page', - 'PDF_begin_page_ext' => 'Safe\PDF_begin_page_ext', - 'PDF_circle' => 'Safe\PDF_circle', - 'PDF_clip' => 'Safe\PDF_clip', - 'PDF_close' => 'Safe\PDF_close', - 'PDF_closepath' => 'Safe\PDF_closepath', - 'PDF_closepath_fill_stroke' => 'Safe\PDF_closepath_fill_stroke', - 'PDF_closepath_stroke' => 'Safe\PDF_closepath_stroke', - 'PDF_close_pdi' => 'Safe\PDF_close_pdi', - 'PDF_close_pdi_page' => 'Safe\PDF_close_pdi_page', - 'PDF_concat' => 'Safe\PDF_concat', - 'PDF_continue_text' => 'Safe\PDF_continue_text', - 'PDF_curveto' => 'Safe\PDF_curveto', - 'PDF_delete' => 'Safe\PDF_delete', - 'PDF_end_layer' => 'Safe\PDF_end_layer', - 'PDF_end_page' => 'Safe\PDF_end_page', - 'PDF_end_page_ext' => 'Safe\PDF_end_page_ext', - 'PDF_end_pattern' => 'Safe\PDF_end_pattern', - 'PDF_end_template' => 'Safe\PDF_end_template', - 'PDF_fill' => 'Safe\PDF_fill', - 'PDF_fill_stroke' => 'Safe\PDF_fill_stroke', - 'PDF_fit_image' => 'Safe\PDF_fit_image', - 'PDF_fit_pdi_page' => 'Safe\PDF_fit_pdi_page', - 'PDF_fit_textline' => 'Safe\PDF_fit_textline', - 'PDF_initgraphics' => 'Safe\PDF_initgraphics', - 'PDF_lineto' => 'Safe\PDF_lineto', - 'PDF_makespotcolor' => 'Safe\PDF_makespotcolor', - 'PDF_moveto' => 'Safe\PDF_moveto', - 'PDF_open_file' => 'Safe\PDF_open_file', - 'PDF_place_image' => 'Safe\PDF_place_image', - 'PDF_place_pdi_page' => 'Safe\PDF_place_pdi_page', - 'PDF_rect' => 'Safe\PDF_rect', - 'PDF_restore' => 'Safe\PDF_restore', - 'PDF_rotate' => 'Safe\PDF_rotate', - 'PDF_save' => 'Safe\PDF_save', - 'PDF_scale' => 'Safe\PDF_scale', - 'PDF_setcolor' => 'Safe\PDF_setcolor', - 'PDF_setdash' => 'Safe\PDF_setdash', - 'PDF_setdashpattern' => 'Safe\PDF_setdashpattern', - 'PDF_setflat' => 'Safe\PDF_setflat', - 'PDF_setfont' => 'Safe\PDF_setfont', - 'PDF_setgray' => 'Safe\PDF_setgray', - 'PDF_setgray_fill' => 'Safe\PDF_setgray_fill', - 'PDF_setgray_stroke' => 'Safe\PDF_setgray_stroke', - 'PDF_setlinejoin' => 'Safe\PDF_setlinejoin', - 'PDF_setlinewidth' => 'Safe\PDF_setlinewidth', - 'PDF_setmatrix' => 'Safe\PDF_setmatrix', - 'PDF_setmiterlimit' => 'Safe\PDF_setmiterlimit', - 'PDF_setrgbcolor' => 'Safe\PDF_setrgbcolor', - 'PDF_setrgbcolor_fill' => 'Safe\PDF_setrgbcolor_fill', - 'PDF_setrgbcolor_stroke' => 'Safe\PDF_setrgbcolor_stroke', - 'PDF_set_border_color' => 'Safe\PDF_set_border_color', - 'PDF_set_border_dash' => 'Safe\PDF_set_border_dash', - 'PDF_set_border_style' => 'Safe\PDF_set_border_style', - 'PDF_set_info' => 'Safe\PDF_set_info', - 'PDF_set_layer_dependency' => 'Safe\PDF_set_layer_dependency', - 'PDF_set_parameter' => 'Safe\PDF_set_parameter', - 'PDF_set_text_pos' => 'Safe\PDF_set_text_pos', - 'PDF_set_value' => 'Safe\PDF_set_value', - 'PDF_show' => 'Safe\PDF_show', - 'PDF_show_xy' => 'Safe\PDF_show_xy', - 'PDF_skew' => 'Safe\PDF_skew', - 'PDF_stroke' => 'Safe\PDF_stroke', - 'pg_cancel_query' => 'Safe\pg_cancel_query', - 'pg_client_encoding' => 'Safe\pg_client_encoding', - 'pg_close' => 'Safe\pg_close', - 'pg_connect' => 'Safe\pg_connect', - 'pg_connection_reset' => 'Safe\pg_connection_reset', - 'pg_convert' => 'Safe\pg_convert', - 'pg_copy_from' => 'Safe\pg_copy_from', - 'pg_copy_to' => 'Safe\pg_copy_to', - 'pg_dbname' => 'Safe\pg_dbname', - 'pg_delete' => 'Safe\pg_delete', - 'pg_end_copy' => 'Safe\pg_end_copy', - 'pg_execute' => 'Safe\pg_execute', - 'pg_field_name' => 'Safe\pg_field_name', - 'pg_field_table' => 'Safe\pg_field_table', - 'pg_field_type' => 'Safe\pg_field_type', - 'pg_flush' => 'Safe\pg_flush', - 'pg_free_result' => 'Safe\pg_free_result', - 'pg_host' => 'Safe\pg_host', - 'pg_insert' => 'Safe\pg_insert', - 'pg_last_error' => 'Safe\pg_last_error', - 'pg_last_notice' => 'Safe\pg_last_notice', - 'pg_last_oid' => 'Safe\pg_last_oid', - 'pg_lo_close' => 'Safe\pg_lo_close', - 'pg_lo_export' => 'Safe\pg_lo_export', - 'pg_lo_import' => 'Safe\pg_lo_import', - 'pg_lo_open' => 'Safe\pg_lo_open', - 'pg_lo_read' => 'Safe\pg_lo_read', - 'pg_lo_read_all' => 'Safe\pg_lo_read_all', - 'pg_lo_seek' => 'Safe\pg_lo_seek', - 'pg_lo_truncate' => 'Safe\pg_lo_truncate', - 'pg_lo_unlink' => 'Safe\pg_lo_unlink', - 'pg_lo_write' => 'Safe\pg_lo_write', - 'pg_meta_data' => 'Safe\pg_meta_data', - 'pg_options' => 'Safe\pg_options', - 'pg_parameter_status' => 'Safe\pg_parameter_status', - 'pg_pconnect' => 'Safe\pg_pconnect', - 'pg_ping' => 'Safe\pg_ping', - 'pg_port' => 'Safe\pg_port', - 'pg_prepare' => 'Safe\pg_prepare', - 'pg_put_line' => 'Safe\pg_put_line', - 'pg_query' => 'Safe\pg_query', - 'pg_query_params' => 'Safe\pg_query_params', - 'pg_result_error_field' => 'Safe\pg_result_error_field', - 'pg_result_seek' => 'Safe\pg_result_seek', - 'pg_select' => 'Safe\pg_select', - 'pg_send_execute' => 'Safe\pg_send_execute', - 'pg_send_prepare' => 'Safe\pg_send_prepare', - 'pg_send_query' => 'Safe\pg_send_query', - 'pg_send_query_params' => 'Safe\pg_send_query_params', - 'pg_socket' => 'Safe\pg_socket', - 'pg_trace' => 'Safe\pg_trace', - 'pg_tty' => 'Safe\pg_tty', - 'pg_update' => 'Safe\pg_update', - 'pg_version' => 'Safe\pg_version', - 'phpcredits' => 'Safe\phpcredits', - 'phpinfo' => 'Safe\phpinfo', - 'png2wbmp' => 'Safe\png2wbmp', - 'posix_access' => 'Safe\posix_access', - 'posix_getgrnam' => 'Safe\posix_getgrnam', - 'posix_getpgid' => 'Safe\posix_getpgid', - 'posix_initgroups' => 'Safe\posix_initgroups', - 'posix_kill' => 'Safe\posix_kill', - 'posix_mkfifo' => 'Safe\posix_mkfifo', - 'posix_mknod' => 'Safe\posix_mknod', - 'posix_setegid' => 'Safe\posix_setegid', - 'posix_seteuid' => 'Safe\posix_seteuid', - 'posix_setgid' => 'Safe\posix_setgid', - 'posix_setpgid' => 'Safe\posix_setpgid', - 'posix_setrlimit' => 'Safe\posix_setrlimit', - 'posix_setuid' => 'Safe\posix_setuid', - 'preg_match' => 'Safe\preg_match', - 'preg_match_all' => 'Safe\preg_match_all', - 'preg_replace' => 'Safe\preg_replace', - 'preg_split' => 'Safe\preg_split', - 'proc_get_status' => 'Safe\proc_get_status', - 'proc_nice' => 'Safe\proc_nice', - 'pspell_add_to_personal' => 'Safe\pspell_add_to_personal', - 'pspell_add_to_session' => 'Safe\pspell_add_to_session', - 'pspell_clear_session' => 'Safe\pspell_clear_session', - 'pspell_config_create' => 'Safe\pspell_config_create', - 'pspell_config_data_dir' => 'Safe\pspell_config_data_dir', - 'pspell_config_dict_dir' => 'Safe\pspell_config_dict_dir', - 'pspell_config_ignore' => 'Safe\pspell_config_ignore', - 'pspell_config_mode' => 'Safe\pspell_config_mode', - 'pspell_config_personal' => 'Safe\pspell_config_personal', - 'pspell_config_repl' => 'Safe\pspell_config_repl', - 'pspell_config_runtogether' => 'Safe\pspell_config_runtogether', - 'pspell_config_save_repl' => 'Safe\pspell_config_save_repl', - 'pspell_new' => 'Safe\pspell_new', - 'pspell_new_config' => 'Safe\pspell_new_config', - 'pspell_save_wordlist' => 'Safe\pspell_save_wordlist', - 'pspell_store_replacement' => 'Safe\pspell_store_replacement', - 'ps_add_launchlink' => 'Safe\ps_add_launchlink', - 'ps_add_locallink' => 'Safe\ps_add_locallink', - 'ps_add_note' => 'Safe\ps_add_note', - 'ps_add_pdflink' => 'Safe\ps_add_pdflink', - 'ps_add_weblink' => 'Safe\ps_add_weblink', - 'ps_arc' => 'Safe\ps_arc', - 'ps_arcn' => 'Safe\ps_arcn', - 'ps_begin_page' => 'Safe\ps_begin_page', - 'ps_begin_pattern' => 'Safe\ps_begin_pattern', - 'ps_begin_template' => 'Safe\ps_begin_template', - 'ps_circle' => 'Safe\ps_circle', - 'ps_clip' => 'Safe\ps_clip', - 'ps_close' => 'Safe\ps_close', - 'ps_closepath' => 'Safe\ps_closepath', - 'ps_closepath_stroke' => 'Safe\ps_closepath_stroke', - 'ps_close_image' => 'Safe\ps_close_image', - 'ps_continue_text' => 'Safe\ps_continue_text', - 'ps_curveto' => 'Safe\ps_curveto', - 'ps_delete' => 'Safe\ps_delete', - 'ps_end_page' => 'Safe\ps_end_page', - 'ps_end_pattern' => 'Safe\ps_end_pattern', - 'ps_end_template' => 'Safe\ps_end_template', - 'ps_fill' => 'Safe\ps_fill', - 'ps_fill_stroke' => 'Safe\ps_fill_stroke', - 'ps_get_parameter' => 'Safe\ps_get_parameter', - 'ps_hyphenate' => 'Safe\ps_hyphenate', - 'ps_include_file' => 'Safe\ps_include_file', - 'ps_lineto' => 'Safe\ps_lineto', - 'ps_moveto' => 'Safe\ps_moveto', - 'ps_new' => 'Safe\ps_new', - 'ps_open_file' => 'Safe\ps_open_file', - 'ps_place_image' => 'Safe\ps_place_image', - 'ps_rect' => 'Safe\ps_rect', - 'ps_restore' => 'Safe\ps_restore', - 'ps_rotate' => 'Safe\ps_rotate', - 'ps_save' => 'Safe\ps_save', - 'ps_scale' => 'Safe\ps_scale', - 'ps_setcolor' => 'Safe\ps_setcolor', - 'ps_setdash' => 'Safe\ps_setdash', - 'ps_setflat' => 'Safe\ps_setflat', - 'ps_setfont' => 'Safe\ps_setfont', - 'ps_setgray' => 'Safe\ps_setgray', - 'ps_setlinecap' => 'Safe\ps_setlinecap', - 'ps_setlinejoin' => 'Safe\ps_setlinejoin', - 'ps_setlinewidth' => 'Safe\ps_setlinewidth', - 'ps_setmiterlimit' => 'Safe\ps_setmiterlimit', - 'ps_setoverprintmode' => 'Safe\ps_setoverprintmode', - 'ps_setpolydash' => 'Safe\ps_setpolydash', - 'ps_set_border_color' => 'Safe\ps_set_border_color', - 'ps_set_border_dash' => 'Safe\ps_set_border_dash', - 'ps_set_border_style' => 'Safe\ps_set_border_style', - 'ps_set_info' => 'Safe\ps_set_info', - 'ps_set_parameter' => 'Safe\ps_set_parameter', - 'ps_set_text_pos' => 'Safe\ps_set_text_pos', - 'ps_set_value' => 'Safe\ps_set_value', - 'ps_shading' => 'Safe\ps_shading', - 'ps_shading_pattern' => 'Safe\ps_shading_pattern', - 'ps_shfill' => 'Safe\ps_shfill', - 'ps_show' => 'Safe\ps_show', - 'ps_show2' => 'Safe\ps_show2', - 'ps_show_xy' => 'Safe\ps_show_xy', - 'ps_show_xy2' => 'Safe\ps_show_xy2', - 'ps_stroke' => 'Safe\ps_stroke', - 'ps_symbol' => 'Safe\ps_symbol', - 'ps_translate' => 'Safe\ps_translate', - 'putenv' => 'Safe\putenv', - 'readfile' => 'Safe\readfile', - 'readgzfile' => 'Safe\readgzfile', - 'readline_add_history' => 'Safe\readline_add_history', - 'readline_callback_handler_install' => 'Safe\readline_callback_handler_install', - 'readline_clear_history' => 'Safe\readline_clear_history', - 'readline_completion_function' => 'Safe\readline_completion_function', - 'readline_read_history' => 'Safe\readline_read_history', - 'readline_write_history' => 'Safe\readline_write_history', - 'readlink' => 'Safe\readlink', - 'realpath' => 'Safe\realpath', - 'register_tick_function' => 'Safe\register_tick_function', - 'rename' => 'Safe\rename', - 'rewind' => 'Safe\rewind', - 'rewinddir' => 'Safe\rewinddir', - 'rmdir' => 'Safe\rmdir', - 'rrd_create' => 'Safe\rrd_create', - 'rsort' => 'Safe\rsort', - 'sapi_windows_cp_conv' => 'Safe\sapi_windows_cp_conv', - 'sapi_windows_cp_set' => 'Safe\sapi_windows_cp_set', - 'sapi_windows_generate_ctrl_event' => 'Safe\sapi_windows_generate_ctrl_event', - 'sapi_windows_vt100_support' => 'Safe\sapi_windows_vt100_support', - 'scandir' => 'Safe\scandir', - 'sem_acquire' => 'Safe\sem_acquire', - 'sem_get' => 'Safe\sem_get', - 'sem_release' => 'Safe\sem_release', - 'sem_remove' => 'Safe\sem_remove', - 'session_abort' => 'Safe\session_abort', - 'session_decode' => 'Safe\session_decode', - 'session_destroy' => 'Safe\session_destroy', - 'session_regenerate_id' => 'Safe\session_regenerate_id', - 'session_reset' => 'Safe\session_reset', - 'session_unset' => 'Safe\session_unset', - 'session_write_close' => 'Safe\session_write_close', - 'settype' => 'Safe\settype', - 'set_include_path' => 'Safe\set_include_path', - 'set_time_limit' => 'Safe\set_time_limit', - 'sha1_file' => 'Safe\sha1_file', - 'shmop_delete' => 'Safe\shmop_delete', - 'shmop_read' => 'Safe\shmop_read', - 'shmop_write' => 'Safe\shmop_write', - 'shm_put_var' => 'Safe\shm_put_var', - 'shm_remove' => 'Safe\shm_remove', - 'shm_remove_var' => 'Safe\shm_remove_var', - 'shuffle' => 'Safe\shuffle', - 'simplexml_import_dom' => 'Safe\simplexml_import_dom', - 'simplexml_load_file' => 'Safe\simplexml_load_file', - 'simplexml_load_string' => 'Safe\simplexml_load_string', - 'sleep' => 'Safe\sleep', - 'socket_accept' => 'Safe\socket_accept', - 'socket_addrinfo_bind' => 'Safe\socket_addrinfo_bind', - 'socket_addrinfo_connect' => 'Safe\socket_addrinfo_connect', - 'socket_bind' => 'Safe\socket_bind', - 'socket_connect' => 'Safe\socket_connect', - 'socket_create' => 'Safe\socket_create', - 'socket_create_listen' => 'Safe\socket_create_listen', - 'socket_create_pair' => 'Safe\socket_create_pair', - 'socket_export_stream' => 'Safe\socket_export_stream', - 'socket_getpeername' => 'Safe\socket_getpeername', - 'socket_getsockname' => 'Safe\socket_getsockname', - 'socket_get_option' => 'Safe\socket_get_option', - 'socket_import_stream' => 'Safe\socket_import_stream', - 'socket_listen' => 'Safe\socket_listen', - 'socket_read' => 'Safe\socket_read', - 'socket_send' => 'Safe\socket_send', - 'socket_sendmsg' => 'Safe\socket_sendmsg', - 'socket_sendto' => 'Safe\socket_sendto', - 'socket_set_block' => 'Safe\socket_set_block', - 'socket_set_nonblock' => 'Safe\socket_set_nonblock', - 'socket_set_option' => 'Safe\socket_set_option', - 'socket_shutdown' => 'Safe\socket_shutdown', - 'socket_write' => 'Safe\socket_write', - 'socket_wsaprotocol_info_export' => 'Safe\socket_wsaprotocol_info_export', - 'socket_wsaprotocol_info_import' => 'Safe\socket_wsaprotocol_info_import', - 'socket_wsaprotocol_info_release' => 'Safe\socket_wsaprotocol_info_release', - 'sodium_crypto_pwhash' => 'Safe\sodium_crypto_pwhash', - 'sodium_crypto_pwhash_str' => 'Safe\sodium_crypto_pwhash_str', - 'solr_get_version' => 'Safe\solr_get_version', - 'sort' => 'Safe\sort', - 'soundex' => 'Safe\soundex', - 'spl_autoload_register' => 'Safe\spl_autoload_register', - 'spl_autoload_unregister' => 'Safe\spl_autoload_unregister', - 'sprintf' => 'Safe\sprintf', - 'sqlsrv_begin_transaction' => 'Safe\sqlsrv_begin_transaction', - 'sqlsrv_cancel' => 'Safe\sqlsrv_cancel', - 'sqlsrv_client_info' => 'Safe\sqlsrv_client_info', - 'sqlsrv_close' => 'Safe\sqlsrv_close', - 'sqlsrv_commit' => 'Safe\sqlsrv_commit', - 'sqlsrv_configure' => 'Safe\sqlsrv_configure', - 'sqlsrv_execute' => 'Safe\sqlsrv_execute', - 'sqlsrv_free_stmt' => 'Safe\sqlsrv_free_stmt', - 'sqlsrv_get_field' => 'Safe\sqlsrv_get_field', - 'sqlsrv_next_result' => 'Safe\sqlsrv_next_result', - 'sqlsrv_num_fields' => 'Safe\sqlsrv_num_fields', - 'sqlsrv_num_rows' => 'Safe\sqlsrv_num_rows', - 'sqlsrv_prepare' => 'Safe\sqlsrv_prepare', - 'sqlsrv_query' => 'Safe\sqlsrv_query', - 'sqlsrv_rollback' => 'Safe\sqlsrv_rollback', - 'ssdeep_fuzzy_compare' => 'Safe\ssdeep_fuzzy_compare', - 'ssdeep_fuzzy_hash' => 'Safe\ssdeep_fuzzy_hash', - 'ssdeep_fuzzy_hash_filename' => 'Safe\ssdeep_fuzzy_hash_filename', - 'ssh2_auth_agent' => 'Safe\ssh2_auth_agent', - 'ssh2_auth_hostbased_file' => 'Safe\ssh2_auth_hostbased_file', - 'ssh2_auth_password' => 'Safe\ssh2_auth_password', - 'ssh2_auth_pubkey_file' => 'Safe\ssh2_auth_pubkey_file', - 'ssh2_connect' => 'Safe\ssh2_connect', - 'ssh2_disconnect' => 'Safe\ssh2_disconnect', - 'ssh2_exec' => 'Safe\ssh2_exec', - 'ssh2_publickey_add' => 'Safe\ssh2_publickey_add', - 'ssh2_publickey_init' => 'Safe\ssh2_publickey_init', - 'ssh2_publickey_remove' => 'Safe\ssh2_publickey_remove', - 'ssh2_scp_recv' => 'Safe\ssh2_scp_recv', - 'ssh2_scp_send' => 'Safe\ssh2_scp_send', - 'ssh2_sftp' => 'Safe\ssh2_sftp', - 'ssh2_sftp_chmod' => 'Safe\ssh2_sftp_chmod', - 'ssh2_sftp_mkdir' => 'Safe\ssh2_sftp_mkdir', - 'ssh2_sftp_rename' => 'Safe\ssh2_sftp_rename', - 'ssh2_sftp_rmdir' => 'Safe\ssh2_sftp_rmdir', - 'ssh2_sftp_symlink' => 'Safe\ssh2_sftp_symlink', - 'ssh2_sftp_unlink' => 'Safe\ssh2_sftp_unlink', - 'stats_covariance' => 'Safe\stats_covariance', - 'stats_standard_deviation' => 'Safe\stats_standard_deviation', - 'stats_stat_correlation' => 'Safe\stats_stat_correlation', - 'stats_stat_innerproduct' => 'Safe\stats_stat_innerproduct', - 'stats_variance' => 'Safe\stats_variance', - 'stream_context_set_params' => 'Safe\stream_context_set_params', - 'stream_copy_to_stream' => 'Safe\stream_copy_to_stream', - 'stream_filter_append' => 'Safe\stream_filter_append', - 'stream_filter_prepend' => 'Safe\stream_filter_prepend', - 'stream_filter_register' => 'Safe\stream_filter_register', - 'stream_filter_remove' => 'Safe\stream_filter_remove', - 'stream_get_contents' => 'Safe\stream_get_contents', - 'stream_isatty' => 'Safe\stream_isatty', - 'stream_resolve_include_path' => 'Safe\stream_resolve_include_path', - 'stream_set_blocking' => 'Safe\stream_set_blocking', - 'stream_set_timeout' => 'Safe\stream_set_timeout', - 'stream_socket_accept' => 'Safe\stream_socket_accept', - 'stream_socket_client' => 'Safe\stream_socket_client', - 'stream_socket_pair' => 'Safe\stream_socket_pair', - 'stream_socket_server' => 'Safe\stream_socket_server', - 'stream_socket_shutdown' => 'Safe\stream_socket_shutdown', - 'stream_supports_lock' => 'Safe\stream_supports_lock', - 'stream_wrapper_register' => 'Safe\stream_wrapper_register', - 'stream_wrapper_restore' => 'Safe\stream_wrapper_restore', - 'stream_wrapper_unregister' => 'Safe\stream_wrapper_unregister', - 'strptime' => 'Safe\strptime', - 'strtotime' => 'Safe\strtotime', - 'substr' => 'Safe\substr', - 'swoole_async_write' => 'Safe\swoole_async_write', - 'swoole_async_writefile' => 'Safe\swoole_async_writefile', - 'swoole_event_defer' => 'Safe\swoole_event_defer', - 'swoole_event_del' => 'Safe\swoole_event_del', - 'swoole_event_write' => 'Safe\swoole_event_write', - 'symlink' => 'Safe\symlink', - 'syslog' => 'Safe\syslog', - 'system' => 'Safe\system', - 'tempnam' => 'Safe\tempnam', - 'timezone_name_from_abbr' => 'Safe\timezone_name_from_abbr', - 'time_nanosleep' => 'Safe\time_nanosleep', - 'time_sleep_until' => 'Safe\time_sleep_until', - 'tmpfile' => 'Safe\tmpfile', - 'touch' => 'Safe\touch', - 'uasort' => 'Safe\uasort', - 'uksort' => 'Safe\uksort', - 'unlink' => 'Safe\unlink', - 'uopz_extend' => 'Safe\uopz_extend', - 'uopz_implement' => 'Safe\uopz_implement', - 'usort' => 'Safe\usort', - 'virtual' => 'Safe\virtual', - 'vsprintf' => 'Safe\vsprintf', - 'xdiff_file_bdiff' => 'Safe\xdiff_file_bdiff', - 'xdiff_file_bpatch' => 'Safe\xdiff_file_bpatch', - 'xdiff_file_diff' => 'Safe\xdiff_file_diff', - 'xdiff_file_diff_binary' => 'Safe\xdiff_file_diff_binary', - 'xdiff_file_patch_binary' => 'Safe\xdiff_file_patch_binary', - 'xdiff_file_rabdiff' => 'Safe\xdiff_file_rabdiff', - 'xdiff_string_bpatch' => 'Safe\xdiff_string_bpatch', - 'xdiff_string_patch' => 'Safe\xdiff_string_patch', - 'xdiff_string_patch_binary' => 'Safe\xdiff_string_patch_binary', - 'xmlrpc_set_type' => 'Safe\xmlrpc_set_type', - 'xml_parser_create' => 'Safe\xml_parser_create', - 'xml_parser_create_ns' => 'Safe\xml_parser_create_ns', - 'xml_set_object' => 'Safe\xml_set_object', - 'yaml_parse' => 'Safe\yaml_parse', - 'yaml_parse_file' => 'Safe\yaml_parse_file', - 'yaml_parse_url' => 'Safe\yaml_parse_url', - 'yaz_ccl_parse' => 'Safe\yaz_ccl_parse', - 'yaz_close' => 'Safe\yaz_close', - 'yaz_connect' => 'Safe\yaz_connect', - 'yaz_database' => 'Safe\yaz_database', - 'yaz_element' => 'Safe\yaz_element', - 'yaz_present' => 'Safe\yaz_present', - 'yaz_search' => 'Safe\yaz_search', - 'yaz_wait' => 'Safe\yaz_wait', - 'zip_entry_close' => 'Safe\zip_entry_close', - 'zip_entry_open' => 'Safe\zip_entry_open', - 'zip_entry_read' => 'Safe\zip_entry_read', - 'zlib_decode' => 'Safe\zlib_decode', - ], - ]]); + $services->set(\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::class)->call('configure', [[\Rector\Renaming\Rector\FuncCall\RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => ['apache_getenv' => 'Safe\\apache_getenv', 'apache_get_version' => 'Safe\\apache_get_version', 'apache_request_headers' => 'Safe\\apache_request_headers', 'apache_reset_timeout' => 'Safe\\apache_reset_timeout', 'apache_response_headers' => 'Safe\\apache_response_headers', 'apache_setenv' => 'Safe\\apache_setenv', 'apcu_cache_info' => 'Safe\\apcu_cache_info', 'apcu_cas' => 'Safe\\apcu_cas', 'apcu_dec' => 'Safe\\apcu_dec', 'apcu_fetch' => 'Safe\\apcu_fetch', 'apcu_inc' => 'Safe\\apcu_inc', 'apcu_sma_info' => 'Safe\\apcu_sma_info', 'apc_cache_info' => 'Safe\\apc_cache_info', 'apc_cas' => 'Safe\\apc_cas', 'apc_compile_file' => 'Safe\\apc_compile_file', 'apc_dec' => 'Safe\\apc_dec', 'apc_define_constants' => 'Safe\\apc_define_constants', 'apc_delete' => 'Safe\\apc_delete', 'apc_delete_file' => 'Safe\\apc_delete_file', 'apc_fetch' => 'Safe\\apc_fetch', 'apc_inc' => 'Safe\\apc_inc', 'apc_load_constants' => 'Safe\\apc_load_constants', 'apc_sma_info' => 'Safe\\apc_sma_info', 'array_combine' => 'Safe\\array_combine', 'array_flip' => 'Safe\\array_flip', 'array_replace' => 'Safe\\array_replace', 'array_replace_recursive' => 'Safe\\array_replace_recursive', 'array_walk_recursive' => 'Safe\\array_walk_recursive', 'arsort' => 'Safe\\arsort', 'asort' => 'Safe\\asort', 'base64_decode' => 'Safe\\base64_decode', 'bzclose' => 'Safe\\bzclose', 'bzflush' => 'Safe\\bzflush', 'bzread' => 'Safe\\bzread', 'bzwrite' => 'Safe\\bzwrite', 'chdir' => 'Safe\\chdir', 'chgrp' => 'Safe\\chgrp', 'chmod' => 'Safe\\chmod', 'chown' => 'Safe\\chown', 'chroot' => 'Safe\\chroot', 'class_alias' => 'Safe\\class_alias', 'class_implements' => 'Safe\\class_implements', 'class_parents' => 'Safe\\class_parents', 'class_uses' => 'Safe\\class_uses', 'cli_set_process_title' => 'Safe\\cli_set_process_title', 'closelog' => 'Safe\\closelog', 'com_event_sink' => 'Safe\\com_event_sink', 'com_load_typelib' => 'Safe\\com_load_typelib', 'com_print_typeinfo' => 'Safe\\com_print_typeinfo', 'convert_uudecode' => 'Safe\\convert_uudecode', 'convert_uuencode' => 'Safe\\convert_uuencode', 'copy' => 'Safe\\copy', 'create_function' => 'Safe\\create_function', 'cubrid_free_result' => 'Safe\\cubrid_free_result', 'cubrid_get_charset' => 'Safe\\cubrid_get_charset', 'cubrid_get_client_info' => 'Safe\\cubrid_get_client_info', 'cubrid_get_db_parameter' => 'Safe\\cubrid_get_db_parameter', 'cubrid_get_server_info' => 'Safe\\cubrid_get_server_info', 'cubrid_insert_id' => 'Safe\\cubrid_insert_id', 'cubrid_lob2_new' => 'Safe\\cubrid_lob2_new', 'cubrid_lob2_size' => 'Safe\\cubrid_lob2_size', 'cubrid_lob2_size64' => 'Safe\\cubrid_lob2_size64', 'cubrid_lob2_tell' => 'Safe\\cubrid_lob2_tell', 'cubrid_lob2_tell64' => 'Safe\\cubrid_lob2_tell64', 'cubrid_set_db_parameter' => 'Safe\\cubrid_set_db_parameter', 'curl_escape' => 'Safe\\curl_escape', 'curl_exec' => 'Safe\\curl_exec', 'curl_getinfo' => 'Safe\\curl_getinfo', 'curl_init' => 'Safe\\curl_init', 'curl_multi_errno' => 'Safe\\curl_multi_errno', 'curl_multi_info_read' => 'Safe\\curl_multi_info_read', 'curl_multi_init' => 'Safe\\curl_multi_init', 'curl_setopt' => 'Safe\\curl_setopt', 'curl_share_errno' => 'Safe\\curl_share_errno', 'curl_share_setopt' => 'Safe\\curl_share_setopt', 'curl_unescape' => 'Safe\\curl_unescape', 'date_parse' => 'Safe\\date_parse', 'date_parse_from_format' => 'Safe\\date_parse_from_format', 'date_sunrise' => 'Safe\\date_sunrise', 'date_sunset' => 'Safe\\date_sunset', 'date_sun_info' => 'Safe\\date_sun_info', 'db2_autocommit' => 'Safe\\db2_autocommit', 'db2_bind_param' => 'Safe\\db2_bind_param', 'db2_client_info' => 'Safe\\db2_client_info', 'db2_close' => 'Safe\\db2_close', 'db2_commit' => 'Safe\\db2_commit', 'db2_execute' => 'Safe\\db2_execute', 'db2_free_result' => 'Safe\\db2_free_result', 'db2_free_stmt' => 'Safe\\db2_free_stmt', 'db2_get_option' => 'Safe\\db2_get_option', 'db2_pclose' => 'Safe\\db2_pclose', 'db2_rollback' => 'Safe\\db2_rollback', 'db2_server_info' => 'Safe\\db2_server_info', 'db2_set_option' => 'Safe\\db2_set_option', 'define' => 'Safe\\define', 'deflate_add' => 'Safe\\deflate_add', 'deflate_init' => 'Safe\\deflate_init', 'disk_free_space' => 'Safe\\disk_free_space', 'disk_total_space' => 'Safe\\disk_total_space', 'dl' => 'Safe\\dl', 'dns_get_record' => 'Safe\\dns_get_record', 'eio_busy' => 'Safe\\eio_busy', 'eio_chmod' => 'Safe\\eio_chmod', 'eio_chown' => 'Safe\\eio_chown', 'eio_close' => 'Safe\\eio_close', 'eio_custom' => 'Safe\\eio_custom', 'eio_dup2' => 'Safe\\eio_dup2', 'eio_event_loop' => 'Safe\\eio_event_loop', 'eio_fallocate' => 'Safe\\eio_fallocate', 'eio_fchmod' => 'Safe\\eio_fchmod', 'eio_fdatasync' => 'Safe\\eio_fdatasync', 'eio_fstat' => 'Safe\\eio_fstat', 'eio_fstatvfs' => 'Safe\\eio_fstatvfs', 'eio_fsync' => 'Safe\\eio_fsync', 'eio_ftruncate' => 'Safe\\eio_ftruncate', 'eio_futime' => 'Safe\\eio_futime', 'eio_grp' => 'Safe\\eio_grp', 'eio_lstat' => 'Safe\\eio_lstat', 'eio_mkdir' => 'Safe\\eio_mkdir', 'eio_mknod' => 'Safe\\eio_mknod', 'eio_nop' => 'Safe\\eio_nop', 'eio_readahead' => 'Safe\\eio_readahead', 'eio_readdir' => 'Safe\\eio_readdir', 'eio_readlink' => 'Safe\\eio_readlink', 'eio_rename' => 'Safe\\eio_rename', 'eio_rmdir' => 'Safe\\eio_rmdir', 'eio_seek' => 'Safe\\eio_seek', 'eio_sendfile' => 'Safe\\eio_sendfile', 'eio_stat' => 'Safe\\eio_stat', 'eio_statvfs' => 'Safe\\eio_statvfs', 'eio_symlink' => 'Safe\\eio_symlink', 'eio_sync' => 'Safe\\eio_sync', 'eio_syncfs' => 'Safe\\eio_syncfs', 'eio_sync_file_range' => 'Safe\\eio_sync_file_range', 'eio_truncate' => 'Safe\\eio_truncate', 'eio_unlink' => 'Safe\\eio_unlink', 'eio_utime' => 'Safe\\eio_utime', 'eio_write' => 'Safe\\eio_write', 'error_log' => 'Safe\\error_log', 'event_add' => 'Safe\\event_add', 'event_base_loopbreak' => 'Safe\\event_base_loopbreak', 'event_base_loopexit' => 'Safe\\event_base_loopexit', 'event_base_new' => 'Safe\\event_base_new', 'event_base_priority_init' => 'Safe\\event_base_priority_init', 'event_base_reinit' => 'Safe\\event_base_reinit', 'event_base_set' => 'Safe\\event_base_set', 'event_buffer_base_set' => 'Safe\\event_buffer_base_set', 'event_buffer_disable' => 'Safe\\event_buffer_disable', 'event_buffer_enable' => 'Safe\\event_buffer_enable', 'event_buffer_new' => 'Safe\\event_buffer_new', 'event_buffer_priority_set' => 'Safe\\event_buffer_priority_set', 'event_buffer_set_callback' => 'Safe\\event_buffer_set_callback', 'event_buffer_write' => 'Safe\\event_buffer_write', 'event_del' => 'Safe\\event_del', 'event_new' => 'Safe\\event_new', 'event_priority_set' => 'Safe\\event_priority_set', 'event_set' => 'Safe\\event_set', 'event_timer_set' => 'Safe\\event_timer_set', 'fastcgi_finish_request' => 'Safe\\fastcgi_finish_request', 'fbird_blob_cancel' => 'Safe\\fbird_blob_cancel', 'fclose' => 'Safe\\fclose', 'fflush' => 'Safe\\fflush', 'file' => 'Safe\\file', 'fileatime' => 'Safe\\fileatime', 'filectime' => 'Safe\\filectime', 'fileinode' => 'Safe\\fileinode', 'filemtime' => 'Safe\\filemtime', 'fileowner' => 'Safe\\fileowner', 'filesize' => 'Safe\\filesize', 'file_get_contents' => 'Safe\\file_get_contents', 'file_put_contents' => 'Safe\\file_put_contents', 'filter_input_array' => 'Safe\\filter_input_array', 'filter_var_array' => 'Safe\\filter_var_array', 'finfo_close' => 'Safe\\finfo_close', 'finfo_open' => 'Safe\\finfo_open', 'flock' => 'Safe\\flock', 'fopen' => 'Safe\\fopen', 'fputcsv' => 'Safe\\fputcsv', 'fread' => 'Safe\\fread', 'fsockopen' => 'Safe\\fsockopen', 'ftp_alloc' => 'Safe\\ftp_alloc', 'ftp_append' => 'Safe\\ftp_append', 'ftp_cdup' => 'Safe\\ftp_cdup', 'ftp_chdir' => 'Safe\\ftp_chdir', 'ftp_chmod' => 'Safe\\ftp_chmod', 'ftp_close' => 'Safe\\ftp_close', 'ftp_connect' => 'Safe\\ftp_connect', 'ftp_delete' => 'Safe\\ftp_delete', 'ftp_fget' => 'Safe\\ftp_fget', 'ftp_fput' => 'Safe\\ftp_fput', 'ftp_get' => 'Safe\\ftp_get', 'ftp_login' => 'Safe\\ftp_login', 'ftp_mkdir' => 'Safe\\ftp_mkdir', 'ftp_mlsd' => 'Safe\\ftp_mlsd', 'ftp_nlist' => 'Safe\\ftp_nlist', 'ftp_pasv' => 'Safe\\ftp_pasv', 'ftp_put' => 'Safe\\ftp_put', 'ftp_pwd' => 'Safe\\ftp_pwd', 'ftp_rename' => 'Safe\\ftp_rename', 'ftp_rmdir' => 'Safe\\ftp_rmdir', 'ftp_site' => 'Safe\\ftp_site', 'ftp_ssl_connect' => 'Safe\\ftp_ssl_connect', 'ftp_systype' => 'Safe\\ftp_systype', 'ftruncate' => 'Safe\\ftruncate', 'fwrite' => 'Safe\\fwrite', 'getallheaders' => 'Safe\\getallheaders', 'getcwd' => 'Safe\\getcwd', 'gethostname' => 'Safe\\gethostname', 'getimagesize' => 'Safe\\getimagesize', 'getlastmod' => 'Safe\\getlastmod', 'getmygid' => 'Safe\\getmygid', 'getmyinode' => 'Safe\\getmyinode', 'getmypid' => 'Safe\\getmypid', 'getmyuid' => 'Safe\\getmyuid', 'getopt' => 'Safe\\getopt', 'getprotobyname' => 'Safe\\getprotobyname', 'getprotobynumber' => 'Safe\\getprotobynumber', 'get_headers' => 'Safe\\get_headers', 'glob' => 'Safe\\glob', 'gmp_binomial' => 'Safe\\gmp_binomial', 'gmp_export' => 'Safe\\gmp_export', 'gmp_import' => 'Safe\\gmp_import', 'gmp_random_seed' => 'Safe\\gmp_random_seed', 'gnupg_adddecryptkey' => 'Safe\\gnupg_adddecryptkey', 'gnupg_addencryptkey' => 'Safe\\gnupg_addencryptkey', 'gnupg_addsignkey' => 'Safe\\gnupg_addsignkey', 'gnupg_cleardecryptkeys' => 'Safe\\gnupg_cleardecryptkeys', 'gnupg_clearencryptkeys' => 'Safe\\gnupg_clearencryptkeys', 'gnupg_clearsignkeys' => 'Safe\\gnupg_clearsignkeys', 'gnupg_setarmor' => 'Safe\\gnupg_setarmor', 'gnupg_setsignmode' => 'Safe\\gnupg_setsignmode', 'gzclose' => 'Safe\\gzclose', 'gzcompress' => 'Safe\\gzcompress', 'gzdecode' => 'Safe\\gzdecode', 'gzdeflate' => 'Safe\\gzdeflate', 'gzencode' => 'Safe\\gzencode', 'gzgets' => 'Safe\\gzgets', 'gzgetss' => 'Safe\\gzgetss', 'gzinflate' => 'Safe\\gzinflate', 'gzpassthru' => 'Safe\\gzpassthru', 'gzrewind' => 'Safe\\gzrewind', 'gzuncompress' => 'Safe\\gzuncompress', 'hash_hkdf' => 'Safe\\hash_hkdf', 'hash_update_file' => 'Safe\\hash_update_file', 'header_register_callback' => 'Safe\\header_register_callback', 'hex2bin' => 'Safe\\hex2bin', 'highlight_file' => 'Safe\\highlight_file', 'highlight_string' => 'Safe\\highlight_string', 'ibase_add_user' => 'Safe\\ibase_add_user', 'ibase_backup' => 'Safe\\ibase_backup', 'ibase_blob_cancel' => 'Safe\\ibase_blob_cancel', 'ibase_blob_create' => 'Safe\\ibase_blob_create', 'ibase_blob_get' => 'Safe\\ibase_blob_get', 'ibase_close' => 'Safe\\ibase_close', 'ibase_commit' => 'Safe\\ibase_commit', 'ibase_commit_ret' => 'Safe\\ibase_commit_ret', 'ibase_connect' => 'Safe\\ibase_connect', 'ibase_delete_user' => 'Safe\\ibase_delete_user', 'ibase_drop_db' => 'Safe\\ibase_drop_db', 'ibase_free_event_handler' => 'Safe\\ibase_free_event_handler', 'ibase_free_query' => 'Safe\\ibase_free_query', 'ibase_free_result' => 'Safe\\ibase_free_result', 'ibase_maintain_db' => 'Safe\\ibase_maintain_db', 'ibase_modify_user' => 'Safe\\ibase_modify_user', 'ibase_name_result' => 'Safe\\ibase_name_result', 'ibase_pconnect' => 'Safe\\ibase_pconnect', 'ibase_restore' => 'Safe\\ibase_restore', 'ibase_rollback' => 'Safe\\ibase_rollback', 'ibase_rollback_ret' => 'Safe\\ibase_rollback_ret', 'ibase_service_attach' => 'Safe\\ibase_service_attach', 'ibase_service_detach' => 'Safe\\ibase_service_detach', 'iconv' => 'Safe\\iconv', 'iconv_get_encoding' => 'Safe\\iconv_get_encoding', 'iconv_set_encoding' => 'Safe\\iconv_set_encoding', 'image2wbmp' => 'Safe\\image2wbmp', 'imageaffine' => 'Safe\\imageaffine', 'imageaffinematrixconcat' => 'Safe\\imageaffinematrixconcat', 'imageaffinematrixget' => 'Safe\\imageaffinematrixget', 'imagealphablending' => 'Safe\\imagealphablending', 'imageantialias' => 'Safe\\imageantialias', 'imagearc' => 'Safe\\imagearc', 'imagebmp' => 'Safe\\imagebmp', 'imagechar' => 'Safe\\imagechar', 'imagecharup' => 'Safe\\imagecharup', 'imagecolorat' => 'Safe\\imagecolorat', 'imagecolordeallocate' => 'Safe\\imagecolordeallocate', 'imagecolormatch' => 'Safe\\imagecolormatch', 'imageconvolution' => 'Safe\\imageconvolution', 'imagecopy' => 'Safe\\imagecopy', 'imagecopymerge' => 'Safe\\imagecopymerge', 'imagecopymergegray' => 'Safe\\imagecopymergegray', 'imagecopyresampled' => 'Safe\\imagecopyresampled', 'imagecopyresized' => 'Safe\\imagecopyresized', 'imagecreate' => 'Safe\\imagecreate', 'imagecreatefrombmp' => 'Safe\\imagecreatefrombmp', 'imagecreatefromgd' => 'Safe\\imagecreatefromgd', 'imagecreatefromgd2' => 'Safe\\imagecreatefromgd2', 'imagecreatefromgd2part' => 'Safe\\imagecreatefromgd2part', 'imagecreatefromgif' => 'Safe\\imagecreatefromgif', 'imagecreatefromjpeg' => 'Safe\\imagecreatefromjpeg', 'imagecreatefrompng' => 'Safe\\imagecreatefrompng', 'imagecreatefromwbmp' => 'Safe\\imagecreatefromwbmp', 'imagecreatefromwebp' => 'Safe\\imagecreatefromwebp', 'imagecreatefromxbm' => 'Safe\\imagecreatefromxbm', 'imagecreatefromxpm' => 'Safe\\imagecreatefromxpm', 'imagecreatetruecolor' => 'Safe\\imagecreatetruecolor', 'imagecrop' => 'Safe\\imagecrop', 'imagecropauto' => 'Safe\\imagecropauto', 'imagedashedline' => 'Safe\\imagedashedline', 'imagedestroy' => 'Safe\\imagedestroy', 'imageellipse' => 'Safe\\imageellipse', 'imagefill' => 'Safe\\imagefill', 'imagefilledarc' => 'Safe\\imagefilledarc', 'imagefilledellipse' => 'Safe\\imagefilledellipse', 'imagefilledpolygon' => 'Safe\\imagefilledpolygon', 'imagefilledrectangle' => 'Safe\\imagefilledrectangle', 'imagefilltoborder' => 'Safe\\imagefilltoborder', 'imagefilter' => 'Safe\\imagefilter', 'imageflip' => 'Safe\\imageflip', 'imagegammacorrect' => 'Safe\\imagegammacorrect', 'imagegd' => 'Safe\\imagegd', 'imagegd2' => 'Safe\\imagegd2', 'imagegif' => 'Safe\\imagegif', 'imagegrabscreen' => 'Safe\\imagegrabscreen', 'imagegrabwindow' => 'Safe\\imagegrabwindow', 'imagejpeg' => 'Safe\\imagejpeg', 'imagelayereffect' => 'Safe\\imagelayereffect', 'imageline' => 'Safe\\imageline', 'imageloadfont' => 'Safe\\imageloadfont', 'imageopenpolygon' => 'Safe\\imageopenpolygon', 'imagepng' => 'Safe\\imagepng', 'imagepolygon' => 'Safe\\imagepolygon', 'imagepsencodefont' => 'Safe\\imagepsencodefont', 'imagepsextendfont' => 'Safe\\imagepsextendfont', 'imagepsfreefont' => 'Safe\\imagepsfreefont', 'imagepsslantfont' => 'Safe\\imagepsslantfont', 'imagerectangle' => 'Safe\\imagerectangle', 'imagerotate' => 'Safe\\imagerotate', 'imagesavealpha' => 'Safe\\imagesavealpha', 'imagescale' => 'Safe\\imagescale', 'imagesetbrush' => 'Safe\\imagesetbrush', 'imagesetclip' => 'Safe\\imagesetclip', 'imagesetinterpolation' => 'Safe\\imagesetinterpolation', 'imagesetpixel' => 'Safe\\imagesetpixel', 'imagesetstyle' => 'Safe\\imagesetstyle', 'imagesetthickness' => 'Safe\\imagesetthickness', 'imagesettile' => 'Safe\\imagesettile', 'imagestring' => 'Safe\\imagestring', 'imagestringup' => 'Safe\\imagestringup', 'imagesx' => 'Safe\\imagesx', 'imagesy' => 'Safe\\imagesy', 'imagetruecolortopalette' => 'Safe\\imagetruecolortopalette', 'imagettfbbox' => 'Safe\\imagettfbbox', 'imagettftext' => 'Safe\\imagettftext', 'imagewbmp' => 'Safe\\imagewbmp', 'imagewebp' => 'Safe\\imagewebp', 'imagexbm' => 'Safe\\imagexbm', 'imap_append' => 'Safe\\imap_append', 'imap_check' => 'Safe\\imap_check', 'imap_clearflag_full' => 'Safe\\imap_clearflag_full', 'imap_close' => 'Safe\\imap_close', 'imap_createmailbox' => 'Safe\\imap_createmailbox', 'imap_deletemailbox' => 'Safe\\imap_deletemailbox', 'imap_gc' => 'Safe\\imap_gc', 'imap_headerinfo' => 'Safe\\imap_headerinfo', 'imap_mail' => 'Safe\\imap_mail', 'imap_mailboxmsginfo' => 'Safe\\imap_mailboxmsginfo', 'imap_mail_copy' => 'Safe\\imap_mail_copy', 'imap_mail_move' => 'Safe\\imap_mail_move', 'imap_mutf7_to_utf8' => 'Safe\\imap_mutf7_to_utf8', 'imap_num_msg' => 'Safe\\imap_num_msg', 'imap_open' => 'Safe\\imap_open', 'imap_renamemailbox' => 'Safe\\imap_renamemailbox', 'imap_savebody' => 'Safe\\imap_savebody', 'imap_setacl' => 'Safe\\imap_setacl', 'imap_setflag_full' => 'Safe\\imap_setflag_full', 'imap_set_quota' => 'Safe\\imap_set_quota', 'imap_subscribe' => 'Safe\\imap_subscribe', 'imap_thread' => 'Safe\\imap_thread', 'imap_timeout' => 'Safe\\imap_timeout', 'imap_undelete' => 'Safe\\imap_undelete', 'imap_unsubscribe' => 'Safe\\imap_unsubscribe', 'imap_utf8_to_mutf7' => 'Safe\\imap_utf8_to_mutf7', 'inet_ntop' => 'Safe\\inet_ntop', 'inflate_add' => 'Safe\\inflate_add', 'inflate_get_read_len' => 'Safe\\inflate_get_read_len', 'inflate_get_status' => 'Safe\\inflate_get_status', 'inflate_init' => 'Safe\\inflate_init', 'ingres_autocommit' => 'Safe\\ingres_autocommit', 'ingres_close' => 'Safe\\ingres_close', 'ingres_commit' => 'Safe\\ingres_commit', 'ingres_connect' => 'Safe\\ingres_connect', 'ingres_execute' => 'Safe\\ingres_execute', 'ingres_field_name' => 'Safe\\ingres_field_name', 'ingres_field_type' => 'Safe\\ingres_field_type', 'ingres_free_result' => 'Safe\\ingres_free_result', 'ingres_pconnect' => 'Safe\\ingres_pconnect', 'ingres_result_seek' => 'Safe\\ingres_result_seek', 'ingres_rollback' => 'Safe\\ingres_rollback', 'ingres_set_environment' => 'Safe\\ingres_set_environment', 'ini_get' => 'Safe\\ini_get', 'ini_set' => 'Safe\\ini_set', 'inotify_init' => 'Safe\\inotify_init', 'inotify_rm_watch' => 'Safe\\inotify_rm_watch', 'iptcembed' => 'Safe\\iptcembed', 'iptcparse' => 'Safe\\iptcparse', 'jpeg2wbmp' => 'Safe\\jpeg2wbmp', 'json_decode' => 'Safe\\json_decode', 'json_encode' => 'Safe\\json_encode', 'json_last_error_msg' => 'Safe\\json_last_error_msg', 'krsort' => 'Safe\\krsort', 'ksort' => 'Safe\\ksort', 'lchgrp' => 'Safe\\lchgrp', 'lchown' => 'Safe\\lchown', 'ldap_add' => 'Safe\\ldap_add', 'ldap_add_ext' => 'Safe\\ldap_add_ext', 'ldap_bind' => 'Safe\\ldap_bind', 'ldap_bind_ext' => 'Safe\\ldap_bind_ext', 'ldap_control_paged_result' => 'Safe\\ldap_control_paged_result', 'ldap_control_paged_result_response' => 'Safe\\ldap_control_paged_result_response', 'ldap_count_entries' => 'Safe\\ldap_count_entries', 'ldap_delete' => 'Safe\\ldap_delete', 'ldap_delete_ext' => 'Safe\\ldap_delete_ext', 'ldap_exop' => 'Safe\\ldap_exop', 'ldap_exop_passwd' => 'Safe\\ldap_exop_passwd', 'ldap_exop_whoami' => 'Safe\\ldap_exop_whoami', 'ldap_explode_dn' => 'Safe\\ldap_explode_dn', 'ldap_first_attribute' => 'Safe\\ldap_first_attribute', 'ldap_first_entry' => 'Safe\\ldap_first_entry', 'ldap_free_result' => 'Safe\\ldap_free_result', 'ldap_get_attributes' => 'Safe\\ldap_get_attributes', 'ldap_get_dn' => 'Safe\\ldap_get_dn', 'ldap_get_entries' => 'Safe\\ldap_get_entries', 'ldap_get_option' => 'Safe\\ldap_get_option', 'ldap_get_values' => 'Safe\\ldap_get_values', 'ldap_get_values_len' => 'Safe\\ldap_get_values_len', 'ldap_list' => 'Safe\\ldap_list', 'ldap_modify_batch' => 'Safe\\ldap_modify_batch', 'ldap_mod_add' => 'Safe\\ldap_mod_add', 'ldap_mod_add_ext' => 'Safe\\ldap_mod_add_ext', 'ldap_mod_del' => 'Safe\\ldap_mod_del', 'ldap_mod_del_ext' => 'Safe\\ldap_mod_del_ext', 'ldap_mod_replace' => 'Safe\\ldap_mod_replace', 'ldap_mod_replace_ext' => 'Safe\\ldap_mod_replace_ext', 'ldap_next_attribute' => 'Safe\\ldap_next_attribute', 'ldap_parse_exop' => 'Safe\\ldap_parse_exop', 'ldap_parse_result' => 'Safe\\ldap_parse_result', 'ldap_read' => 'Safe\\ldap_read', 'ldap_rename' => 'Safe\\ldap_rename', 'ldap_rename_ext' => 'Safe\\ldap_rename_ext', 'ldap_sasl_bind' => 'Safe\\ldap_sasl_bind', 'ldap_search' => 'Safe\\ldap_search', 'ldap_set_option' => 'Safe\\ldap_set_option', 'ldap_unbind' => 'Safe\\ldap_unbind', 'libxml_get_last_error' => 'Safe\\libxml_get_last_error', 'libxml_set_external_entity_loader' => 'Safe\\libxml_set_external_entity_loader', 'link' => 'Safe\\link', 'lzf_compress' => 'Safe\\lzf_compress', 'lzf_decompress' => 'Safe\\lzf_decompress', 'mailparse_msg_extract_part_file' => 'Safe\\mailparse_msg_extract_part_file', 'mailparse_msg_free' => 'Safe\\mailparse_msg_free', 'mailparse_msg_parse' => 'Safe\\mailparse_msg_parse', 'mailparse_msg_parse_file' => 'Safe\\mailparse_msg_parse_file', 'mailparse_stream_encode' => 'Safe\\mailparse_stream_encode', 'mb_chr' => 'Safe\\mb_chr', 'mb_detect_order' => 'Safe\\mb_detect_order', 'mb_encoding_aliases' => 'Safe\\mb_encoding_aliases', 'mb_eregi_replace' => 'Safe\\mb_eregi_replace', 'mb_ereg_replace' => 'Safe\\mb_ereg_replace', 'mb_ereg_replace_callback' => 'Safe\\mb_ereg_replace_callback', 'mb_ereg_search_getregs' => 'Safe\\mb_ereg_search_getregs', 'mb_ereg_search_init' => 'Safe\\mb_ereg_search_init', 'mb_ereg_search_regs' => 'Safe\\mb_ereg_search_regs', 'mb_ereg_search_setpos' => 'Safe\\mb_ereg_search_setpos', 'mb_http_output' => 'Safe\\mb_http_output', 'mb_internal_encoding' => 'Safe\\mb_internal_encoding', 'mb_ord' => 'Safe\\mb_ord', 'mb_parse_str' => 'Safe\\mb_parse_str', 'mb_regex_encoding' => 'Safe\\mb_regex_encoding', 'mb_send_mail' => 'Safe\\mb_send_mail', 'mb_split' => 'Safe\\mb_split', 'md5_file' => 'Safe\\md5_file', 'metaphone' => 'Safe\\metaphone', 'mime_content_type' => 'Safe\\mime_content_type', 'mkdir' => 'Safe\\mkdir', 'mktime' => 'Safe\\mktime', 'msg_queue_exists' => 'Safe\\msg_queue_exists', 'msg_receive' => 'Safe\\msg_receive', 'msg_remove_queue' => 'Safe\\msg_remove_queue', 'msg_send' => 'Safe\\msg_send', 'msg_set_queue' => 'Safe\\msg_set_queue', 'msql_affected_rows' => 'Safe\\msql_affected_rows', 'msql_close' => 'Safe\\msql_close', 'msql_connect' => 'Safe\\msql_connect', 'msql_create_db' => 'Safe\\msql_create_db', 'msql_data_seek' => 'Safe\\msql_data_seek', 'msql_db_query' => 'Safe\\msql_db_query', 'msql_drop_db' => 'Safe\\msql_drop_db', 'msql_field_len' => 'Safe\\msql_field_len', 'msql_field_name' => 'Safe\\msql_field_name', 'msql_field_seek' => 'Safe\\msql_field_seek', 'msql_field_table' => 'Safe\\msql_field_table', 'msql_field_type' => 'Safe\\msql_field_type', 'msql_free_result' => 'Safe\\msql_free_result', 'msql_pconnect' => 'Safe\\msql_pconnect', 'msql_query' => 'Safe\\msql_query', 'msql_select_db' => 'Safe\\msql_select_db', 'mssql_bind' => 'Safe\\mssql_bind', 'mssql_close' => 'Safe\\mssql_close', 'mssql_connect' => 'Safe\\mssql_connect', 'mssql_data_seek' => 'Safe\\mssql_data_seek', 'mssql_field_length' => 'Safe\\mssql_field_length', 'mssql_field_name' => 'Safe\\mssql_field_name', 'mssql_field_seek' => 'Safe\\mssql_field_seek', 'mssql_field_type' => 'Safe\\mssql_field_type', 'mssql_free_result' => 'Safe\\mssql_free_result', 'mssql_free_statement' => 'Safe\\mssql_free_statement', 'mssql_init' => 'Safe\\mssql_init', 'mssql_pconnect' => 'Safe\\mssql_pconnect', 'mssql_query' => 'Safe\\mssql_query', 'mssql_select_db' => 'Safe\\mssql_select_db', 'mysqli_get_cache_stats' => 'Safe\\mysqli_get_cache_stats', 'mysqli_get_client_stats' => 'Safe\\mysqli_get_client_stats', 'mysqlnd_ms_dump_servers' => 'Safe\\mysqlnd_ms_dump_servers', 'mysqlnd_ms_fabric_select_global' => 'Safe\\mysqlnd_ms_fabric_select_global', 'mysqlnd_ms_fabric_select_shard' => 'Safe\\mysqlnd_ms_fabric_select_shard', 'mysqlnd_ms_get_last_used_connection' => 'Safe\\mysqlnd_ms_get_last_used_connection', 'mysqlnd_qc_clear_cache' => 'Safe\\mysqlnd_qc_clear_cache', 'mysqlnd_qc_set_is_select' => 'Safe\\mysqlnd_qc_set_is_select', 'mysqlnd_qc_set_storage_handler' => 'Safe\\mysqlnd_qc_set_storage_handler', 'mysql_close' => 'Safe\\mysql_close', 'mysql_connect' => 'Safe\\mysql_connect', 'mysql_create_db' => 'Safe\\mysql_create_db', 'mysql_data_seek' => 'Safe\\mysql_data_seek', 'mysql_db_name' => 'Safe\\mysql_db_name', 'mysql_db_query' => 'Safe\\mysql_db_query', 'mysql_drop_db' => 'Safe\\mysql_drop_db', 'mysql_fetch_lengths' => 'Safe\\mysql_fetch_lengths', 'mysql_field_flags' => 'Safe\\mysql_field_flags', 'mysql_field_len' => 'Safe\\mysql_field_len', 'mysql_field_name' => 'Safe\\mysql_field_name', 'mysql_field_seek' => 'Safe\\mysql_field_seek', 'mysql_free_result' => 'Safe\\mysql_free_result', 'mysql_get_host_info' => 'Safe\\mysql_get_host_info', 'mysql_get_proto_info' => 'Safe\\mysql_get_proto_info', 'mysql_get_server_info' => 'Safe\\mysql_get_server_info', 'mysql_info' => 'Safe\\mysql_info', 'mysql_list_dbs' => 'Safe\\mysql_list_dbs', 'mysql_list_fields' => 'Safe\\mysql_list_fields', 'mysql_list_processes' => 'Safe\\mysql_list_processes', 'mysql_list_tables' => 'Safe\\mysql_list_tables', 'mysql_num_fields' => 'Safe\\mysql_num_fields', 'mysql_num_rows' => 'Safe\\mysql_num_rows', 'mysql_query' => 'Safe\\mysql_query', 'mysql_real_escape_string' => 'Safe\\mysql_real_escape_string', 'mysql_result' => 'Safe\\mysql_result', 'mysql_select_db' => 'Safe\\mysql_select_db', 'mysql_set_charset' => 'Safe\\mysql_set_charset', 'mysql_tablename' => 'Safe\\mysql_tablename', 'mysql_thread_id' => 'Safe\\mysql_thread_id', 'mysql_unbuffered_query' => 'Safe\\mysql_unbuffered_query', 'natcasesort' => 'Safe\\natcasesort', 'natsort' => 'Safe\\natsort', 'ob_end_clean' => 'Safe\\ob_end_clean', 'ob_end_flush' => 'Safe\\ob_end_flush', 'oci_bind_array_by_name' => 'Safe\\oci_bind_array_by_name', 'oci_bind_by_name' => 'Safe\\oci_bind_by_name', 'oci_cancel' => 'Safe\\oci_cancel', 'oci_close' => 'Safe\\oci_close', 'oci_commit' => 'Safe\\oci_commit', 'oci_connect' => 'Safe\\oci_connect', 'oci_define_by_name' => 'Safe\\oci_define_by_name', 'oci_execute' => 'Safe\\oci_execute', 'oci_fetch_all' => 'Safe\\oci_fetch_all', 'oci_field_name' => 'Safe\\oci_field_name', 'oci_field_precision' => 'Safe\\oci_field_precision', 'oci_field_scale' => 'Safe\\oci_field_scale', 'oci_field_size' => 'Safe\\oci_field_size', 'oci_field_type' => 'Safe\\oci_field_type', 'oci_field_type_raw' => 'Safe\\oci_field_type_raw', 'oci_free_descriptor' => 'Safe\\oci_free_descriptor', 'oci_free_statement' => 'Safe\\oci_free_statement', 'oci_new_collection' => 'Safe\\oci_new_collection', 'oci_new_connect' => 'Safe\\oci_new_connect', 'oci_new_cursor' => 'Safe\\oci_new_cursor', 'oci_new_descriptor' => 'Safe\\oci_new_descriptor', 'oci_num_fields' => 'Safe\\oci_num_fields', 'oci_num_rows' => 'Safe\\oci_num_rows', 'oci_parse' => 'Safe\\oci_parse', 'oci_pconnect' => 'Safe\\oci_pconnect', 'oci_result' => 'Safe\\oci_result', 'oci_rollback' => 'Safe\\oci_rollback', 'oci_server_version' => 'Safe\\oci_server_version', 'oci_set_action' => 'Safe\\oci_set_action', 'oci_set_call_timeout' => 'Safe\\oci_set_call_timeout', 'oci_set_client_identifier' => 'Safe\\oci_set_client_identifier', 'oci_set_client_info' => 'Safe\\oci_set_client_info', 'oci_set_db_operation' => 'Safe\\oci_set_db_operation', 'oci_set_edition' => 'Safe\\oci_set_edition', 'oci_set_module_name' => 'Safe\\oci_set_module_name', 'oci_set_prefetch' => 'Safe\\oci_set_prefetch', 'oci_statement_type' => 'Safe\\oci_statement_type', 'oci_unregister_taf_callback' => 'Safe\\oci_unregister_taf_callback', 'odbc_autocommit' => 'Safe\\odbc_autocommit', 'odbc_binmode' => 'Safe\\odbc_binmode', 'odbc_columnprivileges' => 'Safe\\odbc_columnprivileges', 'odbc_columns' => 'Safe\\odbc_columns', 'odbc_commit' => 'Safe\\odbc_commit', 'odbc_data_source' => 'Safe\\odbc_data_source', 'odbc_exec' => 'Safe\\odbc_exec', 'odbc_execute' => 'Safe\\odbc_execute', 'odbc_fetch_into' => 'Safe\\odbc_fetch_into', 'odbc_field_len' => 'Safe\\odbc_field_len', 'odbc_field_name' => 'Safe\\odbc_field_name', 'odbc_field_num' => 'Safe\\odbc_field_num', 'odbc_field_scale' => 'Safe\\odbc_field_scale', 'odbc_field_type' => 'Safe\\odbc_field_type', 'odbc_foreignkeys' => 'Safe\\odbc_foreignkeys', 'odbc_gettypeinfo' => 'Safe\\odbc_gettypeinfo', 'odbc_longreadlen' => 'Safe\\odbc_longreadlen', 'odbc_prepare' => 'Safe\\odbc_prepare', 'odbc_primarykeys' => 'Safe\\odbc_primarykeys', 'odbc_result' => 'Safe\\odbc_result', 'odbc_result_all' => 'Safe\\odbc_result_all', 'odbc_rollback' => 'Safe\\odbc_rollback', 'odbc_setoption' => 'Safe\\odbc_setoption', 'odbc_specialcolumns' => 'Safe\\odbc_specialcolumns', 'odbc_statistics' => 'Safe\\odbc_statistics', 'odbc_tableprivileges' => 'Safe\\odbc_tableprivileges', 'odbc_tables' => 'Safe\\odbc_tables', 'opcache_compile_file' => 'Safe\\opcache_compile_file', 'opcache_get_status' => 'Safe\\opcache_get_status', 'opendir' => 'Safe\\opendir', 'openlog' => 'Safe\\openlog', 'openssl_cipher_iv_length' => 'Safe\\openssl_cipher_iv_length', 'openssl_csr_export' => 'Safe\\openssl_csr_export', 'openssl_csr_export_to_file' => 'Safe\\openssl_csr_export_to_file', 'openssl_csr_get_subject' => 'Safe\\openssl_csr_get_subject', 'openssl_csr_new' => 'Safe\\openssl_csr_new', 'openssl_csr_sign' => 'Safe\\openssl_csr_sign', 'openssl_decrypt' => 'Safe\\openssl_decrypt', 'openssl_dh_compute_key' => 'Safe\\openssl_dh_compute_key', 'openssl_digest' => 'Safe\\openssl_digest', 'openssl_encrypt' => 'Safe\\openssl_encrypt', 'openssl_open' => 'Safe\\openssl_open', 'openssl_pbkdf2' => 'Safe\\openssl_pbkdf2', 'openssl_pkcs7_decrypt' => 'Safe\\openssl_pkcs7_decrypt', 'openssl_pkcs7_encrypt' => 'Safe\\openssl_pkcs7_encrypt', 'openssl_pkcs7_read' => 'Safe\\openssl_pkcs7_read', 'openssl_pkcs7_sign' => 'Safe\\openssl_pkcs7_sign', 'openssl_pkcs12_export' => 'Safe\\openssl_pkcs12_export', 'openssl_pkcs12_export_to_file' => 'Safe\\openssl_pkcs12_export_to_file', 'openssl_pkcs12_read' => 'Safe\\openssl_pkcs12_read', 'openssl_pkey_export' => 'Safe\\openssl_pkey_export', 'openssl_pkey_export_to_file' => 'Safe\\openssl_pkey_export_to_file', 'openssl_pkey_get_private' => 'Safe\\openssl_pkey_get_private', 'openssl_pkey_get_public' => 'Safe\\openssl_pkey_get_public', 'openssl_pkey_new' => 'Safe\\openssl_pkey_new', 'openssl_private_decrypt' => 'Safe\\openssl_private_decrypt', 'openssl_private_encrypt' => 'Safe\\openssl_private_encrypt', 'openssl_public_decrypt' => 'Safe\\openssl_public_decrypt', 'openssl_public_encrypt' => 'Safe\\openssl_public_encrypt', 'openssl_random_pseudo_bytes' => 'Safe\\openssl_random_pseudo_bytes', 'openssl_seal' => 'Safe\\openssl_seal', 'openssl_sign' => 'Safe\\openssl_sign', 'openssl_x509_export' => 'Safe\\openssl_x509_export', 'openssl_x509_export_to_file' => 'Safe\\openssl_x509_export_to_file', 'openssl_x509_fingerprint' => 'Safe\\openssl_x509_fingerprint', 'openssl_x509_read' => 'Safe\\openssl_x509_read', 'output_add_rewrite_var' => 'Safe\\output_add_rewrite_var', 'output_reset_rewrite_vars' => 'Safe\\output_reset_rewrite_vars', 'parse_ini_file' => 'Safe\\parse_ini_file', 'parse_ini_string' => 'Safe\\parse_ini_string', 'parse_url' => 'Safe\\parse_url', 'password_hash' => 'Safe\\password_hash', 'pcntl_exec' => 'Safe\\pcntl_exec', 'pcntl_getpriority' => 'Safe\\pcntl_getpriority', 'pcntl_setpriority' => 'Safe\\pcntl_setpriority', 'pcntl_signal_dispatch' => 'Safe\\pcntl_signal_dispatch', 'pcntl_sigprocmask' => 'Safe\\pcntl_sigprocmask', 'pcntl_strerror' => 'Safe\\pcntl_strerror', 'PDF_activate_item' => 'Safe\\PDF_activate_item', 'PDF_add_locallink' => 'Safe\\PDF_add_locallink', 'PDF_add_nameddest' => 'Safe\\PDF_add_nameddest', 'PDF_add_note' => 'Safe\\PDF_add_note', 'PDF_add_pdflink' => 'Safe\\PDF_add_pdflink', 'PDF_add_thumbnail' => 'Safe\\PDF_add_thumbnail', 'PDF_add_weblink' => 'Safe\\PDF_add_weblink', 'PDF_attach_file' => 'Safe\\PDF_attach_file', 'PDF_begin_layer' => 'Safe\\PDF_begin_layer', 'PDF_begin_page' => 'Safe\\PDF_begin_page', 'PDF_begin_page_ext' => 'Safe\\PDF_begin_page_ext', 'PDF_circle' => 'Safe\\PDF_circle', 'PDF_clip' => 'Safe\\PDF_clip', 'PDF_close' => 'Safe\\PDF_close', 'PDF_closepath' => 'Safe\\PDF_closepath', 'PDF_closepath_fill_stroke' => 'Safe\\PDF_closepath_fill_stroke', 'PDF_closepath_stroke' => 'Safe\\PDF_closepath_stroke', 'PDF_close_pdi' => 'Safe\\PDF_close_pdi', 'PDF_close_pdi_page' => 'Safe\\PDF_close_pdi_page', 'PDF_concat' => 'Safe\\PDF_concat', 'PDF_continue_text' => 'Safe\\PDF_continue_text', 'PDF_curveto' => 'Safe\\PDF_curveto', 'PDF_delete' => 'Safe\\PDF_delete', 'PDF_end_layer' => 'Safe\\PDF_end_layer', 'PDF_end_page' => 'Safe\\PDF_end_page', 'PDF_end_page_ext' => 'Safe\\PDF_end_page_ext', 'PDF_end_pattern' => 'Safe\\PDF_end_pattern', 'PDF_end_template' => 'Safe\\PDF_end_template', 'PDF_fill' => 'Safe\\PDF_fill', 'PDF_fill_stroke' => 'Safe\\PDF_fill_stroke', 'PDF_fit_image' => 'Safe\\PDF_fit_image', 'PDF_fit_pdi_page' => 'Safe\\PDF_fit_pdi_page', 'PDF_fit_textline' => 'Safe\\PDF_fit_textline', 'PDF_initgraphics' => 'Safe\\PDF_initgraphics', 'PDF_lineto' => 'Safe\\PDF_lineto', 'PDF_makespotcolor' => 'Safe\\PDF_makespotcolor', 'PDF_moveto' => 'Safe\\PDF_moveto', 'PDF_open_file' => 'Safe\\PDF_open_file', 'PDF_place_image' => 'Safe\\PDF_place_image', 'PDF_place_pdi_page' => 'Safe\\PDF_place_pdi_page', 'PDF_rect' => 'Safe\\PDF_rect', 'PDF_restore' => 'Safe\\PDF_restore', 'PDF_rotate' => 'Safe\\PDF_rotate', 'PDF_save' => 'Safe\\PDF_save', 'PDF_scale' => 'Safe\\PDF_scale', 'PDF_setcolor' => 'Safe\\PDF_setcolor', 'PDF_setdash' => 'Safe\\PDF_setdash', 'PDF_setdashpattern' => 'Safe\\PDF_setdashpattern', 'PDF_setflat' => 'Safe\\PDF_setflat', 'PDF_setfont' => 'Safe\\PDF_setfont', 'PDF_setgray' => 'Safe\\PDF_setgray', 'PDF_setgray_fill' => 'Safe\\PDF_setgray_fill', 'PDF_setgray_stroke' => 'Safe\\PDF_setgray_stroke', 'PDF_setlinejoin' => 'Safe\\PDF_setlinejoin', 'PDF_setlinewidth' => 'Safe\\PDF_setlinewidth', 'PDF_setmatrix' => 'Safe\\PDF_setmatrix', 'PDF_setmiterlimit' => 'Safe\\PDF_setmiterlimit', 'PDF_setrgbcolor' => 'Safe\\PDF_setrgbcolor', 'PDF_setrgbcolor_fill' => 'Safe\\PDF_setrgbcolor_fill', 'PDF_setrgbcolor_stroke' => 'Safe\\PDF_setrgbcolor_stroke', 'PDF_set_border_color' => 'Safe\\PDF_set_border_color', 'PDF_set_border_dash' => 'Safe\\PDF_set_border_dash', 'PDF_set_border_style' => 'Safe\\PDF_set_border_style', 'PDF_set_info' => 'Safe\\PDF_set_info', 'PDF_set_layer_dependency' => 'Safe\\PDF_set_layer_dependency', 'PDF_set_parameter' => 'Safe\\PDF_set_parameter', 'PDF_set_text_pos' => 'Safe\\PDF_set_text_pos', 'PDF_set_value' => 'Safe\\PDF_set_value', 'PDF_show' => 'Safe\\PDF_show', 'PDF_show_xy' => 'Safe\\PDF_show_xy', 'PDF_skew' => 'Safe\\PDF_skew', 'PDF_stroke' => 'Safe\\PDF_stroke', 'pg_cancel_query' => 'Safe\\pg_cancel_query', 'pg_client_encoding' => 'Safe\\pg_client_encoding', 'pg_close' => 'Safe\\pg_close', 'pg_connect' => 'Safe\\pg_connect', 'pg_connection_reset' => 'Safe\\pg_connection_reset', 'pg_convert' => 'Safe\\pg_convert', 'pg_copy_from' => 'Safe\\pg_copy_from', 'pg_copy_to' => 'Safe\\pg_copy_to', 'pg_dbname' => 'Safe\\pg_dbname', 'pg_delete' => 'Safe\\pg_delete', 'pg_end_copy' => 'Safe\\pg_end_copy', 'pg_execute' => 'Safe\\pg_execute', 'pg_field_name' => 'Safe\\pg_field_name', 'pg_field_table' => 'Safe\\pg_field_table', 'pg_field_type' => 'Safe\\pg_field_type', 'pg_flush' => 'Safe\\pg_flush', 'pg_free_result' => 'Safe\\pg_free_result', 'pg_host' => 'Safe\\pg_host', 'pg_insert' => 'Safe\\pg_insert', 'pg_last_error' => 'Safe\\pg_last_error', 'pg_last_notice' => 'Safe\\pg_last_notice', 'pg_last_oid' => 'Safe\\pg_last_oid', 'pg_lo_close' => 'Safe\\pg_lo_close', 'pg_lo_export' => 'Safe\\pg_lo_export', 'pg_lo_import' => 'Safe\\pg_lo_import', 'pg_lo_open' => 'Safe\\pg_lo_open', 'pg_lo_read' => 'Safe\\pg_lo_read', 'pg_lo_read_all' => 'Safe\\pg_lo_read_all', 'pg_lo_seek' => 'Safe\\pg_lo_seek', 'pg_lo_truncate' => 'Safe\\pg_lo_truncate', 'pg_lo_unlink' => 'Safe\\pg_lo_unlink', 'pg_lo_write' => 'Safe\\pg_lo_write', 'pg_meta_data' => 'Safe\\pg_meta_data', 'pg_options' => 'Safe\\pg_options', 'pg_parameter_status' => 'Safe\\pg_parameter_status', 'pg_pconnect' => 'Safe\\pg_pconnect', 'pg_ping' => 'Safe\\pg_ping', 'pg_port' => 'Safe\\pg_port', 'pg_prepare' => 'Safe\\pg_prepare', 'pg_put_line' => 'Safe\\pg_put_line', 'pg_query' => 'Safe\\pg_query', 'pg_query_params' => 'Safe\\pg_query_params', 'pg_result_error_field' => 'Safe\\pg_result_error_field', 'pg_result_seek' => 'Safe\\pg_result_seek', 'pg_select' => 'Safe\\pg_select', 'pg_send_execute' => 'Safe\\pg_send_execute', 'pg_send_prepare' => 'Safe\\pg_send_prepare', 'pg_send_query' => 'Safe\\pg_send_query', 'pg_send_query_params' => 'Safe\\pg_send_query_params', 'pg_socket' => 'Safe\\pg_socket', 'pg_trace' => 'Safe\\pg_trace', 'pg_tty' => 'Safe\\pg_tty', 'pg_update' => 'Safe\\pg_update', 'pg_version' => 'Safe\\pg_version', 'phpcredits' => 'Safe\\phpcredits', 'phpinfo' => 'Safe\\phpinfo', 'png2wbmp' => 'Safe\\png2wbmp', 'posix_access' => 'Safe\\posix_access', 'posix_getgrnam' => 'Safe\\posix_getgrnam', 'posix_getpgid' => 'Safe\\posix_getpgid', 'posix_initgroups' => 'Safe\\posix_initgroups', 'posix_kill' => 'Safe\\posix_kill', 'posix_mkfifo' => 'Safe\\posix_mkfifo', 'posix_mknod' => 'Safe\\posix_mknod', 'posix_setegid' => 'Safe\\posix_setegid', 'posix_seteuid' => 'Safe\\posix_seteuid', 'posix_setgid' => 'Safe\\posix_setgid', 'posix_setpgid' => 'Safe\\posix_setpgid', 'posix_setrlimit' => 'Safe\\posix_setrlimit', 'posix_setuid' => 'Safe\\posix_setuid', 'preg_match' => 'Safe\\preg_match', 'preg_match_all' => 'Safe\\preg_match_all', 'preg_replace' => 'Safe\\preg_replace', 'preg_split' => 'Safe\\preg_split', 'proc_get_status' => 'Safe\\proc_get_status', 'proc_nice' => 'Safe\\proc_nice', 'pspell_add_to_personal' => 'Safe\\pspell_add_to_personal', 'pspell_add_to_session' => 'Safe\\pspell_add_to_session', 'pspell_clear_session' => 'Safe\\pspell_clear_session', 'pspell_config_create' => 'Safe\\pspell_config_create', 'pspell_config_data_dir' => 'Safe\\pspell_config_data_dir', 'pspell_config_dict_dir' => 'Safe\\pspell_config_dict_dir', 'pspell_config_ignore' => 'Safe\\pspell_config_ignore', 'pspell_config_mode' => 'Safe\\pspell_config_mode', 'pspell_config_personal' => 'Safe\\pspell_config_personal', 'pspell_config_repl' => 'Safe\\pspell_config_repl', 'pspell_config_runtogether' => 'Safe\\pspell_config_runtogether', 'pspell_config_save_repl' => 'Safe\\pspell_config_save_repl', 'pspell_new' => 'Safe\\pspell_new', 'pspell_new_config' => 'Safe\\pspell_new_config', 'pspell_save_wordlist' => 'Safe\\pspell_save_wordlist', 'pspell_store_replacement' => 'Safe\\pspell_store_replacement', 'ps_add_launchlink' => 'Safe\\ps_add_launchlink', 'ps_add_locallink' => 'Safe\\ps_add_locallink', 'ps_add_note' => 'Safe\\ps_add_note', 'ps_add_pdflink' => 'Safe\\ps_add_pdflink', 'ps_add_weblink' => 'Safe\\ps_add_weblink', 'ps_arc' => 'Safe\\ps_arc', 'ps_arcn' => 'Safe\\ps_arcn', 'ps_begin_page' => 'Safe\\ps_begin_page', 'ps_begin_pattern' => 'Safe\\ps_begin_pattern', 'ps_begin_template' => 'Safe\\ps_begin_template', 'ps_circle' => 'Safe\\ps_circle', 'ps_clip' => 'Safe\\ps_clip', 'ps_close' => 'Safe\\ps_close', 'ps_closepath' => 'Safe\\ps_closepath', 'ps_closepath_stroke' => 'Safe\\ps_closepath_stroke', 'ps_close_image' => 'Safe\\ps_close_image', 'ps_continue_text' => 'Safe\\ps_continue_text', 'ps_curveto' => 'Safe\\ps_curveto', 'ps_delete' => 'Safe\\ps_delete', 'ps_end_page' => 'Safe\\ps_end_page', 'ps_end_pattern' => 'Safe\\ps_end_pattern', 'ps_end_template' => 'Safe\\ps_end_template', 'ps_fill' => 'Safe\\ps_fill', 'ps_fill_stroke' => 'Safe\\ps_fill_stroke', 'ps_get_parameter' => 'Safe\\ps_get_parameter', 'ps_hyphenate' => 'Safe\\ps_hyphenate', 'ps_include_file' => 'Safe\\ps_include_file', 'ps_lineto' => 'Safe\\ps_lineto', 'ps_moveto' => 'Safe\\ps_moveto', 'ps_new' => 'Safe\\ps_new', 'ps_open_file' => 'Safe\\ps_open_file', 'ps_place_image' => 'Safe\\ps_place_image', 'ps_rect' => 'Safe\\ps_rect', 'ps_restore' => 'Safe\\ps_restore', 'ps_rotate' => 'Safe\\ps_rotate', 'ps_save' => 'Safe\\ps_save', 'ps_scale' => 'Safe\\ps_scale', 'ps_setcolor' => 'Safe\\ps_setcolor', 'ps_setdash' => 'Safe\\ps_setdash', 'ps_setflat' => 'Safe\\ps_setflat', 'ps_setfont' => 'Safe\\ps_setfont', 'ps_setgray' => 'Safe\\ps_setgray', 'ps_setlinecap' => 'Safe\\ps_setlinecap', 'ps_setlinejoin' => 'Safe\\ps_setlinejoin', 'ps_setlinewidth' => 'Safe\\ps_setlinewidth', 'ps_setmiterlimit' => 'Safe\\ps_setmiterlimit', 'ps_setoverprintmode' => 'Safe\\ps_setoverprintmode', 'ps_setpolydash' => 'Safe\\ps_setpolydash', 'ps_set_border_color' => 'Safe\\ps_set_border_color', 'ps_set_border_dash' => 'Safe\\ps_set_border_dash', 'ps_set_border_style' => 'Safe\\ps_set_border_style', 'ps_set_info' => 'Safe\\ps_set_info', 'ps_set_parameter' => 'Safe\\ps_set_parameter', 'ps_set_text_pos' => 'Safe\\ps_set_text_pos', 'ps_set_value' => 'Safe\\ps_set_value', 'ps_shading' => 'Safe\\ps_shading', 'ps_shading_pattern' => 'Safe\\ps_shading_pattern', 'ps_shfill' => 'Safe\\ps_shfill', 'ps_show' => 'Safe\\ps_show', 'ps_show2' => 'Safe\\ps_show2', 'ps_show_xy' => 'Safe\\ps_show_xy', 'ps_show_xy2' => 'Safe\\ps_show_xy2', 'ps_stroke' => 'Safe\\ps_stroke', 'ps_symbol' => 'Safe\\ps_symbol', 'ps_translate' => 'Safe\\ps_translate', 'putenv' => 'Safe\\putenv', 'readfile' => 'Safe\\readfile', 'readgzfile' => 'Safe\\readgzfile', 'readline_add_history' => 'Safe\\readline_add_history', 'readline_callback_handler_install' => 'Safe\\readline_callback_handler_install', 'readline_clear_history' => 'Safe\\readline_clear_history', 'readline_completion_function' => 'Safe\\readline_completion_function', 'readline_read_history' => 'Safe\\readline_read_history', 'readline_write_history' => 'Safe\\readline_write_history', 'readlink' => 'Safe\\readlink', 'realpath' => 'Safe\\realpath', 'register_tick_function' => 'Safe\\register_tick_function', 'rename' => 'Safe\\rename', 'rewind' => 'Safe\\rewind', 'rewinddir' => 'Safe\\rewinddir', 'rmdir' => 'Safe\\rmdir', 'rrd_create' => 'Safe\\rrd_create', 'rsort' => 'Safe\\rsort', 'sapi_windows_cp_conv' => 'Safe\\sapi_windows_cp_conv', 'sapi_windows_cp_set' => 'Safe\\sapi_windows_cp_set', 'sapi_windows_generate_ctrl_event' => 'Safe\\sapi_windows_generate_ctrl_event', 'sapi_windows_vt100_support' => 'Safe\\sapi_windows_vt100_support', 'scandir' => 'Safe\\scandir', 'sem_acquire' => 'Safe\\sem_acquire', 'sem_get' => 'Safe\\sem_get', 'sem_release' => 'Safe\\sem_release', 'sem_remove' => 'Safe\\sem_remove', 'session_abort' => 'Safe\\session_abort', 'session_decode' => 'Safe\\session_decode', 'session_destroy' => 'Safe\\session_destroy', 'session_regenerate_id' => 'Safe\\session_regenerate_id', 'session_reset' => 'Safe\\session_reset', 'session_unset' => 'Safe\\session_unset', 'session_write_close' => 'Safe\\session_write_close', 'settype' => 'Safe\\settype', 'set_include_path' => 'Safe\\set_include_path', 'set_time_limit' => 'Safe\\set_time_limit', 'sha1_file' => 'Safe\\sha1_file', 'shmop_delete' => 'Safe\\shmop_delete', 'shmop_read' => 'Safe\\shmop_read', 'shmop_write' => 'Safe\\shmop_write', 'shm_put_var' => 'Safe\\shm_put_var', 'shm_remove' => 'Safe\\shm_remove', 'shm_remove_var' => 'Safe\\shm_remove_var', 'shuffle' => 'Safe\\shuffle', 'simplexml_import_dom' => 'Safe\\simplexml_import_dom', 'simplexml_load_file' => 'Safe\\simplexml_load_file', 'simplexml_load_string' => 'Safe\\simplexml_load_string', 'sleep' => 'Safe\\sleep', 'socket_accept' => 'Safe\\socket_accept', 'socket_addrinfo_bind' => 'Safe\\socket_addrinfo_bind', 'socket_addrinfo_connect' => 'Safe\\socket_addrinfo_connect', 'socket_bind' => 'Safe\\socket_bind', 'socket_connect' => 'Safe\\socket_connect', 'socket_create' => 'Safe\\socket_create', 'socket_create_listen' => 'Safe\\socket_create_listen', 'socket_create_pair' => 'Safe\\socket_create_pair', 'socket_export_stream' => 'Safe\\socket_export_stream', 'socket_getpeername' => 'Safe\\socket_getpeername', 'socket_getsockname' => 'Safe\\socket_getsockname', 'socket_get_option' => 'Safe\\socket_get_option', 'socket_import_stream' => 'Safe\\socket_import_stream', 'socket_listen' => 'Safe\\socket_listen', 'socket_read' => 'Safe\\socket_read', 'socket_send' => 'Safe\\socket_send', 'socket_sendmsg' => 'Safe\\socket_sendmsg', 'socket_sendto' => 'Safe\\socket_sendto', 'socket_set_block' => 'Safe\\socket_set_block', 'socket_set_nonblock' => 'Safe\\socket_set_nonblock', 'socket_set_option' => 'Safe\\socket_set_option', 'socket_shutdown' => 'Safe\\socket_shutdown', 'socket_write' => 'Safe\\socket_write', 'socket_wsaprotocol_info_export' => 'Safe\\socket_wsaprotocol_info_export', 'socket_wsaprotocol_info_import' => 'Safe\\socket_wsaprotocol_info_import', 'socket_wsaprotocol_info_release' => 'Safe\\socket_wsaprotocol_info_release', 'sodium_crypto_pwhash' => 'Safe\\sodium_crypto_pwhash', 'sodium_crypto_pwhash_str' => 'Safe\\sodium_crypto_pwhash_str', 'solr_get_version' => 'Safe\\solr_get_version', 'sort' => 'Safe\\sort', 'soundex' => 'Safe\\soundex', 'spl_autoload_register' => 'Safe\\spl_autoload_register', 'spl_autoload_unregister' => 'Safe\\spl_autoload_unregister', 'sprintf' => 'Safe\\sprintf', 'sqlsrv_begin_transaction' => 'Safe\\sqlsrv_begin_transaction', 'sqlsrv_cancel' => 'Safe\\sqlsrv_cancel', 'sqlsrv_client_info' => 'Safe\\sqlsrv_client_info', 'sqlsrv_close' => 'Safe\\sqlsrv_close', 'sqlsrv_commit' => 'Safe\\sqlsrv_commit', 'sqlsrv_configure' => 'Safe\\sqlsrv_configure', 'sqlsrv_execute' => 'Safe\\sqlsrv_execute', 'sqlsrv_free_stmt' => 'Safe\\sqlsrv_free_stmt', 'sqlsrv_get_field' => 'Safe\\sqlsrv_get_field', 'sqlsrv_next_result' => 'Safe\\sqlsrv_next_result', 'sqlsrv_num_fields' => 'Safe\\sqlsrv_num_fields', 'sqlsrv_num_rows' => 'Safe\\sqlsrv_num_rows', 'sqlsrv_prepare' => 'Safe\\sqlsrv_prepare', 'sqlsrv_query' => 'Safe\\sqlsrv_query', 'sqlsrv_rollback' => 'Safe\\sqlsrv_rollback', 'ssdeep_fuzzy_compare' => 'Safe\\ssdeep_fuzzy_compare', 'ssdeep_fuzzy_hash' => 'Safe\\ssdeep_fuzzy_hash', 'ssdeep_fuzzy_hash_filename' => 'Safe\\ssdeep_fuzzy_hash_filename', 'ssh2_auth_agent' => 'Safe\\ssh2_auth_agent', 'ssh2_auth_hostbased_file' => 'Safe\\ssh2_auth_hostbased_file', 'ssh2_auth_password' => 'Safe\\ssh2_auth_password', 'ssh2_auth_pubkey_file' => 'Safe\\ssh2_auth_pubkey_file', 'ssh2_connect' => 'Safe\\ssh2_connect', 'ssh2_disconnect' => 'Safe\\ssh2_disconnect', 'ssh2_exec' => 'Safe\\ssh2_exec', 'ssh2_publickey_add' => 'Safe\\ssh2_publickey_add', 'ssh2_publickey_init' => 'Safe\\ssh2_publickey_init', 'ssh2_publickey_remove' => 'Safe\\ssh2_publickey_remove', 'ssh2_scp_recv' => 'Safe\\ssh2_scp_recv', 'ssh2_scp_send' => 'Safe\\ssh2_scp_send', 'ssh2_sftp' => 'Safe\\ssh2_sftp', 'ssh2_sftp_chmod' => 'Safe\\ssh2_sftp_chmod', 'ssh2_sftp_mkdir' => 'Safe\\ssh2_sftp_mkdir', 'ssh2_sftp_rename' => 'Safe\\ssh2_sftp_rename', 'ssh2_sftp_rmdir' => 'Safe\\ssh2_sftp_rmdir', 'ssh2_sftp_symlink' => 'Safe\\ssh2_sftp_symlink', 'ssh2_sftp_unlink' => 'Safe\\ssh2_sftp_unlink', 'stats_covariance' => 'Safe\\stats_covariance', 'stats_standard_deviation' => 'Safe\\stats_standard_deviation', 'stats_stat_correlation' => 'Safe\\stats_stat_correlation', 'stats_stat_innerproduct' => 'Safe\\stats_stat_innerproduct', 'stats_variance' => 'Safe\\stats_variance', 'stream_context_set_params' => 'Safe\\stream_context_set_params', 'stream_copy_to_stream' => 'Safe\\stream_copy_to_stream', 'stream_filter_append' => 'Safe\\stream_filter_append', 'stream_filter_prepend' => 'Safe\\stream_filter_prepend', 'stream_filter_register' => 'Safe\\stream_filter_register', 'stream_filter_remove' => 'Safe\\stream_filter_remove', 'stream_get_contents' => 'Safe\\stream_get_contents', 'stream_isatty' => 'Safe\\stream_isatty', 'stream_resolve_include_path' => 'Safe\\stream_resolve_include_path', 'stream_set_blocking' => 'Safe\\stream_set_blocking', 'stream_set_timeout' => 'Safe\\stream_set_timeout', 'stream_socket_accept' => 'Safe\\stream_socket_accept', 'stream_socket_client' => 'Safe\\stream_socket_client', 'stream_socket_pair' => 'Safe\\stream_socket_pair', 'stream_socket_server' => 'Safe\\stream_socket_server', 'stream_socket_shutdown' => 'Safe\\stream_socket_shutdown', 'stream_supports_lock' => 'Safe\\stream_supports_lock', 'stream_wrapper_register' => 'Safe\\stream_wrapper_register', 'stream_wrapper_restore' => 'Safe\\stream_wrapper_restore', 'stream_wrapper_unregister' => 'Safe\\stream_wrapper_unregister', 'strptime' => 'Safe\\strptime', 'strtotime' => 'Safe\\strtotime', 'substr' => 'Safe\\substr', 'swoole_async_write' => 'Safe\\swoole_async_write', 'swoole_async_writefile' => 'Safe\\swoole_async_writefile', 'swoole_event_defer' => 'Safe\\swoole_event_defer', 'swoole_event_del' => 'Safe\\swoole_event_del', 'swoole_event_write' => 'Safe\\swoole_event_write', 'symlink' => 'Safe\\symlink', 'syslog' => 'Safe\\syslog', 'system' => 'Safe\\system', 'tempnam' => 'Safe\\tempnam', 'timezone_name_from_abbr' => 'Safe\\timezone_name_from_abbr', 'time_nanosleep' => 'Safe\\time_nanosleep', 'time_sleep_until' => 'Safe\\time_sleep_until', 'tmpfile' => 'Safe\\tmpfile', 'touch' => 'Safe\\touch', 'uasort' => 'Safe\\uasort', 'uksort' => 'Safe\\uksort', 'unlink' => 'Safe\\unlink', 'uopz_extend' => 'Safe\\uopz_extend', 'uopz_implement' => 'Safe\\uopz_implement', 'usort' => 'Safe\\usort', 'virtual' => 'Safe\\virtual', 'vsprintf' => 'Safe\\vsprintf', 'xdiff_file_bdiff' => 'Safe\\xdiff_file_bdiff', 'xdiff_file_bpatch' => 'Safe\\xdiff_file_bpatch', 'xdiff_file_diff' => 'Safe\\xdiff_file_diff', 'xdiff_file_diff_binary' => 'Safe\\xdiff_file_diff_binary', 'xdiff_file_patch_binary' => 'Safe\\xdiff_file_patch_binary', 'xdiff_file_rabdiff' => 'Safe\\xdiff_file_rabdiff', 'xdiff_string_bpatch' => 'Safe\\xdiff_string_bpatch', 'xdiff_string_patch' => 'Safe\\xdiff_string_patch', 'xdiff_string_patch_binary' => 'Safe\\xdiff_string_patch_binary', 'xmlrpc_set_type' => 'Safe\\xmlrpc_set_type', 'xml_parser_create' => 'Safe\\xml_parser_create', 'xml_parser_create_ns' => 'Safe\\xml_parser_create_ns', 'xml_set_object' => 'Safe\\xml_set_object', 'yaml_parse' => 'Safe\\yaml_parse', 'yaml_parse_file' => 'Safe\\yaml_parse_file', 'yaml_parse_url' => 'Safe\\yaml_parse_url', 'yaz_ccl_parse' => 'Safe\\yaz_ccl_parse', 'yaz_close' => 'Safe\\yaz_close', 'yaz_connect' => 'Safe\\yaz_connect', 'yaz_database' => 'Safe\\yaz_database', 'yaz_element' => 'Safe\\yaz_element', 'yaz_present' => 'Safe\\yaz_present', 'yaz_search' => 'Safe\\yaz_search', 'yaz_wait' => 'Safe\\yaz_wait', 'zip_entry_close' => 'Safe\\zip_entry_close', 'zip_entry_open' => 'Safe\\zip_entry_open', 'zip_entry_read' => 'Safe\\zip_entry_read', 'zlib_decode' => 'Safe\\zlib_decode']]]); }; diff --git a/config/set/type-declaration-strict.php b/config/set/type-declaration-strict.php index 945e951db47..4df05ad0028 100644 --- a/config/set/type-declaration-strict.php +++ b/config/set/type-declaration-strict.php @@ -1,6 +1,7 @@ services(); - $services->set(AddClosureReturnTypeRector::class); - $services->set(ReturnTypeFromStrictTypedPropertyRector::class); - $services->set(TypedPropertyFromStrictConstructorRector::class); - $services->set(ParamTypeFromStrictTypedPropertyRector::class); - $services->set(ReturnTypeFromStrictTypedCallRector::class); - $services->set(AddVoidReturnTypeWhereNoReturnRector::class); + $services->set(\Rector\TypeDeclaration\Rector\Closure\AddClosureReturnTypeRector::class); + $services->set(\Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictTypedPropertyRector::class); + $services->set(\Rector\TypeDeclaration\Rector\Property\TypedPropertyFromStrictConstructorRector::class); + $services->set(\Rector\TypeDeclaration\Rector\Param\ParamTypeFromStrictTypedPropertyRector::class); + $services->set(\Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictTypedCallRector::class); + $services->set(\Rector\TypeDeclaration\Rector\ClassMethod\AddVoidReturnTypeWhereNoReturnRector::class); // $services->set(AddMethodCallBasedStrictParamTypeRector::class); - $services->set(ReturnTypeFromReturnNewRector::class); + $services->set(\Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromReturnNewRector::class); }; diff --git a/config/set/type-declaration.php b/config/set/type-declaration.php index 3c2734e8d8c..e2a4d1c5c03 100644 --- a/config/set/type-declaration.php +++ b/config/set/type-declaration.php @@ -1,6 +1,7 @@ services(); - $services->set(ParamTypeDeclarationRector::class); - $services->set(ReturnTypeDeclarationRector::class); - $services->set(PropertyTypeDeclarationRector::class); - $services->set(AddClosureReturnTypeRector::class); - $services->set(AddArrayParamDocTypeRector::class); - $services->set(AddArrayReturnDocTypeRector::class); + $services->set(\Rector\TypeDeclaration\Rector\FunctionLike\ParamTypeDeclarationRector::class); + $services->set(\Rector\TypeDeclaration\Rector\FunctionLike\ReturnTypeDeclarationRector::class); + $services->set(\Rector\TypeDeclaration\Rector\Property\PropertyTypeDeclarationRector::class); + $services->set(\Rector\TypeDeclaration\Rector\Closure\AddClosureReturnTypeRector::class); + $services->set(\Rector\TypeDeclaration\Rector\ClassMethod\AddArrayParamDocTypeRector::class); + $services->set(\Rector\TypeDeclaration\Rector\ClassMethod\AddArrayReturnDocTypeRector::class); // $services->set(AddParamTypeFromCallersRector::class); }; diff --git a/config/set/unwrap-compat.php b/config/set/unwrap-compat.php index ef27e4184f9..f25dc266d5b 100644 --- a/config/set/unwrap-compat.php +++ b/config/set/unwrap-compat.php @@ -1,11 +1,11 @@ services(); - $services->set(UnwrapFutureCompatibleIfFunctionExistsRector::class); + $services->set(\Rector\DeadCode\Rector\If_\UnwrapFutureCompatibleIfFunctionExistsRector::class); }; diff --git a/packages/BetterPhpDocParser/Annotation/AnnotationNaming.php b/packages/BetterPhpDocParser/Annotation/AnnotationNaming.php index 789f0c56efc..36911aa71f4 100644 --- a/packages/BetterPhpDocParser/Annotation/AnnotationNaming.php +++ b/packages/BetterPhpDocParser/Annotation/AnnotationNaming.php @@ -1,13 +1,12 @@ hasAttribute($attributeToMirror)) { + if (!$oldNode->hasAttribute($attributeToMirror)) { continue; } - $attributeValue = $oldNode->getAttribute($attributeToMirror); $newNode->setAttribute($attributeToMirror, $attributeValue); } diff --git a/packages/BetterPhpDocParser/Comment/CommentsMerger.php b/packages/BetterPhpDocParser/Comment/CommentsMerger.php index a1fcb1dbddf..7b472840b63 100644 --- a/packages/BetterPhpDocParser/Comment/CommentsMerger.php +++ b/packages/BetterPhpDocParser/Comment/CommentsMerger.php @@ -1,98 +1,76 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - /** * @param Node[] $mergedNodes */ - public function keepComments(Node $newNode, array $mergedNodes): void + public function keepComments(\PhpParser\Node $newNode, array $mergedNodes) : void { $comments = $newNode->getComments(); - foreach ($mergedNodes as $mergedNode) { - $comments = array_merge($comments, $mergedNode->getComments()); + $comments = \array_merge($comments, $mergedNode->getComments()); } - if ($comments === []) { return; } - - $newNode->setAttribute(AttributeKey::COMMENTS, $comments); - + $newNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, $comments); // remove so comments "win" - $newNode->setAttribute(AttributeKey::PHP_DOC_INFO, null); + $newNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, null); } - - public function keepParent(Node $newNode, Node $oldNode): void + public function keepParent(\PhpParser\Node $newNode, \PhpParser\Node $oldNode) : void { - $parent = $oldNode->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Node) { + $parent = $oldNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node) { return; } - - $phpDocInfo = $parent->getAttribute(AttributeKey::PHP_DOC_INFO); + $phpDocInfo = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO); $comments = $parent->getComments(); - if ($phpDocInfo === null && $comments === []) { return; } - - $newNode->setAttribute(AttributeKey::PHP_DOC_INFO, $phpDocInfo); - $newNode->setAttribute(AttributeKey::COMMENTS, $comments); + $newNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, $phpDocInfo); + $newNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, $comments); } - - public function keepChildren(Node $newNode, Node $oldNode): void + public function keepChildren(\PhpParser\Node $newNode, \PhpParser\Node $oldNode) : void { $childrenComments = $this->collectChildrenComments($oldNode); - if ($childrenComments === []) { return; } - $commentContent = ''; foreach ($childrenComments as $childComment) { - $commentContent .= $childComment->getText() . PHP_EOL; + $commentContent .= $childComment->getText() . \PHP_EOL; } - - $newNode->setAttribute(AttributeKey::COMMENTS, [new Comment($commentContent)]); + $newNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, [new \PhpParser\Comment($commentContent)]); } - /** * @return Comment[] */ - private function collectChildrenComments(Node $node): array + private function collectChildrenComments(\PhpParser\Node $node) : array { $childrenComments = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($node, function (Node $node) use ( - &$childrenComments - ): void { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($node, function (\PhpParser\Node $node) use(&$childrenComments) : void { $comments = $node->getComments(); - if ($comments !== []) { - $childrenComments = array_merge($childrenComments, $comments); + $childrenComments = \array_merge($childrenComments, $comments); } }); - return $childrenComments; } } diff --git a/packages/BetterPhpDocParser/Contract/BasePhpDocNodeVisitorInterface.php b/packages/BetterPhpDocParser/Contract/BasePhpDocNodeVisitorInterface.php index 8430713d8cc..a9704883bc2 100644 --- a/packages/BetterPhpDocParser/Contract/BasePhpDocNodeVisitorInterface.php +++ b/packages/BetterPhpDocParser/Contract/BasePhpDocNodeVisitorInterface.php @@ -1,11 +1,9 @@ betterTokenIterator = $betterTokenIterator; } - - public function provide(): BetterTokenIterator + public function provide() : \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator { return $this->betterTokenIterator; } diff --git a/packages/BetterPhpDocParser/PhpDoc/DoctrineAnnotationTagValueNode.php b/packages/BetterPhpDocParser/PhpDoc/DoctrineAnnotationTagValueNode.php index 57bd4a9b42d..d2cd1572630 100644 --- a/packages/BetterPhpDocParser/PhpDoc/DoctrineAnnotationTagValueNode.php +++ b/packages/BetterPhpDocParser/PhpDoc/DoctrineAnnotationTagValueNode.php @@ -1,18 +1,15 @@ $values */ @@ -22,37 +19,31 @@ final class DoctrineAnnotationTagValueNode extends AbstractValuesAwareNode ?string $originalContent = null, array $values = [], ?string $silentKey = null - ) { - $this->hasChanged = true; + ) + { + $this->hasChanged = \true; $this->annotationClass = $annotationClass; - parent::__construct($values, $originalContent, $silentKey); } - - public function __toString(): string + public function __toString() : string { - if (! $this->hasChanged) { + if (!$this->hasChanged) { if ($this->originalContent === null) { return ''; } - return $this->originalContent; } - if ($this->values === []) { if ($this->originalContent === '()') { // empty brackets return $this->originalContent; } - return ''; } - $itemContents = $this->printValuesContent($this->values); - return sprintf('(%s)', $itemContents); + return \sprintf('(%s)', $itemContents); } - - public function getAnnotationClass(): string + public function getAnnotationClass() : string { return $this->annotationClass; } diff --git a/packages/BetterPhpDocParser/PhpDoc/SpacelessPhpDocTagNode.php b/packages/BetterPhpDocParser/PhpDoc/SpacelessPhpDocTagNode.php index cc5fa5f11c3..0c4e5dc97bb 100644 --- a/packages/BetterPhpDocParser/PhpDoc/SpacelessPhpDocTagNode.php +++ b/packages/BetterPhpDocParser/PhpDoc/SpacelessPhpDocTagNode.php @@ -1,18 +1,16 @@ name . $this->value; } diff --git a/packages/BetterPhpDocParser/PhpDocInfo/PhpDocInfo.php b/packages/BetterPhpDocParser/PhpDocInfo/PhpDocInfo.php index 17db248dc84..8f59b7152af 100644 --- a/packages/BetterPhpDocParser/PhpDocInfo/PhpDocInfo.php +++ b/packages/BetterPhpDocParser/PhpDocInfo/PhpDocInfo.php @@ -1,10 +1,9 @@ , string> */ - private const TAGS_TYPES_TO_NAMES = [ - ReturnTagValueNode::class => '@return', - ParamTagValueNode::class => '@param', - VarTagValueNode::class => '@var', - MethodTagValueNode::class => '@method', - PropertyTagValueNode::class => '@property', - ]; - + private const TAGS_TYPES_TO_NAMES = [\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode::class => '@return', \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode::class => '@param', \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode::class => '@var', \PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueNode::class => '@method', \PHPStan\PhpDocParser\Ast\PhpDoc\PropertyTagValueNode::class => '@property']; /** * @var bool */ - private $isSingleLine = false; - + private $isSingleLine = \false; /** * @var PhpDocNode */ private $phpDocNode; - /** * @var PhpDocNode */ private $originalPhpDocNode; - /** * @var StaticTypeMapper */ private $staticTypeMapper; - /** * @var \PhpParser\Node */ private $node; - /** * @var bool */ - private $hasChanged = false; - + private $hasChanged = \false; /** * @var AnnotationNaming */ private $annotationNaming; - /** * @var CurrentNodeProvider */ private $currentNodeProvider; - /** * @var RectorChangeCollector */ private $rectorChangeCollector; - /** * @var BetterTokenIterator */ private $betterTokenIterator; - - public function __construct( - PhpDocNode $phpDocNode, - BetterTokenIterator $betterTokenIterator, - StaticTypeMapper $staticTypeMapper, - \PhpParser\Node $node, - AnnotationNaming $annotationNaming, - CurrentNodeProvider $currentNodeProvider, - RectorChangeCollector $rectorChangeCollector - ) { + public function __construct(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode $phpDocNode, \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $betterTokenIterator, \Rector\StaticTypeMapper\StaticTypeMapper $staticTypeMapper, \PhpParser\Node $node, \Rector\BetterPhpDocParser\Annotation\AnnotationNaming $annotationNaming, \Rector\Core\Configuration\CurrentNodeProvider $currentNodeProvider, \Rector\ChangesReporting\Collector\RectorChangeCollector $rectorChangeCollector) + { $this->phpDocNode = $phpDocNode; $this->betterTokenIterator = $betterTokenIterator; $this->originalPhpDocNode = clone $phpDocNode; - - if (! $betterTokenIterator->containsTokenType(Lexer::TOKEN_PHPDOC_EOL)) { - $this->isSingleLine = true; + if (!$betterTokenIterator->containsTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_PHPDOC_EOL)) { + $this->isSingleLine = \true; } - $this->staticTypeMapper = $staticTypeMapper; $this->node = $node; $this->annotationNaming = $annotationNaming; $this->currentNodeProvider = $currentNodeProvider; $this->rectorChangeCollector = $rectorChangeCollector; } - - public function addPhpDocTagNode(PhpDocChildNode $phpDocChildNode): void + public function addPhpDocTagNode(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode $phpDocChildNode) : void { $this->phpDocNode->children[] = $phpDocChildNode; // to give node more space $this->makeMultiLined(); - $this->markAsChanged(); } - - public function getPhpDocNode(): PhpDocNode + public function getPhpDocNode() : \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode { return $this->phpDocNode; } - - public function getOriginalPhpDocNode(): PhpDocNode + public function getOriginalPhpDocNode() : \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode { return $this->originalPhpDocNode; } - /** * @return mixed[] */ - public function getTokens(): array + public function getTokens() : array { return $this->betterTokenIterator->getTokens(); } - - public function getTokenCount(): int + public function getTokenCount() : int { return $this->betterTokenIterator->count(); } - - public function getVarTagValueNode(): ?VarTagValueNode + public function getVarTagValueNode() : ?\PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode { return $this->phpDocNode->getVarTagValues()[0] ?? null; } - /** * @return array */ - public function getTagsByName(string $name): array + public function getTagsByName(string $name) : array { $name = $this->annotationNaming->normalizeName($name); - $tags = $this->phpDocNode->getTags(); - - $tags = array_filter($tags, function (PhpDocTagNode $tag) use ($name): bool { + $tags = \array_filter($tags, function (\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode $tag) use($name) : bool { return $tag->name === $name; }); - - $tags = array_values($tags); - return array_values($tags); + $tags = \array_values($tags); + return \array_values($tags); } - - public function getParamType(string $name): Type + public function getParamType(string $name) : \PHPStan\Type\Type { $paramTagValueNodes = $this->getParamTagValueByName($name); - return $this->getTypeOrMixed($paramTagValueNodes); } - /** * @return ParamTagValueNode[] */ - public function getParamTagValueNodes(): array + public function getParamTagValueNodes() : array { return $this->phpDocNode->getParamTagValues(); } - - public function getParamTagValueNodeByName(string $parameterName): ?ParamTagValueNode + public function getParamTagValueNodeByName(string $parameterName) : ?\PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode { foreach ($this->phpDocNode->getParamTagValues() as $paramTagValueNode) { if ($paramTagValueNode->parameterName !== '$' . $parameterName) { continue; } - return $paramTagValueNode; } - return null; } - - public function getVarType(): Type + public function getVarType() : \PHPStan\Type\Type { return $this->getTypeOrMixed($this->getVarTagValueNode()); } - - public function getReturnType(): Type + public function getReturnType() : \PHPStan\Type\Type { return $this->getTypeOrMixed($this->getReturnTagValue()); } - /** * @param class-string $type */ - public function hasByType(string $type): bool + public function hasByType(string $type) : bool { return (bool) $this->getByType($type); } - /** * @param array> $types */ - public function hasByTypes(array $types): bool + public function hasByTypes(array $types) : bool { foreach ($types as $type) { if ($this->hasByType($type)) { - return true; + return \true; } } - - return false; + return \false; } - /** * @param string[] $names */ - public function hasByNames(array $names): bool + public function hasByNames(array $names) : bool { foreach ($names as $name) { if ($this->hasByName($name)) { - return true; + return \true; } } - - return false; + return \false; } - - public function hasByName(string $name): bool + public function hasByName(string $name) : bool { return (bool) $this->getTagsByName($name); } - - public function getByName(string $name): ?Node + public function getByName(string $name) : ?\PHPStan\PhpDocParser\Ast\Node { return $this->getTagsByName($name)[0] ?? null; } - /** * @param string[] $classes */ - public function getByAnnotationClasses(array $classes): ?DoctrineAnnotationTagValueNode + public function getByAnnotationClasses(array $classes) : ?\Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode { foreach ($classes as $class) { $tagValueNode = $this->getByAnnotationClass($class); - if ($tagValueNode instanceof DoctrineAnnotationTagValueNode) { + if ($tagValueNode instanceof \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode) { return $tagValueNode; } } - return null; } - - public function hasByAnnotationClass(string $class): bool + public function hasByAnnotationClass(string $class) : bool { return $this->getByAnnotationClass($class) !== null; } - /** * @param string[] $annotationsClasses */ - public function hasByAnnotationClasses(array $annotationsClasses): bool + public function hasByAnnotationClasses(array $annotationsClasses) : bool { return $this->getByAnnotationClasses($annotationsClasses) !== null; } - - public function getByAnnotationClass(string $desiredClass): ?DoctrineAnnotationTagValueNode + public function getByAnnotationClass(string $desiredClass) : ?\Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode { foreach ($this->phpDocNode->children as $phpDocChildNode) { - if (! $phpDocChildNode instanceof PhpDocTagNode) { + if (!$phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - // new approach - if (! $phpDocChildNode->value instanceof DoctrineAnnotationTagValueNode) { + if (!$phpDocChildNode->value instanceof \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode) { continue; } - $annotationClass = $phpDocChildNode->value->getAnnotationClass(); if ($annotationClass === $desiredClass) { return $phpDocChildNode->value; } - // fnmatch if ($this->isFnmatch($annotationClass, $desiredClass)) { return $phpDocChildNode->value; } } - return null; } - /** * @param class-string $type * @return TNode|null @@ -321,239 +257,188 @@ final class PhpDocInfo public function getByType(string $type) { foreach ($this->phpDocNode->children as $phpDocChildNode) { - if (is_a($phpDocChildNode, $type, true)) { + if (\is_a($phpDocChildNode, $type, \true)) { return $phpDocChildNode; } - - if (! $phpDocChildNode instanceof PhpDocTagNode) { + if (!$phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - - if (! is_a($phpDocChildNode->value, $type, true)) { + if (!\is_a($phpDocChildNode->value, $type, \true)) { continue; } - return $phpDocChildNode->value; } - return null; } - /** * @deprecated, should accept only strings, to make it useful for developer who don't know internal logics of tag nodes; also not each tag requires node class * @template T of \PHPStan\PhpDocParser\Ast\Node * @param class-string $type */ - public function removeByType(string $type): void + public function removeByType(string $type) : void { foreach ($this->phpDocNode->children as $key => $phpDocChildNode) { - if (is_a($phpDocChildNode, $type, true)) { + if (\is_a($phpDocChildNode, $type, \true)) { unset($this->phpDocNode->children[$key]); $this->markAsChanged(); } - - if (! $phpDocChildNode instanceof PhpDocTagNode) { + if (!$phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - - if (! is_a($phpDocChildNode->value, $type, true)) { + if (!\is_a($phpDocChildNode->value, $type, \true)) { continue; } - unset($this->phpDocNode->children[$key]); $this->markAsChanged(); } } - /** * @return array */ - public function getParamTypesByName(): array + public function getParamTypesByName() : array { $paramTypesByName = []; - foreach ($this->phpDocNode->getParamTagValues() as $paramTagValueNode) { $parameterName = $paramTagValueNode->parameterName; - $paramTypesByName[$parameterName] = $this->staticTypeMapper->mapPHPStanPhpDocTypeToPHPStanType( - $paramTagValueNode, - $this->node - ); + $paramTypesByName[$parameterName] = $this->staticTypeMapper->mapPHPStanPhpDocTypeToPHPStanType($paramTagValueNode, $this->node); } - return $paramTypesByName; } - - public function addTagValueNode(PhpDocTagValueNode $phpDocTagValueNode): void + public function addTagValueNode(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode $phpDocTagValueNode) : void { - if ($phpDocTagValueNode instanceof DoctrineAnnotationTagValueNode) { - $spacelessPhpDocTagNode = new SpacelessPhpDocTagNode( - '@\\' . $phpDocTagValueNode->getAnnotationClass(), - $phpDocTagValueNode - ); + if ($phpDocTagValueNode instanceof \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode) { + $spacelessPhpDocTagNode = new \Rector\BetterPhpDocParser\PhpDoc\SpacelessPhpDocTagNode('@\\' . $phpDocTagValueNode->getAnnotationClass(), $phpDocTagValueNode); $this->addPhpDocTagNode($spacelessPhpDocTagNode); return; } - $name = $this->resolveNameForPhpDocTagValueNode($phpDocTagValueNode); - - $phpDocTagNode = new PhpDocTagNode($name, $phpDocTagValueNode); + $phpDocTagNode = new \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode($name, $phpDocTagValueNode); $this->addPhpDocTagNode($phpDocTagNode); } - - public function isNewNode(): bool + public function isNewNode() : bool { if ($this->phpDocNode->children === []) { - return false; + return \false; } - return $this->betterTokenIterator->count() === 0; } - - public function makeSingleLined(): void + public function makeSingleLined() : void { - $this->isSingleLine = true; + $this->isSingleLine = \true; } - - public function isSingleLine(): bool + public function isSingleLine() : bool { return $this->isSingleLine; } - - public function hasInvalidTag(string $name): bool + public function hasInvalidTag(string $name) : bool { // fallback for invalid tag value node foreach ($this->phpDocNode->children as $phpDocChildNode) { - if (! $phpDocChildNode instanceof PhpDocTagNode) { + if (!$phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - if ($phpDocChildNode->name !== $name) { continue; } - - if (! $phpDocChildNode->value instanceof InvalidTagValueNode) { + if (!$phpDocChildNode->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\InvalidTagValueNode) { continue; } - - return true; + return \true; } - - return false; + return \false; } - - public function getReturnTagValue(): ?ReturnTagValueNode + public function getReturnTagValue() : ?\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode { $returnTagValueNodes = $this->phpDocNode->getReturnTagValues(); return $returnTagValueNodes[0] ?? null; } - - public function getParamTagValueByName(string $name): ?ParamTagValueNode + public function getParamTagValueByName(string $name) : ?\PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode { - $desiredParamNameWithDollar = '$' . ltrim($name, '$'); - + $desiredParamNameWithDollar = '$' . \ltrim($name, '$'); foreach ($this->getParamTagValueNodes() as $paramTagValueNode) { if ($paramTagValueNode->parameterName !== $desiredParamNameWithDollar) { continue; } - return $paramTagValueNode; } - return null; } - /** * @return TemplateTagValueNode[] */ - public function getTemplateTagValueNodes(): array + public function getTemplateTagValueNodes() : array { return $this->phpDocNode->getTemplateTagValues(); } - - public function hasInheritDoc(): bool + public function hasInheritDoc() : bool { return $this->hasByNames(['inheritdoc', 'inheritDoc']); } - /** * @deprecated * Should be handled by attributes of phpdoc node - if stard_and_end is missing in one of nodes, it has been changed * Similar to missing original node in php-aprser */ - public function markAsChanged(): void + public function markAsChanged() : void { - $this->hasChanged = true; - + $this->hasChanged = \true; $node = $this->currentNodeProvider->getNode(); if ($node !== null) { $this->rectorChangeCollector->notifyNodeFileInfo($node); } } - - public function hasChanged(): bool + public function hasChanged() : bool { if ($this->isNewNode()) { - return true; + return \true; } - if ($this->hasChanged) { - return true; + return \true; } - // has a single node with missing start_end - $phpDocNodeTraverser = new PhpDocNodeTraverser(); - $changedPhpDocNodeVisitor = new ChangedPhpDocNodeVisitor(); + $phpDocNodeTraverser = new \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser(); + $changedPhpDocNodeVisitor = new \Rector\BetterPhpDocParser\PhpDocNodeVisitor\ChangedPhpDocNodeVisitor(); $phpDocNodeTraverser->addPhpDocNodeVisitor($changedPhpDocNodeVisitor); $phpDocNodeTraverser->traverse($this->phpDocNode); - return $changedPhpDocNodeVisitor->hasChanged(); } - /** * @return string[] */ - public function getMethodTagNames(): array + public function getMethodTagNames() : array { $methodTagNames = []; foreach ($this->phpDocNode->getMethodTagValues() as $methodTagValueNode) { $methodTagNames[] = $methodTagValueNode->methodName; } - return $methodTagNames; } - - public function makeMultiLined(): void + public function makeMultiLined() : void { - $this->isSingleLine = false; + $this->isSingleLine = \false; } - - private function getTypeOrMixed(?PhpDocTagValueNode $phpDocTagValueNode): Type + private function getTypeOrMixed(?\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode $phpDocTagValueNode) : \PHPStan\Type\Type { if ($phpDocTagValueNode === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - return $this->staticTypeMapper->mapPHPStanPhpDocTypeToPHPStanType($phpDocTagValueNode, $this->node); } - - private function resolveNameForPhpDocTagValueNode(PhpDocTagValueNode $phpDocTagValueNode): string + private function resolveNameForPhpDocTagValueNode(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode $phpDocTagValueNode) : string { foreach (self::TAGS_TYPES_TO_NAMES as $tagValueNodeType => $name) { /** @var class-string $tagValueNodeType */ - if (is_a($phpDocTagValueNode, $tagValueNodeType, true)) { + if (\is_a($phpDocTagValueNode, $tagValueNodeType, \true)) { return $name; } } - - throw new NotImplementedYetException(get_class($phpDocTagValueNode)); + throw new \Rector\Core\Exception\NotImplementedYetException(\get_class($phpDocTagValueNode)); } - - private function isFnmatch(string $currentValue, string $desiredValue): bool + private function isFnmatch(string $currentValue, string $desiredValue) : bool { - if (! Strings::contains($desiredValue, '*')) { - return false; + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($desiredValue, '*')) { + return \false; } - - return fnmatch($desiredValue, $currentValue, FNM_NOESCAPE); + return \fnmatch($desiredValue, $currentValue, \FNM_NOESCAPE); } } diff --git a/packages/BetterPhpDocParser/PhpDocInfo/PhpDocInfoFactory.php b/packages/BetterPhpDocParser/PhpDocInfo/PhpDocInfoFactory.php index df39fb8b288..7d519e4c26f 100644 --- a/packages/BetterPhpDocParser/PhpDocInfo/PhpDocInfoFactory.php +++ b/packages/BetterPhpDocParser/PhpDocInfo/PhpDocInfoFactory.php @@ -1,7 +1,6 @@ */ private $phpDocInfosByObjectHash = []; - - public function __construct( - PhpDocNodeMapper $phpDocNodeMapper, - CurrentNodeProvider $currentNodeProvider, - Lexer $lexer, - BetterPhpDocParser $betterPhpDocParser, - StaticTypeMapper $staticTypeMapper, - AnnotationNaming $annotationNaming, - RectorChangeCollector $rectorChangeCollector - ) { + public function __construct(\Rector\BetterPhpDocParser\PhpDocNodeMapper $phpDocNodeMapper, \Rector\Core\Configuration\CurrentNodeProvider $currentNodeProvider, \PHPStan\PhpDocParser\Lexer\Lexer $lexer, \Rector\BetterPhpDocParser\PhpDocParser\BetterPhpDocParser $betterPhpDocParser, \Rector\StaticTypeMapper\StaticTypeMapper $staticTypeMapper, \Rector\BetterPhpDocParser\Annotation\AnnotationNaming $annotationNaming, \Rector\ChangesReporting\Collector\RectorChangeCollector $rectorChangeCollector) + { $this->betterPhpDocParser = $betterPhpDocParser; $this->lexer = $lexer; $this->currentNodeProvider = $currentNodeProvider; @@ -80,110 +63,77 @@ final class PhpDocInfoFactory $this->annotationNaming = $annotationNaming; $this->rectorChangeCollector = $rectorChangeCollector; } - - public function createFromNodeOrEmpty(Node $node): PhpDocInfo + public function createFromNodeOrEmpty(\PhpParser\Node $node) : \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo { // already added - $phpDocInfo = $node->getAttribute(AttributeKey::PHP_DOC_INFO); - if ($phpDocInfo instanceof PhpDocInfo) { + $phpDocInfo = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO); + if ($phpDocInfo instanceof \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo) { return $phpDocInfo; } - $phpDocInfo = $this->createFromNode($node); - if ($phpDocInfo instanceof PhpDocInfo) { + if ($phpDocInfo instanceof \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo) { return $phpDocInfo; } - return $this->createEmpty($node); } - - public function createFromNode(Node $node): ?PhpDocInfo + public function createFromNode(\PhpParser\Node $node) : ?\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo { - $objectHash = spl_object_hash($node); + $objectHash = \spl_object_hash($node); if (isset($this->phpDocInfosByObjectHash[$objectHash])) { return $this->phpDocInfosByObjectHash[$objectHash]; } - /** needed for @see PhpDocNodeFactoryInterface */ $this->currentNodeProvider->setNode($node); - $docComment = $node->getDocComment(); - if (! $docComment instanceof Doc) { + if (!$docComment instanceof \PhpParser\Comment\Doc) { if ($node->getComments() !== []) { return null; } - // create empty node $content = ''; - $tokenIterator = new BetterTokenIterator([]); - $phpDocNode = new PhpDocNode([]); + $tokenIterator = new \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator([]); + $phpDocNode = new \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode([]); } else { $content = $docComment->getText(); $tokens = $this->lexer->tokenize($content); - $tokenIterator = new BetterTokenIterator($tokens); - + $tokenIterator = new \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator($tokens); $phpDocNode = $this->betterPhpDocParser->parse($tokenIterator); $this->setPositionOfLastToken($phpDocNode); } - $phpDocInfo = $this->createFromPhpDocNode($phpDocNode, $tokenIterator, $node); $this->phpDocInfosByObjectHash[$objectHash] = $phpDocInfo; - return $phpDocInfo; } - - public function createEmpty(Node $node): PhpDocInfo + public function createEmpty(\PhpParser\Node $node) : \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo { /** needed for @see PhpDocNodeFactoryInterface */ $this->currentNodeProvider->setNode($node); - - $phpDocNode = new PhpDocNode([]); - $phpDocInfo = $this->createFromPhpDocNode($phpDocNode, new BetterTokenIterator([]), $node); - + $phpDocNode = new \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode([]); + $phpDocInfo = $this->createFromPhpDocNode($phpDocNode, new \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator([]), $node); // multiline by default $phpDocInfo->makeMultiLined(); - return $phpDocInfo; } - /** * Needed for printing */ - private function setPositionOfLastToken(PhpDocNode $phpDocNode): void + private function setPositionOfLastToken(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode $phpDocNode) : void { if ($phpDocNode->children === []) { return; } - $phpDocChildNodes = $phpDocNode->children; - $lastChildNode = array_pop($phpDocChildNodes); - - $startAndEnd = $lastChildNode->getAttribute(PhpDocAttributeKey::START_AND_END); - - if ($startAndEnd instanceof StartAndEnd) { - $phpDocNode->setAttribute(PhpDocAttributeKey::LAST_PHP_DOC_TOKEN_POSITION, $startAndEnd->getEnd()); + $lastChildNode = \array_pop($phpDocChildNodes); + $startAndEnd = $lastChildNode->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END); + if ($startAndEnd instanceof \Rector\BetterPhpDocParser\ValueObject\StartAndEnd) { + $phpDocNode->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::LAST_PHP_DOC_TOKEN_POSITION, $startAndEnd->getEnd()); } } - - private function createFromPhpDocNode( - PhpDocNode $phpDocNode, - BetterTokenIterator $betterTokenIterator, - Node $node - ): PhpDocInfo { + private function createFromPhpDocNode(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode $phpDocNode, \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $betterTokenIterator, \PhpParser\Node $node) : \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo + { $this->phpDocNodeMapper->transform($phpDocNode, $betterTokenIterator); - - $phpDocInfo = new PhpDocInfo( - $phpDocNode, - $betterTokenIterator, - $this->staticTypeMapper, - $node, - $this->annotationNaming, - $this->currentNodeProvider, - $this->rectorChangeCollector - ); - - $node->setAttribute(AttributeKey::PHP_DOC_INFO, $phpDocInfo); - + $phpDocInfo = new \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo($phpDocNode, $betterTokenIterator, $this->staticTypeMapper, $node, $this->annotationNaming, $this->currentNodeProvider, $this->rectorChangeCollector); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, $phpDocInfo); return $phpDocInfo; } } diff --git a/packages/BetterPhpDocParser/PhpDocInfo/TokenIteratorFactory.php b/packages/BetterPhpDocParser/PhpDocInfo/TokenIteratorFactory.php index 06a7ce90d2d..69befc011c7 100644 --- a/packages/BetterPhpDocParser/PhpDocInfo/TokenIteratorFactory.php +++ b/packages/BetterPhpDocParser/PhpDocInfo/TokenIteratorFactory.php @@ -1,56 +1,46 @@ lexer = $lexer; $this->privatesAccessor = $privatesAccessor; } - - public function create(string $content): BetterTokenIterator + public function create(string $content) : \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator { $tokens = $this->lexer->tokenize($content); - return new BetterTokenIterator($tokens); + return new \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator($tokens); } - - public function createFromTokenIterator(TokenIterator $tokenIterator): BetterTokenIterator + public function createFromTokenIterator(\PHPStan\PhpDocParser\Parser\TokenIterator $tokenIterator) : \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator { - if ($tokenIterator instanceof BetterTokenIterator) { + if ($tokenIterator instanceof \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator) { return $tokenIterator; } - $tokens = $this->privatesAccessor->getPrivateProperty($tokenIterator, 'tokens'); - $betterTokenIterator = new BetterTokenIterator($tokens); - + $betterTokenIterator = new \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator($tokens); // keep original position $currentIndex = $this->privatesAccessor->getPrivateProperty($tokenIterator, 'index'); $this->privatesAccessor->setPrivateProperty($betterTokenIterator, self::INDEX, $currentIndex); - return $betterTokenIterator; } } diff --git a/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocClassRenamer.php b/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocClassRenamer.php index eff9045fbfd..1ae3842a095 100644 --- a/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocClassRenamer.php +++ b/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocClassRenamer.php @@ -1,116 +1,91 @@ classAnnotationMatcher = $classAnnotationMatcher; } - /** * Covers annotations like @ORM, @Serializer, @Assert etc * See https://github.com/rectorphp/rector/issues/1872 * * @param string[] $oldToNewClasses */ - public function changeTypeInAnnotationTypes(Node $node, PhpDocInfo $phpDocInfo, array $oldToNewClasses): void + public function changeTypeInAnnotationTypes(\PhpParser\Node $node, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, array $oldToNewClasses) : void { $this->processAssertChoiceTagValueNode($oldToNewClasses, $phpDocInfo); $this->processDoctrineRelationTagValueNode($node, $oldToNewClasses, $phpDocInfo); $this->processSerializerTypeTagValueNode($oldToNewClasses, $phpDocInfo); } - /** * @param array $oldToNewClasses */ - private function processAssertChoiceTagValueNode(array $oldToNewClasses, PhpDocInfo $phpDocInfo): void + private function processAssertChoiceTagValueNode(array $oldToNewClasses, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void { - $assertChoiceTagValueNode = $phpDocInfo->getByAnnotationClass('Symfony\Component\Validator\Constraints\Choice'); - if (! $assertChoiceTagValueNode instanceof DoctrineAnnotationTagValueNode) { + $assertChoiceTagValueNode = $phpDocInfo->getByAnnotationClass('Symfony\\Component\\Validator\\Constraints\\Choice'); + if (!$assertChoiceTagValueNode instanceof \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode) { return; } - $callback = $assertChoiceTagValueNode->getValueWithoutQuotes('callback'); if ($callback === null) { return; } - foreach ($oldToNewClasses as $oldClass => $newClass) { if ($callback[0] !== $oldClass) { continue; } - $callback[0] = $newClass; - $assertChoiceTagValueNode->changeValue('callback', $callback); break; } } - /** * @param array $oldToNewClasses */ - private function processDoctrineRelationTagValueNode( - Node $node, - array $oldToNewClasses, - PhpDocInfo $phpDocInfo - ): void { - $doctrineAnnotationTagValueNode = $phpDocInfo->getByAnnotationClasses([ - 'Doctrine\ORM\Mapping\OneToMany', - 'Doctrine\ORM\Mapping\ManyToMany', - 'Doctrine\ORM\Mapping\Embedded', - ]); - - if (! $doctrineAnnotationTagValueNode instanceof DoctrineAnnotationTagValueNode) { + private function processDoctrineRelationTagValueNode(\PhpParser\Node $node, array $oldToNewClasses, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void + { + $doctrineAnnotationTagValueNode = $phpDocInfo->getByAnnotationClasses(['Doctrine\\ORM\\Mapping\\OneToMany', 'Doctrine\\ORM\\Mapping\\ManyToMany', 'Doctrine\\ORM\\Mapping\\Embedded']); + if (!$doctrineAnnotationTagValueNode instanceof \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode) { return; } - $this->processDoctrineToMany($doctrineAnnotationTagValueNode, $node, $oldToNewClasses); } - /** * @param array $oldToNewClasses */ - private function processSerializerTypeTagValueNode(array $oldToNewClasses, PhpDocInfo $phpDocInfo): void + private function processSerializerTypeTagValueNode(array $oldToNewClasses, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void { - $doctrineAnnotationTagValueNode = $phpDocInfo->getByAnnotationClass('JMS\Serializer\Annotation\Type'); - if (! $doctrineAnnotationTagValueNode instanceof DoctrineAnnotationTagValueNode) { + $doctrineAnnotationTagValueNode = $phpDocInfo->getByAnnotationClass('JMS\\Serializer\\Annotation\\Type'); + if (!$doctrineAnnotationTagValueNode instanceof \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode) { return; } - foreach ($oldToNewClasses as $oldClass => $newClass) { $className = $doctrineAnnotationTagValueNode->getSilentValue(); - if ($className) { if ($className === $oldClass) { $doctrineAnnotationTagValueNode->changeSilentValue($newClass); continue; } - - $newContent = Strings::replace($className, '#\b' . preg_quote($oldClass, '#') . '\b#', $newClass); + $newContent = \RectorPrefix20210509\Nette\Utils\Strings::replace($className, '#\\b' . \preg_quote($oldClass, '#') . '\\b#', $newClass); if ($newContent === $className) { continue; } - $doctrineAnnotationTagValueNode->changeSilentValue($newContent); continue; } - $currentType = $doctrineAnnotationTagValueNode->getValueWithoutQuotes('type'); if ($currentType === $oldClass) { $doctrineAnnotationTagValueNode->changeValue('type', $newClass); @@ -118,34 +93,26 @@ final class PhpDocClassRenamer } } } - /** * @param array $oldToNewClasses */ - private function processDoctrineToMany( - DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode, - Node $node, - array $oldToNewClasses - ): void { - if ($doctrineAnnotationTagValueNode->getAnnotationClass() === 'Doctrine\ORM\Mapping\Embedded') { + private function processDoctrineToMany(\Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode, \PhpParser\Node $node, array $oldToNewClasses) : void + { + if ($doctrineAnnotationTagValueNode->getAnnotationClass() === 'Doctrine\\ORM\\Mapping\\Embedded') { $classKey = 'class'; } else { $classKey = 'targetEntity'; } - $targetEntity = $doctrineAnnotationTagValueNode->getValueWithoutQuotes($classKey); if ($targetEntity === null) { return; } - // resolve to FQN $tagFullyQualifiedName = $this->classAnnotationMatcher->resolveTagFullyQualifiedName($targetEntity, $node); - foreach ($oldToNewClasses as $oldClass => $newClass) { if ($tagFullyQualifiedName !== $oldClass) { continue; } - $doctrineAnnotationTagValueNode->changeValue($classKey, $newClass); } } diff --git a/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocTagRemover.php b/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocTagRemover.php index 7f76a423a5e..47a3bf6a89e 100644 --- a/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocTagRemover.php +++ b/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocTagRemover.php @@ -1,31 +1,26 @@ getPhpDocNode(); - foreach ($phpDocNode->children as $key => $phpDocChildNode) { - if (! $phpDocChildNode instanceof PhpDocTagNode) { + if (!$phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - if ($this->areAnnotationNamesEqual($name, $phpDocChildNode->name)) { unset($phpDocNode->children[$key]); $phpDocInfo->markAsChanged(); } - - if ($phpDocChildNode->value instanceof DoctrineAnnotationTagValueNode) { + if ($phpDocChildNode->value instanceof \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode) { $tagClass = $phpDocChildNode->value->getAnnotationClass(); if ($tagClass === $name) { unset($phpDocNode->children[$key]); @@ -34,36 +29,29 @@ final class PhpDocTagRemover } } } - - public function removeTagValueFromNode(PhpDocInfo $phpDocInfo, Node $desiredNode): void + public function removeTagValueFromNode(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \PHPStan\PhpDocParser\Ast\Node $desiredNode) : void { $phpDocNode = $phpDocInfo->getPhpDocNode(); - foreach ($phpDocNode->children as $key => $phpDocChildNode) { if ($phpDocChildNode === $desiredNode) { unset($phpDocNode->children[$key]); $phpDocInfo->markAsChanged(); continue; } - - if (! $phpDocChildNode instanceof PhpDocTagNode) { + if (!$phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - if ($phpDocChildNode->value !== $desiredNode) { continue; } - unset($phpDocNode->children[$key]); $phpDocInfo->markAsChanged(); } } - - private function areAnnotationNamesEqual(string $firstAnnotationName, string $secondAnnotationName): bool + private function areAnnotationNamesEqual(string $firstAnnotationName, string $secondAnnotationName) : bool { - $firstAnnotationName = trim($firstAnnotationName, '@'); - $secondAnnotationName = trim($secondAnnotationName, '@'); - + $firstAnnotationName = \trim($firstAnnotationName, '@'); + $secondAnnotationName = \trim($secondAnnotationName, '@'); return $firstAnnotationName === $secondAnnotationName; } } diff --git a/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocTypeChanger.php b/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocTypeChanger.php index 9ff8b421e87..0e914257f4b 100644 --- a/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocTypeChanger.php +++ b/packages/BetterPhpDocParser/PhpDocManipulator/PhpDocTypeChanger.php @@ -1,7 +1,6 @@ typeComparator = $typeComparator; $this->staticTypeMapper = $staticTypeMapper; $this->paramPhpDocNodeFactory = $paramPhpDocNodeFactory; } - - public function changeVarType(PhpDocInfo $phpDocInfo, Type $newType): void + public function changeVarType(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \PHPStan\Type\Type $newType) : void { // better skip, could crash hard if ($phpDocInfo->hasInvalidTag('@var')) { return; } - // make sure the tags are not identical, e.g imported class vs FQN class if ($this->typeComparator->areTypesEqual($phpDocInfo->getVarType(), $newType)) { return; } - // prevent existing type override by mixed - if (! $phpDocInfo->getVarType() instanceof MixedType && $newType instanceof ConstantArrayType && $newType->getItemType() instanceof NeverType) { + if (!$phpDocInfo->getVarType() instanceof \PHPStan\Type\MixedType && $newType instanceof \PHPStan\Type\Constant\ConstantArrayType && $newType->getItemType() instanceof \PHPStan\Type\NeverType) { return; } - // override existing type $newPHPStanPhpDocType = $this->staticTypeMapper->mapPHPStanTypeToPHPStanPhpDocTypeNode($newType); - $currentVarTagValueNode = $phpDocInfo->getVarTagValueNode(); if ($currentVarTagValueNode !== null) { // only change type $currentVarTagValueNode->type = $newPHPStanPhpDocType; } else { // add completely new one - $varTagValueNode = new VarTagValueNode($newPHPStanPhpDocType, '', ''); + $varTagValueNode = new \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode($newPHPStanPhpDocType, '', ''); $phpDocInfo->addTagValueNode($varTagValueNode); } } - - public function changeReturnType(PhpDocInfo $phpDocInfo, Type $newType): void + public function changeReturnType(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \PHPStan\Type\Type $newType) : void { // better not touch this, can crash if ($phpDocInfo->hasInvalidTag('@return')) { return; } - // make sure the tags are not identical, e.g imported class vs FQN class if ($this->typeComparator->areTypesEqual($phpDocInfo->getReturnType(), $newType)) { return; } - // override existing type $newPHPStanPhpDocType = $this->staticTypeMapper->mapPHPStanTypeToPHPStanPhpDocTypeNode($newType); $currentReturnTagValueNode = $phpDocInfo->getReturnTagValue(); - if ($currentReturnTagValueNode !== null) { // only change type $currentReturnTagValueNode->type = $newPHPStanPhpDocType; } else { // add completely new one - $returnTagValueNode = new ReturnTagValueNode($newPHPStanPhpDocType, ''); + $returnTagValueNode = new \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode($newPHPStanPhpDocType, ''); $phpDocInfo->addTagValueNode($returnTagValueNode); } } - - public function changeParamType(PhpDocInfo $phpDocInfo, Type $newType, Param $param, string $paramName): void + public function changeParamType(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \PHPStan\Type\Type $newType, \PhpParser\Node\Param $param, string $paramName) : void { // better skip, could crash hard if ($phpDocInfo->hasInvalidTag('@param')) { return; } - $phpDocType = $this->staticTypeMapper->mapPHPStanTypeToPHPStanPhpDocTypeNode($newType); $paramTagValueNode = $phpDocInfo->getParamTagValueByName($paramName); - // override existing type if ($paramTagValueNode !== null) { // already set - $currentType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType( - $paramTagValueNode->type, - $param - ); - + $currentType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType($paramTagValueNode->type, $param); // avoid overriding better type if ($this->typeComparator->isSubtype($currentType, $newType)) { return; } - if ($this->typeComparator->areTypesEqual($currentType, $newType)) { return; } - $paramTagValueNode->type = $phpDocType; } else { $paramTagValueNode = $this->paramPhpDocNodeFactory->create($phpDocType, $param); diff --git a/packages/BetterPhpDocParser/PhpDocManipulator/PropertyDocBlockManipulator.php b/packages/BetterPhpDocParser/PhpDocManipulator/PropertyDocBlockManipulator.php index 931fca23861..f5c11266b57 100644 --- a/packages/BetterPhpDocParser/PhpDocManipulator/PropertyDocBlockManipulator.php +++ b/packages/BetterPhpDocParser/PhpDocManipulator/PropertyDocBlockManipulator.php @@ -1,7 +1,6 @@ phpDocInfoFactory = $phpDocInfoFactory; } - /** * @param ParamRename $renameValueObject */ - public function renameParameterNameInDocBlock(RenameValueObjectInterface $renameValueObject): void + public function renameParameterNameInDocBlock(\Rector\Naming\Contract\RenameValueObjectInterface $renameValueObject) : void { $functionLike = $renameValueObject->getFunctionLike(); - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($functionLike); $paramTagValueNode = $phpDocInfo->getParamTagValueNodeByName($renameValueObject->getCurrentName()); - if (! $paramTagValueNode instanceof ParamTagValueNode) { + if (!$paramTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode) { return; } - $paramTagValueNode->parameterName = '$' . $renameValueObject->getExpectedName(); - $paramTagValueNode->setAttribute(PhpDocAttributeKey::ORIG_NODE, null); + $paramTagValueNode->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::ORIG_NODE, null); } } diff --git a/packages/BetterPhpDocParser/PhpDocManipulator/VarAnnotationManipulator.php b/packages/BetterPhpDocParser/PhpDocManipulator/VarAnnotationManipulator.php index 0264035684b..4a740d93b96 100644 --- a/packages/BetterPhpDocParser/PhpDocManipulator/VarAnnotationManipulator.php +++ b/packages/BetterPhpDocParser/PhpDocManipulator/VarAnnotationManipulator.php @@ -1,7 +1,6 @@ phpDocInfoFactory = $phpDocInfoFactory; $this->phpDocTypeChanger = $phpDocTypeChanger; } - - public function decorateNodeWithInlineVarType( - Node $node, - TypeWithClassName $typeWithClassName, - string $variableName - ): void { + public function decorateNodeWithInlineVarType(\PhpParser\Node $node, \PHPStan\Type\TypeWithClassName $typeWithClassName, string $variableName) : void + { $phpDocInfo = $this->resolvePhpDocInfo($node); - // already done if ($phpDocInfo->getVarTagValueNode() !== null) { return; } - - $fullyQualifiedIdentifierTypeNode = new FullyQualifiedIdentifierTypeNode($typeWithClassName->getClassName()); - - $varTagValueNode = new VarTagValueNode($fullyQualifiedIdentifierTypeNode, '$' . $variableName, ''); + $fullyQualifiedIdentifierTypeNode = new \Rector\BetterPhpDocParser\ValueObject\Type\FullyQualifiedIdentifierTypeNode($typeWithClassName->getClassName()); + $varTagValueNode = new \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode($fullyQualifiedIdentifierTypeNode, '$' . $variableName, ''); $phpDocInfo->addTagValueNode($varTagValueNode); $phpDocInfo->makeSingleLined(); } - - public function decorateNodeWithType(Node $node, Type $staticType): void + public function decorateNodeWithType(\PhpParser\Node $node, \PHPStan\Type\Type $staticType) : void { - if ($staticType instanceof MixedType) { + if ($staticType instanceof \PHPStan\Type\MixedType) { return; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); $this->phpDocTypeChanger->changeVarType($phpDocInfo, $staticType); } - - private function resolvePhpDocInfo(Node $node): PhpDocInfo + private function resolvePhpDocInfo(\PhpParser\Node $node) : \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo { - $currentStmt = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); - if ($currentStmt instanceof Expression) { + $currentStmt = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); + if ($currentStmt instanceof \PhpParser\Node\Stmt\Expression) { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($currentStmt); } else { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); } - $phpDocInfo->makeSingleLined(); - return $phpDocInfo; } } diff --git a/packages/BetterPhpDocParser/PhpDocNodeMapper.php b/packages/BetterPhpDocParser/PhpDocNodeMapper.php index 075dbcda9cd..501fed7829f 100644 --- a/packages/BetterPhpDocParser/PhpDocNodeMapper.php +++ b/packages/BetterPhpDocParser/PhpDocNodeMapper.php @@ -1,18 +1,16 @@ phpDocNodeVisitors = $phpDocNodeVisitors; $this->currentTokenIteratorProvider = $currentTokenIteratorProvider; $this->parentConnectingPhpDocNodeVisitor = $parentConnectingPhpDocNodeVisitor; $this->cloningPhpDocNodeVisitor = $cloningPhpDocNodeVisitor; } - - public function transform(PhpDocNode $phpDocNode, BetterTokenIterator $betterTokenIterator): void + public function transform(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode $phpDocNode, \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $betterTokenIterator) : void { $this->currentTokenIteratorProvider->setBetterTokenIterator($betterTokenIterator); - - $parentPhpDocNodeTraverser = new PhpDocNodeTraverser(); + $parentPhpDocNodeTraverser = new \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser(); $parentPhpDocNodeTraverser->addPhpDocNodeVisitor($this->parentConnectingPhpDocNodeVisitor); $parentPhpDocNodeTraverser->traverse($phpDocNode); - - $cloningPhpDocNodeTraverser = new PhpDocNodeTraverser(); + $cloningPhpDocNodeTraverser = new \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser(); $cloningPhpDocNodeTraverser->addPhpDocNodeVisitor($this->cloningPhpDocNodeVisitor); $cloningPhpDocNodeTraverser->traverse($phpDocNode); - - $phpDocNodeTraverser = new PhpDocNodeTraverser(); + $phpDocNodeTraverser = new \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser(); foreach ($this->phpDocNodeVisitors as $phpDocNodeVisitor) { $phpDocNodeTraverser->addPhpDocNodeVisitor($phpDocNodeVisitor); } - $phpDocNodeTraverser->traverse($phpDocNode); } } diff --git a/packages/BetterPhpDocParser/PhpDocNodeTraverser/ChangedPhpDocNodeTraverserFactory.php b/packages/BetterPhpDocParser/PhpDocNodeTraverser/ChangedPhpDocNodeTraverserFactory.php index 04a69328c6f..3ed717644d8 100644 --- a/packages/BetterPhpDocParser/PhpDocNodeTraverser/ChangedPhpDocNodeTraverserFactory.php +++ b/packages/BetterPhpDocParser/PhpDocNodeTraverser/ChangedPhpDocNodeTraverserFactory.php @@ -1,29 +1,24 @@ changedPhpDocNodeVisitor = $changedPhpDocNodeVisitor; } - - public function create(): PhpDocNodeTraverser + public function create() : \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser { - $changedPhpDocNodeTraverser = new PhpDocNodeTraverser(); + $changedPhpDocNodeTraverser = new \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser(); $changedPhpDocNodeTraverser->addPhpDocNodeVisitor($this->changedPhpDocNodeVisitor); - return $changedPhpDocNodeTraverser; } } diff --git a/packages/BetterPhpDocParser/PhpDocNodeVisitor/ArrayTypePhpDocNodeVisitor.php b/packages/BetterPhpDocParser/PhpDocNodeVisitor/ArrayTypePhpDocNodeVisitor.php index 9c6ad74cb73..2b0ae8c781a 100644 --- a/packages/BetterPhpDocParser/PhpDocNodeVisitor/ArrayTypePhpDocNodeVisitor.php +++ b/packages/BetterPhpDocParser/PhpDocNodeVisitor/ArrayTypePhpDocNodeVisitor.php @@ -1,7 +1,6 @@ attributeMirrorer = $attributeMirrorer; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) : ?\PHPStan\PhpDocParser\Ast\Node { - if (! $node instanceof ArrayTypeNode) { + if (!$node instanceof \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode) { return null; } - - if ($node instanceof SpacingAwareArrayTypeNode) { + if ($node instanceof \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode) { return null; } - - $spacingAwareArrayTypeNode = new SpacingAwareArrayTypeNode($node->type); + $spacingAwareArrayTypeNode = new \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode($node->type); $this->attributeMirrorer->mirror($node, $spacingAwareArrayTypeNode); - return $spacingAwareArrayTypeNode; } } diff --git a/packages/BetterPhpDocParser/PhpDocNodeVisitor/CallableTypePhpDocNodeVisitor.php b/packages/BetterPhpDocParser/PhpDocNodeVisitor/CallableTypePhpDocNodeVisitor.php index fa5f3badcb1..c7d5df887df 100644 --- a/packages/BetterPhpDocParser/PhpDocNodeVisitor/CallableTypePhpDocNodeVisitor.php +++ b/packages/BetterPhpDocParser/PhpDocNodeVisitor/CallableTypePhpDocNodeVisitor.php @@ -1,7 +1,6 @@ attributeMirrorer = $attributeMirrorer; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) : ?\PHPStan\PhpDocParser\Ast\Node { - if (! $node instanceof CallableTypeNode) { + if (!$node instanceof \PHPStan\PhpDocParser\Ast\Type\CallableTypeNode) { return null; } - - if ($node instanceof SpacingAwareCallableTypeNode) { + if ($node instanceof \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareCallableTypeNode) { return null; } - - $spacingAwareCallableTypeNode = new SpacingAwareCallableTypeNode( - $node->identifier, - $node->parameters, - $node->returnType - ); - + $spacingAwareCallableTypeNode = new \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareCallableTypeNode($node->identifier, $node->parameters, $node->returnType); $this->attributeMirrorer->mirror($node, $spacingAwareCallableTypeNode); - return $spacingAwareCallableTypeNode; } } diff --git a/packages/BetterPhpDocParser/PhpDocNodeVisitor/ChangedPhpDocNodeVisitor.php b/packages/BetterPhpDocParser/PhpDocNodeVisitor/ChangedPhpDocNodeVisitor.php index 07f3a62522c..9daac6b2ebd 100644 --- a/packages/BetterPhpDocParser/PhpDocNodeVisitor/ChangedPhpDocNodeVisitor.php +++ b/packages/BetterPhpDocParser/PhpDocNodeVisitor/ChangedPhpDocNodeVisitor.php @@ -1,36 +1,30 @@ hasChanged = false; + $this->hasChanged = \false; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) : ?\PHPStan\PhpDocParser\Ast\Node { - $origNode = $node->getAttribute(PhpDocAttributeKey::ORIG_NODE); + $origNode = $node->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::ORIG_NODE); if ($origNode === null) { - $this->hasChanged = true; + $this->hasChanged = \true; } - return null; } - - public function hasChanged(): bool + public function hasChanged() : bool { return $this->hasChanged; } diff --git a/packages/BetterPhpDocParser/PhpDocNodeVisitor/IntersectionTypeNodePhpDocNodeVisitor.php b/packages/BetterPhpDocParser/PhpDocNodeVisitor/IntersectionTypeNodePhpDocNodeVisitor.php index ce3442c11e1..aa66b7cef9a 100644 --- a/packages/BetterPhpDocParser/PhpDocNodeVisitor/IntersectionTypeNodePhpDocNodeVisitor.php +++ b/packages/BetterPhpDocParser/PhpDocNodeVisitor/IntersectionTypeNodePhpDocNodeVisitor.php @@ -1,7 +1,6 @@ attributeMirrorer = $attributeMirrorer; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) : ?\PHPStan\PhpDocParser\Ast\Node { - if (! $node instanceof IntersectionTypeNode) { + if (!$node instanceof \PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode) { return null; } - - if ($node instanceof BracketsAwareIntersectionTypeNode) { + if ($node instanceof \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareIntersectionTypeNode) { return null; } - - $bracketsAwareIntersectionTypeNode = new BracketsAwareIntersectionTypeNode($node->types); + $bracketsAwareIntersectionTypeNode = new \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareIntersectionTypeNode($node->types); $this->attributeMirrorer->mirror($node, $bracketsAwareIntersectionTypeNode); - return $bracketsAwareIntersectionTypeNode; } } diff --git a/packages/BetterPhpDocParser/PhpDocNodeVisitor/ParamPhpDocNodeVisitor.php b/packages/BetterPhpDocParser/PhpDocNodeVisitor/ParamPhpDocNodeVisitor.php index f781146fd50..a3a7a1846d5 100644 --- a/packages/BetterPhpDocParser/PhpDocNodeVisitor/ParamPhpDocNodeVisitor.php +++ b/packages/BetterPhpDocParser/PhpDocNodeVisitor/ParamPhpDocNodeVisitor.php @@ -1,7 +1,6 @@ attributeMirrorer = $attributeMirrorer; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) : ?\PHPStan\PhpDocParser\Ast\Node { - if (! $node instanceof ParamTagValueNode) { + if (!$node instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode) { return null; } - - if ($node instanceof VariadicAwareParamTagValueNode) { + if ($node instanceof \Rector\BetterPhpDocParser\ValueObject\PhpDoc\VariadicAwareParamTagValueNode) { return null; } - - $variadicAwareParamTagValueNode = new VariadicAwareParamTagValueNode( - $node->type, - $node->isVariadic, - $node->parameterName, - $node->description - ); - + $variadicAwareParamTagValueNode = new \Rector\BetterPhpDocParser\ValueObject\PhpDoc\VariadicAwareParamTagValueNode($node->type, $node->isVariadic, $node->parameterName, $node->description); $this->attributeMirrorer->mirror($node, $variadicAwareParamTagValueNode); - return $variadicAwareParamTagValueNode; } } diff --git a/packages/BetterPhpDocParser/PhpDocNodeVisitor/TemplatePhpDocNodeVisitor.php b/packages/BetterPhpDocParser/PhpDocNodeVisitor/TemplatePhpDocNodeVisitor.php index a8ce93aebe4..ca79c194af6 100644 --- a/packages/BetterPhpDocParser/PhpDocNodeVisitor/TemplatePhpDocNodeVisitor.php +++ b/packages/BetterPhpDocParser/PhpDocNodeVisitor/TemplatePhpDocNodeVisitor.php @@ -1,7 +1,6 @@ currentTokenIteratorProvider = $currentTokenIteratorProvider; $this->attributeMirrorer = $attributeMirrorer; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) : ?\PHPStan\PhpDocParser\Ast\Node { - if (! $node instanceof TemplateTagValueNode) { + if (!$node instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode) { return null; } - - if ($node instanceof SpacingAwareTemplateTagValueNode) { + if ($node instanceof \Rector\BetterPhpDocParser\ValueObject\PhpDoc\SpacingAwareTemplateTagValueNode) { return null; } - $betterTokenIterator = $this->currentTokenIteratorProvider->provide(); - - $startAndEnd = $node->getAttribute(PhpDocAttributeKey::START_AND_END); - if (! $startAndEnd instanceof StartAndEnd) { - throw new ShouldNotHappenException(); + $startAndEnd = $node->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END); + if (!$startAndEnd instanceof \Rector\BetterPhpDocParser\ValueObject\StartAndEnd) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $prepositions = $this->resolvePreposition($betterTokenIterator, $startAndEnd); - $spacingAwareTemplateTagValueNode = new SpacingAwareTemplateTagValueNode( - $node->name, - $node->bound, - $node->description, - $prepositions - ); - + $spacingAwareTemplateTagValueNode = new \Rector\BetterPhpDocParser\ValueObject\PhpDoc\SpacingAwareTemplateTagValueNode($node->name, $node->bound, $node->description, $prepositions); $this->attributeMirrorer->mirror($node, $spacingAwareTemplateTagValueNode); - return $spacingAwareTemplateTagValueNode; } - - private function resolvePreposition(BetterTokenIterator $betterTokenIterator, StartAndEnd $startAndEnd): string + private function resolvePreposition(\Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $betterTokenIterator, \Rector\BetterPhpDocParser\ValueObject\StartAndEnd $startAndEnd) : string { $partialTokens = $betterTokenIterator->partialTokens($startAndEnd->getStart(), $startAndEnd->getEnd()); - foreach ($partialTokens as $partialToken) { - if ($partialToken[1] !== Lexer::TOKEN_IDENTIFIER) { + if ($partialToken[1] !== \PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_IDENTIFIER) { continue; } - - if (! in_array($partialToken[0], ['as', 'of'], true)) { + if (!\in_array($partialToken[0], ['as', 'of'], \true)) { continue; } - return $partialToken[0]; } - return 'of'; } } diff --git a/packages/BetterPhpDocParser/PhpDocNodeVisitor/UnionTypeNodePhpDocNodeVisitor.php b/packages/BetterPhpDocParser/PhpDocNodeVisitor/UnionTypeNodePhpDocNodeVisitor.php index d30bc2796c8..41f5487b4c3 100644 --- a/packages/BetterPhpDocParser/PhpDocNodeVisitor/UnionTypeNodePhpDocNodeVisitor.php +++ b/packages/BetterPhpDocParser/PhpDocNodeVisitor/UnionTypeNodePhpDocNodeVisitor.php @@ -1,7 +1,6 @@ currentTokenIteratorProvider = $currentTokenIteratorProvider; $this->attributeMirrorer = $attributeMirrorer; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) : ?\PHPStan\PhpDocParser\Ast\Node { - if (! $node instanceof UnionTypeNode) { + if (!$node instanceof \PHPStan\PhpDocParser\Ast\Type\UnionTypeNode) { return null; } - - if ($node instanceof BracketsAwareUnionTypeNode) { + if ($node instanceof \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareUnionTypeNode) { return null; } - // unwrap with parent array type... - $startAndEnd = $node->getAttribute(PhpDocAttributeKey::START_AND_END); - if (! $startAndEnd instanceof StartAndEnd) { - throw new ShouldNotHappenException(); + $startAndEnd = $node->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END); + if (!$startAndEnd instanceof \Rector\BetterPhpDocParser\ValueObject\StartAndEnd) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $betterTokenProvider = $this->currentTokenIteratorProvider->provide(); - $isWrappedInCurlyBrackets = $this->isWrappedInCurlyBrackets($betterTokenProvider, $startAndEnd); - $bracketsAwareUnionTypeNode = new BracketsAwareUnionTypeNode($node->types, $isWrappedInCurlyBrackets); - + $bracketsAwareUnionTypeNode = new \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareUnionTypeNode($node->types, $isWrappedInCurlyBrackets); $this->attributeMirrorer->mirror($node, $bracketsAwareUnionTypeNode); - return $bracketsAwareUnionTypeNode; } - - private function isWrappedInCurlyBrackets(BetterTokenIterator $betterTokenProvider, StartAndEnd $startAndEnd): bool + private function isWrappedInCurlyBrackets(\Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $betterTokenProvider, \Rector\BetterPhpDocParser\ValueObject\StartAndEnd $startAndEnd) : bool { $previousPosition = $startAndEnd->getStart() - 1; - - if ($betterTokenProvider->isTokenTypeOnPosition(Lexer::TOKEN_OPEN_PARENTHESES, $previousPosition)) { - return true; + if ($betterTokenProvider->isTokenTypeOnPosition(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_OPEN_PARENTHESES, $previousPosition)) { + return \true; } - // there is no + 1, as end is right at the next token - return $betterTokenProvider->isTokenTypeOnPosition(Lexer::TOKEN_CLOSE_PARENTHESES, $startAndEnd->getEnd()); + return $betterTokenProvider->isTokenTypeOnPosition(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_PARENTHESES, $startAndEnd->getEnd()); } } diff --git a/packages/BetterPhpDocParser/PhpDocParser/BetterPhpDocParser.php b/packages/BetterPhpDocParser/PhpDocParser/BetterPhpDocParser.php index c19233965d6..c5d5b821ba8 100644 --- a/packages/BetterPhpDocParser/PhpDocParser/BetterPhpDocParser.php +++ b/packages/BetterPhpDocParser/PhpDocParser/BetterPhpDocParser.php @@ -1,7 +1,6 @@ privatesCaller = new PrivatesCaller(); + $this->privatesCaller = new \RectorPrefix20210509\Symplify\PackageBuilder\Reflection\PrivatesCaller(); $this->doctrineAnnotationDecorator = $doctrineAnnotationDecorator; $this->tokenIteratorFactory = $tokenIteratorFactory; } - - public function parse(TokenIterator $tokenIterator): PhpDocNode + public function parse(\PHPStan\PhpDocParser\Parser\TokenIterator $tokenIterator) : \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode { - $tokenIterator->consumeTokenType(Lexer::TOKEN_OPEN_PHPDOC); - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_PHPDOC_EOL); - + $tokenIterator->consumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_OPEN_PHPDOC); + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_PHPDOC_EOL); $children = []; - if (! $tokenIterator->isCurrentTokenType(Lexer::TOKEN_CLOSE_PHPDOC)) { + if (!$tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_PHPDOC)) { $children[] = $this->parseChildAndStoreItsPositions($tokenIterator); - - while ($tokenIterator->tryConsumeTokenType(Lexer::TOKEN_PHPDOC_EOL) && ! $tokenIterator->isCurrentTokenType( - Lexer::TOKEN_CLOSE_PHPDOC - )) { + while ($tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_PHPDOC_EOL) && !$tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_PHPDOC)) { $children[] = $this->parseChildAndStoreItsPositions($tokenIterator); } } - // might be in the middle of annotations - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_CLOSE_PHPDOC); - - $phpDocNode = new PhpDocNode($children); + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_PHPDOC); + $phpDocNode = new \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode($children); // replace generic nodes with DoctrineAnnotations $this->doctrineAnnotationDecorator->decorate($phpDocNode); - return $phpDocNode; } - /** * @param BetterTokenIterator $tokenIterator */ - public function parseTag(TokenIterator $tokenIterator): PhpDocTagNode + public function parseTag(\PHPStan\PhpDocParser\Parser\TokenIterator $tokenIterator) : \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode { $tag = $this->resolveTag($tokenIterator); - $phpDocTagValueNode = $this->parseTagValue($tokenIterator, $tag); - return new PhpDocTagNode($tag, $phpDocTagValueNode); + return new \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode($tag, $phpDocTagValueNode); } - /** * @param BetterTokenIterator $tokenIterator */ - public function parseTagValue(TokenIterator $tokenIterator, string $tag): PhpDocTagValueNode + public function parseTagValue(\PHPStan\PhpDocParser\Parser\TokenIterator $tokenIterator, string $tag) : \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode { $startPosition = $tokenIterator->currentPosition(); $tagValueNode = parent::parseTagValue($tokenIterator, $tag); $endPosition = $tokenIterator->currentPosition(); - - $startAndEnd = new StartAndEnd($startPosition, $endPosition); - $tagValueNode->setAttribute(PhpDocAttributeKey::START_AND_END, $startAndEnd); - + $startAndEnd = new \Rector\BetterPhpDocParser\ValueObject\StartAndEnd($startPosition, $endPosition); + $tagValueNode->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END, $startAndEnd); return $tagValueNode; } - - private function parseChildAndStoreItsPositions(TokenIterator $tokenIterator): PhpDocChildNode + private function parseChildAndStoreItsPositions(\PHPStan\PhpDocParser\Parser\TokenIterator $tokenIterator) : \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode { $betterTokenIterator = $this->tokenIteratorFactory->createFromTokenIterator($tokenIterator); - $startPosition = $betterTokenIterator->currentPosition(); - /** @var PhpDocTagNode|PhpDocTextNode $phpDocNode */ $phpDocNode = $this->privatesCaller->callPrivateMethod($this, 'parseChild', [$betterTokenIterator]); $endPosition = $betterTokenIterator->currentPosition(); - - $startAndEnd = new StartAndEnd($startPosition, $endPosition); - $phpDocNode->setAttribute(PhpDocAttributeKey::START_AND_END, $startAndEnd); - + $startAndEnd = new \Rector\BetterPhpDocParser\ValueObject\StartAndEnd($startPosition, $endPosition); + $phpDocNode->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END, $startAndEnd); return $phpDocNode; } - - private function resolveTag(BetterTokenIterator $tokenIterator): string + private function resolveTag(\Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $tokenIterator) : string { $tag = $tokenIterator->currentTokenValue(); $tokenIterator->next(); - // there is a space → stop if ($tokenIterator->isPrecededByHorizontalWhitespace()) { return $tag; } - // is not e.g "@var " // join tags like "@ORM\Column" etc. - if (! $tokenIterator->isCurrentTokenType(Lexer::TOKEN_IDENTIFIER)) { + if (!$tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_IDENTIFIER)) { return $tag; } - // @todo use joinUntil("(")? $tag .= $tokenIterator->currentTokenValue(); $tokenIterator->next(); - return $tag; } } diff --git a/packages/BetterPhpDocParser/PhpDocParser/BetterTypeParser.php b/packages/BetterPhpDocParser/PhpDocParser/BetterTypeParser.php index 781ca697ecd..4f82130927c 100644 --- a/packages/BetterPhpDocParser/PhpDocParser/BetterTypeParser.php +++ b/packages/BetterPhpDocParser/PhpDocParser/BetterTypeParser.php @@ -1,7 +1,6 @@ tokenIteratorFactory = $tokenIteratorFactory; } - - public function parse(TokenIterator $tokenIterator): TypeNode + public function parse(\PHPStan\PhpDocParser\Parser\TokenIterator $tokenIterator) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { $betterTokenIterator = $this->tokenIteratorFactory->createFromTokenIterator($tokenIterator); - $startPosition = $betterTokenIterator->currentPosition(); $typeNode = parent::parse($betterTokenIterator); $endPosition = $betterTokenIterator->currentPosition(); - - $startAndEnd = new StartAndEnd($startPosition, $endPosition); - $typeNode->setAttribute(PhpDocAttributeKey::START_AND_END, $startAndEnd); - + $startAndEnd = new \Rector\BetterPhpDocParser\ValueObject\StartAndEnd($startPosition, $endPosition); + $typeNode->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END, $startAndEnd); return $typeNode; } } diff --git a/packages/BetterPhpDocParser/PhpDocParser/ClassAnnotationMatcher.php b/packages/BetterPhpDocParser/PhpDocParser/ClassAnnotationMatcher.php index c1741da8d5f..35a6e196db3 100644 --- a/packages/BetterPhpDocParser/PhpDocParser/ClassAnnotationMatcher.php +++ b/packages/BetterPhpDocParser/PhpDocParser/ClassAnnotationMatcher.php @@ -1,17 +1,15 @@ */ private $fullyQualifiedNameByHash = []; - /** * @var ReflectionProvider */ private $reflectionProvider; - - public function __construct(ReflectionProvider $reflectionProvider) + public function __construct(\PHPStan\Reflection\ReflectionProvider $reflectionProvider) { $this->reflectionProvider = $reflectionProvider; } - - public function resolveTagFullyQualifiedName(string $tag, Node $node): string + public function resolveTagFullyQualifiedName(string $tag, \PhpParser\Node $node) : string { - $uniqueHash = $tag . spl_object_hash($node); + $uniqueHash = $tag . \spl_object_hash($node); if (isset($this->fullyQualifiedNameByHash[$uniqueHash])) { return $this->fullyQualifiedNameByHash[$uniqueHash]; } - - $tag = ltrim($tag, '@'); - + $tag = \ltrim($tag, '@'); /** @var Use_[] $uses */ - $uses = (array) $node->getAttribute(AttributeKey::USE_NODES); + $uses = (array) $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::USE_NODES); $fullyQualifiedClass = $this->resolveFullyQualifiedClass($uses, $node, $tag); - $this->fullyQualifiedNameByHash[$uniqueHash] = $fullyQualifiedClass; - return $fullyQualifiedClass; } - /** * @param Use_[] $uses */ - private function resolveFullyQualifiedClass(array $uses, Node $node, string $tag): string + private function resolveFullyQualifiedClass(array $uses, \PhpParser\Node $node, string $tag) : string { - $scope = $node->getAttribute(AttributeKey::SCOPE); - if ($scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if ($scope instanceof \PHPStan\Analyser\Scope) { $namespace = $scope->getNamespace(); if ($namespace !== null) { $namespacedTag = $namespace . '\\' . $tag; @@ -65,47 +55,38 @@ final class ClassAnnotationMatcher } } } - return $this->matchFullAnnotationClassWithUses($tag, $uses) ?? $tag; } - /** * @param Use_[] $uses */ - private function matchFullAnnotationClassWithUses(string $tag, array $uses): ?string + private function matchFullAnnotationClassWithUses(string $tag, array $uses) : ?string { foreach ($uses as $use) { foreach ($use->uses as $useUse) { - if (! $this->isUseMatchingName($tag, $useUse)) { + if (!$this->isUseMatchingName($tag, $useUse)) { continue; } - return $this->resolveName($tag, $useUse); } } - return null; } - - private function isUseMatchingName(string $tag, UseUse $useUse): bool + private function isUseMatchingName(string $tag, \PhpParser\Node\Stmt\UseUse $useUse) : bool { $shortName = $useUse->alias !== null ? $useUse->alias->name : $useUse->name->getLast(); - $shortNamePattern = preg_quote($shortName, '#'); - - return (bool) Strings::match($tag, '#' . $shortNamePattern . '(\\\\[\w]+)?#i'); + $shortNamePattern = \preg_quote($shortName, '#'); + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($tag, '#' . $shortNamePattern . '(\\\\[\\w]+)?#i'); } - - private function resolveName(string $tag, UseUse $useUse): string + private function resolveName(string $tag, \PhpParser\Node\Stmt\UseUse $useUse) : string { if ($useUse->alias === null) { return $useUse->name->toString(); } - - $unaliasedShortClass = Strings::substring($tag, Strings::length($useUse->alias->toString())); - if (Strings::startsWith($unaliasedShortClass, '\\')) { + $unaliasedShortClass = \RectorPrefix20210509\Nette\Utils\Strings::substring($tag, \RectorPrefix20210509\Nette\Utils\Strings::length($useUse->alias->toString())); + if (\RectorPrefix20210509\Nette\Utils\Strings::startsWith($unaliasedShortClass, '\\')) { return $useUse->name . $unaliasedShortClass; } - return $useUse->name . '\\' . $unaliasedShortClass; } } diff --git a/packages/BetterPhpDocParser/PhpDocParser/DoctrineAnnotationDecorator.php b/packages/BetterPhpDocParser/PhpDocParser/DoctrineAnnotationDecorator.php index f4981bc1f81..c5d27cc1ad7 100644 --- a/packages/BetterPhpDocParser/PhpDocParser/DoctrineAnnotationDecorator.php +++ b/packages/BetterPhpDocParser/PhpDocParser/DoctrineAnnotationDecorator.php @@ -1,10 +1,9 @@ currentNodeProvider = $currentNodeProvider; $this->classAnnotationMatcher = $classAnnotationMatcher; $this->staticDoctrineAnnotationParser = $staticDoctrineAnnotationParser; $this->tokenIteratorFactory = $tokenIteratorFactory; $this->attributeMirrorer = $attributeMirrorer; } - - public function decorate(PhpDocNode $phpDocNode): void + public function decorate(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode $phpDocNode) : void { $currentPhpNode = $this->currentNodeProvider->getNode(); - if (! $currentPhpNode instanceof Node) { - throw new ShouldNotHappenException(); + if (!$currentPhpNode instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - // merge split doctrine nested tags $this->mergeNestedDoctrineAnnotations($phpDocNode); - $this->transformGenericTagValueNodesToDoctrineAnnotationTagValueNodes($phpDocNode, $currentPhpNode); } - /** * Join token iterator with all the following nodes if nested */ - private function mergeNestedDoctrineAnnotations(PhpDocNode $phpDocNode): void + private function mergeNestedDoctrineAnnotations(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode $phpDocNode) : void { $removedKeys = []; - foreach ($phpDocNode->children as $key => $phpDocChildNode) { - if (in_array($key, $removedKeys, true)) { + if (\in_array($key, $removedKeys, \true)) { continue; } - - if (! $phpDocChildNode instanceof PhpDocTagNode) { + if (!$phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - - if (! $phpDocChildNode->value instanceof GenericTagValueNode) { + if (!$phpDocChildNode->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode) { continue; } - $genericTagValueNode = $phpDocChildNode->value; - while (isset($phpDocNode->children[$key])) { ++$key; - // no more next nodes - if (! isset($phpDocNode->children[$key])) { + if (!isset($phpDocNode->children[$key])) { break; } - $nextPhpDocChildNode = $phpDocNode->children[$key]; - if (! $nextPhpDocChildNode instanceof PhpDocTagNode) { + if (!$nextPhpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - - if (! $nextPhpDocChildNode->value instanceof GenericTagValueNode) { + if (!$nextPhpDocChildNode->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode) { continue; } - if ($this->isClosedContent($genericTagValueNode->value)) { break; } - - $composedContent = $genericTagValueNode->value . PHP_EOL . $nextPhpDocChildNode->name . $nextPhpDocChildNode->value; + $composedContent = $genericTagValueNode->value . \PHP_EOL . $nextPhpDocChildNode->name . $nextPhpDocChildNode->value; $genericTagValueNode->value = $composedContent; - /** @var StartAndEnd $currentStartAndEnd */ - $currentStartAndEnd = $phpDocChildNode->getAttribute(PhpDocAttributeKey::START_AND_END); - + $currentStartAndEnd = $phpDocChildNode->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END); /** @var StartAndEnd $nextStartAndEnd */ - $nextStartAndEnd = $nextPhpDocChildNode->getAttribute(PhpDocAttributeKey::START_AND_END); - - $startAndEnd = new StartAndEnd($currentStartAndEnd->getStart(), $nextStartAndEnd->getEnd()); - $phpDocChildNode->setAttribute(PhpDocAttributeKey::START_AND_END, $startAndEnd); - + $nextStartAndEnd = $nextPhpDocChildNode->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END); + $startAndEnd = new \Rector\BetterPhpDocParser\ValueObject\StartAndEnd($currentStartAndEnd->getStart(), $nextStartAndEnd->getEnd()); + $phpDocChildNode->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END, $startAndEnd); $currentChildValueNode = $phpDocNode->children[$key]; - if (! $currentChildValueNode instanceof PhpDocTagNode) { + if (!$currentChildValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - $currentGenericTagValueNode = $currentChildValueNode->value; - if (! $currentGenericTagValueNode instanceof GenericTagValueNode) { + if (!$currentGenericTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode) { continue; } - $removedKeys[] = $key; } } - - foreach (array_keys($phpDocNode->children) as $key) { - if (! in_array($key, $removedKeys, true)) { + foreach (\array_keys($phpDocNode->children) as $key) { + if (!\in_array($key, $removedKeys, \true)) { continue; } - unset($phpDocNode->children[$key]); } } - - private function transformGenericTagValueNodesToDoctrineAnnotationTagValueNodes( - PhpDocNode $phpDocNode, - Node $currentPhpNode - ): void { + private function transformGenericTagValueNodesToDoctrineAnnotationTagValueNodes(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode $phpDocNode, \PhpParser\Node $currentPhpNode) : void + { foreach ($phpDocNode->children as $key => $phpDocChildNode) { - if (! $phpDocChildNode instanceof PhpDocTagNode) { + if (!$phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - - if (! $phpDocChildNode->value instanceof GenericTagValueNode) { + if (!$phpDocChildNode->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode) { continue; } - // known doc tag to annotation class - $fullyQualifiedAnnotationClass = $this->classAnnotationMatcher->resolveTagFullyQualifiedName( - $phpDocChildNode->name, - $currentPhpNode - ); - + $fullyQualifiedAnnotationClass = $this->classAnnotationMatcher->resolveTagFullyQualifiedName($phpDocChildNode->name, $currentPhpNode); // not an annotations class - if (! Strings::contains($fullyQualifiedAnnotationClass, '\\')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($fullyQualifiedAnnotationClass, '\\')) { continue; } - $genericTagValueNode = $phpDocChildNode->value; $nestedTokenIterator = $this->tokenIteratorFactory->create($genericTagValueNode->value); - // mimics doctrine behavior just in phpdoc-parser syntax :) // https://github.com/doctrine/annotations/blob/c66f06b7c83e9a2a7523351a9d5a4b55f885e574/lib/Doctrine/Common/Annotations/DocParser.php#L742 $values = $this->staticDoctrineAnnotationParser->resolveAnnotationMethodCall($nestedTokenIterator); - - $formerStartEnd = $genericTagValueNode->getAttribute(PhpDocAttributeKey::START_AND_END); - - $doctrineAnnotationTagValueNode = new DoctrineAnnotationTagValueNode( - $fullyQualifiedAnnotationClass, - $genericTagValueNode->value, - $values, - SilentKeyMap::CLASS_NAMES_TO_SILENT_KEYS[$fullyQualifiedAnnotationClass] ?? null - ); - - $doctrineAnnotationTagValueNode->setAttribute(PhpDocAttributeKey::START_AND_END, $formerStartEnd); - - $spacelessPhpDocTagNode = new SpacelessPhpDocTagNode( - $phpDocChildNode->name, - $doctrineAnnotationTagValueNode - ); - + $formerStartEnd = $genericTagValueNode->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END); + $doctrineAnnotationTagValueNode = new \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode($fullyQualifiedAnnotationClass, $genericTagValueNode->value, $values, \Rector\BetterPhpDocParser\ValueObject\DoctrineAnnotation\SilentKeyMap::CLASS_NAMES_TO_SILENT_KEYS[$fullyQualifiedAnnotationClass] ?? null); + $doctrineAnnotationTagValueNode->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END, $formerStartEnd); + $spacelessPhpDocTagNode = new \Rector\BetterPhpDocParser\PhpDoc\SpacelessPhpDocTagNode($phpDocChildNode->name, $doctrineAnnotationTagValueNode); $this->attributeMirrorer->mirror($phpDocChildNode, $spacelessPhpDocTagNode); $phpDocNode->children[$key] = $spacelessPhpDocTagNode; } } - /** * This is closed block, e.g. {( ... )}, * false on: {( ... ) */ - private function isClosedContent(string $composedContent): bool + private function isClosedContent(string $composedContent) : bool { $composedTokenIterator = $this->tokenIteratorFactory->create($composedContent); $tokenCount = $composedTokenIterator->count(); - $openBracketCount = 0; $closeBracketCount = 0; if ($composedContent === '') { - return true; + return \true; } - do { - if ($composedTokenIterator->isCurrentTokenTypes([ - Lexer::TOKEN_OPEN_CURLY_BRACKET, - Lexer::TOKEN_OPEN_PARENTHESES, - ]) || Strings::contains($composedTokenIterator->currentTokenValue(), '(')) { + if ($composedTokenIterator->isCurrentTokenTypes([\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_OPEN_CURLY_BRACKET, \PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_OPEN_PARENTHESES]) || \RectorPrefix20210509\Nette\Utils\Strings::contains($composedTokenIterator->currentTokenValue(), '(')) { ++$openBracketCount; } - - if ($composedTokenIterator->isCurrentTokenTypes([ - Lexer::TOKEN_CLOSE_CURLY_BRACKET, - Lexer::TOKEN_CLOSE_PARENTHESES, - // sometimes it gets mixed int ") - ]) || Strings::contains($composedTokenIterator->currentTokenValue(), ')')) { + if ($composedTokenIterator->isCurrentTokenTypes([\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_CURLY_BRACKET, \PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_PARENTHESES]) || \RectorPrefix20210509\Nette\Utils\Strings::contains($composedTokenIterator->currentTokenValue(), ')')) { ++$closeBracketCount; } - $composedTokenIterator->next(); - } while ($composedTokenIterator->currentPosition() < ($tokenCount - 1)); - + } while ($composedTokenIterator->currentPosition() < $tokenCount - 1); return $openBracketCount === $closeBracketCount; } } diff --git a/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser.php b/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser.php index ef3bb2bbdc2..caa3481f040 100644 --- a/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser.php +++ b/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser.php @@ -1,7 +1,6 @@ plainValueParser = $plainValueParser; $this->arrayParser = $arrayParser; } - /** * mimics: https://github.com/doctrine/annotations/blob/c66f06b7c83e9a2a7523351a9d5a4b55f885e574/lib/Doctrine/Common/Annotations/DocParser.php#L1024-L1041 * @return array */ - public function resolveAnnotationMethodCall(BetterTokenIterator $tokenIterator): array + public function resolveAnnotationMethodCall(\Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $tokenIterator) : array { - if (! $tokenIterator->isCurrentTokenType(Lexer::TOKEN_OPEN_PARENTHESES)) { + if (!$tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_OPEN_PARENTHESES)) { return []; } - - $tokenIterator->consumeTokenType(Lexer::TOKEN_OPEN_PARENTHESES); - + $tokenIterator->consumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_OPEN_PARENTHESES); // empty () - if ($tokenIterator->isCurrentTokenType(Lexer::TOKEN_CLOSE_PARENTHESES)) { + if ($tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_PARENTHESES)) { return []; } - return $this->resolveAnnotationValues($tokenIterator); } - /** * @see https://github.com/doctrine/annotations/blob/c66f06b7c83e9a2a7523351a9d5a4b55f885e574/lib/Doctrine/Common/Annotations/DocParser.php#L1215-L1224 * @return mixed|mixed[] */ - public function resolveAnnotationValue(BetterTokenIterator $tokenIterator) + public function resolveAnnotationValue(\Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $tokenIterator) { // skips dummy tokens like newlines - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_PHPDOC_EOL); - + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_PHPDOC_EOL); // no assign - if (! $tokenIterator->isNextTokenType(Lexer::TOKEN_EQUAL)) { + if (!$tokenIterator->isNextTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_EQUAL)) { // 1. plain value - mimics https://github.com/doctrine/annotations/blob/0cb0cd2950a5c6cdbf22adbe2bfd5fd1ea68588f/lib/Doctrine/Common/Annotations/DocParser.php#L1234-L1282 return $this->parseValue($tokenIterator); } - // 2. assign key = value - mimics FieldAssignment() https://github.com/doctrine/annotations/blob/0cb0cd2950a5c6cdbf22adbe2bfd5fd1ea68588f/lib/Doctrine/Common/Annotations/DocParser.php#L1291-L1303 $key = $this->parseValue($tokenIterator); - $tokenIterator->consumeTokenType(Lexer::TOKEN_EQUAL); - + $tokenIterator->consumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_EQUAL); // mimics https://github.com/doctrine/annotations/blob/1.13.x/lib/Doctrine/Common/Annotations/DocParser.php#L1236-L1238 $value = $this->parseValue($tokenIterator); - return [ // plain token value $key => $value, ]; } - /** * @see https://github.com/doctrine/annotations/blob/c66f06b7c83e9a2a7523351a9d5a4b55f885e574/lib/Doctrine/Common/Annotations/DocParser.php#L1051-L1079 * @return array */ - private function resolveAnnotationValues(BetterTokenIterator $tokenIterator): array + private function resolveAnnotationValues(\Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $tokenIterator) : array { $values = []; $resolvedValue = $this->resolveAnnotationValue($tokenIterator); - - if (is_array($resolvedValue)) { - $values = array_merge($values, $resolvedValue); + if (\is_array($resolvedValue)) { + $values = \array_merge($values, $resolvedValue); } else { $values[] = $resolvedValue; } - - while ($tokenIterator->isCurrentTokenType(Lexer::TOKEN_COMMA)) { + while ($tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_COMMA)) { $tokenIterator->next(); - $nestedValues = $this->resolveAnnotationValue($tokenIterator); - - if (is_array($nestedValues)) { - $values = array_merge($values, $nestedValues); + if (\is_array($nestedValues)) { + $values = \array_merge($values, $nestedValues); } else { $values[] = $nestedValues; } } - return $values; } - /** * @return bool|int|mixed|mixed[]|string */ - private function parseValue(BetterTokenIterator $tokenIterator) + private function parseValue(\Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $tokenIterator) { - if ($tokenIterator->isCurrentTokenType(Lexer::TOKEN_OPEN_CURLY_BRACKET)) { + if ($tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_OPEN_CURLY_BRACKET)) { $items = $this->arrayParser->parseCurlyArray($tokenIterator); - return new CurlyListNode($items); + return new \Rector\BetterPhpDocParser\ValueObject\PhpDoc\DoctrineAnnotation\CurlyListNode($items); } - return $this->plainValueParser->parseValue($tokenIterator); } } diff --git a/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser/ArrayParser.php b/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser/ArrayParser.php index a1e8f4d38cc..a64e8728150 100644 --- a/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser/ArrayParser.php +++ b/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser/ArrayParser.php @@ -1,12 +1,10 @@ plainValueParser = $plainValueParser; } - /** * Mimics https://github.com/doctrine/annotations/blob/c66f06b7c83e9a2a7523351a9d5a4b55f885e574/lib/Doctrine/Common/Annotations/DocParser.php#L1305-L1352 * @return mixed[] */ - public function parseCurlyArray(BetterTokenIterator $tokenIterator): array + public function parseCurlyArray(\Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $tokenIterator) : array { $values = []; - // nothing - if ($tokenIterator->isCurrentTokenType(Lexer::TOKEN_CLOSE_CURLY_BRACKET)) { + if ($tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_CURLY_BRACKET)) { return []; } - - $tokenIterator->consumeTokenType(Lexer::TOKEN_OPEN_CURLY_BRACKET); - + $tokenIterator->consumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_OPEN_CURLY_BRACKET); // If the array is empty, stop parsing and return. - if ($tokenIterator->isCurrentTokenType(Lexer::TOKEN_CLOSE_CURLY_BRACKET)) { - $tokenIterator->consumeTokenType(Lexer::TOKEN_CLOSE_CURLY_BRACKET); + if ($tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_CURLY_BRACKET)) { + $tokenIterator->consumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_CURLY_BRACKET); return []; } - // first item $values[] = $this->resolveArrayItem($tokenIterator); - // 2nd+ item - while ($tokenIterator->isCurrentTokenType(Lexer::TOKEN_COMMA)) { + while ($tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_COMMA)) { // optional trailing comma - if ($tokenIterator->isNextTokenType(Lexer::TOKEN_CLOSE_CURLY_BRACKET)) { + if ($tokenIterator->isNextTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_CURLY_BRACKET)) { break; } - - $tokenIterator->consumeTokenType(Lexer::TOKEN_COMMA); + $tokenIterator->consumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_COMMA); $values[] = $this->resolveArrayItem($tokenIterator); - // skip newlines - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_PHPDOC_EOL); + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_PHPDOC_EOL); } - - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_PHPDOC_EOL); - + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_PHPDOC_EOL); // special case for nested doctrine annotations - if (! $tokenIterator->isCurrentTokenType(Lexer::TOKEN_CLOSE_PARENTHESES)) { - $tokenIterator->consumeTokenType(Lexer::TOKEN_CLOSE_CURLY_BRACKET); + if (!$tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_PARENTHESES)) { + $tokenIterator->consumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_CURLY_BRACKET); } - return $this->createArrayFromValues($values); } - /** * Mimics https://github.com/doctrine/annotations/blob/c66f06b7c83e9a2a7523351a9d5a4b55f885e574/lib/Doctrine/Common/Annotations/DocParser.php#L1354-L1385 * @return array */ - private function resolveArrayItem(BetterTokenIterator $tokenIterator): array + private function resolveArrayItem(\Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $tokenIterator) : array { // skip newlines - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_PHPDOC_EOL); - - if ($tokenIterator->isNextTokenTypes([Lexer::TOKEN_EQUAL, Lexer::TOKEN_COLON])) { - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_EQUAL); - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_COLON); - - if ($tokenIterator->isNextTokenType(Lexer::TOKEN_IDENTIFIER)) { + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_PHPDOC_EOL); + if ($tokenIterator->isNextTokenTypes([\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_EQUAL, \PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_COLON])) { + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_EQUAL); + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_COLON); + if ($tokenIterator->isNextTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_IDENTIFIER)) { $key = $this->plainValueParser->parseValue($tokenIterator); } else { - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_COMMA); + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_COMMA); $key = $this->plainValueParser->parseValue($tokenIterator); } - - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_EQUAL); - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_COLON); - + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_EQUAL); + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_COLON); return [$key, $this->plainValueParser->parseValue($tokenIterator)]; } - return [null, $this->plainValueParser->parseValue($tokenIterator)]; } - /** * @param mixed[] $values * @return mixed[] */ - private function createArrayFromValues(array $values): array + private function createArrayFromValues(array $values) : array { $array = []; - foreach ($values as $value) { [$key, $val] = $value; - if ($key !== null) { $array[$key] = $val; } else { $array[] = $val; } } - return $array; } } diff --git a/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser/PlainValueParser.php b/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser/PlainValueParser.php index d7a702d6592..360c90c6519 100644 --- a/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser/PlainValueParser.php +++ b/packages/BetterPhpDocParser/PhpDocParser/StaticDoctrineAnnotationParser/PlainValueParser.php @@ -1,7 +1,6 @@ classAnnotationMatcher = $classAnnotationMatcher; $this->currentNodeProvider = $currentNodeProvider; } - /** * @required */ - public function autowirePlainValueParser( - StaticDoctrineAnnotationParser $staticDoctrineAnnotationParser, - ArrayParser $arrayParser - ): void { + public function autowirePlainValueParser(\Rector\BetterPhpDocParser\PhpDocParser\StaticDoctrineAnnotationParser $staticDoctrineAnnotationParser, \Rector\BetterPhpDocParser\PhpDocParser\StaticDoctrineAnnotationParser\ArrayParser $arrayParser) : void + { $this->staticDoctrineAnnotationParser = $staticDoctrineAnnotationParser; $this->arrayParser = $arrayParser; } - /** * @return bool|int|mixed|string */ - public function parseValue(BetterTokenIterator $tokenIterator) + public function parseValue(\Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $tokenIterator) { $currentTokenValue = $tokenIterator->currentTokenValue(); - // temporary hackaround multi-line doctrine annotations - if ($tokenIterator->isCurrentTokenType(Lexer::TOKEN_END)) { + if ($tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_END)) { return $currentTokenValue; } - // consume the token - $isOpenCurlyArray = $tokenIterator->isCurrentTokenType(Lexer::TOKEN_OPEN_CURLY_BRACKET); + $isOpenCurlyArray = $tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_OPEN_CURLY_BRACKET); if ($isOpenCurlyArray) { return $this->arrayParser->parseCurlyArray($tokenIterator); } - $tokenIterator->next(); - // normalize value if ($currentTokenValue === 'false') { - return new ConstExprFalseNode(); + return new \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode(); } - if ($currentTokenValue === 'true') { - return new ConstExprTrueNode(); + return new \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode(); } - - if (is_numeric($currentTokenValue) && (string) (int) $currentTokenValue === $currentTokenValue) { - return new ConstExprIntegerNode($currentTokenValue); + if (\is_numeric($currentTokenValue) && (string) (int) $currentTokenValue === $currentTokenValue) { + return new \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode($currentTokenValue); } - - while ($tokenIterator->isCurrentTokenType(Lexer::TOKEN_DOUBLE_COLON) || - $tokenIterator->isCurrentTokenType(Lexer::TOKEN_IDENTIFIER) - ) { + while ($tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_DOUBLE_COLON) || $tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_IDENTIFIER)) { $currentTokenValue .= $tokenIterator->currentTokenValue(); $tokenIterator->next(); } - // nested entity! - if ($tokenIterator->isCurrentTokenType(Lexer::TOKEN_OPEN_PARENTHESES)) { + if ($tokenIterator->isCurrentTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_OPEN_PARENTHESES)) { return $this->parseNestedDoctrineAnnotationTagValueNode($currentTokenValue, $tokenIterator); } - return $currentTokenValue; } - - private function parseNestedDoctrineAnnotationTagValueNode( - string $currentTokenValue, - BetterTokenIterator $tokenIterator - ): DoctrineAnnotationTagValueNode { + private function parseNestedDoctrineAnnotationTagValueNode(string $currentTokenValue, \Rector\BetterPhpDocParser\ValueObject\Parser\BetterTokenIterator $tokenIterator) : \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode + { // @todo $annotationShortName = $currentTokenValue; $values = $this->staticDoctrineAnnotationParser->resolveAnnotationMethodCall($tokenIterator); - $currentNode = $this->currentNodeProvider->getNode(); - if (! $currentNode instanceof Node) { - throw new ShouldNotHappenException(); + if (!$currentNode instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $fullyQualifiedAnnotationClass = $this->classAnnotationMatcher->resolveTagFullyQualifiedName( - $annotationShortName, - $currentNode - ); - + $fullyQualifiedAnnotationClass = $this->classAnnotationMatcher->resolveTagFullyQualifiedName($annotationShortName, $currentNode); // keep the last ")" - $tokenIterator->tryConsumeTokenType(Lexer::TOKEN_PHPDOC_EOL); - $tokenIterator->consumeTokenType(Lexer::TOKEN_CLOSE_PARENTHESES); - - return new DoctrineAnnotationTagValueNode($fullyQualifiedAnnotationClass, $annotationShortName, $values); + $tokenIterator->tryConsumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_PHPDOC_EOL); + $tokenIterator->consumeTokenType(\PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_CLOSE_PARENTHESES); + return new \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode($fullyQualifiedAnnotationClass, $annotationShortName, $values); } } diff --git a/packages/BetterPhpDocParser/PhpDocParser/TypeNodeAnalyzer.php b/packages/BetterPhpDocParser/PhpDocParser/TypeNodeAnalyzer.php index 513b305ad3e..da7751d55f5 100644 --- a/packages/BetterPhpDocParser/PhpDocParser/TypeNodeAnalyzer.php +++ b/packages/BetterPhpDocParser/PhpDocParser/TypeNodeAnalyzer.php @@ -1,30 +1,26 @@ types as $subType) { - if ($subType instanceof NullableTypeNode) { - return false; + if ($subType instanceof \PHPStan\PhpDocParser\Ast\Type\NullableTypeNode) { + return \false; } } - - return true; + return \true; } } diff --git a/packages/BetterPhpDocParser/Printer/DocBlockInliner.php b/packages/BetterPhpDocParser/Printer/DocBlockInliner.php index bc5e82ecc18..e8bb0b2ed67 100644 --- a/packages/BetterPhpDocParser/Printer/DocBlockInliner.php +++ b/packages/BetterPhpDocParser/Printer/DocBlockInliner.php @@ -1,28 +1,24 @@ children === []) { - return true; + return \true; } - foreach ($phpDocNode->children as $phpDocChildNode) { - if ($phpDocChildNode instanceof PhpDocTextNode) { + if ($phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode) { if ($phpDocChildNode->text !== '') { - return false; + return \false; } } else { - return false; + return \false; } } - - return true; + return \true; } } diff --git a/packages/BetterPhpDocParser/Printer/PhpDocInfoPrinter.php b/packages/BetterPhpDocParser/Printer/PhpDocInfoPrinter.php index e6383960fe2..0820a786d30 100644 --- a/packages/BetterPhpDocParser/Printer/PhpDocInfoPrinter.php +++ b/packages/BetterPhpDocParser/Printer/PhpDocInfoPrinter.php @@ -1,10 +1,9 @@ emptyPhpDocDetector = $emptyPhpDocDetector; $this->docBlockInliner = $docBlockInliner; $this->removeNodesStartAndEndResolver = $removeNodesStartAndEndResolver; $this->changedPhpDocNodeVisitor = $changedPhpDocNodeVisitor; - $this->changedPhpDocNodeTraverser = $changedPhpDocNodeTraverserFactory->create(); } - - public function printNew(PhpDocInfo $phpDocInfo): string + public function printNew(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : string { $docContent = (string) $phpDocInfo->getPhpDocNode(); - // fix missing newline in the end of docblock - keep BC compatible for both cases until phpstan with phpdoc-parser 0.5.2 is released - $docContent = Strings::replace($docContent, self::MISSING_NEWLINE_REGEX, "$1\n */"); - + $docContent = \RectorPrefix20210509\Nette\Utils\Strings::replace($docContent, self::MISSING_NEWLINE_REGEX, "\$1\n */"); if ($phpDocInfo->isSingleLine()) { return $this->docBlockInliner->inline($docContent); } - return $docContent; } - /** * As in php-parser * @@ -157,221 +127,153 @@ final class PhpDocInfoPrinter * - Print(subnode2) * - Tokens[subnode2.endPos .. node.endPos] */ - public function printFormatPreserving(PhpDocInfo $phpDocInfo): string + public function printFormatPreserving(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : string { if ($phpDocInfo->getTokens() === []) { // completely new one, just print string version of it if ($phpDocInfo->getPhpDocNode()->children === []) { return ''; } - return (string) $phpDocInfo->getPhpDocNode(); } - $this->phpDocNode = $phpDocInfo->getPhpDocNode(); $this->tokens = $phpDocInfo->getTokens(); - $this->tokenCount = $phpDocInfo->getTokenCount(); $this->phpDocInfo = $phpDocInfo; - $this->currentTokenPosition = 0; - $phpDocString = $this->printPhpDocNode($this->phpDocNode); - // hotfix of extra space with callable () - return Strings::replace($phpDocString, self::CALLABLE_REGEX, 'callable('); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($phpDocString, self::CALLABLE_REGEX, 'callable('); } - - private function printPhpDocNode(PhpDocNode $phpDocNode): string + private function printPhpDocNode(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode $phpDocNode) : string { // no nodes were, so empty doc if ($this->emptyPhpDocDetector->isPhpDocNodeEmpty($phpDocNode)) { return ''; } - $output = ''; - // node output - $nodeCount = count($phpDocNode->children); - + $nodeCount = \count($phpDocNode->children); foreach ($phpDocNode->children as $key => $phpDocChildNode) { $output .= $this->printDocChildNode($phpDocChildNode, $key + 1, $nodeCount); } - $output = $this->printEnd($output); - // fix missing start - if (! Strings::match($output, self::DOCBLOCK_START_REGEX) && $output) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($output, self::DOCBLOCK_START_REGEX) && $output) { $output = '/**' . $output; } - // fix missing end - if (Strings::match($output, self::OPENING_DOCBLOCK_REGEX) && $output && ! Strings::match( - $output, - self::CLOSING_DOCBLOCK_REGEX - )) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($output, self::OPENING_DOCBLOCK_REGEX) && $output && !\RectorPrefix20210509\Nette\Utils\Strings::match($output, self::CLOSING_DOCBLOCK_REGEX)) { $output .= ' */'; } - return $output; } - - private function printDocChildNode( - PhpDocChildNode $phpDocChildNode, - int $key = 0, - int $nodeCount = 0 - ): string { + private function printDocChildNode(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode $phpDocChildNode, int $key = 0, int $nodeCount = 0) : string + { $output = ''; - $shouldReprintChildNode = $this->shouldReprint($phpDocChildNode); - - if ($phpDocChildNode instanceof PhpDocTagNode) { - if ($shouldReprintChildNode && ($phpDocChildNode->value instanceof ParamTagValueNode || $phpDocChildNode->value instanceof ThrowsTagValueNode || $phpDocChildNode->value instanceof VarTagValueNode || $phpDocChildNode->value instanceof ReturnTagValueNode || $phpDocChildNode->value instanceof PropertyTagValueNode)) { + if ($phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { + if ($shouldReprintChildNode && ($phpDocChildNode->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode || $phpDocChildNode->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ThrowsTagValueNode || $phpDocChildNode->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode || $phpDocChildNode->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode || $phpDocChildNode->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PropertyTagValueNode)) { // the type has changed → reprint - $phpDocChildNodeStartEnd = $phpDocChildNode->getAttribute(PhpDocAttributeKey::START_AND_END); + $phpDocChildNodeStartEnd = $phpDocChildNode->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END); // bump the last position of token after just printed node - if ($phpDocChildNodeStartEnd instanceof StartAndEnd) { + if ($phpDocChildNodeStartEnd instanceof \Rector\BetterPhpDocParser\ValueObject\StartAndEnd) { $this->currentTokenPosition = $phpDocChildNodeStartEnd->getEnd(); } - return $this->standardPrintPhpDocChildNode($phpDocChildNode); } - - if ($phpDocChildNode->value instanceof DoctrineAnnotationTagValueNode && $shouldReprintChildNode) { + if ($phpDocChildNode->value instanceof \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode && $shouldReprintChildNode) { $printedNode = (string) $phpDocChildNode; - // remove extra space between tags - $printedNode = Strings::replace($printedNode, self::TAG_AND_SPACE_REGEX, '$1('); + $printedNode = \RectorPrefix20210509\Nette\Utils\Strings::replace($printedNode, self::TAG_AND_SPACE_REGEX, '$1('); return self::NEWLINE_WITH_ASTERISK . $printedNode; } } - /** @var StartAndEnd|null $startAndEnd */ - $startAndEnd = $phpDocChildNode->getAttribute(PhpDocAttributeKey::START_AND_END); - - if ($startAndEnd instanceof StartAndEnd && ! $shouldReprintChildNode) { + $startAndEnd = $phpDocChildNode->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END); + if ($startAndEnd instanceof \Rector\BetterPhpDocParser\ValueObject\StartAndEnd && !$shouldReprintChildNode) { $isLastToken = $nodeCount === $key; - // correct previously changed node $this->correctPreviouslyReprintedFirstNode($key, $startAndEnd); - - $output = $this->addTokensFromTo( - $output, - $this->currentTokenPosition, - $startAndEnd->getEnd(), - $isLastToken - ); - + $output = $this->addTokensFromTo($output, $this->currentTokenPosition, $startAndEnd->getEnd(), $isLastToken); $this->currentTokenPosition = $startAndEnd->getEnd(); - - return rtrim($output); + return \rtrim($output); } - - if ($startAndEnd instanceof StartAndEnd) { + if ($startAndEnd instanceof \Rector\BetterPhpDocParser\ValueObject\StartAndEnd) { $this->currentTokenPosition = $startAndEnd->getEnd(); } - $standardPrintedPhpDocChildNode = $this->standardPrintPhpDocChildNode($phpDocChildNode); return $output . $standardPrintedPhpDocChildNode; } - - private function printEnd(string $output): string + private function printEnd(string $output) : string { - $lastTokenPosition = $this->phpDocNode->getAttribute( - PhpDocAttributeKey::LAST_PHP_DOC_TOKEN_POSITION - ) ?: $this->currentTokenPosition; + $lastTokenPosition = $this->phpDocNode->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::LAST_PHP_DOC_TOKEN_POSITION) ?: $this->currentTokenPosition; if ($lastTokenPosition === 0) { $lastTokenPosition = 1; } - - return $this->addTokensFromTo($output, $lastTokenPosition, $this->tokenCount, true); + return $this->addTokensFromTo($output, $lastTokenPosition, $this->tokenCount, \true); } - - private function addTokensFromTo(string $output, int $from, int $to, bool $shouldSkipEmptyLinesAbove): string + private function addTokensFromTo(string $output, int $from, int $to, bool $shouldSkipEmptyLinesAbove) : string { // skip removed nodes $positionJumpSet = []; - - $removedStartAndEnds = $this->removeNodesStartAndEndResolver->resolve( - $this->phpDocInfo->getOriginalPhpDocNode(), - $this->phpDocNode, - $this->tokens - ); - + $removedStartAndEnds = $this->removeNodesStartAndEndResolver->resolve($this->phpDocInfo->getOriginalPhpDocNode(), $this->phpDocNode, $this->tokens); foreach ($removedStartAndEnds as $removedStartAndEnd) { $positionJumpSet[$removedStartAndEnd->getStart()] = $removedStartAndEnd->getEnd(); } - // include also space before, in case of inlined docs - if (isset($this->tokens[$from - 1]) && $this->tokens[$from - 1][1] === Lexer::TOKEN_HORIZONTAL_WS) { + if (isset($this->tokens[$from - 1]) && $this->tokens[$from - 1][1] === \PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_HORIZONTAL_WS) { --$from; } - // skip extra empty lines above if this is the last one - if ($shouldSkipEmptyLinesAbove && - Strings::contains($this->tokens[$from][0], PHP_EOL) && - Strings::contains($this->tokens[$from + 1][0], PHP_EOL) - ) { + if ($shouldSkipEmptyLinesAbove && \RectorPrefix20210509\Nette\Utils\Strings::contains($this->tokens[$from][0], \PHP_EOL) && \RectorPrefix20210509\Nette\Utils\Strings::contains($this->tokens[$from + 1][0], \PHP_EOL)) { ++$from; } - return $this->appendToOutput($output, $from, $to, $positionJumpSet); } - /** * @param array $positionJumpSet */ - private function appendToOutput(string $output, int $from, int $to, array $positionJumpSet): string + private function appendToOutput(string $output, int $from, int $to, array $positionJumpSet) : string { for ($i = $from; $i < $to; ++$i) { while (isset($positionJumpSet[$i])) { $i = $positionJumpSet[$i]; continue; } - $output .= $this->tokens[$i][0] ?? ''; } - return $output; } - - private function correctPreviouslyReprintedFirstNode(int $key, StartAndEnd $startAndEnd): void + private function correctPreviouslyReprintedFirstNode(int $key, \Rector\BetterPhpDocParser\ValueObject\StartAndEnd $startAndEnd) : void { if ($this->currentTokenPosition !== 0) { return; } - if ($key === 1) { return; } - $startTokenPosition = $startAndEnd->getStart(); - $tokens = $this->phpDocInfo->getTokens(); - if (! isset($tokens[$startTokenPosition - 1])) { + if (!isset($tokens[$startTokenPosition - 1])) { return; } - $previousToken = $tokens[$startTokenPosition - 1]; - if ($previousToken[1] === Lexer::TOKEN_PHPDOC_EOL) { + if ($previousToken[1] === \PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_PHPDOC_EOL) { --$startTokenPosition; } - $this->currentTokenPosition = $startTokenPosition; } - - private function shouldReprint(PhpDocChildNode $phpDocChildNode): bool + private function shouldReprint(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode $phpDocChildNode) : bool { $this->changedPhpDocNodeTraverser->traverse($phpDocChildNode); return $this->changedPhpDocNodeVisitor->hasChanged(); } - - private function standardPrintPhpDocChildNode(PhpDocChildNode $phpDocChildNode): string + private function standardPrintPhpDocChildNode(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode $phpDocChildNode) : string { if ($this->phpDocInfo->isSingleLine()) { return ' ' . $phpDocChildNode; } - return self::NEWLINE_WITH_ASTERISK . $phpDocChildNode; } } diff --git a/packages/BetterPhpDocParser/Printer/RemoveNodesStartAndEndResolver.php b/packages/BetterPhpDocParser/Printer/RemoveNodesStartAndEndResolver.php index 08061a46a77..e5bf05d379d 100644 --- a/packages/BetterPhpDocParser/Printer/RemoveNodesStartAndEndResolver.php +++ b/packages/BetterPhpDocParser/Printer/RemoveNodesStartAndEndResolver.php @@ -1,7 +1,6 @@ children, $currentPhpDocNode->children); - + $removedChildNodes = \array_diff($originalPhpDocNode->children, $currentPhpDocNode->children); $lastEndPosition = null; - foreach ($removedChildNodes as $removedChildNode) { /** @var StartAndEnd $removedPhpDocNodeInfo */ - $removedPhpDocNodeInfo = $removedChildNode->getAttribute(PhpDocAttributeKey::START_AND_END); - + $removedPhpDocNodeInfo = $removedChildNode->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::START_AND_END); // change start position to start of the line, so the whole line is removed $seekPosition = $removedPhpDocNodeInfo->getStart(); - - while ($seekPosition >= 0 && $tokens[$seekPosition][1] !== Lexer::TOKEN_HORIZONTAL_WS) { - if ($tokens[$seekPosition][1] === Lexer::TOKEN_PHPDOC_EOL) { + while ($seekPosition >= 0 && $tokens[$seekPosition][1] !== \PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_HORIZONTAL_WS) { + if ($tokens[$seekPosition][1] === \PHPStan\PhpDocParser\Lexer\Lexer::TOKEN_PHPDOC_EOL) { break; } - // do not colide if ($lastEndPosition < $seekPosition) { break; } - --$seekPosition; } - $lastEndPosition = $removedPhpDocNodeInfo->getEnd(); - - $removedNodePositions[] = new StartAndEnd(max(0, $seekPosition - 1), $removedPhpDocNodeInfo->getEnd()); + $removedNodePositions[] = new \Rector\BetterPhpDocParser\ValueObject\StartAndEnd(\max(0, $seekPosition - 1), $removedPhpDocNodeInfo->getEnd()); } - return $removedNodePositions; } } diff --git a/packages/BetterPhpDocParser/ValueObject/AroundSpaces.php b/packages/BetterPhpDocParser/ValueObject/AroundSpaces.php index 663c1d96202..793c241df5d 100644 --- a/packages/BetterPhpDocParser/ValueObject/AroundSpaces.php +++ b/packages/BetterPhpDocParser/ValueObject/AroundSpaces.php @@ -1,7 +1,6 @@ closingSpace = $closingSpace; $this->openingSpace = $openingSpace; } - - public function getClosingSpace(): string + public function getClosingSpace() : string { return $this->closingSpace; } - - public function getOpeningSpace(): string + public function getOpeningSpace() : string { return $this->openingSpace; } diff --git a/packages/BetterPhpDocParser/ValueObject/DoctrineAnnotation/SilentKeyMap.php b/packages/BetterPhpDocParser/ValueObject/DoctrineAnnotation/SilentKeyMap.php index 7709e836626..a724bdf6c09 100644 --- a/packages/BetterPhpDocParser/ValueObject/DoctrineAnnotation/SilentKeyMap.php +++ b/packages/BetterPhpDocParser/ValueObject/DoctrineAnnotation/SilentKeyMap.php @@ -1,7 +1,6 @@ */ - public const CLASS_NAMES_TO_SILENT_KEYS = [ - 'Symfony\Component\Routing\Annotation\Route' => 'path', - ]; + public const CLASS_NAMES_TO_SILENT_KEYS = ['Symfony\\Component\\Routing\\Annotation\\Route' => 'path']; } diff --git a/packages/BetterPhpDocParser/ValueObject/NodeTypes.php b/packages/BetterPhpDocParser/ValueObject/NodeTypes.php index 4951c81da06..0993ba322f2 100644 --- a/packages/BetterPhpDocParser/ValueObject/NodeTypes.php +++ b/packages/BetterPhpDocParser/ValueObject/NodeTypes.php @@ -1,7 +1,6 @@ > */ - public const TYPE_AWARE_NODES = [ - VarTagValueNode::class, - ParamTagValueNode::class, - ReturnTagValueNode::class, - ThrowsTagValueNode::class, - PropertyTagValueNode::class, - ]; - + public const TYPE_AWARE_NODES = [\PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode::class, \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode::class, \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode::class, \PHPStan\PhpDocParser\Ast\PhpDoc\ThrowsTagValueNode::class, \PHPStan\PhpDocParser\Ast\PhpDoc\PropertyTagValueNode::class]; /** * @var string[] */ - public const TYPE_AWARE_DOCTRINE_ANNOTATION_CLASSES = [ - 'JMS\Serializer\Annotation\Type', - 'Doctrine\ORM\Mapping\OneToMany', - 'Symfony\Component\Validator\Constraints\Choice', - 'Symfony\Component\Validator\Constraints\Email', - 'Symfony\Component\Validator\Constraints\Range', - ]; + public const TYPE_AWARE_DOCTRINE_ANNOTATION_CLASSES = ['JMS\\Serializer\\Annotation\\Type', 'Doctrine\\ORM\\Mapping\\OneToMany', 'Symfony\\Component\\Validator\\Constraints\\Choice', 'Symfony\\Component\\Validator\\Constraints\\Email', 'Symfony\\Component\\Validator\\Constraints\\Range']; } diff --git a/packages/BetterPhpDocParser/ValueObject/Parser/BetterTokenIterator.php b/packages/BetterPhpDocParser/ValueObject/Parser/BetterTokenIterator.php index 712dc5b2494..8e1987fb6c8 100644 --- a/packages/BetterPhpDocParser/ValueObject/Parser/BetterTokenIterator.php +++ b/packages/BetterPhpDocParser/ValueObject/Parser/BetterTokenIterator.php @@ -1,37 +1,31 @@ $tokens */ public function __construct(array $tokens, int $index = 0) { - $this->privatesAccessor = new PrivatesAccessor(); - + $this->privatesAccessor = new \RectorPrefix20210509\Symplify\PackageBuilder\Reflection\PrivatesAccessor(); if ($tokens === []) { $this->privatesAccessor->setPrivateProperty($this, self::TOKENS, []); $this->privatesAccessor->setPrivateProperty($this, self::INDEX, 0); @@ -39,150 +33,120 @@ final class BetterTokenIterator extends TokenIterator parent::__construct($tokens, $index); } } - /** * @param int[] $types */ - public function isNextTokenTypes(array $types): bool + public function isNextTokenTypes(array $types) : bool { foreach ($types as $type) { if ($this->isNextTokenType($type)) { - return true; + return \true; } } - - return false; + return \false; } - /** * @param int[] $tokenTypes */ - public function isCurrentTokenTypes(array $tokenTypes): bool + public function isCurrentTokenTypes(array $tokenTypes) : bool { foreach ($tokenTypes as $tokenType) { if ($this->isCurrentTokenType($tokenType)) { - return true; + return \true; } } - - return false; + return \false; } - - public function isTokenTypeOnPosition(int $tokenType, int $position): bool + public function isTokenTypeOnPosition(int $tokenType, int $position) : bool { $tokens = $this->getTokens(); $token = $tokens[$position] ?? null; - if ($token === null) { - return false; + return \false; } - return $token[1] === $tokenType; } - - public function isNextTokenType(int $tokenType): bool + public function isNextTokenType(int $tokenType) : bool { if ($this->nextTokenType() === null) { - return false; + return \false; } - return $this->nextTokenType() === $tokenType; } - - public function printFromTo(int $from, int $to): string + public function printFromTo(int $from, int $to) : string { if ($to < $from) { - throw new ShouldNotHappenException('Arguments are flipped'); + throw new \Rector\Core\Exception\ShouldNotHappenException('Arguments are flipped'); } - $tokens = $this->getTokens(); - $content = ''; - foreach ($tokens as $key => $token) { if ($key < $from) { continue; } - if ($key >= $to) { continue; } - $content .= $token[0]; } - return $content; } - - public function print(): string + public function print() : string { $content = ''; foreach ($this->getTokens() as $token) { $content .= $token[0]; } - return $content; } - - public function nextTokenType(): ?int + public function nextTokenType() : ?int { $tokens = $this->getTokens(); - // does next token exist? $nextIndex = $this->currentPosition() + 1; - if (! isset($tokens[$nextIndex])) { + if (!isset($tokens[$nextIndex])) { return null; } - $this->pushSavePoint(); $this->next(); $nextTokenType = $this->currentTokenType(); $this->rollback(); - return $nextTokenType; } - - public function currentPosition(): int + public function currentPosition() : int { return $this->privatesAccessor->getPrivateProperty($this, self::INDEX); } - /** * @return mixed[] */ - public function getTokens(): array + public function getTokens() : array { return $this->privatesAccessor->getPrivateProperty($this, self::TOKENS); } - - public function count(): int + public function count() : int { - return count($this->getTokens()); + return \count($this->getTokens()); } - /** * @return mixed[] */ - public function partialTokens(int $start, int $end): array + public function partialTokens(int $start, int $end) : array { $tokens = $this->getTokens(); - $chunkTokens = []; for ($i = $start; $i <= $end; ++$i) { $chunkTokens[$i] = $tokens[$i]; } - return $chunkTokens; } - - public function containsTokenType(int $type): bool + public function containsTokenType(int $type) : bool { foreach ($this->getTokens() as $token) { if ($token[1] === $type) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/BetterPhpDocParser/ValueObject/PhpDoc/DoctrineAnnotation/AbstractValuesAwareNode.php b/packages/BetterPhpDocParser/ValueObject/PhpDoc/DoctrineAnnotation/AbstractValuesAwareNode.php index 426bd088b09..5f540b09023 100644 --- a/packages/BetterPhpDocParser/ValueObject/PhpDoc/DoctrineAnnotation/AbstractValuesAwareNode.php +++ b/packages/BetterPhpDocParser/ValueObject/PhpDoc/DoctrineAnnotation/AbstractValuesAwareNode.php @@ -1,45 +1,37 @@ .*?)"#'; - /** * @var mixed[] */ protected $values = []; - /** * @var bool */ - protected $hasChanged = false; - + protected $hasChanged = \false; /** * @var string|null */ protected $silentKey; - /** * @var string|null */ protected $originalContent; - /** * @param mixed[] $values */ @@ -49,31 +41,25 @@ abstract class AbstractValuesAwareNode implements PhpDocTagValueNode $this->originalContent = $originalContent; $this->silentKey = $silentKey; } - - public function removeValue(string $key): void + public function removeValue(string $key) : void { $quotedKey = '"' . $key . '"'; - // isset? - if (! isset($this->values[$key]) && ! isset($this->values[$quotedKey])) { + if (!isset($this->values[$key]) && !isset($this->values[$quotedKey])) { return; } - unset($this->values[$key]); unset($this->values[$quotedKey]); - // invoke reprint - $this->setAttribute(PhpDocAttributeKey::ORIG_NODE, null); + $this->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::ORIG_NODE, null); } - /** * @return mixed[] */ - public function getValues(): array + public function getValues() : array { return $this->values; } - /** * @param string|int $key * @return mixed|Node|null @@ -81,32 +67,27 @@ abstract class AbstractValuesAwareNode implements PhpDocTagValueNode public function getValue($key) { // to allow false as default - if (! array_key_exists($key, $this->values)) { + if (!\array_key_exists($key, $this->values)) { return null; } - return $this->values[$key]; } - /** * @param mixed $value */ - public function changeValue(string $key, $value): void + public function changeValue(string $key, $value) : void { // is quoted? if (isset($this->values[$key])) { - $isQuoted = (bool) Strings::match($this->values[$key], self::UNQUOTED_VALUE_REGEX); + $isQuoted = (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($this->values[$key], self::UNQUOTED_VALUE_REGEX); if ($isQuoted) { $value = '"' . $value . '"'; } } - $this->values[$key] = $value; - // invoke reprint - $this->setAttribute(PhpDocAttributeKey::ORIG_NODE, null); + $this->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::ORIG_NODE, null); } - /** * @param string|int $key * @return mixed|null @@ -117,28 +98,23 @@ abstract class AbstractValuesAwareNode implements PhpDocTagValueNode if ($value === null) { return null; } - return $this->removeQuotes($value); } - /** * @param mixed $value */ - public function changeSilentValue($value): void + public function changeSilentValue($value) : void { // is quoted? - $isQuoted = (bool) Strings::match($this->values[0], self::UNQUOTED_VALUE_REGEX); + $isQuoted = (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($this->values[0], self::UNQUOTED_VALUE_REGEX); if ($isQuoted) { $value = '"' . $value . '"'; } - $this->values[0] = $value; - $this->hasChanged = true; - + $this->hasChanged = \true; // invoke reprint - $this->setAttribute(PhpDocAttributeKey::ORIG_NODE, null); + $this->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::ORIG_NODE, null); } - /** * @return mixed|null */ @@ -148,98 +124,81 @@ abstract class AbstractValuesAwareNode implements PhpDocTagValueNode if ($value === null) { return null; } - return $this->removeQuotes($value); } - /** * Useful for attributes * @return array */ - public function getValuesWithExplicitSilentAndWithoutQuotes(): array + public function getValuesWithExplicitSilentAndWithoutQuotes() : array { $explicitKeysValues = []; - - foreach (array_keys($this->values) as $key) { + foreach (\array_keys($this->values) as $key) { $valueWithoutQuotes = $this->getValueWithoutQuotes($key); - - if (is_int($key) && $this->silentKey !== null) { + if (\is_int($key) && $this->silentKey !== null) { $explicitKeysValues[$this->silentKey] = $valueWithoutQuotes; } else { $explicitKeysValues[$key] = $valueWithoutQuotes; } } - return $explicitKeysValues; } - /** * @param mixed|string $value * @return mixed|string */ protected function removeQuotes($value) { - if (! is_string($value)) { + if (!\is_string($value)) { return $value; } - - $matches = Strings::match($value, self::UNQUOTED_VALUE_REGEX); + $matches = \RectorPrefix20210509\Nette\Utils\Strings::match($value, self::UNQUOTED_VALUE_REGEX); if ($matches === null) { return $value; } - return $matches['content']; } - /** * @param mixed[] $values */ - protected function printValuesContent(array $values): string + protected function printValuesContent(array $values) : string { $itemContents = ''; - $lastItemKey = array_key_last($values); - + \end($values); + $lastItemKey = \key($values); foreach ($values as $key => $value) { - if (is_int($key)) { + if (\is_int($key)) { $itemContents .= $this->stringifyValue($value); } else { $itemContents .= $key . '=' . $this->stringifyValue($value); } - if ($lastItemKey !== $key) { $itemContents .= ', '; } } - return $itemContents; } - /** * @param mixed $value */ - private function stringifyValue($value): string + private function stringifyValue($value) : string { // @todo resolve original casing - if ($value === false) { + if ($value === \false) { return 'false'; } - - if ($value === true) { + if ($value === \true) { return 'true'; } - - if (is_int($value)) { + if (\is_int($value)) { return (string) $value; } - - if (is_float($value)) { + if (\is_float($value)) { return (string) $value; } - - if (is_array($value)) { + if (\is_array($value)) { return $this->printValuesContent($value); } - return (string) $value; } } diff --git a/packages/BetterPhpDocParser/ValueObject/PhpDoc/DoctrineAnnotation/CurlyListNode.php b/packages/BetterPhpDocParser/ValueObject/PhpDoc/DoctrineAnnotation/CurlyListNode.php index 2c14aa127de..f5f1df174bf 100644 --- a/packages/BetterPhpDocParser/ValueObject/PhpDoc/DoctrineAnnotation/CurlyListNode.php +++ b/packages/BetterPhpDocParser/ValueObject/PhpDoc/DoctrineAnnotation/CurlyListNode.php @@ -1,48 +1,41 @@ values); - + \end($this->values); + $lastItemKey = \key($this->values); foreach ($this->values as $key => $value) { - if (is_int($key)) { + if (\is_int($key)) { $itemContents .= $this->stringifyValue($value); } else { $itemContents .= $key . '=' . $this->stringifyValue($value); } - if ($lastItemKey !== $key) { $itemContents .= ', '; } } - return '{' . $itemContents . '}'; } - /** * @param mixed $value */ - private function stringifyValue($value): string + private function stringifyValue($value) : string { - if ($value === false) { + if ($value === \false) { return 'false'; } - - if ($value === true) { + if ($value === \true) { return 'true'; } - - if (is_array($value)) { - return implode(', ', $value); + if (\is_array($value)) { + return \implode(', ', $value); } - return (string) $value; } } diff --git a/packages/BetterPhpDocParser/ValueObject/PhpDoc/SpacingAwareTemplateTagValueNode.php b/packages/BetterPhpDocParser/ValueObject/PhpDoc/SpacingAwareTemplateTagValueNode.php index d78d7fc2189..27db38d1d5c 100644 --- a/packages/BetterPhpDocParser/ValueObject/PhpDoc/SpacingAwareTemplateTagValueNode.php +++ b/packages/BetterPhpDocParser/ValueObject/PhpDoc/SpacingAwareTemplateTagValueNode.php @@ -1,32 +1,27 @@ preposition = $preposition; } - - public function __toString(): string + public function __toString() : string { // @see https://github.com/rectorphp/rector/issues/3438 # 'as'/'of' $bound = $this->bound !== null ? ' ' . $this->preposition . ' ' . $this->bound : ''; - $content = $this->name . $bound . ' ' . $this->description; - return trim($content); + return \trim($content); } } diff --git a/packages/BetterPhpDocParser/ValueObject/PhpDoc/VariadicAwareParamTagValueNode.php b/packages/BetterPhpDocParser/ValueObject/PhpDoc/VariadicAwareParamTagValueNode.php index 6312f2b8676..e337ecc0453 100644 --- a/packages/BetterPhpDocParser/ValueObject/PhpDoc/VariadicAwareParamTagValueNode.php +++ b/packages/BetterPhpDocParser/ValueObject/PhpDoc/VariadicAwareParamTagValueNode.php @@ -1,19 +1,15 @@ isVariadic ? '...' : ''; - - $content = sprintf('%s %s%s %s', $this->type, $variadic, $this->parameterName, $this->description); - - return trim($content); + $content = \sprintf('%s %s%s %s', $this->type, $variadic, $this->parameterName, $this->description); + return \trim($content); } } diff --git a/packages/BetterPhpDocParser/ValueObject/PhpDocAttributeKey.php b/packages/BetterPhpDocParser/ValueObject/PhpDocAttributeKey.php index 5ad236f1d95..f2cb9bab56e 100644 --- a/packages/BetterPhpDocParser/ValueObject/PhpDocAttributeKey.php +++ b/packages/BetterPhpDocParser/ValueObject/PhpDocAttributeKey.php @@ -1,30 +1,25 @@ start = $start; $this->end = $end; } - - public function getStart(): int + public function getStart() : int { return $this->start; } - - public function getEnd(): int + public function getEnd() : int { return $this->end; } - - public function contains(int $position): bool + public function contains(int $position) : bool { if ($position < $this->start) { - return false; + return \false; } - return $position < $this->end; } } diff --git a/packages/BetterPhpDocParser/ValueObject/Type/BracketsAwareIntersectionTypeNode.php b/packages/BetterPhpDocParser/ValueObject/Type/BracketsAwareIntersectionTypeNode.php index 710fe71a644..b1f8e869103 100644 --- a/packages/BetterPhpDocParser/ValueObject/Type/BracketsAwareIntersectionTypeNode.php +++ b/packages/BetterPhpDocParser/ValueObject/Type/BracketsAwareIntersectionTypeNode.php @@ -1,15 +1,13 @@ types); + return \implode('&', $this->types); } } diff --git a/packages/BetterPhpDocParser/ValueObject/Type/BracketsAwareUnionTypeNode.php b/packages/BetterPhpDocParser/ValueObject/Type/BracketsAwareUnionTypeNode.php index 532b575500f..e57b1cf5fcd 100644 --- a/packages/BetterPhpDocParser/ValueObject/Type/BracketsAwareUnionTypeNode.php +++ b/packages/BetterPhpDocParser/ValueObject/Type/BracketsAwareUnionTypeNode.php @@ -1,42 +1,35 @@ isWrappedInBrackets = $isWrappedInBrackets; } - /** * Preserve common format */ - public function __toString(): string + public function __toString() : string { - if (! $this->isWrappedInBrackets) { - return implode('|', $this->types); + if (!$this->isWrappedInBrackets) { + return \implode('|', $this->types); } - - return '(' . implode('|', $this->types) . ')'; + return '(' . \implode('|', $this->types) . ')'; } - - public function isWrappedInBrackets(): bool + public function isWrappedInBrackets() : bool { return $this->isWrappedInBrackets; } diff --git a/packages/BetterPhpDocParser/ValueObject/Type/EmptyGenericTypeNode.php b/packages/BetterPhpDocParser/ValueObject/Type/EmptyGenericTypeNode.php index 4c13b1c371b..e5675d88b78 100644 --- a/packages/BetterPhpDocParser/ValueObject/Type/EmptyGenericTypeNode.php +++ b/packages/BetterPhpDocParser/ValueObject/Type/EmptyGenericTypeNode.php @@ -1,20 +1,17 @@ type; } diff --git a/packages/BetterPhpDocParser/ValueObject/Type/FullyQualifiedIdentifierTypeNode.php b/packages/BetterPhpDocParser/ValueObject/Type/FullyQualifiedIdentifierTypeNode.php index 12b3d1ba524..b1a909c63bb 100644 --- a/packages/BetterPhpDocParser/ValueObject/Type/FullyQualifiedIdentifierTypeNode.php +++ b/packages/BetterPhpDocParser/ValueObject/Type/FullyQualifiedIdentifierTypeNode.php @@ -1,14 +1,12 @@ name; } diff --git a/packages/BetterPhpDocParser/ValueObject/Type/SpacingAwareArrayTypeNode.php b/packages/BetterPhpDocParser/ValueObject/Type/SpacingAwareArrayTypeNode.php index c4529cee044..6b3c54ece3f 100644 --- a/packages/BetterPhpDocParser/ValueObject/Type/SpacingAwareArrayTypeNode.php +++ b/packages/BetterPhpDocParser/ValueObject/Type/SpacingAwareArrayTypeNode.php @@ -1,74 +1,57 @@ type instanceof CallableTypeNode) { - return sprintf('(%s)[]', (string) $this->type); + if ($this->type instanceof \PHPStan\PhpDocParser\Ast\Type\CallableTypeNode) { + return \sprintf('(%s)[]', (string) $this->type); } - $typeAsString = (string) $this->type; - if ($this->isGenericArrayCandidate($this->type)) { - return sprintf('array<%s>', $typeAsString); + return \sprintf('array<%s>', $typeAsString); } - - if ($this->type instanceof ArrayTypeNode) { + if ($this->type instanceof \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode) { return $this->printArrayType($this->type); } - - if ($this->type instanceof BracketsAwareUnionTypeNode) { + if ($this->type instanceof \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareUnionTypeNode) { return $this->printUnionType($this->type); } - return $typeAsString . '[]'; } - - private function isGenericArrayCandidate(TypeNode $typeNode): bool + private function isGenericArrayCandidate(\PHPStan\PhpDocParser\Ast\Type\TypeNode $typeNode) : bool { - if (! $this->getAttribute(ArrayTypeMapper::HAS_GENERIC_TYPE_PARENT)) { - return false; + if (!$this->getAttribute(\Rector\PHPStanStaticTypeMapper\TypeMapper\ArrayTypeMapper::HAS_GENERIC_TYPE_PARENT)) { + return \false; } - - return $typeNode instanceof UnionTypeNode || $typeNode instanceof ArrayTypeNode; + return $typeNode instanceof \PHPStan\PhpDocParser\Ast\Type\UnionTypeNode || $typeNode instanceof \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; } - - private function printArrayType(ArrayTypeNode $arrayTypeNode): string + private function printArrayType(\PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode $arrayTypeNode) : string { $typeAsString = (string) $arrayTypeNode; - - $singleTypesAsString = explode('|', $typeAsString); + $singleTypesAsString = \explode('|', $typeAsString); foreach ($singleTypesAsString as $key => $singleTypeAsString) { $singleTypesAsString[$key] = $singleTypeAsString . '[]'; } - - return implode('|', $singleTypesAsString); + return \implode('|', $singleTypesAsString); } - - private function printUnionType(BracketsAwareUnionTypeNode $bracketsAwareUnionTypeNode): string + private function printUnionType(\Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareUnionTypeNode $bracketsAwareUnionTypeNode) : string { $unionedTypes = []; - if ($bracketsAwareUnionTypeNode->isWrappedInBrackets()) { return $bracketsAwareUnionTypeNode . '[]'; } - foreach ($bracketsAwareUnionTypeNode->types as $unionedType) { $unionedTypes[] = $unionedType . '[]'; } - - return implode('|', $unionedTypes); + return \implode('|', $unionedTypes); } } diff --git a/packages/BetterPhpDocParser/ValueObject/Type/SpacingAwareCallableTypeNode.php b/packages/BetterPhpDocParser/ValueObject/Type/SpacingAwareCallableTypeNode.php index ad9d64293e6..15d022d2261 100644 --- a/packages/BetterPhpDocParser/ValueObject/Type/SpacingAwareCallableTypeNode.php +++ b/packages/BetterPhpDocParser/ValueObject/Type/SpacingAwareCallableTypeNode.php @@ -1,56 +1,44 @@ createExplicitCallable(); } - - private function createExplicitCallable(): string + private function createExplicitCallable() : string { /** @var IdentifierTypeNode|GenericTypeNode $returnType */ $returnType = $this->returnType; - $parameterTypeString = $this->createParameterTypeString(); - $returnTypeAsString = (string) $returnType; - if (Strings::contains($returnTypeAsString, '|')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($returnTypeAsString, '|')) { $returnTypeAsString = '(' . $returnTypeAsString . ')'; } - $parameterTypeString = $this->normalizeParameterType($parameterTypeString, $returnTypeAsString); $returnTypeAsString = $this->normalizeReturnType($parameterTypeString, $returnTypeAsString); - - return sprintf('%s%s%s', $this->identifier->name, $parameterTypeString, $returnTypeAsString); + return \sprintf('%s%s%s', $this->identifier->name, $parameterTypeString, $returnTypeAsString); } - - private function createParameterTypeString(): string + private function createParameterTypeString() : string { $parameterTypeStrings = []; foreach ($this->parameters as $parameter) { - $parameterTypeStrings[] = trim((string) $parameter); + $parameterTypeStrings[] = \trim((string) $parameter); } - - $parameterTypeString = implode(', ', $parameterTypeStrings); - - return trim($parameterTypeString); + $parameterTypeString = \implode(', ', $parameterTypeStrings); + return \trim($parameterTypeString); } - - private function normalizeParameterType(string $parameterTypeString, string $returnTypeAsString): string + private function normalizeParameterType(string $parameterTypeString, string $returnTypeAsString) : string { if ($parameterTypeString !== '') { return '(' . $parameterTypeString . ')'; @@ -63,8 +51,7 @@ final class SpacingAwareCallableTypeNode extends CallableTypeNode } return '()'; } - - private function normalizeReturnType(string $parameterTypeString, string $returnTypeAsString): string + private function normalizeReturnType(string $parameterTypeString, string $returnTypeAsString) : string { if ($returnTypeAsString !== 'mixed') { return ':' . $returnTypeAsString; diff --git a/packages/BetterPhpDocParser/ValueObjectFactory/PhpDocNode/Symfony/SymfonyRouteTagValueNodeFactory.php b/packages/BetterPhpDocParser/ValueObjectFactory/PhpDocNode/Symfony/SymfonyRouteTagValueNodeFactory.php index 5ae002bdc33..e3755ed6d66 100644 --- a/packages/BetterPhpDocParser/ValueObjectFactory/PhpDocNode/Symfony/SymfonyRouteTagValueNodeFactory.php +++ b/packages/BetterPhpDocParser/ValueObjectFactory/PhpDocNode/Symfony/SymfonyRouteTagValueNodeFactory.php @@ -1,23 +1,16 @@ $items */ - public function createFromItems(array $items): DoctrineAnnotationTagValueNode + public function createFromItems(array $items) : \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode { - return new DoctrineAnnotationTagValueNode( - 'Symfony\Component\Routing\Annotation\Route', - null, - $items, - 'path' - ); + return new \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode('Symfony\\Component\\Routing\\Annotation\\Route', null, $items, 'path'); } } diff --git a/packages/Caching/Application/CachedFileInfoFilterAndReporter.php b/packages/Caching/Application/CachedFileInfoFilterAndReporter.php index f98a8e9b876..8d7ba2f17b6 100644 --- a/packages/Caching/Application/CachedFileInfoFilterAndReporter.php +++ b/packages/Caching/Application/CachedFileInfoFilterAndReporter.php @@ -1,56 +1,45 @@ configuration = $configuration; $this->changedFilesDetector = $changedFilesDetector; $this->unchangedFilesFilter = $unchangedFilesFilter; } - /** * @param SmartFileInfo[] $phpFileInfos * @return SmartFileInfo[] */ - public function filterFileInfos(array $phpFileInfos): array + public function filterFileInfos(array $phpFileInfos) : array { - if (! $this->configuration->isCacheEnabled()) { + if (!$this->configuration->isCacheEnabled()) { return $phpFileInfos; } - // cache stuff if ($this->configuration->shouldClearCache()) { $this->changedFilesDetector->clear(); } - return $this->unchangedFilesFilter->filterAndJoinWithDependentFileInfos($phpFileInfos); } } diff --git a/packages/Caching/Cache/NetteCacheFactory.php b/packages/Caching/Cache/NetteCacheFactory.php index dd97111629f..78f7300d193 100644 --- a/packages/Caching/Cache/NetteCacheFactory.php +++ b/packages/Caching/Cache/NetteCacheFactory.php @@ -1,45 +1,37 @@ parameterProvider = $parameterProvider; $this->smartFileSystem = $smartFileSystem; } - - public function create(): Cache + public function create() : \RectorPrefix20210509\Nette\Caching\Cache { - $cacheDirectory = $this->parameterProvider->provideStringParameter(Option::CACHE_DIR); - + $cacheDirectory = $this->parameterProvider->provideStringParameter(\Rector\Core\Configuration\Option::CACHE_DIR); // ensure cache directory exists - if (! $this->smartFileSystem->exists($cacheDirectory)) { + if (!$this->smartFileSystem->exists($cacheDirectory)) { $this->smartFileSystem->mkdir($cacheDirectory); } - - $fileStorage = new FileStorage($cacheDirectory); - + $fileStorage = new \RectorPrefix20210509\Nette\Caching\Storages\FileStorage($cacheDirectory); // namespace is unique per project - return new Cache($fileStorage, getcwd()); + return new \RectorPrefix20210509\Nette\Caching\Cache($fileStorage, \getcwd()); } } diff --git a/packages/Caching/Config/FileHashComputer.php b/packages/Caching/Config/FileHashComputer.php index c6de54096d8..e2c60a2294d 100644 --- a/packages/Caching/Config/FileHashComputer.php +++ b/packages/Caching/Config/FileHashComputer.php @@ -1,75 +1,59 @@ ensureIsPhp($fileInfo); - - $containerBuilder = new ContainerBuilder(); + $containerBuilder = new \RectorPrefix20210509\Symfony\Component\DependencyInjection\ContainerBuilder(); $fileLoader = $this->createFileLoader($fileInfo, $containerBuilder); - $fileLoader->load($fileInfo->getRealPath()); - $parameterBag = $containerBuilder->getParameterBag(); - return $this->arrayToHash($containerBuilder->getDefinitions()) . $this->arrayToHash($parameterBag->all()); } - - private function ensureIsPhp(SmartFileInfo $fileInfo): void + private function ensureIsPhp(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo) : void { if ($fileInfo->hasSuffixes(['php'])) { return; } - - throw new ShouldNotHappenException(sprintf( + throw new \Rector\Core\Exception\ShouldNotHappenException(\sprintf( // getRealPath() cannot be used, as it breaks in phar 'Provide only PHP file, ready for Symfony Dependency Injection. "%s" given', $fileInfo->getRelativeFilePath() )); } - - private function createFileLoader(SmartFileInfo $fileInfo, ContainerBuilder $containerBuilder): LoaderInterface + private function createFileLoader(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo, \RectorPrefix20210509\Symfony\Component\DependencyInjection\ContainerBuilder $containerBuilder) : \RectorPrefix20210509\Symfony\Component\Config\Loader\LoaderInterface { - $fileLocator = new FileLocator([$fileInfo->getPath()]); - - $fileLoaders = [ - new GlobFileLoader($containerBuilder, $fileLocator), - new PhpFileLoader($containerBuilder, $fileLocator), - ]; - - $loaderResolver = new LoaderResolver($fileLoaders); + $fileLocator = new \RectorPrefix20210509\Symfony\Component\Config\FileLocator([$fileInfo->getPath()]); + $fileLoaders = [new \RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\GlobFileLoader($containerBuilder, $fileLocator), new \RectorPrefix20210509\Symfony\Component\DependencyInjection\Loader\PhpFileLoader($containerBuilder, $fileLocator)]; + $loaderResolver = new \RectorPrefix20210509\Symfony\Component\Config\Loader\LoaderResolver($fileLoaders); $loader = $loaderResolver->resolve($fileInfo->getRealPath()); - if (! $loader) { - throw new ShouldNotHappenException(); + if (!$loader) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - return $loader; } - /** * @param mixed[] $array */ - private function arrayToHash(array $array): string + private function arrayToHash(array $array) : string { - $serializedArray = serialize($array); - return md5($serializedArray); + $serializedArray = \serialize($array); + return \md5($serializedArray); } } diff --git a/packages/Caching/Detector/ChangedFilesDetector.php b/packages/Caching/Detector/ChangedFilesDetector.php index fee471647f2..d5e08bb731c 100644 --- a/packages/Caching/Detector/ChangedFilesDetector.php +++ b/packages/Caching/Detector/ChangedFilesDetector.php @@ -1,14 +1,12 @@ fileHashComputer = $fileHashComputer; $this->cache = $cache; } - /** * @param string[] $dependentFiles */ - public function addFileWithDependencies(SmartFileInfo $smartFileInfo, array $dependentFiles): void + public function addFileWithDependencies(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo, array $dependentFiles) : void { $fileInfoCacheKey = $this->getFileInfoCacheKey($smartFileInfo); $hash = $this->hashFile($smartFileInfo); - $this->cache->save($fileInfoCacheKey, $hash); $this->cache->save($fileInfoCacheKey . '_files', $dependentFiles); } - - public function hasFileChanged(SmartFileInfo $smartFileInfo): bool + public function hasFileChanged(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : bool { $currentFileHash = $this->hashFile($smartFileInfo); - $fileInfoCacheKey = $this->getFileInfoCacheKey($smartFileInfo); - $cachedValue = $this->cache->load($fileInfoCacheKey); return $currentFileHash !== $cachedValue; } - - public function invalidateFile(SmartFileInfo $smartFileInfo): void + public function invalidateFile(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : void { $fileInfoCacheKey = $this->getFileInfoCacheKey($smartFileInfo); $this->cache->remove($fileInfoCacheKey); } - - public function clear(): void + public function clear() : void { - $this->cache->clean([ - Cache::ALL => true, - ]); + $this->cache->clean([\RectorPrefix20210509\Nette\Caching\Cache::ALL => \true]); } - /** * @return SmartFileInfo[] */ - public function getDependentFileInfos(SmartFileInfo $fileInfo): array + public function getDependentFileInfos(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo) : array { $fileInfoCacheKey = $this->getFileInfoCacheKey($fileInfo); - $cacheValue = $this->cache->load($fileInfoCacheKey . '_files'); if ($cacheValue === null) { return []; } - $dependentFileInfos = []; - $dependentFiles = $cacheValue; foreach ($dependentFiles as $dependentFile) { - if (! file_exists($dependentFile)) { + if (!\file_exists($dependentFile)) { continue; } - - $dependentFileInfos[] = new SmartFileInfo($dependentFile); + $dependentFileInfos[] = new \Symplify\SmartFileSystem\SmartFileInfo($dependentFile); } - return $dependentFileInfos; } - /** * @api */ - public function setFirstResolvedConfigFileInfo(SmartFileInfo $fileInfo): void + public function setFirstResolvedConfigFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo) : void { // the first config is core to all → if it was changed, just invalidate it $configHash = $this->fileHashComputer->compute($fileInfo); $this->storeConfigurationDataHash($fileInfo, $configHash); } - - private function getFileInfoCacheKey(SmartFileInfo $smartFileInfo): string + private function getFileInfoCacheKey(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : string { - return sha1($smartFileInfo->getRealPath()); + return \sha1($smartFileInfo->getRealPath()); } - - private function hashFile(SmartFileInfo $smartFileInfo): string + private function hashFile(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : string { - return (string) sha1_file($smartFileInfo->getRealPath()); + return (string) \sha1_file($smartFileInfo->getRealPath()); } - - private function storeConfigurationDataHash(SmartFileInfo $fileInfo, string $configurationHash): void + private function storeConfigurationDataHash(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo, string $configurationHash) : void { - $key = self::CONFIGURATION_HASH_KEY . '_' . Strings::webalize($fileInfo->getRealPath()); + $key = self::CONFIGURATION_HASH_KEY . '_' . \RectorPrefix20210509\Nette\Utils\Strings::webalize($fileInfo->getRealPath()); $this->invalidateCacheIfConfigurationChanged($key, $configurationHash); - $this->cache->save($key, $configurationHash); } - - private function invalidateCacheIfConfigurationChanged(string $key, string $configurationHash): void + private function invalidateCacheIfConfigurationChanged(string $key, string $configurationHash) : void { $oldCachedValue = $this->cache->load($key); if ($oldCachedValue === $configurationHash) { return; } - // should be unique per getcwd() $this->clear(); } diff --git a/packages/Caching/FileSystem/DependencyResolver.php b/packages/Caching/FileSystem/DependencyResolver.php index 448dec8874d..cc62c049de2 100644 --- a/packages/Caching/FileSystem/DependencyResolver.php +++ b/packages/Caching/FileSystem/DependencyResolver.php @@ -1,7 +1,6 @@ fileHelper = $fileHelper; $this->phpStanDependencyResolver = $phpStanDependencyResolver; $this->nodeScopeResolver = $nodeScopeResolver; $this->privatesAccessor = $privatesAccessor; } - /** * @return string[] */ - public function resolveDependencies(Node $node, MutatingScope $mutatingScope): array + public function resolveDependencies(\PhpParser\Node $node, \PHPStan\Analyser\MutatingScope $mutatingScope) : array { - $analysedFileAbsolutesPaths = $this->privatesAccessor->getPrivateProperty( - $this->nodeScopeResolver, - 'analysedFiles' - ); - + $analysedFileAbsolutesPaths = $this->privatesAccessor->getPrivateProperty($this->nodeScopeResolver, 'analysedFiles'); $dependencyFiles = []; - $nodeDependencies = $this->phpStanDependencyResolver->resolveDependencies($node, $mutatingScope); foreach ($nodeDependencies as $nodeDependency) { $dependencyFile = $nodeDependency->getFileName(); - if (! $dependencyFile) { + if (!$dependencyFile) { continue; } - $dependencyFile = $this->fileHelper->normalizePath($dependencyFile); if ($mutatingScope->getFile() === $dependencyFile) { continue; } - - if (! in_array($dependencyFile, $analysedFileAbsolutesPaths, true)) { + if (!\in_array($dependencyFile, $analysedFileAbsolutesPaths, \true)) { continue; } - $dependencyFiles[] = $dependencyFile; } - - $dependencyFiles = array_unique($dependencyFiles, SORT_STRING); - - return array_values($dependencyFiles); + $dependencyFiles = \array_unique($dependencyFiles, \SORT_STRING); + return \array_values($dependencyFiles); } } diff --git a/packages/Caching/UnchangedFilesFilter.php b/packages/Caching/UnchangedFilesFilter.php index 7036319da6b..5a1fe0f9437 100644 --- a/packages/Caching/UnchangedFilesFilter.php +++ b/packages/Caching/UnchangedFilesFilter.php @@ -1,51 +1,38 @@ changedFilesDetector = $changedFilesDetector; } - /** * @param SmartFileInfo[] $fileInfos * @return SmartFileInfo[] */ - public function filterAndJoinWithDependentFileInfos(array $fileInfos): array + public function filterAndJoinWithDependentFileInfos(array $fileInfos) : array { $changedFileInfos = []; $dependentFileInfos = []; - foreach ($fileInfos as $fileInfo) { - if (! $this->changedFilesDetector->hasFileChanged($fileInfo)) { + if (!$this->changedFilesDetector->hasFileChanged($fileInfo)) { continue; } - $changedFileInfos[] = $fileInfo; - $this->changedFilesDetector->invalidateFile($fileInfo); - - $dependentFileInfos = array_merge( - $dependentFileInfos, - $this->changedFilesDetector->getDependentFileInfos($fileInfo) - ); + $dependentFileInfos = \array_merge($dependentFileInfos, $this->changedFilesDetector->getDependentFileInfos($fileInfo)); } - // add dependent files - $dependentFileInfos = array_merge($dependentFileInfos, $changedFileInfos); - - return array_unique($dependentFileInfos); + $dependentFileInfos = \array_merge($dependentFileInfos, $changedFileInfos); + return \array_unique($dependentFileInfos); } } diff --git a/packages/ChangesReporting/Annotation/AnnotationExtractor.php b/packages/ChangesReporting/Annotation/AnnotationExtractor.php index 418b163014f..1151a7a2224 100644 --- a/packages/ChangesReporting/Annotation/AnnotationExtractor.php +++ b/packages/ChangesReporting/Annotation/AnnotationExtractor.php @@ -1,13 +1,11 @@ $className */ - public function extractAnnotationFromClass(string $className, string $annotation): ?string + public function extractAnnotationFromClass(string $className, string $annotation) : ?string { - $reflectionClass = new ReflectionClass($className); - + $reflectionClass = new \ReflectionClass($className); $docComment = $reflectionClass->getDocComment(); - if (! is_string($docComment)) { + if (!\is_string($docComment)) { return null; } - // @see https://regex101.com/r/oYGaWU/1 - $pattern = '#' . preg_quote($annotation, '#') . '\s+(?.*?)$#m'; - $matches = Strings::match($docComment, $pattern); + $pattern = '#' . \preg_quote($annotation, '#') . '\\s+(?.*?)$#m'; + $matches = \RectorPrefix20210509\Nette\Utils\Strings::match($docComment, $pattern); return $matches['content'] ?? null; } } diff --git a/packages/ChangesReporting/Annotation/RectorsChangelogResolver.php b/packages/ChangesReporting/Annotation/RectorsChangelogResolver.php index 58924de97a4..82d37191400 100644 --- a/packages/ChangesReporting/Annotation/RectorsChangelogResolver.php +++ b/packages/ChangesReporting/Annotation/RectorsChangelogResolver.php @@ -1,45 +1,39 @@ annotationExtractor = $annotationExtractor; } - /** * @param array> $rectorClasses * @return array */ - public function resolve(array $rectorClasses): array + public function resolve(array $rectorClasses) : array { $rectorClassesToChangelogUrls = $this->resolveIncludingMissing($rectorClasses); - return array_filter($rectorClassesToChangelogUrls); + return \array_filter($rectorClassesToChangelogUrls); } - /** * @param array> $rectorClasses * @return array */ - public function resolveIncludingMissing(array $rectorClasses): array + public function resolveIncludingMissing(array $rectorClasses) : array { $rectorClassesToChangelogUrls = []; foreach ($rectorClasses as $rectorClass) { $changelogUrl = $this->annotationExtractor->extractAnnotationFromClass($rectorClass, '@changelog'); $rectorClassesToChangelogUrls[$rectorClass] = $changelogUrl; } - return $rectorClassesToChangelogUrls; } } diff --git a/packages/ChangesReporting/Collector/AffectedFilesCollector.php b/packages/ChangesReporting/Collector/AffectedFilesCollector.php index 197cdde2c76..d3bb46ebf91 100644 --- a/packages/ChangesReporting/Collector/AffectedFilesCollector.php +++ b/packages/ChangesReporting/Collector/AffectedFilesCollector.php @@ -1,33 +1,28 @@ getSmartFileInfo(); $this->affectedFiles[$smartFileInfo->getRealPath()] = $file; } - - public function getNext(): ?File + public function getNext() : ?\Rector\Core\ValueObject\Application\File { if ($this->affectedFiles !== []) { - return current($this->affectedFiles); + return \current($this->affectedFiles); } return null; } - - public function removeFromList(File $file): void + public function removeFromList(\Rector\Core\ValueObject\Application\File $file) : void { $smartFileInfo = $file->getSmartFileInfo(); unset($this->affectedFiles[$smartFileInfo->getRealPath()]); diff --git a/packages/ChangesReporting/Collector/RectorChangeCollector.php b/packages/ChangesReporting/Collector/RectorChangeCollector.php index 42fdda97274..20d8ede5b1b 100644 --- a/packages/ChangesReporting/Collector/RectorChangeCollector.php +++ b/packages/ChangesReporting/Collector/RectorChangeCollector.php @@ -1,7 +1,6 @@ currentRectorProvider = $currentRectorProvider; $this->currentFileProvider = $currentFileProvider; } - - public function notifyNodeFileInfo(Node $node): void + public function notifyNodeFileInfo(\PhpParser\Node $node) : void { $file = $this->currentFileProvider->getFile(); - if (! $file instanceof File) { + if (!$file instanceof \Rector\Core\ValueObject\Application\File) { // this file was changed before and this is a sub-new node // array Traverse to all new nodes would have to be used, but it's not worth the performance return; } - $currentRector = $this->currentRectorProvider->getCurrentRector(); - if (! $currentRector instanceof RectorInterface) { - throw new ShouldNotHappenException(); + if (!$currentRector instanceof \Rector\Core\Contract\Rector\RectorInterface) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $rectorWithLineChange = new RectorWithLineChange($currentRector, $node->getLine()); + $rectorWithLineChange = new \Rector\ChangesReporting\ValueObject\RectorWithLineChange($currentRector, $node->getLine()); $file->addRectorClassWithLine($rectorWithLineChange); } } diff --git a/packages/ChangesReporting/Contract/Output/OutputFormatterInterface.php b/packages/ChangesReporting/Contract/Output/OutputFormatterInterface.php index 77c4a375e9e..6bf618215e7 100644 --- a/packages/ChangesReporting/Contract/Output/OutputFormatterInterface.php +++ b/packages/ChangesReporting/Contract/Output/OutputFormatterInterface.php @@ -1,14 +1,11 @@ outputStyle = $outputStyle; $this->configuration = $configuration; $this->rectorsChangelogResolver = $rectorsChangelogResolver; } - - public function report(ProcessResult $processResult): void + public function report(\Rector\Core\ValueObject\ProcessResult $processResult) : void { if ($this->configuration->getOutputFile()) { - $message = sprintf( - 'Option "--%s" can be used only with "--%s %s"', - Option::OPTION_OUTPUT_FILE, - Option::OPTION_OUTPUT_FORMAT, - 'json' - ); + $message = \sprintf('Option "--%s" can be used only with "--%s %s"', \Rector\Core\Configuration\Option::OPTION_OUTPUT_FILE, \Rector\Core\Configuration\Option::OPTION_OUTPUT_FORMAT, 'json'); $this->outputStyle->error($message); } - if ($this->configuration->shouldShowDiffs()) { $this->reportFileDiffs($processResult->getFileDiffs()); } - $this->reportErrors($processResult->getErrors()); $this->reportRemovedFilesAndNodes($processResult); - if ($processResult->getErrors() !== []) { return; } - $message = $this->createSuccessMessage($processResult); $this->outputStyle->success($message); } - - public function getName(): string + public function getName() : string { return self::NAME; } - /** * @param FileDiff[] $fileDiffs */ - private function reportFileDiffs(array $fileDiffs): void + private function reportFileDiffs(array $fileDiffs) : void { - if (count($fileDiffs) <= 0) { + if (\count($fileDiffs) <= 0) { return; } - // normalize - ksort($fileDiffs); - $message = sprintf('%d file%s with changes', count($fileDiffs), count($fileDiffs) === 1 ? '' : 's'); - + \ksort($fileDiffs); + $message = \sprintf('%d file%s with changes', \count($fileDiffs), \count($fileDiffs) === 1 ? '' : 's'); $this->outputStyle->title($message); - $i = 0; foreach ($fileDiffs as $fileDiff) { $relativeFilePath = $fileDiff->getRelativeFilePath(); - $message = sprintf('%d) %s', ++$i, $relativeFilePath); - + $message = \sprintf('%d) %s', ++$i, $relativeFilePath); $this->outputStyle->writeln($message); $this->outputStyle->newLine(); $this->outputStyle->writeln($fileDiff->getDiffConsoleFormatted()); - $rectorsChangelogsLines = $this->createRectorChangelogLines($fileDiff); - if ($fileDiff->getRectorChanges() !== []) { $this->outputStyle->writeln('Applied rules:'); $this->outputStyle->listing($rectorsChangelogsLines); @@ -117,93 +89,66 @@ final class ConsoleOutputFormatter implements OutputFormatterInterface } } } - /** * @param RectorError[] $errors */ - private function reportErrors(array $errors): void + private function reportErrors(array $errors) : void { foreach ($errors as $error) { $errorMessage = $error->getMessage(); $errorMessage = $this->normalizePathsToRelativeWithLine($errorMessage); - - $message = sprintf( - 'Could not process "%s" file%s, due to: %s"%s".', - $error->getRelativeFilePath(), - $error->getRectorClass() ? ' by "' . $error->getRectorClass() . '"' : '', - PHP_EOL, - $errorMessage - ); - + $message = \sprintf('Could not process "%s" file%s, due to: %s"%s".', $error->getRelativeFilePath(), $error->getRectorClass() ? ' by "' . $error->getRectorClass() . '"' : '', \PHP_EOL, $errorMessage); if ($error->getLine()) { $message .= ' On line: ' . $error->getLine(); } - $this->outputStyle->error($message); } } - - private function reportRemovedFilesAndNodes(ProcessResult $processResult): void + private function reportRemovedFilesAndNodes(\Rector\Core\ValueObject\ProcessResult $processResult) : void { if ($processResult->getAddedFilesCount() !== 0) { - $message = sprintf('%d files were added', $processResult->getAddedFilesCount()); + $message = \sprintf('%d files were added', $processResult->getAddedFilesCount()); $this->outputStyle->note($message); } - if ($processResult->getRemovedFilesCount() !== 0) { - $message = sprintf('%d files were removed', $processResult->getRemovedFilesCount()); + $message = \sprintf('%d files were removed', $processResult->getRemovedFilesCount()); $this->outputStyle->note($message); } - $this->reportRemovedNodes($processResult); } - - private function normalizePathsToRelativeWithLine(string $errorMessage): string + private function normalizePathsToRelativeWithLine(string $errorMessage) : string { - $regex = '#' . preg_quote(getcwd(), '#') . '/#'; - $errorMessage = Strings::replace($errorMessage, $regex, ''); - return Strings::replace($errorMessage, self::ON_LINE_REGEX, ':'); + $regex = '#' . \preg_quote(\getcwd(), '#') . '/#'; + $errorMessage = \RectorPrefix20210509\Nette\Utils\Strings::replace($errorMessage, $regex, ''); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($errorMessage, self::ON_LINE_REGEX, ':'); } - - private function reportRemovedNodes(ProcessResult $processResult): void + private function reportRemovedNodes(\Rector\Core\ValueObject\ProcessResult $processResult) : void { if ($processResult->getRemovedNodeCount() === 0) { return; } - - $message = sprintf('%d nodes were removed', $processResult->getRemovedNodeCount()); + $message = \sprintf('%d nodes were removed', $processResult->getRemovedNodeCount()); $this->outputStyle->warning($message); } - - private function createSuccessMessage(ProcessResult $processResult): string + private function createSuccessMessage(\Rector\Core\ValueObject\ProcessResult $processResult) : string { - $changeCount = count($processResult->getFileDiffs()) + $processResult->getRemovedAndAddedFilesCount(); - + $changeCount = \count($processResult->getFileDiffs()) + $processResult->getRemovedAndAddedFilesCount(); if ($changeCount === 0) { return 'Rector is done!'; } - - return sprintf( - '%d file%s %s by Rector', - $changeCount, - $changeCount > 1 ? 's' : '', - $this->configuration->isDryRun() ? 'would have changed (dry-run)' : ($changeCount === 1 ? 'has' : 'have') . ' been changed' - ); + return \sprintf('%d file%s %s by Rector', $changeCount, $changeCount > 1 ? 's' : '', $this->configuration->isDryRun() ? 'would have changed (dry-run)' : ($changeCount === 1 ? 'has' : 'have') . ' been changed'); } - /** * @return string[] */ - private function createRectorChangelogLines(FileDiff $fileDiff): array + private function createRectorChangelogLines(\Rector\Core\ValueObject\Reporting\FileDiff $fileDiff) : array { $rectorsChangelogs = $this->rectorsChangelogResolver->resolveIncludingMissing($fileDiff->getRectorClasses()); - $rectorsChangelogsLines = []; foreach ($rectorsChangelogs as $rectorClass => $changelog) { - $rectorShortClass = (string) Strings::after($rectorClass, '\\', -1); + $rectorShortClass = (string) \RectorPrefix20210509\Nette\Utils\Strings::after($rectorClass, '\\', -1); $rectorsChangelogsLines[] = $changelog === null ? $rectorShortClass : $rectorShortClass . ' (' . $changelog . ')'; } - return $rectorsChangelogsLines; } } diff --git a/packages/ChangesReporting/Output/JsonOutputFormatter.php b/packages/ChangesReporting/Output/JsonOutputFormatter.php index efe4ce173c3..ebb7e5a6e7f 100644 --- a/packages/ChangesReporting/Output/JsonOutputFormatter.php +++ b/packages/ChangesReporting/Output/JsonOutputFormatter.php @@ -1,128 +1,85 @@ configuration = $configuration; $this->smartFileSystem = $smartFileSystem; $this->rectorsChangelogResolver = $rectorsChangelogResolver; } - - public function getName(): string + public function getName() : string { return self::NAME; } - - public function report(ProcessResult $processResult): void + public function report(\Rector\Core\ValueObject\ProcessResult $processResult) : void { - $errorsArray = [ - 'meta' => [ - 'version' => $this->configuration->getPrettyVersion(), - 'config' => $this->configuration->getMainConfigFilePath(), - ], - 'totals' => [ - 'changed_files' => count($processResult->getFileDiffs()), - 'removed_and_added_files_count' => $processResult->getRemovedAndAddedFilesCount(), - 'removed_node_count' => $processResult->getRemovedNodeCount(), - ], - ]; - + $errorsArray = ['meta' => ['version' => $this->configuration->getPrettyVersion(), 'config' => $this->configuration->getMainConfigFilePath()], 'totals' => ['changed_files' => \count($processResult->getFileDiffs()), 'removed_and_added_files_count' => $processResult->getRemovedAndAddedFilesCount(), 'removed_node_count' => $processResult->getRemovedNodeCount()]]; $fileDiffs = $processResult->getFileDiffs(); - ksort($fileDiffs); + \ksort($fileDiffs); foreach ($fileDiffs as $fileDiff) { $relativeFilePath = $fileDiff->getRelativeFilePath(); - $appliedRectorsWithChangelog = $this->rectorsChangelogResolver->resolve($fileDiff->getRectorClasses()); - - $errorsArray['file_diffs'][] = [ - 'file' => $relativeFilePath, - 'diff' => $fileDiff->getDiff(), - 'applied_rectors' => $fileDiff->getRectorClasses(), - 'applied_rectors_with_changelog' => $appliedRectorsWithChangelog, - ]; - + $errorsArray['file_diffs'][] = ['file' => $relativeFilePath, 'diff' => $fileDiff->getDiff(), 'applied_rectors' => $fileDiff->getRectorClasses(), 'applied_rectors_with_changelog' => $appliedRectorsWithChangelog]; // for Rector CI $errorsArray['changed_files'][] = $relativeFilePath; } - $errors = $processResult->getErrors(); - $errorsArray['totals']['errors'] = count($errors); - + $errorsArray['totals']['errors'] = \count($errors); $errorsData = $this->createErrorsData($errors); if ($errorsData !== []) { $errorsArray['errors'] = $errorsData; } - - $json = Json::encode($errorsArray, Json::PRETTY); - + $json = \RectorPrefix20210509\Nette\Utils\Json::encode($errorsArray, \RectorPrefix20210509\Nette\Utils\Json::PRETTY); $outputFile = $this->configuration->getOutputFile(); if ($outputFile !== null) { - $this->smartFileSystem->dumpFile($outputFile, $json . PHP_EOL); + $this->smartFileSystem->dumpFile($outputFile, $json . \PHP_EOL); } else { - echo $json . PHP_EOL; + echo $json . \PHP_EOL; } } - /** * @param mixed[] $errors * @return mixed[] */ - private function createErrorsData(array $errors): array + private function createErrorsData(array $errors) : array { $errorsData = []; - foreach ($errors as $error) { - $errorData = [ - 'message' => $error->getMessage(), - 'file' => $error->getRelativeFilePath(), - ]; - + $errorData = ['message' => $error->getMessage(), 'file' => $error->getRelativeFilePath()]; if ($error->getRectorClass()) { $errorData['caused_by'] = $error->getRectorClass(); } - if ($error->getLine() !== null) { $errorData['line'] = $error->getLine(); } - $errorsData[] = $errorData; } - return $errorsData; } } diff --git a/packages/ChangesReporting/ValueObject/RectorWithLineChange.php b/packages/ChangesReporting/ValueObject/RectorWithLineChange.php index 9d3bad5aa23..0acd15bc5ad 100644 --- a/packages/ChangesReporting/ValueObject/RectorWithLineChange.php +++ b/packages/ChangesReporting/ValueObject/RectorWithLineChange.php @@ -1,38 +1,32 @@ rector = $rector; $this->line = $line; } - /** * @return class-string */ - public function getRectorClass(): string + public function getRectorClass() : string { - return get_class($this->rector); + return \get_class($this->rector); } - - public function getLine(): int + public function getLine() : int { return $this->line; } diff --git a/packages/ChangesReporting/ValueObjectFactory/ErrorFactory.php b/packages/ChangesReporting/ValueObjectFactory/ErrorFactory.php index 23483684317..bdc9bc825e6 100644 --- a/packages/ChangesReporting/ValueObjectFactory/ErrorFactory.php +++ b/packages/ChangesReporting/ValueObjectFactory/ErrorFactory.php @@ -1,28 +1,24 @@ exceptionCorrector = $exceptionCorrector; } - - public function createAutoloadError(AnalysedCodeException $analysedCodeException): RectorError + public function createAutoloadError(\PHPStan\AnalysedCodeException $analysedCodeException) : \Rector\Core\ValueObject\Application\RectorError { $message = $this->exceptionCorrector->getAutoloadExceptionMessageAndAddLocation($analysedCodeException); - return new RectorError($message); + return new \Rector\Core\ValueObject\Application\RectorError($message); } } diff --git a/packages/ChangesReporting/ValueObjectFactory/FileDiffFactory.php b/packages/ChangesReporting/ValueObjectFactory/FileDiffFactory.php index e712b0284ca..19218ea3928 100644 --- a/packages/ChangesReporting/ValueObjectFactory/FileDiffFactory.php +++ b/packages/ChangesReporting/ValueObjectFactory/FileDiffFactory.php @@ -1,40 +1,30 @@ defaultDiffer = $defaultDiffer; $this->consoleDiffer = $consoleDiffer; } - - public function createFileDiff(File $file, string $oldContent, string $newContent): FileDiff + public function createFileDiff(\Rector\Core\ValueObject\Application\File $file, string $oldContent, string $newContent) : \Rector\Core\ValueObject\Reporting\FileDiff { // always keep the most recent diff - return new FileDiff( - $file->getSmartFileInfo(), - $this->defaultDiffer->diff($oldContent, $newContent), - $this->consoleDiffer->diff($oldContent, $newContent), - $file->getRectorWithLineChanges() - ); + return new \Rector\Core\ValueObject\Reporting\FileDiff($file->getSmartFileInfo(), $this->defaultDiffer->diff($oldContent, $newContent), $this->consoleDiffer->diff($oldContent, $newContent), $file->getRectorWithLineChanges()); } } diff --git a/packages/Comments/CommentRemover.php b/packages/Comments/CommentRemover.php index ba1bd20d2a7..8f32afb6e83 100644 --- a/packages/Comments/CommentRemover.php +++ b/packages/Comments/CommentRemover.php @@ -1,7 +1,6 @@ commentRemovingNodeTraverser = $commentRemovingNodeTraverser; } - /** * @param Node[]|Node|null $node * @return Node[]|null */ - public function removeFromNode($node): ?array + public function removeFromNode($node) : ?array { if ($node === null) { return null; } - $copiedNodes = $node; - - $nodes = is_array($copiedNodes) ? $copiedNodes : [$copiedNodes]; + $nodes = \is_array($copiedNodes) ? $copiedNodes : [$copiedNodes]; return $this->commentRemovingNodeTraverser->traverse($nodes); } - - public function rollbackComments(Node $node, Comment $comment): void + public function rollbackComments(\PhpParser\Node $node, \PhpParser\Comment $comment) : void { - $node->setAttribute(AttributeKey::COMMENTS, null); - $node->setDocComment(new Doc($comment->getText())); - $node->setAttribute(AttributeKey::PHP_DOC_INFO, null); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, null); + $node->setDocComment(new \PhpParser\Comment\Doc($comment->getText())); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, null); } } diff --git a/packages/Comments/NodeDocBlock/DocBlockUpdater.php b/packages/Comments/NodeDocBlock/DocBlockUpdater.php index 57f9f2ef07d..d712966c680 100644 --- a/packages/Comments/NodeDocBlock/DocBlockUpdater.php +++ b/packages/Comments/NodeDocBlock/DocBlockUpdater.php @@ -1,7 +1,6 @@ phpDocInfoPrinter = $phpDocInfoPrinter; } - - public function updateNodeWithPhpDocInfo(Node $node): void + public function updateNodeWithPhpDocInfo(\PhpParser\Node $node) : void { // nothing to change? don't save it - $phpDocInfo = $node->getAttribute(AttributeKey::PHP_DOC_INFO); - if (! $phpDocInfo instanceof PhpDocInfo) { + $phpDocInfo = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO); + if (!$phpDocInfo instanceof \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo) { return; } - - if (! $phpDocInfo->hasChanged()) { + if (!$phpDocInfo->hasChanged()) { return; } - $phpDoc = $this->printPhpDocInfoToString($phpDocInfo); - // make sure, that many separated comments are not removed if ($phpDoc === '') { - if (count($node->getComments()) > 1) { + if (\count($node->getComments()) > 1) { foreach ($node->getComments() as $comment) { - $phpDoc .= $comment->getText() . PHP_EOL; + $phpDoc .= $comment->getText() . \PHP_EOL; } } - if ($phpDocInfo->getOriginalPhpDocNode()->children !== []) { // all comments were removed → null - $node->setAttribute(AttributeKey::COMMENTS, null); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, null); } - return; } - // this is needed to remove duplicated // commentsAsText - $node->setDocComment(new Doc($phpDoc)); + $node->setDocComment(new \PhpParser\Comment\Doc($phpDoc)); } - - private function printPhpDocInfoToString(PhpDocInfo $phpDocInfo): string + private function printPhpDocInfoToString(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : string { if ($phpDocInfo->isNewNode()) { return $this->phpDocInfoPrinter->printNew($phpDocInfo); } - return $this->phpDocInfoPrinter->printFormatPreserving($phpDocInfo); } } diff --git a/packages/Comments/NodeTraverser/CommentRemovingNodeTraverser.php b/packages/Comments/NodeTraverser/CommentRemovingNodeTraverser.php index fecfb3aee34..e4aa38323cd 100644 --- a/packages/Comments/NodeTraverser/CommentRemovingNodeTraverser.php +++ b/packages/Comments/NodeTraverser/CommentRemovingNodeTraverser.php @@ -1,15 +1,13 @@ addVisitor($commentRemovingNodeVisitor); } diff --git a/packages/Comments/NodeVisitor/CommentRemovingNodeVisitor.php b/packages/Comments/NodeVisitor/CommentRemovingNodeVisitor.php index 0a1a912be7b..623b178008b 100644 --- a/packages/Comments/NodeVisitor/CommentRemovingNodeVisitor.php +++ b/packages/Comments/NodeVisitor/CommentRemovingNodeVisitor.php @@ -1,23 +1,19 @@ setAttribute(AttributeKey::COMMENTS, []); - $clonedNode->setAttribute(AttributeKey::PHP_DOC_INFO, null); - + $clonedNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, []); + $clonedNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, null); return $clonedNode; } } diff --git a/packages/FamilyTree/NodeAnalyzer/ClassChildAnalyzer.php b/packages/FamilyTree/NodeAnalyzer/ClassChildAnalyzer.php index bb9876af78b..1700cdd0089 100644 --- a/packages/FamilyTree/NodeAnalyzer/ClassChildAnalyzer.php +++ b/packages/FamilyTree/NodeAnalyzer/ClassChildAnalyzer.php @@ -1,66 +1,54 @@ familyRelationsAnalyzer = $familyRelationsAnalyzer; } - - public function hasChildClassMethod(ClassReflection $classReflection, string $methodName): bool + public function hasChildClassMethod(\PHPStan\Reflection\ClassReflection $classReflection, string $methodName) : bool { $childrenClassReflections = $this->familyRelationsAnalyzer->getChildrenOfClassReflection($classReflection); - foreach ($childrenClassReflections as $childClassReflection) { - if (! $childClassReflection->hasMethod($methodName)) { + if (!$childClassReflection->hasMethod($methodName)) { continue; } - $constructorReflectionMethod = $childClassReflection->getNativeMethod($methodName); - if (! $constructorReflectionMethod instanceof PhpMethodReflection) { + if (!$constructorReflectionMethod instanceof \PHPStan\Reflection\Php\PhpMethodReflection) { continue; } - $methodDeclaringClassReflection = $constructorReflectionMethod->getDeclaringClass(); if ($methodDeclaringClassReflection->getName() === $childClassReflection->getName()) { - return true; + return \true; } } - - return false; + return \false; } - - public function hasParentClassMethod(ClassReflection $classReflection, string $methodName): bool + public function hasParentClassMethod(\PHPStan\Reflection\ClassReflection $classReflection, string $methodName) : bool { foreach ($classReflection->getParents() as $parentClassReflections) { - if (! $parentClassReflections->hasMethod($methodName)) { + if (!$parentClassReflections->hasMethod($methodName)) { continue; } - $constructMethodReflection = $parentClassReflections->getNativeMethod($methodName); - if (! $constructMethodReflection instanceof PhpMethodReflection) { + if (!$constructMethodReflection instanceof \PHPStan\Reflection\Php\PhpMethodReflection) { continue; } - $methodDeclaringMethodClass = $constructMethodReflection->getDeclaringClass(); if ($methodDeclaringMethodClass->getName() === $parentClassReflections->getName()) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/FamilyTree/NodeAnalyzer/PropertyUsageAnalyzer.php b/packages/FamilyTree/NodeAnalyzer/PropertyUsageAnalyzer.php index add7a2a9a6c..bf285808769 100644 --- a/packages/FamilyTree/NodeAnalyzer/PropertyUsageAnalyzer.php +++ b/packages/FamilyTree/NodeAnalyzer/PropertyUsageAnalyzer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; $this->familyRelationsAnalyzer = $familyRelationsAnalyzer; $this->nodeRepository = $nodeRepository; } - - public function isPropertyFetchedInChildClass(Property $property): bool + public function isPropertyFetchedInChildClass(\PhpParser\Node\Stmt\Property $property) : bool { - $className = $property->getAttribute(AttributeKey::CLASS_NAME); + $className = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { - return false; + return \false; } - - $scope = $property->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - throw new ShouldNotHappenException(); + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - if ($classReflection->isClass() && $classReflection->isFinal()) { - return false; + return \false; } - $propertyName = $this->nodeNameResolver->getName($property); - $childrenClassReflections = $this->familyRelationsAnalyzer->getChildrenOfClassReflection($classReflection); - foreach ($childrenClassReflections as $childClassReflection) { $childClass = $this->nodeRepository->findClass($childClassReflection->getName()); - if (! $childClass instanceof Class_) { + if (!$childClass instanceof \PhpParser\Node\Stmt\Class_) { continue; } - - $isPropertyFetched = (bool) $this->betterNodeFinder->findFirst( - $childClass->stmts, - function (Node $node) use ($propertyName): bool { - return $this->nodeNameResolver->isLocalPropertyFetchNamed($node, $propertyName); - } - ); - + $isPropertyFetched = (bool) $this->betterNodeFinder->findFirst($childClass->stmts, function (\PhpParser\Node $node) use($propertyName) : bool { + return $this->nodeNameResolver->isLocalPropertyFetchNamed($node, $propertyName); + }); if ($isPropertyFetched) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/FamilyTree/Reflection/FamilyRelationsAnalyzer.php b/packages/FamilyTree/Reflection/FamilyRelationsAnalyzer.php index 9c3df2998ea..3e5d3b3a5ae 100644 --- a/packages/FamilyTree/Reflection/FamilyRelationsAnalyzer.php +++ b/packages/FamilyTree/Reflection/FamilyRelationsAnalyzer.php @@ -1,49 +1,40 @@ reflectionProvider = $reflectionProvider; $this->privatesAccessor = $privatesAccessor; } - /** * @return ClassReflection[] */ - public function getChildrenOfClassReflection(ClassReflection $desiredClassReflection): array + public function getChildrenOfClassReflection(\PHPStan\Reflection\ClassReflection $desiredClassReflection) : array { /** @var ClassReflection[] $classReflections */ $classReflections = $this->privatesAccessor->getPrivateProperty($this->reflectionProvider, 'classes'); - $childrenClassReflections = []; - foreach ($classReflections as $classReflection) { - if (! $classReflection->isSubclassOf($desiredClassReflection->getName())) { + if (!$classReflection->isSubclassOf($desiredClassReflection->getName())) { continue; } - $childrenClassReflections[] = $classReflection; } - return $childrenClassReflections; } } diff --git a/packages/FileFormatter/Contract/EditorConfig/EditorConfigParserInterface.php b/packages/FileFormatter/Contract/EditorConfig/EditorConfigParserInterface.php index 6d6f383bd45..15f77b0e40e 100644 --- a/packages/FileFormatter/Contract/EditorConfig/EditorConfigParserInterface.php +++ b/packages/FileFormatter/Contract/EditorConfig/EditorConfigParserInterface.php @@ -5,36 +5,27 @@ namespace Rector\FileFormatter\Contract\EditorConfig; use Rector\Core\ValueObject\Application\File; use Rector\FileFormatter\ValueObject\EditorConfigConfiguration; use Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder; - interface EditorConfigParserInterface { /** * @var string */ public const INDENT_STYLE = 'indent_style'; - /** * @var string */ public const INDENT_SIZE = 'indent_size'; - /** * @var string */ public const END_OF_LINE = 'end_of_line'; - /** * @var string */ public const INSERT_FINAL_NEWLINE = 'insert_final_newline'; - /** * @var string */ public const TAB_WIDTH = 'tab_width'; - - public function extractConfigurationForFile( - File $file, - EditorConfigConfigurationBuilder $editorConfigConfigurationBuilder - ): EditorConfigConfiguration; + public function extractConfigurationForFile(\Rector\Core\ValueObject\Application\File $file, \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder $editorConfigConfigurationBuilder) : \Rector\FileFormatter\ValueObject\EditorConfigConfiguration; } diff --git a/packages/FileFormatter/Contract/Formatter/FileFormatterInterface.php b/packages/FileFormatter/Contract/Formatter/FileFormatterInterface.php index 5e19cf9365e..d01498e03d2 100644 --- a/packages/FileFormatter/Contract/Formatter/FileFormatterInterface.php +++ b/packages/FileFormatter/Contract/Formatter/FileFormatterInterface.php @@ -5,12 +5,9 @@ namespace Rector\FileFormatter\Contract\Formatter; use Rector\Core\ValueObject\Application\File; use Rector\FileFormatter\ValueObject\EditorConfigConfiguration; use Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder; - interface FileFormatterInterface { - public function supports(File $file): bool; - - public function format(File $file, EditorConfigConfiguration $editorConfigConfiguration): void; - - public function createDefaultEditorConfigConfigurationBuilder(): EditorConfigConfigurationBuilder; + public function supports(\Rector\Core\ValueObject\Application\File $file) : bool; + public function format(\Rector\Core\ValueObject\Application\File $file, \Rector\FileFormatter\ValueObject\EditorConfigConfiguration $editorConfigConfiguration) : void; + public function createDefaultEditorConfigConfigurationBuilder() : \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder; } diff --git a/packages/FileFormatter/EditorConfig/EditorConfigIdiosyncraticParser.php b/packages/FileFormatter/EditorConfig/EditorConfigIdiosyncraticParser.php index 62c3b0e2558..4f7b6dc1b47 100644 --- a/packages/FileFormatter/EditorConfig/EditorConfigIdiosyncraticParser.php +++ b/packages/FileFormatter/EditorConfig/EditorConfigIdiosyncraticParser.php @@ -1,65 +1,49 @@ editorConfig = $editorConfig; } - - public function extractConfigurationForFile( - File $file, - EditorConfigConfigurationBuilder $editorConfigConfigurationBuilder - ): EditorConfigConfiguration { + public function extractConfigurationForFile(\Rector\Core\ValueObject\Application\File $file, \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder $editorConfigConfigurationBuilder) : \Rector\FileFormatter\ValueObject\EditorConfigConfiguration + { $smartFileInfo = $file->getSmartFileInfo(); $configuration = $this->editorConfig->getConfigForPath($smartFileInfo->getRealPath()); - - if (array_key_exists(self::INDENT_STYLE, $configuration)) { + if (\array_key_exists(self::INDENT_STYLE, $configuration)) { $indentStyle = (string) $configuration[self::INDENT_STYLE]->getValue(); - $editorConfigConfigurationBuilder->withIndentStyle($indentStyle); } - - if (array_key_exists(self::INDENT_SIZE, $configuration)) { + if (\array_key_exists(self::INDENT_SIZE, $configuration)) { $indentSize = (int) $configuration[self::INDENT_SIZE]->getValue(); - $editorConfigConfigurationBuilder->withIndentSize($indentSize); } - - if (array_key_exists(self::END_OF_LINE, $configuration)) { + if (\array_key_exists(self::END_OF_LINE, $configuration)) { $endOfLine = (string) $configuration[self::END_OF_LINE]->getValue(); - $editorConfigConfigurationBuilder->withEndOfLineFromEditorConfig($endOfLine); } - - if (array_key_exists(self::INSERT_FINAL_NEWLINE, $configuration)) { + if (\array_key_exists(self::INSERT_FINAL_NEWLINE, $configuration)) { $insertFinalNewline = (bool) $configuration[self::INSERT_FINAL_NEWLINE]->getValue(); - $editorConfigConfigurationBuilder->withInsertFinalNewline($insertFinalNewline); } - - if (array_key_exists(self::TAB_WIDTH, $configuration)) { + if (\array_key_exists(self::TAB_WIDTH, $configuration)) { $editorConfigConfigurationBuilder->withIndentSize($configuration[self::TAB_WIDTH]->getValue()); } - return $editorConfigConfigurationBuilder->build(); } } diff --git a/packages/FileFormatter/Exception/InvalidIndentSizeException.php b/packages/FileFormatter/Exception/InvalidIndentSizeException.php index d99e9d4d3a1..bd35f7a3f56 100644 --- a/packages/FileFormatter/Exception/InvalidIndentSizeException.php +++ b/packages/FileFormatter/Exception/InvalidIndentSizeException.php @@ -1,17 +1,17 @@ $allowedStyles + * @return $this */ - public static function fromStyleAndAllowedStyles(string $style, array $allowedStyles): self + public static function fromStyleAndAllowedStyles(string $style, array $allowedStyles) { - $message = sprintf('Given style "%s" is not allowed. Allowed are "%s"', $style, implode(' ', $allowedStyles)); - + $message = \sprintf('Given style "%s" is not allowed. Allowed are "%s"', $style, \implode(' ', $allowedStyles)); return new self($message); } } diff --git a/packages/FileFormatter/Exception/InvalidNewLineStringException.php b/packages/FileFormatter/Exception/InvalidNewLineStringException.php index 9936e7645f4..69038247a3d 100644 --- a/packages/FileFormatter/Exception/InvalidNewLineStringException.php +++ b/packages/FileFormatter/Exception/InvalidNewLineStringException.php @@ -1,19 +1,22 @@ editorConfigParser = $editorConfigParser; $this->fileFormatters = $fileFormatters; $this->parameterProvider = $parameterProvider; } - /** * @param File[] $files */ - public function format(array $files): void + public function format(array $files) : void { foreach ($files as $file) { - if (! $file->hasChanged()) { + if (!$file->hasChanged()) { continue; } - foreach ($this->fileFormatters as $fileFormatter) { - if (! $fileFormatter->supports($file)) { + if (!$fileFormatter->supports($file)) { continue; } - $editorConfigConfigurationBuilder = $fileFormatter->createDefaultEditorConfigConfigurationBuilder(); - $this->sniffOriginalFileContent($file, $editorConfigConfigurationBuilder); - $editorConfiguration = $this->createEditorConfiguration($file, $editorConfigConfigurationBuilder); - $fileFormatter->format($file, $editorConfiguration); } } } - - private function sniffOriginalFileContent( - File $file, - EditorConfigConfigurationBuilder $editorConfigConfigurationBuilder - ): void { + private function sniffOriginalFileContent(\Rector\Core\ValueObject\Application\File $file, \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder $editorConfigConfigurationBuilder) : void + { // Try to sniff into the original content to get the indentation and new line try { - $indent = Indent::fromContent($file->getOriginalFileContent()); + $indent = \Rector\FileFormatter\ValueObject\Indent::fromContent($file->getOriginalFileContent()); $editorConfigConfigurationBuilder->withIndent($indent); - } catch (ParseIndentException $parseIndentException) { + } catch (\Rector\FileFormatter\Exception\ParseIndentException $parseIndentException) { } - try { - $newLine = NewLine::fromContent($file->getOriginalFileContent()); + $newLine = \Rector\FileFormatter\ValueObject\NewLine::fromContent($file->getOriginalFileContent()); $editorConfigConfigurationBuilder->withNewLine($newLine); - } catch (InvalidNewLineStringException $invalidNewLineStringException) { + } catch (\Rector\FileFormatter\Exception\InvalidNewLineStringException $invalidNewLineStringException) { } } - - private function createEditorConfiguration( - File $file, - EditorConfigConfigurationBuilder $editorConfigConfigurationBuilder - ): EditorConfigConfiguration { - if (! $this->parameterProvider->provideBoolParameter(Option::ENABLE_EDITORCONFIG)) { + private function createEditorConfiguration(\Rector\Core\ValueObject\Application\File $file, \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder $editorConfigConfigurationBuilder) : \Rector\FileFormatter\ValueObject\EditorConfigConfiguration + { + if (!$this->parameterProvider->provideBoolParameter(\Rector\Core\Configuration\Option::ENABLE_EDITORCONFIG)) { return $editorConfigConfigurationBuilder->build(); } - return $this->editorConfigParser->extractConfigurationForFile($file, $editorConfigConfigurationBuilder); } } diff --git a/packages/FileFormatter/Formatter/JsonFileFormatter.php b/packages/FileFormatter/Formatter/JsonFileFormatter.php index 9bec24eed04..06dc27481ab 100644 --- a/packages/FileFormatter/Formatter/JsonFileFormatter.php +++ b/packages/FileFormatter/Formatter/JsonFileFormatter.php @@ -1,57 +1,42 @@ jsonPrinter = $jsonPrinter; } - - public function supports(File $file): bool + public function supports(\Rector\Core\ValueObject\Application\File $file) : bool { $smartFileInfo = $file->getSmartFileInfo(); - return $smartFileInfo->getExtension() === 'json'; } - - public function format(File $file, EditorConfigConfiguration $editorConfigConfiguration): void + public function format(\Rector\Core\ValueObject\Application\File $file, \Rector\FileFormatter\ValueObject\EditorConfigConfiguration $editorConfigConfiguration) : void { - $newFileContent = $this->jsonPrinter->print( - $file->getFileContent(), - $editorConfigConfiguration->getIndent(), - $editorConfigConfiguration->getNewLine() - ); - + $newFileContent = $this->jsonPrinter->print($file->getFileContent(), $editorConfigConfiguration->getIndent(), $editorConfigConfiguration->getNewLine()); $newFileContent .= $editorConfigConfiguration->getFinalNewline(); - $file->changeFileContent($newFileContent); } - - public function createDefaultEditorConfigConfigurationBuilder(): EditorConfigConfigurationBuilder + public function createDefaultEditorConfigConfigurationBuilder() : \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder { - $editorConfigConfigurationBuilder = EditorConfigConfigurationBuilder::anEditorConfigConfiguration(); - - $editorConfigConfigurationBuilder->withIndent(Indent::createSpaceWithSize(4)); - + $editorConfigConfigurationBuilder = \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder::anEditorConfigConfiguration(); + $editorConfigConfigurationBuilder->withIndent(\Rector\FileFormatter\ValueObject\Indent::createSpaceWithSize(4)); return $editorConfigConfigurationBuilder; } } diff --git a/packages/FileFormatter/Formatter/XmlFileFormatter.php b/packages/FileFormatter/Formatter/XmlFileFormatter.php index 272ef825956..50ebb0d2041 100644 --- a/packages/FileFormatter/Formatter/XmlFileFormatter.php +++ b/packages/FileFormatter/Formatter/XmlFileFormatter.php @@ -1,56 +1,44 @@ xmlFormatter = $xmlFormatter; } - - public function supports(File $file): bool + public function supports(\Rector\Core\ValueObject\Application\File $file) : bool { $smartFileInfo = $file->getSmartFileInfo(); - return $smartFileInfo->getExtension() === 'xml'; } - - public function format(File $file, EditorConfigConfiguration $editorConfigConfiguration): void + public function format(\Rector\Core\ValueObject\Application\File $file, \Rector\FileFormatter\ValueObject\EditorConfigConfiguration $editorConfigConfiguration) : void { $this->xmlFormatter->setIndentCharacter($editorConfigConfiguration->getIndentStyleCharacter()); $this->xmlFormatter->setIndentSize($editorConfigConfiguration->getIndentSize()); - $newFileContent = $this->xmlFormatter->format($file->getFileContent()); - $newFileContent .= $editorConfigConfiguration->getFinalNewline(); - $file->changeFileContent($newFileContent); } - - public function createDefaultEditorConfigConfigurationBuilder(): EditorConfigConfigurationBuilder + public function createDefaultEditorConfigConfigurationBuilder() : \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder { - $editorConfigConfigurationBuilder = EditorConfigConfigurationBuilder::anEditorConfigConfiguration(); - - $editorConfigConfigurationBuilder->withIndent(Indent::createTabWithSize(1)); - + $editorConfigConfigurationBuilder = \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder::anEditorConfigConfiguration(); + $editorConfigConfigurationBuilder->withIndent(\Rector\FileFormatter\ValueObject\Indent::createTabWithSize(1)); return $editorConfigConfigurationBuilder; } } diff --git a/packages/FileFormatter/Formatter/YamlFileFormatter.php b/packages/FileFormatter/Formatter/YamlFileFormatter.php index 7787d5960c3..68d330218ba 100644 --- a/packages/FileFormatter/Formatter/YamlFileFormatter.php +++ b/packages/FileFormatter/Formatter/YamlFileFormatter.php @@ -1,7 +1,6 @@ getSmartFileInfo(); - - return in_array($smartFileInfo->getExtension(), ['yaml', 'yml'], true); + return \in_array($smartFileInfo->getExtension(), ['yaml', 'yml'], \true); } - - public function format(File $file, EditorConfigConfiguration $editorConfigConfiguration): void + public function format(\Rector\Core\ValueObject\Application\File $file, \Rector\FileFormatter\ValueObject\EditorConfigConfiguration $editorConfigConfiguration) : void { - $yaml = Yaml::parse($file->getFileContent()); - - $newFileContent = Yaml::dump($yaml, 99, $editorConfigConfiguration->getIndentSize()); - + $yaml = \RectorPrefix20210509\Symfony\Component\Yaml\Yaml::parse($file->getFileContent()); + $newFileContent = \RectorPrefix20210509\Symfony\Component\Yaml\Yaml::dump($yaml, 99, $editorConfigConfiguration->getIndentSize()); $newFileContent .= $editorConfigConfiguration->getFinalNewline(); - $file->changeFileContent($newFileContent); } - - public function createDefaultEditorConfigConfigurationBuilder(): EditorConfigConfigurationBuilder + public function createDefaultEditorConfigConfigurationBuilder() : \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder { - $editorConfigConfigurationBuilder = EditorConfigConfigurationBuilder::anEditorConfigConfiguration(); - - $editorConfigConfigurationBuilder->withIndent(Indent::createSpaceWithSize(2)); - + $editorConfigConfigurationBuilder = \Rector\FileFormatter\ValueObjectFactory\EditorConfigConfigurationBuilder::anEditorConfigConfiguration(); + $editorConfigConfigurationBuilder->withIndent(\Rector\FileFormatter\ValueObject\Indent::createSpaceWithSize(2)); return $editorConfigConfigurationBuilder; } } diff --git a/packages/FileFormatter/ValueObject/EditorConfigConfiguration.php b/packages/FileFormatter/ValueObject/EditorConfigConfiguration.php index 1400a713960..922b81269cd 100644 --- a/packages/FileFormatter/ValueObject/EditorConfigConfiguration.php +++ b/packages/FileFormatter/ValueObject/EditorConfigConfiguration.php @@ -1,7 +1,6 @@ indent = $indent; $this->newLine = $newLine; $this->insertFinalNewline = $insertFinalNewline; } - - public function getNewLine(): string + public function getNewLine() : string { return $this->newLine->__toString(); } - - public function getFinalNewline(): string + public function getFinalNewline() : string { return $this->insertFinalNewline ? $this->getNewLine() : ''; } - - public function getIndent(): string + public function getIndent() : string { return $this->indent->__toString(); } - - public function getIndentStyleCharacter(): string + public function getIndentStyleCharacter() : string { return $this->indent->getIndentStyleCharacter(); } - - public function getIndentStyle(): string + public function getIndentStyle() : string { return $this->indent->getIndentStyle(); } - - public function getIndentSize(): int + public function getIndentSize() : int { return $this->indent->getIndentSize(); } diff --git a/packages/FileFormatter/ValueObject/Indent.php b/packages/FileFormatter/ValueObject/Indent.php index 42ec1b6fa29..a421a1cb586 100644 --- a/packages/FileFormatter/ValueObject/Indent.php +++ b/packages/FileFormatter/ValueObject/Indent.php @@ -1,15 +1,13 @@ ' ', - self::TAB => "\t", - ]; - + public const CHARACTERS = [self::SPACE => ' ', self::TAB => "\t"]; /** * @var string */ private const SPACE = 'space'; - /** * @var string */ private const TAB = 'tab'; - /** * @see https://regex101.com/r/A2XiaF/1 * @var string */ - private const VALID_INDENT_REGEX = '/^( *|\t+)$/'; - + private const VALID_INDENT_REGEX = '/^( *|\\t+)$/'; /** * @var int */ private const MINIMUM_SIZE = 1; - /** * @see https://regex101.com/r/3HFEjX/1 * @var string */ - private const PARSE_INDENT_REGEX = '/^(?P( +|\t+)).*/m'; - + private const PARSE_INDENT_REGEX = '/^(?P( +|\\t+)).*/m'; /** * @var string */ private $string; - private function __construct(string $string) { $this->string = $string; } - - public function __toString(): string + public function __toString() : string { return $this->string; } - - public static function fromString(string $string): self + /** + * @return $this + */ + public static function fromString(string $string) { - $validIndent = preg_match(self::VALID_INDENT_REGEX, $string); - + $validIndent = \preg_match(self::VALID_INDENT_REGEX, $string); if ($validIndent !== 1) { - throw InvalidIndentStringException::fromString($string); + throw \Rector\FileFormatter\Exception\InvalidIndentStringException::fromString($string); } - return new self($string); } - - public static function createSpaceWithSize(int $size): self + /** + * @return $this + */ + public static function createSpaceWithSize(int $size) { return self::fromSizeAndStyle($size, self::SPACE); } - - public static function createTabWithSize(int $size): self + /** + * @return $this + */ + public static function createTabWithSize(int $size) { return self::fromSizeAndStyle($size, self::TAB); } - - public static function fromSizeAndStyle(int $size, string $style): self + /** + * @return $this + */ + public static function fromSizeAndStyle(int $size, string $style) { if ($size < self::MINIMUM_SIZE) { - throw InvalidIndentSizeException::fromSizeAndMinimumSize($size, self::MINIMUM_SIZE); + throw \Rector\FileFormatter\Exception\InvalidIndentSizeException::fromSizeAndMinimumSize($size, self::MINIMUM_SIZE); } - - if (! array_key_exists($style, self::CHARACTERS)) { - throw InvalidIndentStyleException::fromStyleAndAllowedStyles($style, array_keys(self::CHARACTERS)); + if (!\array_key_exists($style, self::CHARACTERS)) { + throw \Rector\FileFormatter\Exception\InvalidIndentStyleException::fromStyleAndAllowedStyles($style, \array_keys(self::CHARACTERS)); } - - $value = str_repeat(self::CHARACTERS[$style], $size); - + $value = \str_repeat(self::CHARACTERS[$style], $size); return new self($value); } - - public static function fromContent(string $string): self + /** + * @return $this + */ + public static function fromContent(string $string) { - $validIndent = preg_match(self::PARSE_INDENT_REGEX, $string, $match); + $validIndent = \preg_match(self::PARSE_INDENT_REGEX, $string, $match); if ($validIndent === 1) { return self::fromString($match['indent']); } - - throw ParseIndentException::fromString($string); + throw \Rector\FileFormatter\Exception\ParseIndentException::fromString($string); } - - public function getIndentSize(): int + public function getIndentSize() : int { - return strlen($this->string); + return \strlen($this->string); } - - public function getIndentStyle(): string + public function getIndentStyle() : string { return $this->startsWithSpace() ? self::SPACE : self::TAB; } - - public function getIndentStyleCharacter(): string + public function getIndentStyleCharacter() : string { return $this->startsWithSpace() ? self::CHARACTERS[self::SPACE] : self::CHARACTERS[self::TAB]; } - - private function startsWithSpace(): bool + private function startsWithSpace() : bool { - return Strings::startsWith($this->string, ' '); + return \RectorPrefix20210509\Nette\Utils\Strings::startsWith($this->string, ' '); } } diff --git a/packages/FileFormatter/ValueObject/NewLine.php b/packages/FileFormatter/ValueObject/NewLine.php index 25c1efe5f6c..31dee1c4de2 100644 --- a/packages/FileFormatter/ValueObject/NewLine.php +++ b/packages/FileFormatter/ValueObject/NewLine.php @@ -1,12 +1,10 @@ */ - private const ALLOWED_END_OF_LINE = [ - self::LINE_FEED => "\n", - self::CARRIAGE_RETURN => "\r", - self::CARRIAGE_RETURN_LINE_FEED => "\r\n", - ]; - + private const ALLOWED_END_OF_LINE = [self::LINE_FEED => "\n", self::CARRIAGE_RETURN => "\r", self::CARRIAGE_RETURN_LINE_FEED => "\r\n"]; /** * @var string */ private $string; - private function __construct(string $string) { $this->string = $string; } - - public function __toString(): string + public function __toString() : string { return $this->string; } - - public static function fromSingleCharacter(string $string): self + /** + * @return $this + */ + public static function fromSingleCharacter(string $string) { - $validNewLineRegularExpression = '/^(?>\r\n|\n|\r)$/'; - $validNewLine = preg_match($validNewLineRegularExpression, $string); - + $validNewLineRegularExpression = '/^(?>\\r\\n|\\n|\\r)$/'; + $validNewLine = \preg_match($validNewLineRegularExpression, $string); if ($validNewLine !== 1) { - throw InvalidNewLineStringException::fromString($string); + throw \Rector\FileFormatter\Exception\InvalidNewLineStringException::fromString($string); } - return new self($string); } - - public static function fromContent(string $string): self + /** + * @return $this + */ + public static function fromContent(string $string) { - $validNewLineRegularExpression = '/(?P\r\n|\n|\r)/'; - $validNewLine = preg_match($validNewLineRegularExpression, $string, $match); + $validNewLineRegularExpression = '/(?P\\r\\n|\\n|\\r)/'; + $validNewLine = \preg_match($validNewLineRegularExpression, $string, $match); if ($validNewLine === 1) { return self::fromSingleCharacter($match['newLine']); } - - return self::fromSingleCharacter(PHP_EOL); + return self::fromSingleCharacter(\PHP_EOL); } - - public static function fromEditorConfig(string $endOfLine): self + /** + * @return $this + */ + public static function fromEditorConfig(string $endOfLine) { - if (! array_key_exists($endOfLine, self::ALLOWED_END_OF_LINE)) { - $allowedEndOfLineValues = array_keys(self::ALLOWED_END_OF_LINE); - $message = sprintf( - 'The endOfLine "%s" is not allowed. Allowed are "%s"', - $endOfLine, - implode(',', $allowedEndOfLineValues) - ); - throw InvalidNewLineStringException::create($message); + if (!\array_key_exists($endOfLine, self::ALLOWED_END_OF_LINE)) { + $allowedEndOfLineValues = \array_keys(self::ALLOWED_END_OF_LINE); + $message = \sprintf('The endOfLine "%s" is not allowed. Allowed are "%s"', $endOfLine, \implode(',', $allowedEndOfLineValues)); + throw \Rector\FileFormatter\Exception\InvalidNewLineStringException::create($message); } - return self::fromSingleCharacter(self::ALLOWED_END_OF_LINE[$endOfLine]); } } diff --git a/packages/FileFormatter/ValueObjectFactory/EditorConfigConfigurationBuilder.php b/packages/FileFormatter/ValueObjectFactory/EditorConfigConfigurationBuilder.php index d1c75195f0b..95bcdfee33d 100644 --- a/packages/FileFormatter/ValueObjectFactory/EditorConfigConfigurationBuilder.php +++ b/packages/FileFormatter/ValueObjectFactory/EditorConfigConfigurationBuilder.php @@ -1,99 +1,95 @@ indentStyle = 'space'; $this->indentSize = 2; - $this->newLine = NewLine::fromEditorConfig('lf'); - $this->insertFinalNewline = true; + $this->newLine = \Rector\FileFormatter\ValueObject\NewLine::fromEditorConfig('lf'); + $this->insertFinalNewline = \true; } - - public static function anEditorConfigConfiguration(): self + /** + * @return $this + */ + public static function anEditorConfigConfiguration() { return new self(); } - - public function withNewLine(NewLine $newLine): self + /** + * @return $this + */ + public function withNewLine(\Rector\FileFormatter\ValueObject\NewLine $newLine) { $this->newLine = $newLine; - return $this; } - - public function withIndent(Indent $indent): self + /** + * @return $this + */ + public function withIndent(\Rector\FileFormatter\ValueObject\Indent $indent) { $this->indentSize = $indent->getIndentSize(); $this->indentStyle = $indent->getIndentStyle(); - return $this; } - - public function withIndentStyle(string $indentStyle): self + /** + * @return $this + */ + public function withIndentStyle(string $indentStyle) { $this->indentStyle = $indentStyle; - return $this; } - - public function withIndentSize(int $indentSize): self + /** + * @return $this + */ + public function withIndentSize(int $indentSize) { $this->indentSize = $indentSize; - return $this; } - - public function withInsertFinalNewline(bool $insertFinalNewline): self + /** + * @return $this + */ + public function withInsertFinalNewline(bool $insertFinalNewline) { $this->insertFinalNewline = $insertFinalNewline; - return $this; } - - public function withEndOfLineFromEditorConfig(string $endOfLine): self + /** + * @return $this + */ + public function withEndOfLineFromEditorConfig(string $endOfLine) { - $this->newLine = NewLine::fromEditorConfig($endOfLine); - + $this->newLine = \Rector\FileFormatter\ValueObject\NewLine::fromEditorConfig($endOfLine); return $this; } - - public function build(): EditorConfigConfiguration + public function build() : \Rector\FileFormatter\ValueObject\EditorConfigConfiguration { $newLine = $this->newLine; - - return new EditorConfigConfiguration( - Indent::fromSizeAndStyle($this->indentSize, $this->indentStyle), - $newLine, - $this->insertFinalNewline - ); + return new \Rector\FileFormatter\ValueObject\EditorConfigConfiguration(\Rector\FileFormatter\ValueObject\Indent::fromSizeAndStyle($this->indentSize, $this->indentStyle), $newLine, $this->insertFinalNewline); } } diff --git a/packages/FileSystemRector/Contract/AddedFileInterface.php b/packages/FileSystemRector/Contract/AddedFileInterface.php index 01f7ed5f174..7802beaee1b 100644 --- a/packages/FileSystemRector/Contract/AddedFileInterface.php +++ b/packages/FileSystemRector/Contract/AddedFileInterface.php @@ -1,10 +1,9 @@ parser = $parser; $this->nodeScopeAndMetadataDecorator = $nodeScopeAndMetadataDecorator; } - /** * @return Node[] */ - public function parseFileInfoToNodesAndDecorate(SmartFileInfo $smartFileInfo): array + public function parseFileInfoToNodesAndDecorate(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : array { $oldStmts = $this->parser->parseFileInfo($smartFileInfo); - $file = new File($smartFileInfo, $smartFileInfo->getContents()); - + $file = new \Rector\Core\ValueObject\Application\File($smartFileInfo, $smartFileInfo->getContents()); return $this->nodeScopeAndMetadataDecorator->decorateNodesFromFile($file, $oldStmts, $smartFileInfo); } } diff --git a/packages/FileSystemRector/ValueObject/AddedFileWithContent.php b/packages/FileSystemRector/ValueObject/AddedFileWithContent.php index f90505b3cdb..269cc0f6fa7 100644 --- a/packages/FileSystemRector/ValueObject/AddedFileWithContent.php +++ b/packages/FileSystemRector/ValueObject/AddedFileWithContent.php @@ -1,40 +1,33 @@ filePath = $filePath; $this->fileContent = $fileContent; } - - public function getFilePath(): string + public function getFilePath() : string { return $this->filePath; } - - public function getFileContent(): string + public function getFileContent() : string { return $this->fileContent; } diff --git a/packages/FileSystemRector/ValueObject/AddedFileWithNodes.php b/packages/FileSystemRector/ValueObject/AddedFileWithNodes.php index 46ea21006ec..dac33c9abfd 100644 --- a/packages/FileSystemRector/ValueObject/AddedFileWithNodes.php +++ b/packages/FileSystemRector/ValueObject/AddedFileWithNodes.php @@ -1,25 +1,21 @@ filePath = $filePath; $this->nodes = $nodes; } - - public function getFilePath(): string + public function getFilePath() : string { return $this->filePath; } - /** * @return Node[] */ - public function getNodes(): array + public function getNodes() : array { return $this->nodes; } diff --git a/packages/FileSystemRector/ValueObjectFactory/AddedFileWithNodesFactory.php b/packages/FileSystemRector/ValueObjectFactory/AddedFileWithNodesFactory.php index fad1ba4d4ba..9d3a1c8f158 100644 --- a/packages/FileSystemRector/ValueObjectFactory/AddedFileWithNodesFactory.php +++ b/packages/FileSystemRector/ValueObjectFactory/AddedFileWithNodesFactory.php @@ -1,10 +1,9 @@ betterNodeFinder = $betterNodeFinder; $this->fileRelocationResolver = $fileRelocationResolver; $this->categoryNamespaceProvider = $categoryNamespaceProvider; $this->renamedClassesCollector = $renamedClassesCollector; $this->fileInfoDeletionAnalyzer = $fileInfoDeletionAnalyzer; } - - public function createWithDesiredGroup( - SmartFileInfo $oldFileInfo, - File $file, - string $desiredGroupName - ): ?AddedFileWithNodes { + public function createWithDesiredGroup(\Symplify\SmartFileSystem\SmartFileInfo $oldFileInfo, \Rector\Core\ValueObject\Application\File $file, string $desiredGroupName) : ?\Rector\FileSystemRector\ValueObject\AddedFileWithNodes + { $fileNodes = $file->getNewStmts(); - - $currentNamespace = $this->betterNodeFinder->findFirstInstanceOf($fileNodes, Namespace_::class); - + $currentNamespace = $this->betterNodeFinder->findFirstInstanceOf($fileNodes, \PhpParser\Node\Stmt\Namespace_::class); // file without namespace → skip - if (! $currentNamespace instanceof Namespace_) { + if (!$currentNamespace instanceof \PhpParser\Node\Stmt\Namespace_) { return null; } - if ($currentNamespace->name === null) { return null; } - // is already in the right group $currentNamespaceName = $currentNamespace->name->toString(); - if (Strings::endsWith($currentNamespaceName, '\\' . $desiredGroupName)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($currentNamespaceName, '\\' . $desiredGroupName)) { return null; } - - $oldClassName = $currentNamespaceName . '\\' . $this->fileInfoDeletionAnalyzer->clearNameFromTestingPrefix( - $oldFileInfo->getBasenameWithoutSuffix() - ); - + $oldClassName = $currentNamespaceName . '\\' . $this->fileInfoDeletionAnalyzer->clearNameFromTestingPrefix($oldFileInfo->getBasenameWithoutSuffix()); // change namespace to new one $newNamespaceName = $this->createNewNamespaceName($desiredGroupName, $currentNamespace); $newClassName = $this->createNewClassName($oldFileInfo, $newNamespaceName); - // classes are identical, no rename if ($oldClassName === $newClassName) { return null; } - - if (Strings::match($oldClassName, '#\b' . $desiredGroupName . '\b#')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($oldClassName, '#\\b' . $desiredGroupName . '\\b#')) { return null; } - // 1. rename namespace $this->renameNamespace($file->getNewStmts(), $newNamespaceName); - // 2. return changed nodes and new file destination - $newFileDestination = $this->fileRelocationResolver->createNewFileDestination( - $oldFileInfo, - $desiredGroupName, - $this->categoryNamespaceProvider->provide() - ); - + $newFileDestination = $this->fileRelocationResolver->createNewFileDestination($oldFileInfo, $desiredGroupName, $this->categoryNamespaceProvider->provide()); // 3. update fully qualifed name of the class like - will be used further - $classLike = $this->betterNodeFinder->findFirstInstanceOf($fileNodes, ClassLike::class); - if (! $classLike instanceof ClassLike) { + $classLike = $this->betterNodeFinder->findFirstInstanceOf($fileNodes, \PhpParser\Node\Stmt\ClassLike::class); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { return null; } - // clone to prevent deep override $classLike = clone $classLike; - $classLike->namespacedName = new FullyQualified($newClassName); - + $classLike->namespacedName = new \PhpParser\Node\Name\FullyQualified($newClassName); $this->renamedClassesCollector->addClassRename($oldClassName, $newClassName); - - return new AddedFileWithNodes($newFileDestination, $fileNodes); + return new \Rector\FileSystemRector\ValueObject\AddedFileWithNodes($newFileDestination, $fileNodes); } - - private function createNewNamespaceName(string $desiredGroupName, Namespace_ $currentNamespace): string + private function createNewNamespaceName(string $desiredGroupName, \PhpParser\Node\Stmt\Namespace_ $currentNamespace) : string { - return $this->fileRelocationResolver->resolveNewNamespaceName( - $currentNamespace, - $desiredGroupName, - $this->categoryNamespaceProvider->provide() - ); + return $this->fileRelocationResolver->resolveNewNamespaceName($currentNamespace, $desiredGroupName, $this->categoryNamespaceProvider->provide()); } - - private function createNewClassName(SmartFileInfo $smartFileInfo, string $newNamespaceName): string + private function createNewClassName(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo, string $newNamespaceName) : string { - $basename = $this->fileInfoDeletionAnalyzer->clearNameFromTestingPrefix( - $smartFileInfo->getBasenameWithoutSuffix() - ); + $basename = $this->fileInfoDeletionAnalyzer->clearNameFromTestingPrefix($smartFileInfo->getBasenameWithoutSuffix()); return $newNamespaceName . '\\' . $basename; } - /** * @param Node[] $nodes */ - private function renameNamespace(array $nodes, string $newNamespaceName): void + private function renameNamespace(array $nodes, string $newNamespaceName) : void { foreach ($nodes as $node) { - if (! $node instanceof Namespace_) { + if (!$node instanceof \PhpParser\Node\Stmt\Namespace_) { continue; } - - $node->name = new Name($newNamespaceName); + $node->name = new \PhpParser\Node\Name($newNamespaceName); } } } diff --git a/packages/NodeCollector/NodeAnalyzer/ArrayCallableMethodReferenceAnalyzer.php b/packages/NodeCollector/NodeAnalyzer/ArrayCallableMethodReferenceAnalyzer.php index 47aed0db03a..5cf3bec61c4 100644 --- a/packages/NodeCollector/NodeAnalyzer/ArrayCallableMethodReferenceAnalyzer.php +++ b/packages/NodeCollector/NodeAnalyzer/ArrayCallableMethodReferenceAnalyzer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; } - /** * Matches array like: "[$this, 'methodName']" → ['ClassName', 'methodName'] */ - public function match(Array_ $array): ?ArrayCallable + public function match(\PhpParser\Node\Expr\Array_ $array) : ?\Rector\NodeCollector\ValueObject\ArrayCallable { $arrayItems = $array->items; - if (count($arrayItems) !== 2) { + if (\count($arrayItems) !== 2) { return null; } - if ($array->items[0] === null) { return null; } - if ($array->items[1] === null) { return null; } - // $this, self, static, FQN - if (! $this->isThisVariable($array->items[0]->value)) { + if (!$this->isThisVariable($array->items[0]->value)) { return null; } - - if (! $array->items[1]->value instanceof String_) { + if (!$array->items[1]->value instanceof \PhpParser\Node\Scalar\String_) { return null; } - /** @var String_ $string */ $string = $array->items[1]->value; - $methodName = $string->value; - $className = $array->getAttribute(AttributeKey::CLASS_NAME); - + $className = $array->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { return null; } - - return new ArrayCallable($className, $methodName); + return new \Rector\NodeCollector\ValueObject\ArrayCallable($className, $methodName); } - - private function isThisVariable(Expr $expr): bool + private function isThisVariable(\PhpParser\Node\Expr $expr) : bool { // $this - if ($expr instanceof Variable && $this->nodeNameResolver->isName($expr, 'this')) { - return true; + if ($expr instanceof \PhpParser\Node\Expr\Variable && $this->nodeNameResolver->isName($expr, 'this')) { + return \true; } - - if ($expr instanceof ClassConstFetch) { - if (! $this->nodeNameResolver->isName($expr->name, 'class')) { - return false; + if ($expr instanceof \PhpParser\Node\Expr\ClassConstFetch) { + if (!$this->nodeNameResolver->isName($expr->name, 'class')) { + return \false; } - // self::class, static::class if ($this->nodeNameResolver->isNames($expr->class, ['self', 'static'])) { - return true; + return \true; } - /** @var string|null $className */ - $className = $expr->getAttribute(AttributeKey::CLASS_NAME); - + $className = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { - return false; + return \false; } - return $this->nodeNameResolver->isName($expr->class, $className); } - - return false; + return \false; } } diff --git a/packages/NodeCollector/NodeAnalyzer/BooleanAndAnalyzer.php b/packages/NodeCollector/NodeAnalyzer/BooleanAndAnalyzer.php index f86d1d83aa4..c12bd02745f 100644 --- a/packages/NodeCollector/NodeAnalyzer/BooleanAndAnalyzer.php +++ b/packages/NodeCollector/NodeAnalyzer/BooleanAndAnalyzer.php @@ -1,32 +1,28 @@ right; $booleanAnd = $booleanAnd->left; - - if (! $booleanAnd instanceof BooleanAnd) { + if (!$booleanAnd instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { $conditions[] = $booleanAnd; break; } } - - krsort($conditions); + \krsort($conditions); return $conditions; } } diff --git a/packages/NodeCollector/NodeCollector/NodeRepository.php b/packages/NodeCollector/NodeCollector/NodeRepository.php index aede5d9e45a..6ac2fed0a6f 100644 --- a/packages/NodeCollector/NodeCollector/NodeRepository.php +++ b/packages/NodeCollector/NodeCollector/NodeRepository.php @@ -1,11 +1,10 @@ */ private $classMethodsByType = []; - /** * @var array */ private $functionsByName = []; - /** * @var array>> */ private $callsByTypeAndMethod = []; - /** * E.g. [$this, 'someLocalMethod'] * * @var array> */ private $arrayCallablesByTypeAndMethod = []; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var NodeTypeResolver */ private $nodeTypeResolver; - /** * @var ArrayCallableMethodReferenceAnalyzer */ private $arrayCallableMethodReferenceAnalyzer; - /** * @var ParsedPropertyFetchNodeCollector */ private $parsedPropertyFetchNodeCollector; - /** * @var ParsedNodeCollector */ private $parsedNodeCollector; - /** * @var TypeUnwrapper */ private $typeUnwrapper; - /** * @var array */ private $attributes = []; - /** * @var ReflectionProvider */ private $reflectionProvider; - - public function __construct( - ArrayCallableMethodReferenceAnalyzer $arrayCallableMethodReferenceAnalyzer, - ParsedPropertyFetchNodeCollector $parsedPropertyFetchNodeCollector, - NodeNameResolver $nodeNameResolver, - ParsedNodeCollector $parsedNodeCollector, - TypeUnwrapper $typeUnwrapper, - ReflectionProvider $reflectionProvider, - NodeTypeResolver $nodeTypeResolver - ) { + public function __construct(\Rector\NodeCollector\NodeAnalyzer\ArrayCallableMethodReferenceAnalyzer $arrayCallableMethodReferenceAnalyzer, \Rector\NodeCollector\NodeCollector\ParsedPropertyFetchNodeCollector $parsedPropertyFetchNodeCollector, \Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\NodeCollector\NodeCollector\ParsedNodeCollector $parsedNodeCollector, \Rector\PHPStanStaticTypeMapper\Utils\TypeUnwrapper $typeUnwrapper, \PHPStan\Reflection\ReflectionProvider $reflectionProvider, \Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver) + { $this->nodeNameResolver = $nodeNameResolver; $this->arrayCallableMethodReferenceAnalyzer = $arrayCallableMethodReferenceAnalyzer; $this->parsedPropertyFetchNodeCollector = $parsedPropertyFetchNodeCollector; @@ -127,224 +106,183 @@ final class NodeRepository $this->reflectionProvider = $reflectionProvider; $this->nodeTypeResolver = $nodeTypeResolver; } - - public function collect(Node $node): void + public function collect(\PhpParser\Node $node) : void { - if ($node instanceof ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { $this->addMethod($node); return; } - // array callable - [$this, 'someCall'] - if ($node instanceof Array_) { + if ($node instanceof \PhpParser\Node\Expr\Array_) { $this->collectArray($node); return; } - - if ($node instanceof MethodCall || $node instanceof StaticCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall || $node instanceof \PhpParser\Node\Expr\StaticCall) { $this->addCall($node); } - - if ($node instanceof Function_) { + if ($node instanceof \PhpParser\Node\Stmt\Function_) { $functionName = $this->nodeNameResolver->getName($node); $this->functionsByName[$functionName] = $node; } - - if ($node instanceof Attribute) { + if ($node instanceof \PhpParser\Node\Attribute) { $attributeClass = $this->nodeNameResolver->getName($node->name); $this->attributes[$attributeClass][] = $node; } } - - public function findFunction(string $name): ?Function_ + public function findFunction(string $name) : ?\PhpParser\Node\Stmt\Function_ { return $this->functionsByName[$name] ?? null; } - /** * @return array */ - public function findMethodCallsOnClass(string $className): array + public function findMethodCallsOnClass(string $className) : array { return $this->callsByTypeAndMethod[$className] ?? []; } - /** * @return StaticCall[] */ - public function findStaticCallsByClassMethod(ClassMethod $classMethod): array + public function findStaticCallsByClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $calls = $this->findCallsByClassMethod($classMethod); - return array_filter($calls, function (Node $node): bool { - return $node instanceof StaticCall; + return \array_filter($calls, function (\PhpParser\Node $node) : bool { + return $node instanceof \PhpParser\Node\Expr\StaticCall; }); } - - public function findClassMethodByStaticCall(StaticCall $staticCall): ?ClassMethod + public function findClassMethodByStaticCall(\PhpParser\Node\Expr\StaticCall $staticCall) : ?\PhpParser\Node\Stmt\ClassMethod { $method = $this->nodeNameResolver->getName($staticCall->name); if ($method === null) { return null; } - $objectType = $this->nodeTypeResolver->resolve($staticCall->class); - $classes = TypeUtils::getDirectClassNames($objectType); - + $classes = \PHPStan\Type\TypeUtils::getDirectClassNames($objectType); foreach ($classes as $class) { $possibleClassMethod = $this->findClassMethod($class, $method); if ($possibleClassMethod !== null) { return $possibleClassMethod; } } - return null; } - - public function findClassMethod(string $className, string $methodName): ?ClassMethod + public function findClassMethod(string $className, string $methodName) : ?\PhpParser\Node\Stmt\ClassMethod { - if (Strings::contains($methodName, '\\')) { - $message = sprintf('Class and method arguments are switched in "%s"', __METHOD__); - throw new ShouldNotHappenException($message); + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($methodName, '\\')) { + $message = \sprintf('Class and method arguments are switched in "%s"', __METHOD__); + throw new \Rector\Core\Exception\ShouldNotHappenException($message); } - if (isset($this->classMethodsByType[$className][$methodName])) { return $this->classMethodsByType[$className][$methodName]; } - - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return null; } - $classReflection = $this->reflectionProvider->getClass($className); foreach ($classReflection->getParents() as $parentClassReflection) { if (isset($this->classMethodsByType[$parentClassReflection->getName()][$methodName])) { return $this->classMethodsByType[$parentClassReflection->getName()][$methodName]; } } - return null; } - /** * @return MethodCall[] */ - public function getMethodsCalls(): array + public function getMethodsCalls() : array { - $calls = Arrays::flatten($this->callsByTypeAndMethod); - - return array_filter($calls, function (Node $node): bool { - return $node instanceof MethodCall; + $calls = \RectorPrefix20210509\Nette\Utils\Arrays::flatten($this->callsByTypeAndMethod); + return \array_filter($calls, function (\PhpParser\Node $node) : bool { + return $node instanceof \PhpParser\Node\Expr\MethodCall; }); } - /** * @param MethodReflection|ReflectionMethod $methodReflection */ - public function findClassMethodByMethodReflection(object $methodReflection): ?ClassMethod + public function findClassMethodByMethodReflection($methodReflection) : ?\PhpParser\Node\Stmt\ClassMethod { $methodName = $methodReflection->getName(); - $declaringClass = $methodReflection->getDeclaringClass(); $className = $declaringClass->getName(); - return $this->findClassMethod($className, $methodName); } - /** * @return PropertyFetch[] */ - public function findPropertyFetchesByProperty(Property $property): array + public function findPropertyFetchesByProperty(\PhpParser\Node\Stmt\Property $property) : array { /** @var string|null $className */ - $className = $property->getAttribute(AttributeKey::CLASS_NAME); + $className = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { return []; } - $propertyName = $this->nodeNameResolver->getName($property); return $this->parsedPropertyFetchNodeCollector->findPropertyFetchesByTypeAndName($className, $propertyName); } - /** * @return PropertyFetch[] */ - public function findPropertyFetchesByPropertyFetch(PropertyFetch $propertyFetch): array + public function findPropertyFetchesByPropertyFetch(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : array { $propertyFetcheeType = $this->nodeTypeResolver->getStaticType($propertyFetch->var); - if (! $propertyFetcheeType instanceof TypeWithClassName) { + if (!$propertyFetcheeType instanceof \PHPStan\Type\TypeWithClassName) { return []; } - $className = $this->nodeTypeResolver->getFullyQualifiedClassName($propertyFetcheeType); - /** @var string $propertyName */ $propertyName = $this->nodeNameResolver->getName($propertyFetch); - return $this->parsedPropertyFetchNodeCollector->findPropertyFetchesByTypeAndName($className, $propertyName); } - /** * @return MethodCall[]|StaticCall[]|ArrayCallable[] */ - public function findCallsByClassMethod(ClassMethod $classMethod): array + public function findCallsByClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { - $class = $classMethod->getAttribute(AttributeKey::CLASS_NAME); - if (! is_string($class)) { - throw new ShouldNotHappenException(); + $class = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + if (!\is_string($class)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $methodName = $this->nodeNameResolver->getName($classMethod); return $this->findCallsByClassAndMethod($class, $methodName); } - - public function hasClassChildren(Class_ $desiredClass): bool + public function hasClassChildren(\PhpParser\Node\Stmt\Class_ $desiredClass) : bool { - $desiredClassName = $desiredClass->getAttribute(AttributeKey::CLASS_NAME); + $desiredClassName = $desiredClass->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($desiredClassName === null) { - return false; + return \false; } - foreach ($this->parsedNodeCollector->getClasses() as $classNode) { - $currentClassName = $classNode->getAttribute(AttributeKey::CLASS_NAME); + $currentClassName = $classNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($currentClassName === null) { continue; } - - if (! $this->isChildOrEqualClassLike($desiredClassName, $currentClassName)) { + if (!$this->isChildOrEqualClassLike($desiredClassName, $currentClassName)) { continue; } - - return true; + return \true; } - - return false; + return \false; } - /** * @return Class_[] */ - public function findClassesBySuffix(string $suffix): array + public function findClassesBySuffix(string $suffix) : array { $classNodes = []; - foreach ($this->parsedNodeCollector->getClasses() as $className => $classNode) { - if (! Strings::endsWith($className, $suffix)) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::endsWith($className, $suffix)) { continue; } - $classNodes[] = $classNode; } - return $classNodes; } - /** * @return Trait_[] */ - public function findUsedTraitsInClass(ClassLike $classLike): array + public function findUsedTraitsInClass(\PhpParser\Node\Stmt\ClassLike $classLike) : array { $traits = []; - foreach ($classLike->getTraitUses() as $traitUse) { foreach ($traitUse->traits as $trait) { $traitName = $this->nodeNameResolver->getName($trait); @@ -354,324 +292,259 @@ final class NodeRepository } } } - return $traits; } - /** * @return Class_[]|Interface_[] */ - public function findClassesAndInterfacesByType(string $type): array + public function findClassesAndInterfacesByType(string $type) : array { - return array_merge($this->findChildrenOfClass($type), $this->findImplementersOfInterface($type)); + return \array_merge($this->findChildrenOfClass($type), $this->findImplementersOfInterface($type)); } - /** * @return Class_[] */ - public function findChildrenOfClass(string $class): array + public function findChildrenOfClass(string $class) : array { $childrenClasses = []; - foreach ($this->parsedNodeCollector->getClasses() as $classNode) { - $currentClassName = $classNode->getAttribute(AttributeKey::CLASS_NAME); - if (! $this->isChildOrEqualClassLike($class, $currentClassName)) { + $currentClassName = $classNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + if (!$this->isChildOrEqualClassLike($class, $currentClassName)) { continue; } - $childrenClasses[] = $classNode; } - return $childrenClasses; } - - public function findInterface(string $class): ?Interface_ + public function findInterface(string $class) : ?\PhpParser\Node\Stmt\Interface_ { return $this->parsedNodeCollector->findInterface($class); } - - public function findClass(string $name): ?Class_ + public function findClass(string $name) : ?\PhpParser\Node\Stmt\Class_ { return $this->parsedNodeCollector->findClass($name); } - - public function findClassMethodByMethodCall(MethodCall $methodCall): ?ClassMethod + public function findClassMethodByMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node\Stmt\ClassMethod { $className = $this->resolveCallerClassName($methodCall); if ($className === null) { return null; } - $methodName = $this->nodeNameResolver->getName($methodCall->name); if ($methodName === null) { return null; } - return $this->findClassMethod($className, $methodName); } - - public function findClassConstByClassConstFetch(ClassConstFetch $classConstFetch): ?ClassConst + public function findClassConstByClassConstFetch(\PhpParser\Node\Expr\ClassConstFetch $classConstFetch) : ?\PhpParser\Node\Stmt\ClassConst { return $this->parsedNodeCollector->findClassConstByClassConstFetch($classConstFetch); } - /** * @return Attribute[] */ - public function findAttributes(string $class): array + public function findAttributes(string $class) : array { return $this->attributes[$class] ?? []; } - /** * @param PropertyFetch|StaticPropertyFetch $expr */ - public function findPropertyByPropertyFetch(Expr $expr): ?Property + public function findPropertyByPropertyFetch(\PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Stmt\Property { - $propertyCaller = $expr instanceof StaticPropertyFetch ? $expr->class : $expr->var; - + $propertyCaller = $expr instanceof \PhpParser\Node\Expr\StaticPropertyFetch ? $expr->class : $expr->var; $propertyCallerType = $this->nodeTypeResolver->getStaticType($propertyCaller); - if (! $propertyCallerType instanceof TypeWithClassName) { + if (!$propertyCallerType instanceof \PHPStan\Type\TypeWithClassName) { return null; } - $className = $this->nodeTypeResolver->getFullyQualifiedClassName($propertyCallerType); $class = $this->findClass($className); - if (! $class instanceof Class_) { + if (!$class instanceof \PhpParser\Node\Stmt\Class_) { return null; } - $propertyName = $this->nodeNameResolver->getName($expr->name); if ($propertyName === null) { return null; } - return $class->getProperty($propertyName); } - /** * @return Class_[] */ - public function getClasses(): array + public function getClasses() : array { return $this->parsedNodeCollector->getClasses(); } - - public function findClassConstant(string $className, string $constantName): ?ClassConst + public function findClassConstant(string $className, string $constantName) : ?\PhpParser\Node\Stmt\ClassConst { return $this->parsedNodeCollector->findClassConstant($className, $constantName); } - - public function findTrait(string $name): ?Trait_ + public function findTrait(string $name) : ?\PhpParser\Node\Stmt\Trait_ { return $this->parsedNodeCollector->findTrait($name); } - - public function findByShortName(string $shortName): ?Class_ + public function findByShortName(string $shortName) : ?\PhpParser\Node\Stmt\Class_ { return $this->parsedNodeCollector->findByShortName($shortName); } - /** * @return StaticCall[] */ - public function getStaticCalls(): array + public function getStaticCalls() : array { return $this->parsedNodeCollector->getStaticCalls(); } - - public function resolveCallerClassName(MethodCall $methodCall): ?string + public function resolveCallerClassName(\PhpParser\Node\Expr\MethodCall $methodCall) : ?string { $callerType = $this->nodeTypeResolver->getStaticType($methodCall->var); $callerObjectType = $this->typeUnwrapper->unwrapFirstObjectTypeFromUnionType($callerType); - if (! $callerObjectType instanceof TypeWithClassName) { + if (!$callerObjectType instanceof \PHPStan\Type\TypeWithClassName) { return null; } - return $callerObjectType->getClassName(); } - - public function findClassLike(string $classLikeName): ?ClassLike + public function findClassLike(string $classLikeName) : ?\PhpParser\Node\Stmt\ClassLike { - return $this->findClass($classLikeName) ?? $this->findInterface($classLikeName) ?? $this->findTrait( - $classLikeName - ); + return $this->findClass($classLikeName) ?? $this->findInterface($classLikeName) ?? $this->findTrait($classLikeName); } - - private function collectArray(Array_ $array): void + private function collectArray(\PhpParser\Node\Expr\Array_ $array) : void { $arrayCallable = $this->arrayCallableMethodReferenceAnalyzer->match($array); - if (! $arrayCallable instanceof ArrayCallable) { + if (!$arrayCallable instanceof \Rector\NodeCollector\ValueObject\ArrayCallable) { return; } - - if (! $this->reflectionProvider->hasClass($arrayCallable->getClass())) { + if (!$this->reflectionProvider->hasClass($arrayCallable->getClass())) { return; } - $classReflection = $this->reflectionProvider->getClass($arrayCallable->getClass()); - if (! $classReflection->isClass()) { + if (!$classReflection->isClass()) { return; } - - if (! $classReflection->hasMethod($arrayCallable->getMethod())) { + if (!$classReflection->hasMethod($arrayCallable->getMethod())) { return; } - $this->arrayCallablesByTypeAndMethod[$arrayCallable->getClass()][$arrayCallable->getMethod()][] = $arrayCallable; } - - private function addMethod(ClassMethod $classMethod): void + private function addMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { - $className = $classMethod->getAttribute(AttributeKey::CLASS_NAME); - + $className = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); // anonymous if ($className === null) { return; } - $methodName = $this->nodeNameResolver->getName($classMethod); $this->classMethodsByType[$className][$methodName] = $classMethod; } - /** * @param MethodCall|StaticCall $node */ - private function addCall(Node $node): void + private function addCall(\PhpParser\Node $node) : void { // one node can be of multiple-class types - if ($node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { $classType = $this->resolveNodeClassTypes($node->var); } else { /** @var StaticCall $node */ $classType = $this->resolveNodeClassTypes($node->class); } - // anonymous - if ($classType instanceof MixedType) { + if ($classType instanceof \PHPStan\Type\MixedType) { return; } - $methodName = $this->nodeNameResolver->getName($node->name); if ($methodName === null) { return; } - $this->addCallByType($node, $classType, $methodName); } - /** * @return MethodCall[]|StaticCall[]|ArrayCallable[] */ - private function findCallsByClassAndMethod(string $className, string $methodName): array + private function findCallsByClassAndMethod(string $className, string $methodName) : array { return $this->callsByTypeAndMethod[$className][$methodName] ?? $this->arrayCallablesByTypeAndMethod[$className][$methodName] ?? []; } - - private function isChildOrEqualClassLike(string $desiredClass, ?string $currentClassName): bool + private function isChildOrEqualClassLike(string $desiredClass, ?string $currentClassName) : bool { if ($currentClassName === null) { - return false; + return \false; } - - if (! $this->reflectionProvider->hasClass($desiredClass)) { - return false; + if (!$this->reflectionProvider->hasClass($desiredClass)) { + return \false; } - - if (! $this->reflectionProvider->hasClass($currentClassName)) { - return false; + if (!$this->reflectionProvider->hasClass($currentClassName)) { + return \false; } - $desiredClassReflection = $this->reflectionProvider->getClass($desiredClass); $currentClassReflection = $this->reflectionProvider->getClass($currentClassName); - - if (! $currentClassReflection->isSubclassOf($desiredClassReflection->getName())) { - return false; + if (!$currentClassReflection->isSubclassOf($desiredClassReflection->getName())) { + return \false; } return $currentClassName !== $desiredClass; } - /** * @return Interface_[] */ - private function findImplementersOfInterface(string $interface): array + private function findImplementersOfInterface(string $interface) : array { $implementerInterfaces = []; - foreach ($this->parsedNodeCollector->getInterfaces() as $interfaceNode) { - $className = $interfaceNode->getAttribute(AttributeKey::CLASS_NAME); - - if (! $this->isChildOrEqualClassLike($interface, $className)) { + $className = $interfaceNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + if (!$this->isChildOrEqualClassLike($interface, $className)) { continue; } - $implementerInterfaces[] = $interfaceNode; } - return $implementerInterfaces; } - - private function resolveNodeClassTypes(Node $node): Type + private function resolveNodeClassTypes(\PhpParser\Node $node) : \PHPStan\Type\Type { - if ($node instanceof MethodCall && $node->var instanceof Variable && $node->var->name === 'this') { + if ($node instanceof \PhpParser\Node\Expr\MethodCall && $node->var instanceof \PhpParser\Node\Expr\Variable && $node->var->name === 'this') { /** @var string|null $className */ - $className = $node->getAttribute(AttributeKey::CLASS_NAME); + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className) { - return new ObjectType($className); + return new \PHPStan\Type\ObjectType($className); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - if ($node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { return $this->nodeTypeResolver->resolve($node->var); } - return $this->nodeTypeResolver->resolve($node); } - /** * @param MethodCall|StaticCall $node */ - private function addCallByType(Node $node, Type $classType, string $methodName): void + private function addCallByType(\PhpParser\Node $node, \PHPStan\Type\Type $classType, string $methodName) : void { - if ($classType instanceof TypeWithClassName) { - if ($classType instanceof ThisType) { + if ($classType instanceof \PHPStan\Type\TypeWithClassName) { + if ($classType instanceof \PHPStan\Type\ThisType) { $classType = $classType->getStaticObjectType(); } - $this->callsByTypeAndMethod[$classType->getClassName()][$methodName][] = $node; $this->addParentTypeWithClassName($classType, $node, $methodName); } - - if ($classType instanceof UnionType) { + if ($classType instanceof \PHPStan\Type\UnionType) { foreach ($classType->getTypes() as $unionedType) { - if (! $unionedType instanceof ObjectType) { + if (!$unionedType instanceof \PHPStan\Type\ObjectType) { continue; } - $this->callsByTypeAndMethod[$unionedType->getClassName()][$methodName][] = $node; } } } - /** * @param MethodCall|StaticCall $node */ - private function addParentTypeWithClassName( - TypeWithClassName $typeWithClassName, - Node $node, - string $methodName - ): void { + private function addParentTypeWithClassName(\PHPStan\Type\TypeWithClassName $typeWithClassName, \PhpParser\Node $node, string $methodName) : void + { // include also parent types - if (! $typeWithClassName instanceof ObjectType) { + if (!$typeWithClassName instanceof \PHPStan\Type\ObjectType) { return; } - - if (! $this->reflectionProvider->hasClass($typeWithClassName->getClassName())) { + if (!$this->reflectionProvider->hasClass($typeWithClassName->getClassName())) { return; } - $classReflection = $this->reflectionProvider->getClass($typeWithClassName->getClassName()); foreach ($classReflection->getAncestors() as $ancestorClassReflection) { $this->callsByTypeAndMethod[$ancestorClassReflection->getName()][$methodName][] = $node; diff --git a/packages/NodeCollector/NodeCollector/ParsedNodeCollector.php b/packages/NodeCollector/NodeCollector/ParsedNodeCollector.php index 614894b9cfc..6421910ed38 100644 --- a/packages/NodeCollector/NodeCollector/ParsedNodeCollector.php +++ b/packages/NodeCollector/NodeCollector/ParsedNodeCollector.php @@ -1,10 +1,9 @@ > */ private const COLLECTABLE_NODE_TYPES = [ - Class_::class, - Interface_::class, - ClassConst::class, - ClassConstFetch::class, - Trait_::class, - ClassMethod::class, + \PhpParser\Node\Stmt\Class_::class, + \PhpParser\Node\Stmt\Interface_::class, + \PhpParser\Node\Stmt\ClassConst::class, + \PhpParser\Node\Expr\ClassConstFetch::class, + \PhpParser\Node\Stmt\Trait_::class, + \PhpParser\Node\Stmt\ClassMethod::class, // simply collected - StaticCall::class, - MethodCall::class, + \PhpParser\Node\Expr\StaticCall::class, + \PhpParser\Node\Expr\MethodCall::class, // for array callable - [$this, 'someCall'] - Array_::class, + \PhpParser\Node\Expr\Array_::class, ]; - /** * @var Class_[] */ private $classes = []; - /** * @var ClassConst[][] */ private $constantsByType = []; - /** * @var Interface_[] */ private $interfaces = []; - /** * @var Trait_[] */ private $traits = []; - /** * @var StaticCall[] */ private $staticCalls = []; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var ParentClassScopeResolver */ private $parentClassScopeResolver; - /** * @var ClassAnalyzer */ private $classAnalyzer; - - public function __construct( - NodeNameResolver $nodeNameResolver, - ParentClassScopeResolver $parentClassScopeResolver, - ClassAnalyzer $classAnalyzer - ) { + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\NodeCollector\ScopeResolver\ParentClassScopeResolver $parentClassScopeResolver, \Rector\Core\NodeAnalyzer\ClassAnalyzer $classAnalyzer) + { $this->nodeNameResolver = $nodeNameResolver; $this->parentClassScopeResolver = $parentClassScopeResolver; $this->classAnalyzer = $classAnalyzer; } - /** * @return Interface_[] */ - public function getInterfaces(): array + public function getInterfaces() : array { return $this->interfaces; } - /** * @return Class_[] */ - public function getClasses(): array + public function getClasses() : array { return $this->classes; } - - public function findClass(string $name): ?Class_ + public function findClass(string $name) : ?\PhpParser\Node\Stmt\Class_ { return $this->classes[$name] ?? null; } - - public function findInterface(string $name): ?Interface_ + public function findInterface(string $name) : ?\PhpParser\Node\Stmt\Interface_ { return $this->interfaces[$name] ?? null; } - - public function findTrait(string $name): ?Trait_ + public function findTrait(string $name) : ?\PhpParser\Node\Stmt\Trait_ { return $this->traits[$name] ?? null; } - /** * Guessing the nearest neighboor. * Used e.g. for "XController" */ - public function findByShortName(string $shortName): ?Class_ + public function findByShortName(string $shortName) : ?\PhpParser\Node\Stmt\Class_ { foreach ($this->classes as $className => $classNode) { - if (Strings::endsWith($className, '\\' . $shortName)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($className, '\\' . $shortName)) { return $classNode; } } - return null; } - - public function findClassConstant(string $className, string $constantName): ?ClassConst + public function findClassConstant(string $className, string $constantName) : ?\PhpParser\Node\Stmt\ClassConst { - if (Strings::contains($constantName, '\\')) { - throw new ShouldNotHappenException(sprintf('Switched arguments in "%s"', __METHOD__)); + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($constantName, '\\')) { + throw new \Rector\Core\Exception\ShouldNotHappenException(\sprintf('Switched arguments in "%s"', __METHOD__)); } - return $this->constantsByType[$className][$constantName] ?? null; } - - public function isCollectableNode(Node $node): bool + public function isCollectableNode(\PhpParser\Node $node) : bool { foreach (self::COLLECTABLE_NODE_TYPES as $collectableNodeType) { /** @var class-string $collectableNodeType */ - if (is_a($node, $collectableNodeType, true)) { - return true; + if (\is_a($node, $collectableNodeType, \true)) { + return \true; } } - - return false; + return \false; } - - public function collect(Node $node): void + public function collect(\PhpParser\Node $node) : void { - if ($node instanceof Class_) { + if ($node instanceof \PhpParser\Node\Stmt\Class_) { $this->addClass($node); return; } - - if ($node instanceof Interface_ || $node instanceof Trait_) { + if ($node instanceof \PhpParser\Node\Stmt\Interface_ || $node instanceof \PhpParser\Node\Stmt\Trait_) { $this->collectInterfaceOrTrait($node); return; } - - if ($node instanceof ClassConst) { + if ($node instanceof \PhpParser\Node\Stmt\ClassConst) { $this->addClassConstant($node); return; } - - if ($node instanceof StaticCall) { + if ($node instanceof \PhpParser\Node\Expr\StaticCall) { $this->staticCalls[] = $node; return; } } - - public function findClassConstByClassConstFetch(ClassConstFetch $classConstFetch): ?ClassConst + public function findClassConstByClassConstFetch(\PhpParser\Node\Expr\ClassConstFetch $classConstFetch) : ?\PhpParser\Node\Stmt\ClassConst { $className = $this->nodeNameResolver->getName($classConstFetch->class); if ($className === null) { return null; } - $class = $this->resolveClassConstant($classConstFetch, $className); if ($class === null) { return null; } - /** @var string $constantName */ $constantName = $this->nodeNameResolver->getName($classConstFetch->name); - return $this->findClassConstant($class, $constantName); } - /** * @return StaticCall[] */ - public function getStaticCalls(): array + public function getStaticCalls() : array { return $this->staticCalls; } - - private function addClass(Class_ $class): void + private function addClass(\PhpParser\Node\Stmt\Class_ $class) : void { if ($this->classAnalyzer->isAnonymousClass($class)) { return; } - - $className = $class->getAttribute(AttributeKey::CLASS_NAME); + $className = $class->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $this->classes[$className] = $class; } - /** * @param Interface_|Trait_ $classLike */ - private function collectInterfaceOrTrait(ClassLike $classLike): void + private function collectInterfaceOrTrait(\PhpParser\Node\Stmt\ClassLike $classLike) : void { $name = $this->nodeNameResolver->getName($classLike); if ($name === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - if ($classLike instanceof Interface_) { + if ($classLike instanceof \PhpParser\Node\Stmt\Interface_) { $this->interfaces[$name] = $classLike; - } elseif ($classLike instanceof Trait_) { + } elseif ($classLike instanceof \PhpParser\Node\Stmt\Trait_) { $this->traits[$name] = $classLike; } } - - private function addClassConstant(ClassConst $classConst): void + private function addClassConstant(\PhpParser\Node\Stmt\ClassConst $classConst) : void { - $className = $classConst->getAttribute(AttributeKey::CLASS_NAME); + $className = $classConst->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { // anonymous class constant return; } - $constantName = $this->nodeNameResolver->getName($classConst); - $this->constantsByType[$className][$constantName] = $classConst; } - - private function resolveClassConstant(ClassConstFetch $classConstFetch, string $className): ?string + private function resolveClassConstant(\PhpParser\Node\Expr\ClassConstFetch $classConstFetch, string $className) : ?string { if ($className === 'self') { - return $classConstFetch->getAttribute(AttributeKey::CLASS_NAME); + return $classConstFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); } - if ($className === 'parent') { return $this->parentClassScopeResolver->resolveParentClassName($classConstFetch); } - return $className; } } diff --git a/packages/NodeCollector/NodeCollector/ParsedPropertyFetchNodeCollector.php b/packages/NodeCollector/NodeCollector/ParsedPropertyFetchNodeCollector.php index 2f84d1f2e3c..dcec1a0aac3 100644 --- a/packages/NodeCollector/NodeCollector/ParsedPropertyFetchNodeCollector.php +++ b/packages/NodeCollector/NodeCollector/ParsedPropertyFetchNodeCollector.php @@ -1,7 +1,6 @@ > */ private $propertyFetchesByTypeAndName = []; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var NodeTypeResolver */ private $nodeTypeResolver; - - public function __construct(NodeNameResolver $nodeNameResolver, NodeTypeResolver $nodeTypeResolver) + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver) { $this->nodeNameResolver = $nodeNameResolver; $this->nodeTypeResolver = $nodeTypeResolver; } - - public function collect(Node $node): void + public function collect(\PhpParser\Node $node) : void { - if (! $node instanceof PropertyFetch && ! $node instanceof StaticPropertyFetch) { + if (!$node instanceof \PhpParser\Node\Expr\PropertyFetch && !$node instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { return; } - $propertyType = $this->resolvePropertyCallerType($node); - if ($propertyType instanceof MixedType) { + if ($propertyType instanceof \PHPStan\Type\MixedType) { return; } - // make sure name is valid - if ($node->name instanceof StaticCall || $node->name instanceof MethodCall) { + if ($node->name instanceof \PhpParser\Node\Expr\StaticCall || $node->name instanceof \PhpParser\Node\Expr\MethodCall) { return; } - $propertyName = $this->nodeNameResolver->getName($node->name); if ($propertyName === null) { return; } - $this->addPropertyFetchWithTypeAndName($propertyType, $node, $propertyName); } - /** * @return PropertyFetch[] */ - public function findPropertyFetchesByTypeAndName(string $className, string $propertyName): array + public function findPropertyFetchesByTypeAndName(string $className, string $propertyName) : array { return $this->propertyFetchesByTypeAndName[$className][$propertyName] ?? []; } - /** * @param PropertyFetch|StaticPropertyFetch $node */ - private function resolvePropertyCallerType(Node $node): Type + private function resolvePropertyCallerType(\PhpParser\Node $node) : \PHPStan\Type\Type { - if ($node instanceof PropertyFetch) { + if ($node instanceof \PhpParser\Node\Expr\PropertyFetch) { return $this->nodeTypeResolver->resolve($node->var); } - return $this->nodeTypeResolver->resolve($node->class); } - /** * @param PropertyFetch|StaticPropertyFetch $propertyFetchNode */ - private function addPropertyFetchWithTypeAndName( - Type $propertyType, - Node $propertyFetchNode, - string $propertyName - ): void { - if ($propertyType instanceof TypeWithClassName) { + private function addPropertyFetchWithTypeAndName(\PHPStan\Type\Type $propertyType, \PhpParser\Node $propertyFetchNode, string $propertyName) : void + { + if ($propertyType instanceof \PHPStan\Type\TypeWithClassName) { $this->propertyFetchesByTypeAndName[$propertyType->getClassName()][$propertyName][] = $propertyFetchNode; } - - if ($propertyType instanceof UnionType) { + if ($propertyType instanceof \PHPStan\Type\UnionType) { foreach ($propertyType->getTypes() as $unionedType) { $this->addPropertyFetchWithTypeAndName($unionedType, $propertyFetchNode, $propertyName); } diff --git a/packages/NodeCollector/NodeVisitor/NodeCollectorNodeVisitor.php b/packages/NodeCollector/NodeVisitor/NodeCollectorNodeVisitor.php index 77079938e00..77f070172bb 100644 --- a/packages/NodeCollector/NodeVisitor/NodeCollectorNodeVisitor.php +++ b/packages/NodeCollector/NodeVisitor/NodeCollectorNodeVisitor.php @@ -1,7 +1,6 @@ nodeRepository = $nodeRepository; $this->parsedNodeCollector = $parsedNodeCollector; $this->parsedPropertyFetchNodeCollector = $parsedPropertyFetchNodeCollector; } - - public function enterNode(Node $node) + public function enterNode(\PhpParser\Node $node) { if ($this->parsedNodeCollector->isCollectableNode($node)) { $this->parsedNodeCollector->collect($node); } - $this->nodeRepository->collect($node); $this->parsedPropertyFetchNodeCollector->collect($node); - return null; } } diff --git a/packages/NodeCollector/Reflection/MethodReflectionProvider.php b/packages/NodeCollector/Reflection/MethodReflectionProvider.php index b1cefe0dff2..3f5a013ef1f 100644 --- a/packages/NodeCollector/Reflection/MethodReflectionProvider.php +++ b/packages/NodeCollector/Reflection/MethodReflectionProvider.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->reflectionProvider = $reflectionProvider; $this->nodeNameResolver = $nodeNameResolver; } - /** * @return Type[] */ - public function provideParameterTypesFromMethodReflection(MethodReflection $methodReflection): array + public function provideParameterTypesFromMethodReflection(\PHPStan\Reflection\MethodReflection $methodReflection) : array { - if ($methodReflection instanceof NativeMethodReflection) { + if ($methodReflection instanceof \PHPStan\Reflection\Native\NativeMethodReflection) { // method "getParameters()" does not exist there return []; } - $parameterTypes = []; - $parameterReflections = $this->getParameterReflectionsFromMethodReflection($methodReflection); foreach ($parameterReflections as $parameterReflection) { $parameterTypes[] = $parameterReflection->getType(); } - return $parameterTypes; } - - public function provideByMethodCall(MethodCall $methodCall): ?MethodReflection + public function provideByMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PHPStan\Reflection\MethodReflection { - $className = $methodCall->getAttribute(AttributeKey::CLASS_NAME); - if (! is_string($className)) { + $className = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + if (!\is_string($className)) { return null; } - $methodName = $this->nodeNameResolver->getName($methodCall->name); if ($methodName === null) { return null; } - - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return null; } - $classReflection = $this->reflectionProvider->getClass($className); - if (! $classReflection->hasMethod($methodName)) { + if (!$classReflection->hasMethod($methodName)) { return null; } - return $classReflection->getNativeMethod($methodName); } - /** * @return Type[] */ - public function provideParameterTypesByStaticCall(StaticCall $staticCall): array + public function provideParameterTypesByStaticCall(\PhpParser\Node\Expr\StaticCall $staticCall) : array { $methodReflection = $this->provideByStaticCall($staticCall); - if (! $methodReflection instanceof MethodReflection) { + if (!$methodReflection instanceof \PHPStan\Reflection\MethodReflection) { return []; } - return $this->provideParameterTypesFromMethodReflection($methodReflection); } - - public function provideByStaticCall(StaticCall $staticCall): ?MethodReflection + public function provideByStaticCall(\PhpParser\Node\Expr\StaticCall $staticCall) : ?\PHPStan\Reflection\MethodReflection { $objectType = $this->nodeTypeResolver->resolve($staticCall->class); - $classes = TypeUtils::getDirectClassNames($objectType); - + $classes = \PHPStan\Type\TypeUtils::getDirectClassNames($objectType); $methodName = $this->nodeNameResolver->getName($staticCall->name); if ($methodName === null) { return null; } - return $this->provideByClassNamesAndMethodName($classes, $methodName, $staticCall); } - /** * @return Type[] */ - public function provideParameterTypesByClassMethod(ClassMethod $classMethod): array + public function provideParameterTypesByClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $methodReflection = $this->provideByClassMethod($classMethod); - if (! $methodReflection instanceof MethodReflection) { + if (!$methodReflection instanceof \PHPStan\Reflection\MethodReflection) { return []; } - return $this->provideParameterTypesFromMethodReflection($methodReflection); } - - public function provideByClassMethod(ClassMethod $classMethod): ?MethodReflection + public function provideByClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PHPStan\Reflection\MethodReflection { - $class = $classMethod->getAttribute(AttributeKey::CLASS_NAME); - if (! is_string($class)) { + $class = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + if (!\is_string($class)) { return null; } - $method = $this->nodeNameResolver->getName($classMethod->name); - if (! is_string($method)) { + if (!\is_string($method)) { return null; } - - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - return $classReflection->getMethod($method, $scope); } - /** * @return ParameterReflection[] */ - public function getParameterReflectionsFromMethodReflection(MethodReflection $methodReflection): array + public function getParameterReflectionsFromMethodReflection(\PHPStan\Reflection\MethodReflection $methodReflection) : array { - $parametersAcceptor = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants()); + $parametersAcceptor = \PHPStan\Reflection\ParametersAcceptorSelector::selectSingle($methodReflection->getVariants()); return $parametersAcceptor->getParameters(); } - /** * @return string[] */ - public function provideParameterNamesByNew(New_ $new): array + public function provideParameterNamesByNew(\PhpParser\Node\Expr\New_ $new) : array { $objectType = $this->nodeTypeResolver->resolve($new->class); - - $classes = TypeUtils::getDirectClassNames($objectType); - + $classes = \PHPStan\Type\TypeUtils::getDirectClassNames($objectType); $parameterNames = []; - foreach ($classes as $class) { - if (! $this->reflectionProvider->hasClass($class)) { + if (!$this->reflectionProvider->hasClass($class)) { continue; } - $classReflection = $this->reflectionProvider->getClass($class); - - if (! $classReflection->hasMethod(MethodName::CONSTRUCT)) { + if (!$classReflection->hasMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT)) { continue; } - $nativeClassReflection = $classReflection->getNativeReflection(); - $methodReflection = $nativeClassReflection->getMethod(MethodName::CONSTRUCT); - + $methodReflection = $nativeClassReflection->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); foreach ($methodReflection->getParameters() as $reflectionParameter) { $parameterNames[] = $reflectionParameter->getName(); } } - return $parameterNames; } - /** * @param string[] $classes */ - private function provideByClassNamesAndMethodName( - array $classes, - string $methodName, - StaticCall $staticCall - ): ?MethodReflection { + private function provideByClassNamesAndMethodName(array $classes, string $methodName, \PhpParser\Node\Expr\StaticCall $staticCall) : ?\PHPStan\Reflection\MethodReflection + { /** @var Scope|null $scope */ - $scope = $staticCall->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - throw new ShouldNotHappenException(); + $scope = $staticCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - foreach ($classes as $class) { $classReflection = $this->reflectionProvider->getClass($class); - if (! $classReflection->hasMethod($methodName)) { + if (!$classReflection->hasMethod($methodName)) { continue; } - return $classReflection->getMethod($methodName, $scope); } - return null; } } diff --git a/packages/NodeCollector/ScopeResolver/ParentClassScopeResolver.php b/packages/NodeCollector/ScopeResolver/ParentClassScopeResolver.php index f95c9d9c4c7..6e6df86070f 100644 --- a/packages/NodeCollector/ScopeResolver/ParentClassScopeResolver.php +++ b/packages/NodeCollector/ScopeResolver/ParentClassScopeResolver.php @@ -1,33 +1,28 @@ getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - $parentClassReflection = $classReflection->getParentClass(); - if ($parentClassReflection === false) { + if ($parentClassReflection === \false) { return null; } - return $parentClassReflection->getName(); } } diff --git a/packages/NodeCollector/StaticAnalyzer.php b/packages/NodeCollector/StaticAnalyzer.php index d49cfea9da2..27ac11c4522 100644 --- a/packages/NodeCollector/StaticAnalyzer.php +++ b/packages/NodeCollector/StaticAnalyzer.php @@ -1,70 +1,56 @@ nodeRepository = $nodeRepository; $this->reflectionProvider = $reflectionProvider; } - - public function isStaticMethod(string $methodName, string $className): bool + public function isStaticMethod(string $methodName, string $className) : bool { $classMethod = $this->nodeRepository->findClassMethod($className, $methodName); if ($classMethod !== null) { return $classMethod->isStatic(); } - // could be static in doc type magic // @see https://regex101.com/r/tlvfTB/1 - if (! $this->reflectionProvider->hasClass($className)) { - return false; + if (!$this->reflectionProvider->hasClass($className)) { + return \false; } - $classReflection = $this->reflectionProvider->getClass($className); if ($this->hasStaticAnnotation($methodName, $classReflection)) { - return true; + return \true; } - // probably magic method → we don't know - if (! $classReflection->hasNativeMethod($methodName)) { - return false; + if (!$classReflection->hasNativeMethod($methodName)) { + return \false; } - $methodReflection = $classReflection->getNativeMethod($methodName); return $methodReflection->isStatic(); } - - private function hasStaticAnnotation(string $methodName, ClassReflection $classReflection): bool + private function hasStaticAnnotation(string $methodName, \PHPStan\Reflection\ClassReflection $classReflection) : bool { $resolvedPhpDocBlock = $classReflection->getResolvedPhpDoc(); - if (! $resolvedPhpDocBlock instanceof ResolvedPhpDocBlock) { - return false; + if (!$resolvedPhpDocBlock instanceof \PHPStan\PhpDoc\ResolvedPhpDocBlock) { + return \false; } - - return (bool) Strings::match( - $resolvedPhpDocBlock->getPhpDocString(), - '#@method\s*static\s*(.*?)\b' . $methodName . '\b#' - ); + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($resolvedPhpDocBlock->getPhpDocString(), '#@method\\s*static\\s*(.*?)\\b' . $methodName . '\\b#'); } } diff --git a/packages/NodeCollector/ValueObject/ArrayCallable.php b/packages/NodeCollector/ValueObject/ArrayCallable.php index e503e074033..aca982ce28e 100644 --- a/packages/NodeCollector/ValueObject/ArrayCallable.php +++ b/packages/NodeCollector/ValueObject/ArrayCallable.php @@ -1,7 +1,6 @@ class = $class; $this->method = $method; } - - public function getClass(): string + public function getClass() : string { return $this->class; } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } diff --git a/packages/NodeNameResolver/Contract/NodeNameResolverInterface.php b/packages/NodeNameResolver/Contract/NodeNameResolverInterface.php index cb02e3e864f..057d3814d17 100644 --- a/packages/NodeNameResolver/Contract/NodeNameResolverInterface.php +++ b/packages/NodeNameResolver/Contract/NodeNameResolverInterface.php @@ -1,17 +1,14 @@ */ - public function getNode(): string; - - public function resolve(Node $node): ?string; + public function getNode() : string; + public function resolve(\PhpParser\Node $node) : ?string; } diff --git a/packages/NodeNameResolver/Error/InvalidNameNodeReporter.php b/packages/NodeNameResolver/Error/InvalidNameNodeReporter.php index d4069b7ec45..7570f9040bf 100644 --- a/packages/NodeNameResolver/Error/InvalidNameNodeReporter.php +++ b/packages/NodeNameResolver/Error/InvalidNameNodeReporter.php @@ -1,7 +1,6 @@ currentFileProvider = $currentFileProvider; $this->betterStandardPrinter = $betterStandardPrinter; } - /** * @param MethodCall|StaticCall $node */ - public function reportInvalidNodeForName(Node $node): void + public function reportInvalidNodeForName(\PhpParser\Node $node) : void { - $message = sprintf('Pick more specific node than "%s", e.g. "$node->name"', get_class($node)); - + $message = \sprintf('Pick more specific node than "%s", e.g. "$node->name"', \get_class($node)); $file = $this->currentFileProvider->getFile(); - - if ($file instanceof File) { + if ($file instanceof \Rector\Core\ValueObject\Application\File) { $smartFileInfo = $file->getSmartFileInfo(); - $message .= PHP_EOL . PHP_EOL; - $message .= sprintf( - 'Caused in "%s" file on line %d on code "%s"', - $smartFileInfo->getRelativeFilePathFromCwd(), - $node->getStartLine(), - $this->betterStandardPrinter->print($node) - ); + $message .= \PHP_EOL . \PHP_EOL; + $message .= \sprintf('Caused in "%s" file on line %d on code "%s"', $smartFileInfo->getRelativeFilePathFromCwd(), $node->getStartLine(), $this->betterStandardPrinter->print($node)); } - - $backtrace = debug_backtrace(); + $backtrace = \debug_backtrace(); $rectorBacktrace = $this->matchRectorBacktraceCall($backtrace); - if ($rectorBacktrace) { // issues to find the file in prefixed - if (file_exists($rectorBacktrace[self::FILE])) { - $smartFileInfo = new SmartFileInfo($rectorBacktrace[self::FILE]); + if (\file_exists($rectorBacktrace[self::FILE])) { + $smartFileInfo = new \Symplify\SmartFileSystem\SmartFileInfo($rectorBacktrace[self::FILE]); $fileAndLine = $smartFileInfo->getRelativeFilePathFromCwd() . ':' . $rectorBacktrace['line']; } else { $fileAndLine = $rectorBacktrace[self::FILE] . ':' . $rectorBacktrace['line']; } - - $message .= PHP_EOL . PHP_EOL; - $message .= sprintf('Look at "%s"', $fileAndLine); + $message .= \PHP_EOL . \PHP_EOL; + $message .= \sprintf('Look at "%s"', $fileAndLine); } - - throw new ShouldNotHappenException($message); + throw new \Rector\Core\Exception\ShouldNotHappenException($message); } - /** * @param mixed[] $backtrace * @return string[]|null */ - private function matchRectorBacktraceCall(array $backtrace): ?array + private function matchRectorBacktraceCall(array $backtrace) : ?array { foreach ($backtrace as $singleBacktrace) { - if (! isset($singleBacktrace['object'])) { + if (!isset($singleBacktrace['object'])) { continue; } - // match a Rector class - if (! is_a($singleBacktrace['object'], RectorInterface::class)) { + if (!\is_a($singleBacktrace['object'], \Rector\Core\Contract\Rector\RectorInterface::class)) { continue; } - return $singleBacktrace; } - return $backtrace[1] ?? null; } } diff --git a/packages/NodeNameResolver/NodeNameResolver.php b/packages/NodeNameResolver/NodeNameResolver.php index d52324fdf4c..e82ebe0c42a 100644 --- a/packages/NodeNameResolver/NodeNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver.php @@ -1,10 +1,9 @@ regexPatternDetector = $regexPatternDetector; $this->nodeNameResolvers = $nodeNameResolvers; $this->classNaming = $classNaming; $this->invalidNameNodeReporter = $invalidNameNodeReporter; } - /** * @param string[] $names */ - public function isNames(Node $node, array $names): bool + public function isNames(\PhpParser\Node $node, array $names) : bool { foreach ($names as $name) { if ($this->isName($node, $name)) { - return true; + return \true; } } - - return false; + return \false; } - /** * @param Node|Node[] $node */ - public function isName($node, string $name): bool + public function isName($node, string $name) : bool { - if ($node instanceof MethodCall) { - return false; + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - if ($node instanceof StaticCall) { - return false; + if ($node instanceof \PhpParser\Node\Expr\StaticCall) { + return \false; } - $nodes = is_array($node) ? $node : [$node]; - + $nodes = \is_array($node) ? $node : [$node]; foreach ($nodes as $node) { if ($this->isSingleName($node, $name)) { - return true; + return \true; } } - - return false; + return \false; } - - public function getName(Node $node): ?string + public function getName(\PhpParser\Node $node) : ?string { - if ($node instanceof MethodCall || $node instanceof StaticCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall || $node instanceof \PhpParser\Node\Expr\StaticCall) { if ($this->isCallOrIdentifier($node->name)) { return null; } - $this->invalidNameNodeReporter->reportInvalidNodeForName($node); } - foreach ($this->nodeNameResolvers as $nodeNameResolver) { - if (! is_a($node, $nodeNameResolver->getNode(), true)) { + if (!\is_a($node, $nodeNameResolver->getNode(), \true)) { continue; } - return $nodeNameResolver->resolve($node); } - // more complex - if (! property_exists($node, 'name')) { + if (!\property_exists($node, 'name')) { return null; } - // unable to resolve - if ($node->name instanceof Expr) { + if ($node->name instanceof \PhpParser\Node\Expr) { return null; } - return (string) $node->name; } - - public function areNamesEqual(Node $firstNode, Node $secondNode): bool + public function areNamesEqual(\PhpParser\Node $firstNode, \PhpParser\Node $secondNode) : bool { $secondResolvedName = $this->getName($secondNode); if ($secondResolvedName === null) { - return false; + return \false; } - return $this->isName($firstNode, $secondResolvedName); } - /** * @param Name[]|Node[] $nodes * @return string[] */ - public function getNames(array $nodes): array + public function getNames(array $nodes) : array { $names = []; foreach ($nodes as $node) { $name = $this->getName($node); - if (! is_string($name)) { - throw new ShouldNotHappenException(); + if (!\is_string($name)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $names[] = $name; } - return $names; } - - public function isLocalPropertyFetchNamed(Node $node, string $name): bool + public function isLocalPropertyFetchNamed(\PhpParser\Node $node, string $name) : bool { - if (! $node instanceof PropertyFetch) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - - if ($node->var instanceof MethodCall) { - return false; + if ($node->var instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - - if (! $this->isName($node->var, 'this')) { - return false; + if (!$this->isName($node->var, 'this')) { + return \false; } - - if ($node->name instanceof Expr) { - return false; + if ($node->name instanceof \PhpParser\Node\Expr) { + return \false; } - return $this->isName($node->name, $name); } - /** * Ends with ucname * Starts with adjective, e.g. (Post $firstPost, Post $secondPost) */ - public function endsWith(string $currentName, string $expectedName): bool + public function endsWith(string $currentName, string $expectedName) : bool { - $suffixNamePattern = '#\w+' . ucfirst($expectedName) . '#'; - return (bool) Strings::match($currentName, $suffixNamePattern); + $suffixNamePattern = '#\\w+' . \ucfirst($expectedName) . '#'; + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($currentName, $suffixNamePattern); } - /** * @param string|Name|Identifier|ClassLike $name */ - public function getShortName($name): string + public function getShortName($name) : string { return $this->classNaming->getShortName($name); } - /** * @param array $renameMap */ - public function matchNameFromMap(Node $node, array $renameMap): ?string + public function matchNameFromMap(\PhpParser\Node $node, array $renameMap) : ?string { $name = $this->getName($node); return $renameMap[$name] ?? null; } - - private function isCallOrIdentifier(Node $node): bool + private function isCallOrIdentifier(\PhpParser\Node $node) : bool { - if ($node instanceof MethodCall) { - return true; + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { + return \true; } - - if ($node instanceof StaticCall) { - return true; + if ($node instanceof \PhpParser\Node\Expr\StaticCall) { + return \true; } - - return $node instanceof Identifier; + return $node instanceof \PhpParser\Node\Identifier; } - - private function isSingleName(Node $node, string $name): bool + private function isSingleName(\PhpParser\Node $node, string $name) : bool { - if ($node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { // method call cannot have a name, only the variable or method name - return false; + return \false; } - $resolvedName = $this->getName($node); if ($resolvedName === null) { - return false; + return \false; } - if ($name === '') { - return false; + return \false; } - // is probably regex pattern if ($this->regexPatternDetector->isRegexPattern($name)) { - return (bool) Strings::match($resolvedName, $name); + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($resolvedName, $name); } - // is probably fnmatch - if (Strings::contains($name, '*')) { - return fnmatch($name, $resolvedName, FNM_NOESCAPE); + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($name, '*')) { + return \fnmatch($name, $resolvedName, \FNM_NOESCAPE); } - // special case if ($name === 'Object') { return $name === $resolvedName; } - - return strtolower($resolvedName) === strtolower($name); + return \strtolower($resolvedName) === \strtolower($name); } } diff --git a/packages/NodeNameResolver/NodeNameResolver/ClassConstFetchNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/ClassConstFetchNameResolver.php index a811d852001..04e397228bc 100644 --- a/packages/NodeNameResolver/NodeNameResolver/ClassConstFetchNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/ClassConstFetchNameResolver.php @@ -1,41 +1,36 @@ nodeNameResolver = $nodeNameResolver; } - /** * @return class-string */ - public function getNode(): string + public function getNode() : string { - return ClassConstFetch::class; + return \PhpParser\Node\Expr\ClassConstFetch::class; } - /** * @param ClassConstFetch $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { $class = $this->nodeNameResolver->getName($node->class); $name = $this->nodeNameResolver->getName($node->name); @@ -45,7 +40,6 @@ final class ClassConstFetchNameResolver implements NodeNameResolverInterface if ($name === null) { return null; } - return $class . '::' . $name; } } diff --git a/packages/NodeNameResolver/NodeNameResolver/ClassConstNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/ClassConstNameResolver.php index c682105667c..11b34364d8a 100644 --- a/packages/NodeNameResolver/NodeNameResolver/ClassConstNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/ClassConstNameResolver.php @@ -1,48 +1,41 @@ nodeNameResolver = $nodeNameResolver; } - /** * @return class-string */ - public function getNode(): string + public function getNode() : string { - return ClassConst::class; + return \PhpParser\Node\Stmt\ClassConst::class; } - /** * @param ClassConst $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { if ($node->consts === []) { return null; } - $onlyConstant = $node->consts[0]; - return $this->nodeNameResolver->getName($onlyConstant); } } diff --git a/packages/NodeNameResolver/NodeNameResolver/ClassNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/ClassNameResolver.php index 182bd085129..ca33172e167 100644 --- a/packages/NodeNameResolver/NodeNameResolver/ClassNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/ClassNameResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; } - /** * @return class-string */ - public function getNode(): string + public function getNode() : string { - return ClassLike::class; + return \PhpParser\Node\Stmt\ClassLike::class; } - /** * @param Class_ $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { - if (property_exists($node, 'namespacedName')) { + if (\property_exists($node, 'namespacedName')) { return $node->namespacedName->toString(); } - if ($node->name === null) { return null; } - return $this->nodeNameResolver->getName($node->name); } } diff --git a/packages/NodeNameResolver/NodeNameResolver/EmptyNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/EmptyNameResolver.php index cabc52ff45e..028788b2a93 100644 --- a/packages/NodeNameResolver/NodeNameResolver/EmptyNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/EmptyNameResolver.php @@ -1,27 +1,24 @@ */ - public function getNode(): string + public function getNode() : string { - return Empty_::class; + return \PhpParser\Node\Expr\Empty_::class; } - /** * @param Empty_ $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { return 'empty'; } diff --git a/packages/NodeNameResolver/NodeNameResolver/FuncCallNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/FuncCallNameResolver.php index d32420d4632..c5169aeefb9 100644 --- a/packages/NodeNameResolver/NodeNameResolver/FuncCallNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/FuncCallNameResolver.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - /** * @return class-string */ - public function getNode(): string + public function getNode() : string { - return FuncCall::class; + return \PhpParser\Node\Expr\FuncCall::class; } - /** * If some function is namespaced, it will be used over global one. * But only if it really exists. * * @param FuncCall $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { - if ($node->name instanceof Expr) { + if ($node->name instanceof \PhpParser\Node\Expr) { return null; } - $functionName = $node->name; - - $namespaceName = $functionName->getAttribute(AttributeKey::NAMESPACED_NAME); - if ($namespaceName instanceof FullyQualified) { + $namespaceName = $functionName->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NAMESPACED_NAME); + if ($namespaceName instanceof \PhpParser\Node\Name\FullyQualified) { $functionFqnName = $namespaceName->toString(); - if ($this->reflectionProvider->hasFunction($namespaceName, null)) { return $functionFqnName; } } - return (string) $functionName; } } diff --git a/packages/NodeNameResolver/NodeNameResolver/FunctionNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/FunctionNameResolver.php index 96fe1695dab..90b39f71e9a 100644 --- a/packages/NodeNameResolver/NodeNameResolver/FunctionNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/FunctionNameResolver.php @@ -1,7 +1,6 @@ */ - public function getNode(): string + public function getNode() : string { - return Function_::class; + return \PhpParser\Node\Stmt\Function_::class; } - /** * @param Function_ $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { $bareName = (string) $node->name; - - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return $bareName; } - $namespaceName = $scope->getNamespace(); if ($namespaceName) { return $namespaceName . '\\' . $bareName; } - return $bareName; } } diff --git a/packages/NodeNameResolver/NodeNameResolver/NameNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/NameNameResolver.php index 63a50421c12..b13d4fe7a68 100644 --- a/packages/NodeNameResolver/NodeNameResolver/NameNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/NameNameResolver.php @@ -1,7 +1,6 @@ funcCallNameResolver = $funcCallNameResolver; } - /** * @return class-string */ - public function getNode(): string + public function getNode() : string { - return Name::class; + return \PhpParser\Node\Name::class; } - /** * @param Name $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { // possible function parent - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof FuncCall) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Expr\FuncCall) { return $this->funcCallNameResolver->resolve($parent); } - - $resolvedName = $node->getAttribute(AttributeKey::RESOLVED_NAME); - if ($resolvedName instanceof FullyQualified) { + $resolvedName = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::RESOLVED_NAME); + if ($resolvedName instanceof \PhpParser\Node\Name\FullyQualified) { return $resolvedName->toString(); } - return $node->toString(); } } diff --git a/packages/NodeNameResolver/NodeNameResolver/ParamNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/ParamNameResolver.php index a5910693dc0..78d8302fb13 100644 --- a/packages/NodeNameResolver/NodeNameResolver/ParamNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/ParamNameResolver.php @@ -1,41 +1,36 @@ nodeNameResolver = $nodeNameResolver; } - /** * @return class-string */ - public function getNode(): string + public function getNode() : string { - return Param::class; + return \PhpParser\Node\Param::class; } - /** * @param Param $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { return $this->nodeNameResolver->getName($node->var); } diff --git a/packages/NodeNameResolver/NodeNameResolver/PropertyNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/PropertyNameResolver.php index 502f331a1c8..8c71922f25a 100644 --- a/packages/NodeNameResolver/NodeNameResolver/PropertyNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/PropertyNameResolver.php @@ -1,48 +1,41 @@ nodeNameResolver = $nodeNameResolver; } - /** * @return class-string */ - public function getNode(): string + public function getNode() : string { - return Property::class; + return \PhpParser\Node\Stmt\Property::class; } - /** * @param Property $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { if ($node->props === []) { return null; } - $onlyProperty = $node->props[0]; - return $this->nodeNameResolver->getName($onlyProperty); } } diff --git a/packages/NodeNameResolver/NodeNameResolver/UseNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/UseNameResolver.php index 794cd3922d7..293963fbc62 100644 --- a/packages/NodeNameResolver/NodeNameResolver/UseNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/UseNameResolver.php @@ -1,48 +1,41 @@ nodeNameResolver = $nodeNameResolver; } - /** * @return class-string */ - public function getNode(): string + public function getNode() : string { - return Use_::class; + return \PhpParser\Node\Stmt\Use_::class; } - /** * @param Use_ $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { if ($node->uses === []) { return null; } - $onlyUse = $node->uses[0]; - return $this->nodeNameResolver->getName($onlyUse); } } diff --git a/packages/NodeNameResolver/NodeNameResolver/VariableNameResolver.php b/packages/NodeNameResolver/NodeNameResolver/VariableNameResolver.php index 0ccf9102cd8..197a9cddf5c 100644 --- a/packages/NodeNameResolver/NodeNameResolver/VariableNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver/VariableNameResolver.php @@ -1,7 +1,6 @@ */ - public function getNode(): string + public function getNode() : string { - return Variable::class; + return \PhpParser\Node\Expr\Variable::class; } - /** * @param Variable $node */ - public function resolve(Node $node): ?string + public function resolve(\PhpParser\Node $node) : ?string { - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // skip $some->$dynamicMethodName() - if ($parentNode instanceof MethodCall && $node === $parentNode->name) { + if ($parentNode instanceof \PhpParser\Node\Expr\MethodCall && $node === $parentNode->name) { return null; } - // skip $some->$dynamicPropertyName - if ($parentNode instanceof PropertyFetch && $node === $parentNode->name) { + if ($parentNode instanceof \PhpParser\Node\Expr\PropertyFetch && $node === $parentNode->name) { return null; } - - if ($node->name instanceof Expr) { + if ($node->name instanceof \PhpParser\Node\Expr) { return null; } - return $node->name; } } diff --git a/packages/NodeNameResolver/Regex/RegexPatternDetector.php b/packages/NodeNameResolver/Regex/RegexPatternDetector.php index 165c9a37788..79ca4c6e49c 100644 --- a/packages/NodeNameResolver/Regex/RegexPatternDetector.php +++ b/packages/NodeNameResolver/Regex/RegexPatternDetector.php @@ -1,11 +1,9 @@ > */ - private const BREAK_NODES = [FunctionLike::class, ClassMethod::class]; - + private const BREAK_NODES = [\PhpParser\Node\FunctionLike::class, \PhpParser\Node\Stmt\ClassMethod::class]; /** * @var array> */ - private const LOOP_NODES = [For_::class, Foreach_::class, While_::class, Do_::class, Switch_::class]; - + private const LOOP_NODES = [\PhpParser\Node\Stmt\For_::class, \PhpParser\Node\Stmt\Foreach_::class, \PhpParser\Node\Stmt\While_::class, \PhpParser\Node\Stmt\Do_::class, \PhpParser\Node\Stmt\Switch_::class]; /** * @var BetterNodeFinder */ private $betterNodeFinder; - /** * @var NodeTypeResolver */ private $nodeTypeResolver; - - public function __construct(BetterNodeFinder $betterNodeFinder, NodeTypeResolver $nodeTypeResolver) + public function __construct(\Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder, \Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver) { $this->betterNodeFinder = $betterNodeFinder; $this->nodeTypeResolver = $nodeTypeResolver; } - - public function isInLoop(Node $node): bool + public function isInLoop(\PhpParser\Node $node) : bool { - $stopNodes = array_merge(self::LOOP_NODES, self::BREAK_NODES); - + $stopNodes = \array_merge(self::LOOP_NODES, self::BREAK_NODES); $firstParent = $this->betterNodeFinder->findParentTypes($node, $stopNodes); - if (! $firstParent instanceof Node) { - return false; + if (!$firstParent instanceof \PhpParser\Node) { + return \false; } - foreach (self::LOOP_NODES as $type) { - if (is_a($firstParent, $type, true)) { - return true; + if (\is_a($firstParent, $type, \true)) { + return \true; } } - - return false; + return \false; } - - public function isInIf(Node $node): bool + public function isInIf(\PhpParser\Node $node) : bool { - $breakNodes = array_merge([If_::class], self::BREAK_NODES); - + $breakNodes = \array_merge([\PhpParser\Node\Stmt\If_::class], self::BREAK_NODES); $previousNode = $this->betterNodeFinder->findParentTypes($node, $breakNodes); - - if (! $previousNode instanceof Node) { - return false; + if (!$previousNode instanceof \PhpParser\Node) { + return \false; } - - return $previousNode instanceof If_; + return $previousNode instanceof \PhpParser\Node\Stmt\If_; } - - public function isHasAssignWithIndirectReturn(Node $node, If_ $if): bool + public function isHasAssignWithIndirectReturn(\PhpParser\Node $node, \PhpParser\Node\Stmt\If_ $if) : bool { $loopNodes = self::LOOP_NODES; - foreach ($loopNodes as $loopNode) { - $loopObjectType = new ObjectType($loopNode); + $loopObjectType = new \PHPStan\Type\ObjectType($loopNode); $parentType = $this->nodeTypeResolver->resolve($node); $superType = $parentType->isSuperTypeOf($loopObjectType); $isLoopType = $superType->yes(); - - if (! $isLoopType) { + if (!$isLoopType) { continue; } - - $next = $node->getAttribute(AttributeKey::NEXT_NODE); - if ($next instanceof Node) { - if ($next instanceof Return_ && $next->expr === null) { + $next = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if ($next instanceof \PhpParser\Node) { + if ($next instanceof \PhpParser\Node\Stmt\Return_ && $next->expr === null) { continue; } - - $hasAssign = (bool) $this->betterNodeFinder->findInstanceOf($if->stmts, Assign::class); - if (! $hasAssign) { + $hasAssign = (bool) $this->betterNodeFinder->findInstanceOf($if->stmts, \PhpParser\Node\Expr\Assign::class); + if (!$hasAssign) { continue; } - - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/NodeNestingScope/FlowOfControlLocator.php b/packages/NodeNestingScope/FlowOfControlLocator.php index 5480a0b26c2..d857ba276dc 100644 --- a/packages/NodeNestingScope/FlowOfControlLocator.php +++ b/packages/NodeNestingScope/FlowOfControlLocator.php @@ -1,7 +1,6 @@ getAttribute(AttributeKey::PARENT_NODE)) { - if ($currentNode instanceof Expression) { + while ($currentNode = $currentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE)) { + if ($currentNode instanceof \PhpParser\Node\Stmt\Expression) { continue; } - - if (! $currentNode instanceof Node) { + if (!$currentNode instanceof \PhpParser\Node) { continue; } - if ($functionLike === $currentNode) { // to high break; } - $nestingHash .= $this->resolveBinaryOpNestingHash($currentNode, $previous); - - $nestingHash .= spl_object_hash($currentNode); - + $nestingHash .= \spl_object_hash($currentNode); $previous = $currentNode; } - return $nestingHash; } - - private function resolveBinaryOpNestingHash(Node $currentNode, Node $previous): string + private function resolveBinaryOpNestingHash(\PhpParser\Node $currentNode, \PhpParser\Node $previous) : string { - if (! $currentNode instanceof BinaryOp) { + if (!$currentNode instanceof \PhpParser\Node\Expr\BinaryOp) { return ''; } - // left && right have differnt nesting if ($currentNode->left === $previous) { return 'binary_left__'; } - if ($currentNode->right === $previous) { return 'binary_right__'; } - return ''; } } diff --git a/packages/NodeNestingScope/NodeFinder/ScopeAwareNodeFinder.php b/packages/NodeNestingScope/NodeFinder/ScopeAwareNodeFinder.php index 6af2b42fdcf..c483956d374 100644 --- a/packages/NodeNestingScope/NodeFinder/ScopeAwareNodeFinder.php +++ b/packages/NodeNestingScope/NodeFinder/ScopeAwareNodeFinder.php @@ -1,86 +1,67 @@ betterNodeFinder = $betterNodeFinder; } - /** * Find node based on $callable or null, when the nesting scope is broken * @param array> $allowedTypes */ - public function findParentType(Node $node, array $allowedTypes): ?Node + public function findParentType(\PhpParser\Node $node, array $allowedTypes) : ?\PhpParser\Node { - $callable = function (Node $node) use ($allowedTypes): bool { + $callable = function (\PhpParser\Node $node) use($allowedTypes) : bool { foreach ($allowedTypes as $allowedType) { - if (! is_a($node, $allowedType)) { + if (!\is_a($node, $allowedType)) { continue; } - - return true; + return \true; } - - return false; + return \false; }; - return $this->findParent($node, $callable, $allowedTypes); } - /** * Find node based on $callable or null, when the nesting scope is broken * @param array> $allowedTypes */ - public function findParent(Node $node, callable $callable, array $allowedTypes): ?Node + public function findParent(\PhpParser\Node $node, callable $callable, array $allowedTypes) : ?\PhpParser\Node { /** @var array> $parentNestingBreakTypes */ - $parentNestingBreakTypes = array_diff(ControlStructure::BREAKING_SCOPE_NODE_TYPES, $allowedTypes); - - $this->isBreakingNodeFoundFirst = false; - - $foundNode = $this->betterNodeFinder->findFirstPrevious($node, function (Node $node) use ( - $callable, - $parentNestingBreakTypes - ): bool { + $parentNestingBreakTypes = \array_diff(\Rector\NodeNestingScope\ValueObject\ControlStructure::BREAKING_SCOPE_NODE_TYPES, $allowedTypes); + $this->isBreakingNodeFoundFirst = \false; + $foundNode = $this->betterNodeFinder->findFirstPrevious($node, function (\PhpParser\Node $node) use($callable, $parentNestingBreakTypes) : bool { if ($callable($node)) { - return true; + return \true; } - foreach ($parentNestingBreakTypes as $parentNestingBreakType) { - if (! is_a($node, $parentNestingBreakType, true)) { + if (!\is_a($node, $parentNestingBreakType, \true)) { continue; } - - $this->isBreakingNodeFoundFirst = true; - return true; + $this->isBreakingNodeFoundFirst = \true; + return \true; } - - return false; + return \false; }); - if ($this->isBreakingNodeFoundFirst) { return null; } - return $foundNode; } } diff --git a/packages/NodeNestingScope/ParentScopeFinder.php b/packages/NodeNestingScope/ParentScopeFinder.php index 14fbb6932a3..0dbd1581cd5 100644 --- a/packages/NodeNestingScope/ParentScopeFinder.php +++ b/packages/NodeNestingScope/ParentScopeFinder.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; } - /** * @return ClassMethod|Function_|Class_|Namespace_|Closure|null */ - public function find(Node $node): ?Node + public function find(\PhpParser\Node $node) : ?\PhpParser\Node { - return $this->betterNodeFinder->findParentTypes($node, [ - Closure::class, - Function_::class, - ClassMethod::class, - Class_::class, - Namespace_::class, - ]); + return $this->betterNodeFinder->findParentTypes($node, [\PhpParser\Node\Expr\Closure::class, \PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Stmt\Namespace_::class]); } } diff --git a/packages/NodeNestingScope/ScopeNestingComparator.php b/packages/NodeNestingScope/ScopeNestingComparator.php index 3826a6dcd3a..9bd0fa50ffd 100644 --- a/packages/NodeNestingScope/ScopeNestingComparator.php +++ b/packages/NodeNestingScope/ScopeNestingComparator.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeComparator = $nodeComparator; } - - public function areReturnScopeNested(Return_ $return, Node $secondNodeScopeNode): bool + public function areReturnScopeNested(\PhpParser\Node\Stmt\Return_ $return, \PhpParser\Node $secondNodeScopeNode) : bool { - $firstNodeScopeNode = $this->betterNodeFinder->findParentTypes( - $return, - ControlStructure::RETURN_ISOLATING_SCOPE_NODE_TYPES - ); - + $firstNodeScopeNode = $this->betterNodeFinder->findParentTypes($return, \Rector\NodeNestingScope\ValueObject\ControlStructure::RETURN_ISOLATING_SCOPE_NODE_TYPES); return $this->nodeComparator->areNodesEqual($firstNodeScopeNode, $secondNodeScopeNode); } - - public function areScopeNestingEqual(Node $firstNode, Node $secondNode): bool + public function areScopeNestingEqual(\PhpParser\Node $firstNode, \PhpParser\Node $secondNode) : bool { $firstNodeScopeNode = $this->findParentControlStructure($firstNode); $secondNodeScopeNode = $this->findParentControlStructure($secondNode); - return $this->nodeComparator->areNodesEqual($firstNodeScopeNode, $secondNodeScopeNode); } - - public function isNodeConditionallyScoped(Expr $expr): bool + public function isNodeConditionallyScoped(\PhpParser\Node\Expr $expr) : bool { - $foundParent = $this->betterNodeFinder->findParentTypes( - $expr, - ControlStructure::CONDITIONAL_NODE_SCOPE_TYPES + [FunctionLike::class] - ); - - if (! $foundParent instanceof Node) { - return false; + $foundParent = $this->betterNodeFinder->findParentTypes($expr, \Rector\NodeNestingScope\ValueObject\ControlStructure::CONDITIONAL_NODE_SCOPE_TYPES + [\PhpParser\Node\FunctionLike::class]); + if (!$foundParent instanceof \PhpParser\Node) { + return \false; } - // is in both if/else branches if ($this->isInBothIfElseBranch($foundParent, $expr)) { - return false; + return \false; } - if (! $foundParent instanceof Else_) { - return ! $foundParent instanceof FunctionLike; + if (!$foundParent instanceof \PhpParser\Node\Stmt\Else_) { + return !$foundParent instanceof \PhpParser\Node\FunctionLike; } - if (! $this->nodeComparator->areNodesEqual($expr, $this->doubleIfBranchExprs)) { - return ! $foundParent instanceof FunctionLike; + if (!$this->nodeComparator->areNodesEqual($expr, $this->doubleIfBranchExprs)) { + return !$foundParent instanceof \PhpParser\Node\FunctionLike; } - return false; + return \false; } - - public function isInBothIfElseBranch(Node $foundParentNode, Expr $seekedExpr): bool + public function isInBothIfElseBranch(\PhpParser\Node $foundParentNode, \PhpParser\Node\Expr $seekedExpr) : bool { - if ($foundParentNode instanceof Else_) { + if ($foundParentNode instanceof \PhpParser\Node\Stmt\Else_) { return $this->nodeComparator->isNodeEqual($seekedExpr, $this->doubleIfBranchExprs); } - - if (! $foundParentNode instanceof If_) { - return false; + if (!$foundParentNode instanceof \PhpParser\Node\Stmt\If_) { + return \false; } - - $foundIfNode = $this->betterNodeFinder->find($foundParentNode->stmts, function ($node) use ($seekedExpr): bool { + $foundIfNode = $this->betterNodeFinder->find($foundParentNode->stmts, function ($node) use($seekedExpr) : bool { return $this->nodeComparator->areNodesEqual($node, $seekedExpr); }); - if ($foundParentNode->else === null) { - return false; + return \false; } - - $foundElseNode = $this->betterNodeFinder->find($foundParentNode->else, function ($node) use ( - $seekedExpr - ): bool { + $foundElseNode = $this->betterNodeFinder->find($foundParentNode->else, function ($node) use($seekedExpr) : bool { return $this->nodeComparator->areNodesEqual($node, $seekedExpr); }); - if ($foundIfNode && $foundElseNode) { $this->doubleIfBranchExprs[] = $seekedExpr; - return true; + return \true; } - - return false; + return \false; } - - private function findParentControlStructure(Node $node): ?Node + private function findParentControlStructure(\PhpParser\Node $node) : ?\PhpParser\Node { - return $this->betterNodeFinder->findParentTypes($node, ControlStructure::BREAKING_SCOPE_NODE_TYPES); + return $this->betterNodeFinder->findParentTypes($node, \Rector\NodeNestingScope\ValueObject\ControlStructure::BREAKING_SCOPE_NODE_TYPES); } } diff --git a/packages/NodeNestingScope/ValueObject/ControlStructure.php b/packages/NodeNestingScope/ValueObject/ControlStructure.php index a4a7db114fe..923f1838f41 100644 --- a/packages/NodeNestingScope/ValueObject/ControlStructure.php +++ b/packages/NodeNestingScope/ValueObject/ControlStructure.php @@ -1,7 +1,6 @@ > */ - public const RETURN_ISOLATING_SCOPE_NODE_TYPES = [ - Function_::class, - ClassMethod::class, - Closure::class, - ArrowFunction::class, - ]; - + public const RETURN_ISOLATING_SCOPE_NODE_TYPES = [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\Closure::class, \PhpParser\Node\Expr\ArrowFunction::class]; /** * @var array> */ - public const BREAKING_SCOPE_NODE_TYPES = [ - For_::class, - Foreach_::class, - If_::class, - While_::class, - Do_::class, - Else_::class, - ElseIf_::class, - Catch_::class, - Case_::class, - FunctionLike::class, - ]; - + public const BREAKING_SCOPE_NODE_TYPES = [\PhpParser\Node\Stmt\For_::class, \PhpParser\Node\Stmt\Foreach_::class, \PhpParser\Node\Stmt\If_::class, \PhpParser\Node\Stmt\While_::class, \PhpParser\Node\Stmt\Do_::class, \PhpParser\Node\Stmt\Else_::class, \PhpParser\Node\Stmt\ElseIf_::class, \PhpParser\Node\Stmt\Catch_::class, \PhpParser\Node\Stmt\Case_::class, \PhpParser\Node\FunctionLike::class]; /** * These situations happens only if condition is met * @var array> */ - public const CONDITIONAL_NODE_SCOPE_TYPES = [ - If_::class, - While_::class, - Do_::class, - Else_::class, - ElseIf_::class, - Catch_::class, - Case_::class, - Match_::class, - Switch_::class, - Foreach_::class, - ]; + public const CONDITIONAL_NODE_SCOPE_TYPES = [\PhpParser\Node\Stmt\If_::class, \PhpParser\Node\Stmt\While_::class, \PhpParser\Node\Stmt\Do_::class, \PhpParser\Node\Stmt\Else_::class, \PhpParser\Node\Stmt\ElseIf_::class, \PhpParser\Node\Stmt\Catch_::class, \PhpParser\Node\Stmt\Case_::class, \PhpParser\Node\Expr\Match_::class, \PhpParser\Node\Stmt\Switch_::class, \PhpParser\Node\Stmt\Foreach_::class]; } diff --git a/packages/NodeRemoval/AssignRemover.php b/packages/NodeRemoval/AssignRemover.php index 6a5a9e5587d..ee124f42b40 100644 --- a/packages/NodeRemoval/AssignRemover.php +++ b/packages/NodeRemoval/AssignRemover.php @@ -1,7 +1,6 @@ nodesToReplaceCollector = $nodesToReplaceCollector; $this->rectorChangeCollector = $rectorChangeCollector; $this->nodeRemover = $nodeRemover; $this->livingCodeManipulator = $livingCodeManipulator; } - - public function removeAssignNode(Assign $assign): void + public function removeAssignNode(\PhpParser\Node\Expr\Assign $assign) : void { - $currentStatement = $assign->getAttribute(AttributeKey::CURRENT_STATEMENT); + $currentStatement = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); $this->livingCodeManipulator->addLivingCodeBeforeNode($assign->var, $currentStatement); - /** @var Assign $assign */ - $parent = $assign->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Expression) { + $parent = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Stmt\Expression) { $this->nodeRemover->removeNode($assign); } else { $this->nodesToReplaceCollector->addReplaceNodeWithAnotherNode($assign, $assign->expr); diff --git a/packages/NodeRemoval/BreakingRemovalGuard.php b/packages/NodeRemoval/BreakingRemovalGuard.php index 1e17b10b748..d5a366c6f6f 100644 --- a/packages/NodeRemoval/BreakingRemovalGuard.php +++ b/packages/NodeRemoval/BreakingRemovalGuard.php @@ -1,7 +1,6 @@ isLegalNodeRemoval($node)) { return; } - // validate the node can be removed - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Node) { - throw new ShouldNotHappenException(); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - throw new ShouldNotHappenException(sprintf( - 'Node "%s" on line %d is child of "%s", so it cannot be removed as it would break PHP code. Change or remove the parent node instead.', - get_class($node), - $node->getLine(), - get_class($parentNode) - )); + throw new \Rector\Core\Exception\ShouldNotHappenException(\sprintf('Node "%s" on line %d is child of "%s", so it cannot be removed as it would break PHP code. Change or remove the parent node instead.', \get_class($node), $node->getLine(), \get_class($parentNode))); } - - public function isLegalNodeRemoval(Node $node): bool + public function isLegalNodeRemoval(\PhpParser\Node $node) : bool { - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof If_ && $parent->cond === $node) { - return false; + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Stmt\If_ && $parent->cond === $node) { + return \false; } - - if ($parent instanceof BooleanNot) { - $parent = $parent->getAttribute(AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Expr\BooleanNot) { + $parent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); } - if ($parent instanceof Assign) { - return false; + if ($parent instanceof \PhpParser\Node\Expr\Assign) { + return \false; } if ($this->isIfCondition($node)) { - return false; + return \false; } - return ! $this->isWhileCondition($node); + return !$this->isWhileCondition($node); } - - private function isIfCondition(Node $node): bool + private function isIfCondition(\PhpParser\Node $node) : bool { - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof If_) { - return false; + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Stmt\If_) { + return \false; } - return $parentNode->cond === $node; } - - private function isWhileCondition(Node $node): bool + private function isWhileCondition(\PhpParser\Node $node) : bool { - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof While_) { - return false; + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Stmt\While_) { + return \false; } - return $parentNode->cond === $node; } } diff --git a/packages/NodeRemoval/ClassMethodRemover.php b/packages/NodeRemoval/ClassMethodRemover.php index e84d49d5f74..53818b51252 100644 --- a/packages/NodeRemoval/ClassMethodRemover.php +++ b/packages/NodeRemoval/ClassMethodRemover.php @@ -1,7 +1,6 @@ nodeRepository = $nodeRepository; $this->nodeRemover = $nodeRemover; $this->livingCodeManipulator = $livingCodeManipulator; } - - public function removeClassMethodAndUsages(ClassMethod $classMethod): void + public function removeClassMethodAndUsages(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { $this->nodeRemover->removeNode($classMethod); - $calls = $this->nodeRepository->findCallsByClassMethod($classMethod); foreach ($calls as $call) { - if ($call instanceof ArrayCallable) { + if ($call instanceof \Rector\NodeCollector\ValueObject\ArrayCallable) { continue; } - $this->removeMethodCall($call); } } - /** * @param MethodCall|StaticCall $node */ - private function removeMethodCall(Node $node): void + private function removeMethodCall(\PhpParser\Node $node) : void { - $currentStatement = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); + $currentStatement = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); foreach ($node->args as $arg) { $this->livingCodeManipulator->addLivingCodeBeforeNode($arg->value, $currentStatement); } - $this->nodeRemover->removeNode($node); } } diff --git a/packages/NodeRemoval/NodeRemover.php b/packages/NodeRemoval/NodeRemover.php index 91bd4a7a2b1..ae95f89e98c 100644 --- a/packages/NodeRemoval/NodeRemover.php +++ b/packages/NodeRemoval/NodeRemover.php @@ -1,7 +1,6 @@ nodesToRemoveCollector = $nodesToRemoveCollector; $this->rectorChangeCollector = $rectorChangeCollector; } - - public function removeNode(Node $node): void + public function removeNode(\PhpParser\Node $node) : void { // this make sure to keep just added nodes, e.g. added class constant, that doesn't have analysis of full code in this run // if this is missing, there are false positive e.g. for unused private constant - $isJustAddedNode = ! (bool) $node->getAttribute(AttributeKey::ORIGINAL_NODE); + $isJustAddedNode = !(bool) $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE); if ($isJustAddedNode) { return; } - $this->nodesToRemoveCollector->addNodeToRemove($node); $this->rectorChangeCollector->notifyNodeFileInfo($node); } - /** * @param Class_|ClassMethod|Function_ $nodeWithStatements */ - public function removeNodeFromStatements(Node $nodeWithStatements, Node $nodeToRemove): void + public function removeNodeFromStatements(\PhpParser\Node $nodeWithStatements, \PhpParser\Node $nodeToRemove) : void { foreach ((array) $nodeWithStatements->stmts as $key => $stmt) { if ($nodeToRemove !== $stmt) { continue; } - unset($nodeWithStatements->stmts[$key]); break; } } - /** * @param Node[] $nodes */ - public function removeNodes(array $nodes): void + public function removeNodes(array $nodes) : void { foreach ($nodes as $node) { $this->removeNode($node); } } - /** * @param Closure|ClassMethod|Function_ $node */ - public function removeStmt(Node $node, int $key): void + public function removeStmt(\PhpParser\Node $node, int $key) : void { if ($node->stmts === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - // notify about remove node $this->rectorChangeCollector->notifyNodeFileInfo($node->stmts[$key]); - unset($node->stmts[$key]); } - /** * @param int|Param $keyOrParam */ - public function removeParam(ClassMethod $classMethod, $keyOrParam): void + public function removeParam(\PhpParser\Node\Stmt\ClassMethod $classMethod, $keyOrParam) : void { - $key = $keyOrParam instanceof Param ? $keyOrParam->getAttribute(AttributeKey::PARAMETER_POSITION) : $keyOrParam; - + $key = $keyOrParam instanceof \PhpParser\Node\Param ? $keyOrParam->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARAMETER_POSITION) : $keyOrParam; if ($classMethod->params === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - // notify about remove node $this->rectorChangeCollector->notifyNodeFileInfo($classMethod->params[$key]); - unset($classMethod->params[$key]); } - /** * @param FuncCall|MethodCall|StaticCall $node */ - public function removeArg(Node $node, int $key): void + public function removeArg(\PhpParser\Node $node, int $key) : void { if ($node->args === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - // notify about remove node $this->rectorChangeCollector->notifyNodeFileInfo($node->args[$key]); - unset($node->args[$key]); } - - public function removeImplements(Class_ $class, int $key): void + public function removeImplements(\PhpParser\Node\Stmt\Class_ $class, int $key) : void { if ($class->implements === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - // notify about remove node $this->rectorChangeCollector->notifyNodeFileInfo($class->implements[$key]); - unset($class->implements[$key]); } } diff --git a/packages/NodeTypeResolver/Contract/NodeTypeResolverInterface.php b/packages/NodeTypeResolver/Contract/NodeTypeResolverInterface.php index a4e72df161e..6ab1544fd7c 100644 --- a/packages/NodeTypeResolver/Contract/NodeTypeResolverInterface.php +++ b/packages/NodeTypeResolver/Contract/NodeTypeResolverInterface.php @@ -1,18 +1,15 @@ > */ - public function getNodeClasses(): array; - - public function resolve(Node $node): Type; + public function getNodeClasses() : array; + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type; } diff --git a/packages/NodeTypeResolver/Contract/SourceLocatorProviderInterface.php b/packages/NodeTypeResolver/Contract/SourceLocatorProviderInterface.php index 5e1368f10f8..16d92e81495 100644 --- a/packages/NodeTypeResolver/Contract/SourceLocatorProviderInterface.php +++ b/packages/NodeTypeResolver/Contract/SourceLocatorProviderInterface.php @@ -1,12 +1,10 @@ provideStringParameter(Option::PHPSTAN_FOR_RECTOR_PATH); + $additionalConfigFiles[] = $parameterProvider->provideStringParameter(\Rector\Core\Configuration\Option::PHPSTAN_FOR_RECTOR_PATH); $additionalConfigFiles[] = __DIR__ . '/../../../config/phpstan/static-reflection.neon'; $additionalConfigFiles[] = __DIR__ . '/../../../config/phpstan/better-infer.neon'; - - $existingAdditionalConfigFiles = array_filter($additionalConfigFiles, 'file_exists'); - - $this->container = $containerFactory->create(sys_get_temp_dir(), $existingAdditionalConfigFiles, []); + $existingAdditionalConfigFiles = \array_filter($additionalConfigFiles, 'file_exists'); + $this->container = $containerFactory->create(\sys_get_temp_dir(), $existingAdditionalConfigFiles, []); } - /** * @api */ - public function createReflectionProvider(): ReflectionProvider + public function createReflectionProvider() : \PHPStan\Reflection\ReflectionProvider { - return $this->container->getByType(ReflectionProvider::class); + return $this->container->getByType(\PHPStan\Reflection\ReflectionProvider::class); } - /** * @api */ - public function createNodeScopeResolver(): NodeScopeResolver + public function createNodeScopeResolver() : \PHPStan\Analyser\NodeScopeResolver { - return $this->container->getByType(NodeScopeResolver::class); + return $this->container->getByType(\PHPStan\Analyser\NodeScopeResolver::class); } - /** * @api */ - public function createTypeSpecifier(): TypeSpecifier + public function createTypeSpecifier() : \PHPStan\Analyser\TypeSpecifier { - return $this->container->getByType(TypeSpecifier::class); + return $this->container->getByType(\PHPStan\Analyser\TypeSpecifier::class); } - /** * @api */ - public function createScopeFactory(): ScopeFactory + public function createScopeFactory() : \PHPStan\Analyser\ScopeFactory { - return $this->container->getByType(ScopeFactory::class); + return $this->container->getByType(\PHPStan\Analyser\ScopeFactory::class); } - /** * @api */ - public function createDependencyResolver(): DependencyResolver + public function createDependencyResolver() : \PHPStan\Dependency\DependencyResolver { - return $this->container->getByType(DependencyResolver::class); + return $this->container->getByType(\PHPStan\Dependency\DependencyResolver::class); } - /** * @api */ - public function createFileHelper(): FileHelper + public function createFileHelper() : \PHPStan\File\FileHelper { - return $this->container->getByType(FileHelper::class); + return $this->container->getByType(\PHPStan\File\FileHelper::class); } - /** * @api */ - public function createOperatorTypeSpecifyingExtensionRegistryProvider(): OperatorTypeSpecifyingExtensionRegistryProvider + public function createOperatorTypeSpecifyingExtensionRegistryProvider() : \PHPStan\DependencyInjection\Type\OperatorTypeSpecifyingExtensionRegistryProvider { - return $this->container->getByType(OperatorTypeSpecifyingExtensionRegistryProvider::class); + return $this->container->getByType(\PHPStan\DependencyInjection\Type\OperatorTypeSpecifyingExtensionRegistryProvider::class); } - /** * @api */ - public function createTypeNodeResolver(): TypeNodeResolver + public function createTypeNodeResolver() : \PHPStan\PhpDoc\TypeNodeResolver { - return $this->container->getByType(TypeNodeResolver::class); + return $this->container->getByType(\PHPStan\PhpDoc\TypeNodeResolver::class); } - /** * @api */ - public function createDynamicSourceLocatorProvider(): DynamicSourceLocatorProvider + public function createDynamicSourceLocatorProvider() : \Rector\NodeTypeResolver\Reflection\BetterReflection\SourceLocatorProvider\DynamicSourceLocatorProvider { - return $this->container->getByType(DynamicSourceLocatorProvider::class); + return $this->container->getByType(\Rector\NodeTypeResolver\Reflection\BetterReflection\SourceLocatorProvider\DynamicSourceLocatorProvider::class); } } diff --git a/packages/NodeTypeResolver/Exception/MissingTagException.php b/packages/NodeTypeResolver/Exception/MissingTagException.php index c2e2a958e10..52fb38917ff 100644 --- a/packages/NodeTypeResolver/Exception/MissingTagException.php +++ b/packages/NodeTypeResolver/Exception/MissingTagException.php @@ -1,11 +1,9 @@ phpStanNodeScopeResolver = $phpStanNodeScopeResolver; $this->cloningVisitor = $cloningVisitor; $this->functionMethodAndClassNodeVisitor = $functionMethodAndClassNodeVisitor; @@ -80,66 +62,54 @@ final class NodeScopeAndMetadataDecorator $this->nodeConnectingVisitor = $nodeConnectingVisitor; $this->functionLikeParamArgPositionNodeVisitor = $functionLikeParamArgPositionNodeVisitor; } - /** * @param Stmt[] $nodes * @return Stmt[] */ - public function decorateNodesFromFile(File $file, array $nodes, SmartFileInfo $smartFileInfo): array + public function decorateNodesFromFile(\Rector\Core\ValueObject\Application\File $file, array $nodes, \Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : array { - $nodeTraverser = new NodeTraverser(); - $nodeTraverser->addVisitor(new NameResolver(null, [ - 'preserveOriginalNames' => true, + $nodeTraverser = new \PhpParser\NodeTraverser(); + $nodeTraverser->addVisitor(new \PhpParser\NodeVisitor\NameResolver(null, [ + 'preserveOriginalNames' => \true, // required by PHPStan - 'replaceNodes' => true, + 'replaceNodes' => \true, ])); - $nodes = $nodeTraverser->traverse($nodes); $nodes = $this->phpStanNodeScopeResolver->processNodes($nodes, $smartFileInfo); - - $nodeTraverser = new NodeTraverser(); - - $preservingNameResolver = new NameResolver(null, [ - 'preserveOriginalNames' => true, + $nodeTraverser = new \PhpParser\NodeTraverser(); + $preservingNameResolver = new \PhpParser\NodeVisitor\NameResolver(null, [ + 'preserveOriginalNames' => \true, // this option would override old non-fqn-namespaced nodes otherwise, so it needs to be disabled - 'replaceNodes' => false, + 'replaceNodes' => \false, ]); - $nodeTraverser->addVisitor($preservingNameResolver); $nodes = $nodeTraverser->traverse($nodes); - - $nodeTraverser = new NodeTraverser(); + $nodeTraverser = new \PhpParser\NodeTraverser(); // needed also for format preserving printing $nodeTraverser->addVisitor($this->cloningVisitor); $nodeTraverser->addVisitor($this->nodeConnectingVisitor); $nodeTraverser->addVisitor($this->functionMethodAndClassNodeVisitor); $nodeTraverser->addVisitor($this->namespaceNodeVisitor); $nodeTraverser->addVisitor($this->functionLikeParamArgPositionNodeVisitor); - - $fileNodeVisitor = new FileNodeVisitor($file); + $fileNodeVisitor = new \Rector\NodeTypeResolver\NodeVisitor\FileNodeVisitor($file); $nodeTraverser->addVisitor($fileNodeVisitor); - $nodes = $nodeTraverser->traverse($nodes); - // this split is needed, so nodes have names, classes and namespaces - $nodeTraverser = new NodeTraverser(); + $nodeTraverser = new \PhpParser\NodeTraverser(); $nodeTraverser->addVisitor($this->statementNodeVisitor); $nodeTraverser->addVisitor($this->nodeCollectorNodeVisitor); - return $nodeTraverser->traverse($nodes); } - /** * @param Stmt[] $nodes * @return Stmt[] */ - public function decorateNodesFromString(array $nodes): array + public function decorateNodesFromString(array $nodes) : array { - $nodeTraverser = new NodeTraverser(); + $nodeTraverser = new \PhpParser\NodeTraverser(); $nodeTraverser->addVisitor($this->nodeConnectingVisitor); $nodeTraverser->addVisitor($this->functionMethodAndClassNodeVisitor); $nodeTraverser->addVisitor($this->statementNodeVisitor); - return $nodeTraverser->traverse($nodes); } } diff --git a/packages/NodeTypeResolver/NodeTypeCorrector/GenericClassStringTypeCorrector.php b/packages/NodeTypeResolver/NodeTypeCorrector/GenericClassStringTypeCorrector.php index 54a4a143806..ffe9e38b0f7 100644 --- a/packages/NodeTypeResolver/NodeTypeCorrector/GenericClassStringTypeCorrector.php +++ b/packages/NodeTypeResolver/NodeTypeCorrector/GenericClassStringTypeCorrector.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function correct(Type $mainType): Type + public function correct(\PHPStan\Type\Type $mainType) : \PHPStan\Type\Type { // inspired from https://github.com/phpstan/phpstan-src/blob/94e3443b2d21404a821e05b901dd4b57fcbd4e7f/src/Type/Generic/TemplateTypeHelper.php#L18 - return TypeTraverser::map($mainType, function (Type $type, callable $traverse): Type { - if (! $type instanceof ConstantStringType) { + return \PHPStan\Type\TypeTraverser::map($mainType, function (\PHPStan\Type\Type $type, callable $traverse) : Type { + if (!$type instanceof \PHPStan\Type\Constant\ConstantStringType) { return $traverse($type); } - - if (! $this->reflectionProvider->hasClass($type->getValue())) { + if (!$this->reflectionProvider->hasClass($type->getValue())) { return $traverse($type); } - - return new GenericClassStringType(new ObjectType($type->getValue())); + return new \PHPStan\Type\Generic\GenericClassStringType(new \PHPStan\Type\ObjectType($type->getValue())); }); } } diff --git a/packages/NodeTypeResolver/NodeTypeCorrector/HasOffsetTypeCorrector.php b/packages/NodeTypeResolver/NodeTypeCorrector/HasOffsetTypeCorrector.php index 62019aa1fa1..1ce99ef4377 100644 --- a/packages/NodeTypeResolver/NodeTypeCorrector/HasOffsetTypeCorrector.php +++ b/packages/NodeTypeResolver/NodeTypeCorrector/HasOffsetTypeCorrector.php @@ -1,42 +1,35 @@ getTypes() as $intersectionedType) { - if ($intersectionedType instanceof HasOffsetType) { + if ($intersectionedType instanceof \PHPStan\Type\Accessory\HasOffsetType) { continue; } - - if ($intersectionedType instanceof NonEmptyArrayType) { + if ($intersectionedType instanceof \PHPStan\Type\Accessory\NonEmptyArrayType) { continue; } - $clearTypes[] = $intersectionedType; } - - if (count($clearTypes) === 1) { + if (\count($clearTypes) === 1) { return $clearTypes[0]; } - - return new IntersectionType($clearTypes); + return new \PHPStan\Type\IntersectionType($clearTypes); } } diff --git a/packages/NodeTypeResolver/NodeTypeCorrector/PregMatchTypeCorrector.php b/packages/NodeTypeResolver/NodeTypeCorrector/PregMatchTypeCorrector.php index f960755bf24..8b9a954f62e 100644 --- a/packages/NodeTypeResolver/NodeTypeCorrector/PregMatchTypeCorrector.php +++ b/packages/NodeTypeResolver/NodeTypeCorrector/PregMatchTypeCorrector.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; $this->parentScopeFinder = $parentScopeFinder; $this->nodeComparator = $nodeComparator; } - /** * Special case for "preg_match(), preg_match_all()" - with 3rd argument * @see https://github.com/rectorphp/rector/issues/786 */ - public function correct(Node $node, Type $originalType): Type + public function correct(\PhpParser\Node $node, \PHPStan\Type\Type $originalType) : \PHPStan\Type\Type { - if (! $node instanceof Variable) { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { return $originalType; } - - if ($originalType instanceof ArrayType) { + if ($originalType instanceof \PHPStan\Type\ArrayType) { return $originalType; } - $variableUsages = $this->getVariableUsages($node); foreach ($variableUsages as $variableUsage) { - $possiblyArg = $variableUsage->getAttribute(AttributeKey::PARENT_NODE); - if (! $possiblyArg instanceof Arg) { + $possiblyArg = $variableUsage->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$possiblyArg instanceof \PhpParser\Node\Arg) { continue; } - - $funcCallNode = $possiblyArg->getAttribute(AttributeKey::PARENT_NODE); - - if (! $funcCallNode instanceof FuncCall) { + $funcCallNode = $possiblyArg->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$funcCallNode instanceof \PhpParser\Node\Expr\FuncCall) { continue; } - - if (! $this->nodeNameResolver->isNames($funcCallNode, ['preg_match', 'preg_match_all'])) { + if (!$this->nodeNameResolver->isNames($funcCallNode, ['preg_match', 'preg_match_all'])) { continue; } - - if (! isset($funcCallNode->args[2])) { + if (!isset($funcCallNode->args[2])) { continue; } - // are the same variables - if (! $this->nodeComparator->areNodesEqual($funcCallNode->args[2]->value, $node)) { + if (!$this->nodeComparator->areNodesEqual($funcCallNode->args[2]->value, $node)) { continue; } - - return new ArrayType(new MixedType(), new MixedType()); + return new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); } - return $originalType; } - /** * @return Node[] */ - private function getVariableUsages(Variable $variable): array + private function getVariableUsages(\PhpParser\Node\Expr\Variable $variable) : array { $scope = $this->parentScopeFinder->find($variable); if ($scope === null) { return []; } - - return $this->betterNodeFinder->find((array) $scope->stmts, function (Node $node) use ($variable): bool { - if (! $node instanceof Variable) { - return false; + return $this->betterNodeFinder->find((array) $scope->stmts, function (\PhpParser\Node $node) use($variable) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } return $node->name === $variable->name; }); diff --git a/packages/NodeTypeResolver/NodeTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver.php index b1549e89377..9d6e9c1d440 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver.php @@ -1,7 +1,6 @@ , NodeTypeResolverInterface> */ private $nodeTypeResolvers = []; - /** * @var ObjectTypeSpecifier */ private $objectTypeSpecifier; - /** * @var ArrayTypeAnalyzer */ private $arrayTypeAnalyzer; - /** * @var ClassAnalyzer */ private $classAnalyzer; - /** * @var GenericClassStringTypeCorrector */ private $genericClassStringTypeCorrector; - /** * @var ReflectionProvider */ private $reflectionProvider; - /** * @var HasOffsetTypeCorrector */ private $hasOffsetTypeCorrector; - /** * @var IdentifierTypeResolver */ private $identifierTypeResolver; - /** * @var RenamedClassesDataCollector */ private $renamedClassesDataCollector; - /** * @param NodeTypeResolverInterface[] $nodeTypeResolvers */ - public function __construct( - ObjectTypeSpecifier $objectTypeSpecifier, - ClassAnalyzer $classAnalyzer, - GenericClassStringTypeCorrector $genericClassStringTypeCorrector, - ReflectionProvider $reflectionProvider, - HasOffsetTypeCorrector $hasOffsetTypeCorrector, - IdentifierTypeResolver $identifierTypeResolver, - RenamedClassesDataCollector $renamedClassesDataCollector, - array $nodeTypeResolvers - ) { + public function __construct(\Rector\TypeDeclaration\PHPStan\Type\ObjectTypeSpecifier $objectTypeSpecifier, \Rector\Core\NodeAnalyzer\ClassAnalyzer $classAnalyzer, \Rector\NodeTypeResolver\NodeTypeCorrector\GenericClassStringTypeCorrector $genericClassStringTypeCorrector, \PHPStan\Reflection\ReflectionProvider $reflectionProvider, \Rector\NodeTypeResolver\NodeTypeCorrector\HasOffsetTypeCorrector $hasOffsetTypeCorrector, \Rector\NodeTypeResolver\NodeTypeResolver\IdentifierTypeResolver $identifierTypeResolver, \Rector\Core\Configuration\RenamedClassesDataCollector $renamedClassesDataCollector, array $nodeTypeResolvers) + { foreach ($nodeTypeResolvers as $nodeTypeResolver) { $this->addNodeTypeResolver($nodeTypeResolver); } - $this->objectTypeSpecifier = $objectTypeSpecifier; $this->classAnalyzer = $classAnalyzer; $this->genericClassStringTypeCorrector = $genericClassStringTypeCorrector; @@ -122,403 +102,319 @@ final class NodeTypeResolver $this->identifierTypeResolver = $identifierTypeResolver; $this->renamedClassesDataCollector = $renamedClassesDataCollector; } - /** * Prevents circular dependency * * @required */ - public function autowireNodeTypeResolver(ArrayTypeAnalyzer $arrayTypeAnalyzer): void + public function autowireNodeTypeResolver(\Rector\NodeTypeResolver\TypeAnalyzer\ArrayTypeAnalyzer $arrayTypeAnalyzer) : void { $this->arrayTypeAnalyzer = $arrayTypeAnalyzer; } - /** * @param ObjectType[] $requiredTypes */ - public function isObjectTypes(Node $node, array $requiredTypes): bool + public function isObjectTypes(\PhpParser\Node $node, array $requiredTypes) : bool { foreach ($requiredTypes as $requiredType) { if ($this->isObjectType($node, $requiredType)) { - return true; + return \true; } } - - return false; + return \false; } - - public function isObjectType(Node $node, ObjectType $requiredObjectType): bool + public function isObjectType(\PhpParser\Node $node, \PHPStan\Type\ObjectType $requiredObjectType) : bool { - if ($node instanceof ClassConstFetch) { - throw new ShouldNotHappenException(); + if ($node instanceof \PhpParser\Node\Expr\ClassConstFetch) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $resolvedType = $this->resolve($node); - if ($resolvedType instanceof MixedType) { - return false; + if ($resolvedType instanceof \PHPStan\Type\MixedType) { + return \false; } - - if ($resolvedType instanceof ThisType) { + if ($resolvedType instanceof \PHPStan\Type\ThisType) { $resolvedType = $resolvedType->getStaticObjectType(); } - - if ($resolvedType instanceof ObjectType) { + if ($resolvedType instanceof \PHPStan\Type\ObjectType) { return $this->resolveObjectType($resolvedType, $requiredObjectType); } - return $this->isMatchingUnionType($resolvedType, $requiredObjectType); } - - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { $type = $this->resolveByNodeTypeResolvers($node); if ($type !== null) { return $this->hasOffsetTypeCorrector->correct($type); } - - $scope = $node->getAttribute(AttributeKey::SCOPE); - - if (! $scope instanceof Scope) { - if ($node instanceof ConstFetch && $node->name instanceof Name) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + if ($node instanceof \PhpParser\Node\Expr\ConstFetch && $node->name instanceof \PhpParser\Node\Name) { $name = (string) $node->name; - if (strtolower($name) === 'null') { - return new NullType(); + if (\strtolower($name) === 'null') { + return new \PHPStan\Type\NullType(); } } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - if (! $node instanceof Expr) { + if (!$node instanceof \PhpParser\Node\Expr) { // scalar type, e.g. from param type name - if ($node instanceof Identifier) { + if ($node instanceof \PhpParser\Node\Identifier) { return $this->identifierTypeResolver->resolve($node); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - // skip anonymous classes, ref https://github.com/rectorphp/rector/issues/1574 - if ($node instanceof New_ && $this->classAnalyzer->isAnonymousClass($node->class)) { - return new ObjectWithoutClassType(); + if ($node instanceof \PhpParser\Node\Expr\New_ && $this->classAnalyzer->isAnonymousClass($node->class)) { + return new \PHPStan\Type\ObjectWithoutClassType(); } - $type = $scope->getType($node); - // hot fix for phpstan not resolving chain method calls - if (! $node instanceof MethodCall) { + if (!$node instanceof \PhpParser\Node\Expr\MethodCall) { return $type; } - - if (! $type instanceof MixedType) { + if (!$type instanceof \PHPStan\Type\MixedType) { return $type; } - return $this->resolve($node->var); } - /** * e.g. string|null, ObjectNull|null */ - public function isNullableType(Node $node): bool + public function isNullableType(\PhpParser\Node $node) : bool { $nodeType = $this->resolve($node); - return TypeCombinator::containsNull($nodeType); + return \PHPStan\Type\TypeCombinator::containsNull($nodeType); } - - public function getNativeType(Expr $expr): Type + public function getNativeType(\PhpParser\Node\Expr $expr) : \PHPStan\Type\Type { - $scope = $expr->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return new MixedType(); + $scope = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return new \PHPStan\Type\MixedType(); } - return $scope->getNativeType($expr); } - - public function getStaticType(Node $node): Type + public function getStaticType(\PhpParser\Node $node) : \PHPStan\Type\Type { - if ($node instanceof Param) { + if ($node instanceof \PhpParser\Node\Param) { return $this->resolve($node); } - - if ($node instanceof New_) { + if ($node instanceof \PhpParser\Node\Expr\New_) { return $this->resolve($node); } - - if ($node instanceof Return_) { + if ($node instanceof \PhpParser\Node\Stmt\Return_) { return $this->resolve($node); } - - if (! $node instanceof Expr) { - return new MixedType(); + if (!$node instanceof \PhpParser\Node\Expr) { + return new \PHPStan\Type\MixedType(); } - if ($this->arrayTypeAnalyzer->isArrayType($node)) { return $this->resolveArrayType($node); } - - if ($node instanceof Scalar) { + if ($node instanceof \PhpParser\Node\Scalar) { return $this->resolve($node); } - - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return new MixedType(); + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return new \PHPStan\Type\MixedType(); } - $staticType = $scope->getType($node); - if ($staticType instanceof GenericObjectType) { + if ($staticType instanceof \PHPStan\Type\Generic\GenericObjectType) { return $staticType; } - - if ($staticType instanceof ObjectType) { + if ($staticType instanceof \PHPStan\Type\ObjectType) { return $this->objectTypeSpecifier->narrowToFullyQualifiedOrAliasedObjectType($node, $staticType); } - return $staticType; } - - public function isNumberType(Node $node): bool + public function isNumberType(\PhpParser\Node $node) : bool { - if ($this->isStaticType($node, IntegerType::class)) { - return true; + if ($this->isStaticType($node, \PHPStan\Type\IntegerType::class)) { + return \true; } - - return $this->isStaticType($node, FloatType::class); + return $this->isStaticType($node, \PHPStan\Type\FloatType::class); } - /** * @param class-string $staticTypeClass */ - public function isStaticType(Node $node, string $staticTypeClass): bool + public function isStaticType(\PhpParser\Node $node, string $staticTypeClass) : bool { - if (! is_a($staticTypeClass, Type::class, true)) { - throw new ShouldNotHappenException(sprintf( - '"%s" in "%s()" must be type of "%s"', - $staticTypeClass, - __METHOD__, - Type::class - )); + if (!\is_a($staticTypeClass, \PHPStan\Type\Type::class, \true)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(\sprintf('"%s" in "%s()" must be type of "%s"', $staticTypeClass, __METHOD__, \PHPStan\Type\Type::class)); } - - return is_a($this->resolve($node), $staticTypeClass); + return \is_a($this->resolve($node), $staticTypeClass); } - /** * @param class-string $desiredType */ - public function isNullableTypeOfSpecificType(Node $node, string $desiredType): bool + public function isNullableTypeOfSpecificType(\PhpParser\Node $node, string $desiredType) : bool { $nodeType = $this->resolve($node); - if (! $nodeType instanceof UnionType) { - return false; + if (!$nodeType instanceof \PHPStan\Type\UnionType) { + return \false; } - - if (! TypeCombinator::containsNull($nodeType)) { - return false; + if (!\PHPStan\Type\TypeCombinator::containsNull($nodeType)) { + return \false; } - - if (count($nodeType->getTypes()) !== 2) { - return false; + if (\count($nodeType->getTypes()) !== 2) { + return \false; } - foreach ($nodeType->getTypes() as $type) { - if (is_a($type, $desiredType, true)) { - return true; + if (\is_a($type, $desiredType, \true)) { + return \true; } } - - return false; + return \false; } - - public function isPropertyBoolean(Property $property): bool + public function isPropertyBoolean(\PhpParser\Node\Stmt\Property $property) : bool { - if ($this->isStaticType($property, BooleanType::class)) { - return true; + if ($this->isStaticType($property, \PHPStan\Type\BooleanType::class)) { + return \true; } - $defaultNodeValue = $property->props[0]->default; - if (! $defaultNodeValue instanceof Expr) { - return false; + if (!$defaultNodeValue instanceof \PhpParser\Node\Expr) { + return \false; } - - return $this->isStaticType($defaultNodeValue, BooleanType::class); + return $this->isStaticType($defaultNodeValue, \PHPStan\Type\BooleanType::class); } - /** * @return class-string */ - public function getFullyQualifiedClassName(TypeWithClassName $typeWithClassName): string + public function getFullyQualifiedClassName(\PHPStan\Type\TypeWithClassName $typeWithClassName) : string { - if ($typeWithClassName instanceof ShortenedObjectType) { + if ($typeWithClassName instanceof \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType) { return $typeWithClassName->getFullyQualifiedName(); } - return $typeWithClassName->getClassName(); } - /** * @param Type[] $desiredTypes */ - public function isSameObjectTypes(ObjectType $objectType, array $desiredTypes): bool + public function isSameObjectTypes(\PHPStan\Type\ObjectType $objectType, array $desiredTypes) : bool { foreach ($desiredTypes as $desiredType) { $desiredTypeEquals = $desiredType->equals($objectType); if ($desiredTypeEquals) { - return true; + return \true; } } - - return false; + return \false; } - - public function isMethodStaticCallOrClassMethodObjectType(Node $node, ObjectType $objectType): bool + public function isMethodStaticCallOrClassMethodObjectType(\PhpParser\Node $node, \PHPStan\Type\ObjectType $objectType) : bool { - if ($node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { // method call is variable return return $this->isObjectType($node->var, $objectType); } - - if ($node instanceof StaticCall) { + if ($node instanceof \PhpParser\Node\Expr\StaticCall) { return $this->isObjectType($node->class, $objectType); } - - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return false; + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } - return $this->isObjectType($classLike, $objectType); } - - public function resolveObjectTypeFromScope(Scope $scope): ?ObjectType + public function resolveObjectTypeFromScope(\PHPStan\Analyser\Scope $scope) : ?\PHPStan\Type\ObjectType { $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - $className = $classReflection->getName(); - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return null; } - - return new ObjectType($className, null, $classReflection); + return new \PHPStan\Type\ObjectType($className, null, $classReflection); } - - private function addNodeTypeResolver(NodeTypeResolverInterface $nodeTypeResolver): void + private function addNodeTypeResolver(\Rector\NodeTypeResolver\Contract\NodeTypeResolverInterface $nodeTypeResolver) : void { foreach ($nodeTypeResolver->getNodeClasses() as $nodeClass) { $this->nodeTypeResolvers[$nodeClass] = $nodeTypeResolver; } } - - private function isMatchingUnionType(Type $resolvedType, ObjectType $requiredObjectType): bool + private function isMatchingUnionType(\PHPStan\Type\Type $resolvedType, \PHPStan\Type\ObjectType $requiredObjectType) : bool { - $type = TypeCombinator::removeNull($resolvedType); + $type = \PHPStan\Type\TypeCombinator::removeNull($resolvedType); // for falsy nullables - $type = TypeCombinator::remove($type, new ConstantBooleanType(false)); - - if (! $type instanceof ObjectType) { - return false; + $type = \PHPStan\Type\TypeCombinator::remove($type, new \PHPStan\Type\Constant\ConstantBooleanType(\false)); + if (!$type instanceof \PHPStan\Type\ObjectType) { + return \false; } - - return $type->isInstanceOf($requiredObjectType->getClassName()) - ->yes(); + return $type->isInstanceOf($requiredObjectType->getClassName())->yes(); } - - private function resolveArrayType(Expr $expr): Type + private function resolveArrayType(\PhpParser\Node\Expr $expr) : \PHPStan\Type\Type { /** @var Scope|null $scope */ - $scope = $expr->getAttribute(AttributeKey::SCOPE); - - if ($scope instanceof Scope) { + $scope = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if ($scope instanceof \PHPStan\Analyser\Scope) { $arrayType = $scope->getType($expr); $arrayType = $this->genericClassStringTypeCorrector->correct($arrayType); return $this->removeNonEmptyArrayFromIntersectionWithArrayType($arrayType); } - - return new ArrayType(new MixedType(), new MixedType()); + return new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); } - - private function resolveByNodeTypeResolvers(Node $node): ?Type + private function resolveByNodeTypeResolvers(\PhpParser\Node $node) : ?\PHPStan\Type\Type { foreach ($this->nodeTypeResolvers as $nodeClass => $nodeTypeResolver) { - if (! is_a($node, $nodeClass, true)) { + if (!\is_a($node, $nodeClass, \true)) { continue; } - return $nodeTypeResolver->resolve($node); } - return null; } - - private function removeNonEmptyArrayFromIntersectionWithArrayType(Type $type): Type + private function removeNonEmptyArrayFromIntersectionWithArrayType(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - if (! $type instanceof IntersectionType) { + if (!$type instanceof \PHPStan\Type\IntersectionType) { return $type; } - - if (count($type->getTypes()) !== 2) { + if (\count($type->getTypes()) !== 2) { return $type; } - - if (! $type->isSubTypeOf(new NonEmptyArrayType())->yes()) { + if (!$type->isSubTypeOf(new \PHPStan\Type\Accessory\NonEmptyArrayType())->yes()) { return $type; } - $otherType = null; foreach ($type->getTypes() as $intersectionedType) { - if ($intersectionedType instanceof NonEmptyArrayType) { + if ($intersectionedType instanceof \PHPStan\Type\Accessory\NonEmptyArrayType) { continue; } - $otherType = $intersectionedType; break; } - if ($otherType === null) { return $type; } - return $otherType; } - - private function isObjectTypeOfObjectType(ObjectType $resolvedObjectType, ObjectType $requiredObjectType): bool + private function isObjectTypeOfObjectType(\PHPStan\Type\ObjectType $resolvedObjectType, \PHPStan\Type\ObjectType $requiredObjectType) : bool { if ($resolvedObjectType->isInstanceOf($requiredObjectType->getClassName())->yes()) { - return true; + return \true; } - if ($resolvedObjectType->getClassName() === $requiredObjectType->getClassName()) { - return true; + return \true; } - - if (! $this->reflectionProvider->hasClass($resolvedObjectType->getClassName())) { - return false; + if (!$this->reflectionProvider->hasClass($resolvedObjectType->getClassName())) { + return \false; } - $classReflection = $this->reflectionProvider->getClass($resolvedObjectType->getClassName()); foreach ($classReflection->getAncestors() as $ancestorClassReflection) { if ($ancestorClassReflection->hasTraitUse($requiredObjectType->getClassName())) { - return true; + return \true; } } - return $classReflection->isSubclassOf($requiredObjectType->getClassName()); } - - private function resolveObjectType(ObjectType $resolvedObjectType, ObjectType $requiredObjectType): bool + private function resolveObjectType(\PHPStan\Type\ObjectType $resolvedObjectType, \PHPStan\Type\ObjectType $requiredObjectType) : bool { $renamedObjectType = $this->renamedClassesDataCollector->matchClassName($resolvedObjectType); - if (! $renamedObjectType instanceof ObjectType) { + if (!$renamedObjectType instanceof \PHPStan\Type\ObjectType) { return $this->isObjectTypeOfObjectType($resolvedObjectType, $requiredObjectType); } - if (! $this->isObjectTypeOfObjectType($renamedObjectType, $requiredObjectType)) { + if (!$this->isObjectTypeOfObjectType($renamedObjectType, $requiredObjectType)) { return $this->isObjectTypeOfObjectType($resolvedObjectType, $requiredObjectType); } - return true; + return \true; } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/CastTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/CastTypeResolver.php index f8e28cca72f..8f1f12ed6ac 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/CastTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/CastTypeResolver.php @@ -1,7 +1,6 @@ , class-string> */ - private const CAST_CLASS_TO_TYPE_MAP = [ - Bool_::class => BooleanType::class, - String_::class => StringType::class, - Int_::class => IntegerType::class, - Double::class => FloatType::class, - ]; - + private const CAST_CLASS_TO_TYPE_MAP = [\PhpParser\Node\Expr\Cast\Bool_::class => \PHPStan\Type\BooleanType::class, \PhpParser\Node\Expr\Cast\String_::class => \PHPStan\Type\StringType::class, \PhpParser\Node\Expr\Cast\Int_::class => \PHPStan\Type\IntegerType::class, \PhpParser\Node\Expr\Cast\Double::class => \PHPStan\Type\FloatType::class]; /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [Cast::class]; + return [\PhpParser\Node\Expr\Cast::class]; } - /** * @param Cast $node */ - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { foreach (self::CAST_CLASS_TO_TYPE_MAP as $castClass => $typeClass) { - if (is_a($node, $castClass, true)) { + if (\is_a($node, $castClass, \true)) { return new $typeClass(); } } - - if ($node instanceof Array_) { - return new ArrayType(new MixedType(), new MixedType()); + if ($node instanceof \PhpParser\Node\Expr\Cast\Array_) { + return new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); } - - throw new NotImplementedYetException(get_class($node)); + throw new \Rector\Core\Exception\NotImplementedYetException(\get_class($node)); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/ClassAndInterfaceTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/ClassAndInterfaceTypeResolver.php index 58a2f537d7f..0c2afbc4621 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/ClassAndInterfaceTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/ClassAndInterfaceTypeResolver.php @@ -1,7 +1,6 @@ > */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [Class_::class, Interface_::class]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Stmt\Interface_::class]; } - /** * @param Class_|Interface_ $node */ - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { - $scope = $node->getAttribute(AttributeKey::SCOPE); - - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { // new node probably - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return new MixedType(); + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return new \PHPStan\Type\MixedType(); } - - return new ObjectType($classReflection->getName(), null, $classReflection); + return new \PHPStan\Type\ObjectType($classReflection->getName(), null, $classReflection); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/ClassMethodOrClassConstTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/ClassMethodOrClassConstTypeResolver.php index c9bc8c9add3..d17cdfac957 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/ClassMethodOrClassConstTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/ClassMethodOrClassConstTypeResolver.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; } - /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [ClassMethod::class, ClassConst::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\ClassConst::class]; } - /** * @param ClassMethod|ClassConst $node */ - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { // anonymous class - return new ObjectWithoutClassType(); + return new \PHPStan\Type\ObjectWithoutClassType(); } - return $this->nodeTypeResolver->resolve($classLike); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/IdentifierTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/IdentifierTypeResolver.php index b60324b3ee9..87c488a86d8 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/IdentifierTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/IdentifierTypeResolver.php @@ -1,7 +1,6 @@ toLowerString() === 'string') { - return new StringType(); + return new \PHPStan\Type\StringType(); } - if ($identifier->toLowerString() === 'bool') { - return new BooleanType(); + return new \PHPStan\Type\BooleanType(); } - if ($identifier->toLowerString() === 'int') { - return new IntegerType(); + return new \PHPStan\Type\IntegerType(); } - if ($identifier->toLowerString() === 'float') { - return new FloatType(); + return new \PHPStan\Type\FloatType(); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/NameTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/NameTypeResolver.php index 37ba464fa13..7a4fa7ff71d 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/NameTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/NameTypeResolver.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [Name::class, FullyQualified::class]; + return [\PhpParser\Node\Name::class, \PhpParser\Node\Name\FullyQualified::class]; } - /** * @param Name $node */ - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { if ($node->toString() === 'parent') { return $this->resolveParent($node); } - $fullyQualifiedName = $this->resolveFullyQualifiedName($node); - return new ObjectType($fullyQualifiedName); + return new \PHPStan\Type\ObjectType($fullyQualifiedName); } - /** * @return ObjectType|UnionType|MixedType */ - private function resolveParent(Name $name): Type + private function resolveParent(\PhpParser\Node\Name $name) : \PHPStan\Type\Type { - $className = $name->getAttribute(AttributeKey::CLASS_NAME); + $className = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - if (! $this->reflectionProvider->hasClass($className)) { - return new MixedType(); + if (!$this->reflectionProvider->hasClass($className)) { + return new \PHPStan\Type\MixedType(); } - $classReflection = $this->reflectionProvider->getClass($className); - $parentClassObjectTypes = []; foreach ($classReflection->getParents() as $parentClassReflection) { - $parentClassObjectTypes[] = new ObjectType($parentClassReflection->getName()); + $parentClassObjectTypes[] = new \PHPStan\Type\ObjectType($parentClassReflection->getName()); } - if ($parentClassObjectTypes === []) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - if (count($parentClassObjectTypes) === 1) { + if (\count($parentClassObjectTypes) === 1) { return $parentClassObjectTypes[0]; } - - return new UnionType($parentClassObjectTypes); + return new \PHPStan\Type\UnionType($parentClassObjectTypes); } - - private function resolveFullyQualifiedName(Name $name): string + private function resolveFullyQualifiedName(\PhpParser\Node\Name $name) : string { $nameValue = $name->toString(); - if (in_array($nameValue, ['self', 'static', 'this'], true)) { + if (\in_array($nameValue, ['self', 'static', 'this'], \true)) { /** @var string|null $class */ - $class = $name->getAttribute(AttributeKey::CLASS_NAME); + $class = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($class === null) { // anonymous class probably return 'Anonymous'; } - return $class; } - /** @var Name|null $resolvedNameNode */ - $resolvedNameNode = $name->getAttribute(AttributeKey::RESOLVED_NAME); - if ($resolvedNameNode instanceof Name) { + $resolvedNameNode = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::RESOLVED_NAME); + if ($resolvedNameNode instanceof \PhpParser\Node\Name) { return $resolvedNameNode->toString(); } - return $nameValue; } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/NewTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/NewTypeResolver.php index 532326ab314..7d5b8bd2678 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/NewTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/NewTypeResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->classAnalyzer = $classAnalyzer; $this->unionTypeFactory = $unionTypeFactory; } - /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [New_::class]; + return [\PhpParser\Node\Expr\New_::class]; } - /** * @param New_ $node */ - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { - if ($node->class instanceof Name) { + if ($node->class instanceof \PhpParser\Node\Name) { $className = $this->nodeNameResolver->getName($node->class); - if (! in_array($className, ['self', 'parent'], true)) { - return new ObjectType($className); + if (!\in_array($className, ['self', 'parent'], \true)) { + return new \PHPStan\Type\ObjectType($className); } } - $isAnonymousClass = $this->classAnalyzer->isAnonymousClass($node->class); if ($isAnonymousClass) { return $this->resolveAnonymousClassType($node); } - - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { // new node probably - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - return $scope->getType($node); } - - private function resolveAnonymousClassType(New_ $new): ObjectWithoutClassType + private function resolveAnonymousClassType(\PhpParser\Node\Expr\New_ $new) : \PHPStan\Type\ObjectWithoutClassType { - if (! $new->class instanceof Class_) { - return new ObjectWithoutClassType(); + if (!$new->class instanceof \PhpParser\Node\Stmt\Class_) { + return new \PHPStan\Type\ObjectWithoutClassType(); } - $types = []; - /** @var Class_ $class */ $class = $new->class; if ($class->extends !== null) { $parentClass = (string) $class->extends; - $types[] = new FullyQualifiedObjectType($parentClass); + $types[] = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($parentClass); } - foreach ($class->implements as $implement) { $parentClass = (string) $implement; - $types[] = new FullyQualifiedObjectType($parentClass); + $types[] = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($parentClass); } - - if (count($types) > 1) { + if (\count($types) > 1) { $unionType = $this->unionTypeFactory->createUnionObjectType($types); - return new ObjectWithoutClassType($unionType); + return new \PHPStan\Type\ObjectWithoutClassType($unionType); } - - if (count($types) === 1) { - return new ObjectWithoutClassType($types[0]); + if (\count($types) === 1) { + return new \PHPStan\Type\ObjectWithoutClassType($types[0]); } - - return new ObjectWithoutClassType(); + return new \PHPStan\Type\ObjectWithoutClassType(); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/ParamTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/ParamTypeResolver.php index d6ca28cc298..0758b37f624 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/ParamTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/ParamTypeResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->phpDocInfoFactory = $phpDocInfoFactory; } - /** * @required */ - public function autowireParamTypeResolver( - NodeTypeResolver $nodeTypeResolver, - StaticTypeMapper $staticTypeMapper - ): void { + public function autowireParamTypeResolver(\Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver, \Rector\StaticTypeMapper\StaticTypeMapper $staticTypeMapper) : void + { $this->nodeTypeResolver = $nodeTypeResolver; $this->staticTypeMapper = $staticTypeMapper; } - /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [Param::class]; + return [\PhpParser\Node\Param::class]; } - /** * @param Param $node */ - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { $paramType = $this->resolveFromParamType($node); - if (! $paramType instanceof MixedType) { + if (!$paramType instanceof \PHPStan\Type\MixedType) { return $paramType; } - $firstVariableUseType = $this->resolveFromFirstVariableUse($node); - if (! $firstVariableUseType instanceof MixedType) { + if (!$firstVariableUseType instanceof \PHPStan\Type\MixedType) { return $firstVariableUseType; } - return $this->resolveFromFunctionDocBlock($node); } - - private function resolveFromParamType(Param $param): Type + private function resolveFromParamType(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { if ($param->type === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - if ($param->type instanceof Identifier) { - return new MixedType(); + if ($param->type instanceof \PhpParser\Node\Identifier) { + return new \PHPStan\Type\MixedType(); } - return $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); } - - private function resolveFromFirstVariableUse(Param $param): Type + private function resolveFromFirstVariableUse(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { - $classMethod = $param->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { - return new MixedType(); + $classMethod = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return new \PHPStan\Type\MixedType(); } - $paramName = $this->nodeNameResolver->getName($param); - $paramStaticType = new MixedType(); - + $paramStaticType = new \PHPStan\Type\MixedType(); // special case for param inside method/function - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $classMethod->stmts, - function (Node $node) use ($paramName, &$paramStaticType): ?int { - if (! $node instanceof Variable) { - return null; - } - - if (! $this->nodeNameResolver->isName($node, $paramName)) { - return null; - } - - $paramStaticType = $this->nodeTypeResolver->resolve($node); - - return NodeTraverser::STOP_TRAVERSAL; + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->stmts, function (\PhpParser\Node $node) use($paramName, &$paramStaticType) : ?int { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return null; } - ); - + if (!$this->nodeNameResolver->isName($node, $paramName)) { + return null; + } + $paramStaticType = $this->nodeTypeResolver->resolve($node); + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; + }); return $paramStaticType; } - - private function resolveFromFunctionDocBlock(Param $param): Type + private function resolveFromFunctionDocBlock(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { $phpDocInfo = $this->getFunctionLikePhpDocInfo($param); $paramName = $this->nodeNameResolver->getName($param); return $phpDocInfo->getParamType($paramName); } - - private function getFunctionLikePhpDocInfo(Param $param): PhpDocInfo + private function getFunctionLikePhpDocInfo(\PhpParser\Node\Param $param) : \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo { - $parentNode = $param->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof FunctionLike) { - throw new ShouldNotHappenException(); + $parentNode = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\FunctionLike) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - return $this->phpDocInfoFactory->createFromNodeOrEmpty($parentNode); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/PropertyFetchTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/PropertyFetchTypeResolver.php index 157ac28f58c..c3a3cfaf115 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/PropertyFetchTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/PropertyFetchTypeResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->traitNodeScopeCollector = $traitNodeScopeCollector; $this->reflectionProvider = $reflectionProvider; } - /** * @required */ - public function autowirePropertyFetchTypeResolver(NodeTypeResolver $nodeTypeResolver): void + public function autowirePropertyFetchTypeResolver(\Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver) : void { $this->nodeTypeResolver = $nodeTypeResolver; } - /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [PropertyFetch::class]; + return [\PhpParser\Node\Expr\PropertyFetch::class]; } - /** * @param PropertyFetch $node */ - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { // compensate 3rd party non-analysed property reflection $vendorPropertyType = $this->getVendorPropertyFetchType($node); - if (! $vendorPropertyType instanceof MixedType) { + if (!$vendorPropertyType instanceof \PHPStan\Type\MixedType) { return $vendorPropertyType; } - /** @var Scope|null $scope */ - $scope = $node->getAttribute(AttributeKey::SCOPE); - - if (! $scope instanceof Scope) { - $classNode = $node->getAttribute(AttributeKey::CLASS_NODE); - if ($classNode instanceof Trait_) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + $classNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if ($classNode instanceof \PhpParser\Node\Stmt\Trait_) { /** @var string $traitName */ - $traitName = $classNode->getAttribute(AttributeKey::CLASS_NAME); - + $traitName = $classNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); $scope = $this->traitNodeScopeCollector->getScopeForTraitAndNode($traitName, $node); } } - - if (! $scope instanceof Scope) { - $classNode = $node->getAttribute(AttributeKey::CLASS_NODE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + $classNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); // fallback to class, since property fetches are not scoped by PHPStan - if ($classNode instanceof ClassLike) { - $scope = $classNode->getAttribute(AttributeKey::SCOPE); + if ($classNode instanceof \PhpParser\Node\Stmt\ClassLike) { + $scope = $classNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); } - - if (! $scope instanceof Scope) { - return new MixedType(); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return new \PHPStan\Type\MixedType(); } } - return $scope->getType($node); } - - private function getVendorPropertyFetchType(PropertyFetch $propertyFetch): Type + private function getVendorPropertyFetchType(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : \PHPStan\Type\Type { // 3rd party code $propertyName = $this->nodeNameResolver->getName($propertyFetch->name); if ($propertyName === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - $varType = $this->nodeTypeResolver->resolve($propertyFetch->var); - if (! $varType instanceof ObjectType) { - return new MixedType(); + if (!$varType instanceof \PHPStan\Type\ObjectType) { + return new \PHPStan\Type\MixedType(); } - - if (! $this->reflectionProvider->hasClass($varType->getClassName())) { - return new MixedType(); + if (!$this->reflectionProvider->hasClass($varType->getClassName())) { + return new \PHPStan\Type\MixedType(); } - $classReflection = $this->reflectionProvider->getClass($varType->getClassName()); - if (! $classReflection->hasProperty($propertyName)) { - return new MixedType(); + if (!$classReflection->hasProperty($propertyName)) { + return new \PHPStan\Type\MixedType(); } - - $propertyFetchScope = $propertyFetch->getAttribute(AttributeKey::SCOPE); + $propertyFetchScope = $propertyFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); if ($propertyFetchScope === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - $propertyReflection = $classReflection->getProperty($propertyName, $propertyFetchScope); - return $propertyReflection->getReadableType(); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/PropertyTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/PropertyTypeResolver.php index 4dcc6339692..a94393f7ea7 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/PropertyTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/PropertyTypeResolver.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; } - /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $propertyNode */ - public function resolve(Node $propertyNode): Type + public function resolve(\PhpParser\Node $propertyNode) : \PHPStan\Type\Type { // fake property to local PropertyFetch → PHPStan understands that - $propertyFetch = new PropertyFetch(new Variable('this'), (string) $propertyNode->props[0]->name); - $propertyFetch->setAttribute(AttributeKey::SCOPE, $propertyNode->getAttribute(AttributeKey::SCOPE)); - + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), (string) $propertyNode->props[0]->name); + $propertyFetch->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE, $propertyNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE)); return $this->nodeTypeResolver->resolve($propertyFetch); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/ReturnTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/ReturnTypeResolver.php index 75193392330..047f368f5e9 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/ReturnTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/ReturnTypeResolver.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; } - /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [Return_::class]; + return [\PhpParser\Node\Stmt\Return_::class]; } - /** * @param Return_ $node */ - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { if ($node->expr === null) { - return new VoidType(); + return new \PHPStan\Type\VoidType(); } - return $this->nodeTypeResolver->resolve($node->expr); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/ScalarTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/ScalarTypeResolver.php index f2295ec0fc6..d78e9853e6b 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/ScalarTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/ScalarTypeResolver.php @@ -1,7 +1,6 @@ > */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [Scalar::class]; + return [\PhpParser\Node\Scalar::class]; } - - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { - if ($node instanceof DNumber) { - return new ConstantFloatType($node->value); + if ($node instanceof \PhpParser\Node\Scalar\DNumber) { + return new \PHPStan\Type\Constant\ConstantFloatType($node->value); } - - if ($node instanceof String_) { - return new ConstantStringType($node->value); + if ($node instanceof \PhpParser\Node\Scalar\String_) { + return new \PHPStan\Type\Constant\ConstantStringType($node->value); } - - if ($node instanceof LNumber) { - return new ConstantIntegerType($node->value); + if ($node instanceof \PhpParser\Node\Scalar\LNumber) { + return new \PHPStan\Type\Constant\ConstantIntegerType($node->value); } - - if ($node instanceof MagicConst) { - return new ConstantStringType($node->getName()); + if ($node instanceof \PhpParser\Node\Scalar\MagicConst) { + return new \PHPStan\Type\Constant\ConstantStringType($node->getName()); } - - if ($node instanceof Encapsed) { - return new MixedType(); + if ($node instanceof \PhpParser\Node\Scalar\Encapsed) { + return new \PHPStan\Type\MixedType(); } - - throw new NotImplementedYetException(); + throw new \Rector\Core\Exception\NotImplementedYetException(); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/StaticCallMethodCallTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/StaticCallMethodCallTypeResolver.php index 7bb6c844545..92649576160 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/StaticCallMethodCallTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/StaticCallMethodCallTypeResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; } - /** * @required */ - public function autowireStaticCallMethodCallTypeResolver(NodeTypeResolver $nodeTypeResolver): void + public function autowireStaticCallMethodCallTypeResolver(\Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver) : void { $this->nodeTypeResolver = $nodeTypeResolver; } - /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [StaticCall::class, MethodCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Expr\MethodCall::class]; } - /** * @param StaticCall|MethodCall $node */ - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { $methodName = $this->nodeNameResolver->getName($node->name); - // no specific method found, return class types, e.g. ::$method() - if (! is_string($methodName)) { - return new MixedType(); + if (!\is_string($methodName)) { + return new \PHPStan\Type\MixedType(); } - - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return new MixedType(); + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return new \PHPStan\Type\MixedType(); } - $nodeReturnType = $scope->getType($node); - if (! $nodeReturnType instanceof MixedType) { + if (!$nodeReturnType instanceof \PHPStan\Type\MixedType) { return $nodeReturnType; } - - if ($node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { $callerType = $this->nodeTypeResolver->resolve($node->var); } else { $callerType = $this->nodeTypeResolver->resolve($node->class); } - foreach ($callerType->getReferencedClasses() as $referencedClass) { $classMethodReturnType = $this->resolveClassMethodReturnType($referencedClass, $methodName, $scope); - if (! $classMethodReturnType instanceof MixedType) { + if (!$classMethodReturnType instanceof \PHPStan\Type\MixedType) { return $classMethodReturnType; } } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - private function resolveClassMethodReturnType(string $referencedClass, string $methodName, Scope $scope): Type + private function resolveClassMethodReturnType(string $referencedClass, string $methodName, \PHPStan\Analyser\Scope $scope) : \PHPStan\Type\Type { - if (! $this->reflectionProvider->hasClass($referencedClass)) { - return new MixedType(); + if (!$this->reflectionProvider->hasClass($referencedClass)) { + return new \PHPStan\Type\MixedType(); } - $classReflection = $this->reflectionProvider->getClass($referencedClass); - foreach ($classReflection->getAncestors() as $ancestorClassReflection) { - if (! $ancestorClassReflection->hasMethod($methodName)) { + if (!$ancestorClassReflection->hasMethod($methodName)) { continue; } - $methodReflection = $ancestorClassReflection->getMethod($methodName, $scope); - if ($methodReflection instanceof PhpMethodReflection) { + if ($methodReflection instanceof \PHPStan\Reflection\Php\PhpMethodReflection) { $parametersAcceptor = $methodReflection->getVariants()[0]; return $parametersAcceptor->getReturnType(); } } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/TraitTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/TraitTypeResolver.php index bd7b6673df0..13bb1896f32 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/TraitTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/TraitTypeResolver.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [Trait_::class]; + return [\PhpParser\Node\Stmt\Trait_::class]; } - /** * @param Trait_ $traitNode */ - public function resolve(Node $traitNode): Type + public function resolve(\PhpParser\Node $traitNode) : \PHPStan\Type\Type { $traitName = (string) $traitNode->namespacedName; - if (! $this->reflectionProvider->hasClass($traitName)) { - return new MixedType(); + if (!$this->reflectionProvider->hasClass($traitName)) { + return new \PHPStan\Type\MixedType(); } - $classReflection = $this->reflectionProvider->getClass($traitName); - $types = []; - $types[] = new ObjectType($traitName); - + $types[] = new \PHPStan\Type\ObjectType($traitName); foreach ($classReflection->getTraits() as $usedTraitReflection) { - $types[] = new ObjectType($usedTraitReflection->getName()); + $types[] = new \PHPStan\Type\ObjectType($usedTraitReflection->getName()); } - - if (count($types) === 1) { + if (\count($types) === 1) { return $types[0]; } - - if (count($types) > 1) { - return new UnionType($types); + if (\count($types) > 1) { + return new \PHPStan\Type\UnionType($types); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } } diff --git a/packages/NodeTypeResolver/NodeTypeResolver/VariableTypeResolver.php b/packages/NodeTypeResolver/NodeTypeResolver/VariableTypeResolver.php index 2944058d300..e7df695bbbb 100644 --- a/packages/NodeTypeResolver/NodeTypeResolver/VariableTypeResolver.php +++ b/packages/NodeTypeResolver/NodeTypeResolver/VariableTypeResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->traitNodeScopeCollector = $traitNodeScopeCollector; $this->phpDocInfoFactory = $phpDocInfoFactory; } - /** * @return array> */ - public function getNodeClasses(): array + public function getNodeClasses() : array { - return [Variable::class]; + return [\PhpParser\Node\Expr\Variable::class]; } - /** * @param Variable $node */ - public function resolve(Node $node): Type + public function resolve(\PhpParser\Node $node) : \PHPStan\Type\Type { $variableName = $this->nodeNameResolver->getName($node); if ($variableName === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - $scopeType = $this->resolveTypesFromScope($node, $variableName); - if (! $scopeType instanceof MixedType) { + if (!$scopeType instanceof \PHPStan\Type\MixedType) { return $scopeType; } - // get from annotation $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); return $phpDocInfo->getVarType(); } - - private function resolveTypesFromScope(Variable $variable, string $variableName): Type + private function resolveTypesFromScope(\PhpParser\Node\Expr\Variable $variable, string $variableName) : \PHPStan\Type\Type { $scope = $this->resolveNodeScope($variable); - if (! $scope instanceof Scope) { - return new MixedType(); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return new \PHPStan\Type\MixedType(); } - - if (! $scope->hasVariableType($variableName)->yes()) { - return new MixedType(); + if (!$scope->hasVariableType($variableName)->yes()) { + return new \PHPStan\Type\MixedType(); } - // this → object type is easier to work with and consistent with the rest of the code return $scope->getVariableType($variableName); } - - private function resolveNodeScope(Variable $variable): ?Scope + private function resolveNodeScope(\PhpParser\Node\Expr\Variable $variable) : ?\PHPStan\Analyser\Scope { /** @var Scope|null $nodeScope */ - $nodeScope = $variable->getAttribute(AttributeKey::SCOPE); + $nodeScope = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); if ($nodeScope !== null) { return $nodeScope; } - // is node in trait - $classLike = $variable->getAttribute(AttributeKey::CLASS_NODE); - if ($classLike instanceof Trait_) { + $classLike = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if ($classLike instanceof \PhpParser\Node\Stmt\Trait_) { /** @var string $traitName */ - $traitName = $variable->getAttribute(AttributeKey::CLASS_NAME); + $traitName = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); $traitNodeScope = $this->traitNodeScopeCollector->getScopeForTraitAndNode($traitName, $variable); - if ($traitNodeScope !== null) { return $traitNodeScope; } } - return $this->resolveFromParentNodes($variable); } - - private function resolveFromParentNodes(Variable $variable): ?Scope + private function resolveFromParentNodes(\PhpParser\Node\Expr\Variable $variable) : ?\PHPStan\Analyser\Scope { foreach (self::PARENT_NODE_ATTRIBUTES as $parentNodeAttribute) { $parentNode = $variable->getAttribute($parentNodeAttribute); - if (! $parentNode instanceof Node) { + if (!$parentNode instanceof \PhpParser\Node) { continue; } - - $parentNodeScope = $parentNode->getAttribute(AttributeKey::SCOPE); - if (! $parentNodeScope instanceof Scope) { + $parentNodeScope = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$parentNodeScope instanceof \PHPStan\Analyser\Scope) { continue; } - return $parentNodeScope; } return null; diff --git a/packages/NodeTypeResolver/NodeVisitor/FileNodeVisitor.php b/packages/NodeTypeResolver/NodeVisitor/FileNodeVisitor.php index b8ca1a81289..261b290c9ee 100644 --- a/packages/NodeTypeResolver/NodeVisitor/FileNodeVisitor.php +++ b/packages/NodeTypeResolver/NodeVisitor/FileNodeVisitor.php @@ -1,35 +1,31 @@ file = $file; } - /** * @return Node */ - public function enterNode(Node $node): ?Node + public function enterNode(\PhpParser\Node $node) : ?\PhpParser\Node { - $node->setAttribute(AttributeKey::FILE, $this->file); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::FILE, $this->file); return $node; } } diff --git a/packages/NodeTypeResolver/NodeVisitor/FunctionLikeParamArgPositionNodeVisitor.php b/packages/NodeTypeResolver/NodeVisitor/FunctionLikeParamArgPositionNodeVisitor.php index 0dff20a547a..fe144a08f3f 100644 --- a/packages/NodeTypeResolver/NodeVisitor/FunctionLikeParamArgPositionNodeVisitor.php +++ b/packages/NodeTypeResolver/NodeVisitor/FunctionLikeParamArgPositionNodeVisitor.php @@ -1,7 +1,6 @@ getParams() as $position => $param) { - $param->setAttribute(AttributeKey::PARAMETER_POSITION, $position); + $param->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARAMETER_POSITION, $position); } } - - if ($node instanceof MethodCall || $node instanceof StaticCall || $node instanceof FuncCall || $node instanceof New_) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall || $node instanceof \PhpParser\Node\Expr\StaticCall || $node instanceof \PhpParser\Node\Expr\FuncCall || $node instanceof \PhpParser\Node\Expr\New_) { foreach ($node->args as $position => $arg) { - $arg->setAttribute(AttributeKey::ARGUMENT_POSITION, $position); + $arg->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ARGUMENT_POSITION, $position); } } - return $node; } } diff --git a/packages/NodeTypeResolver/NodeVisitor/FunctionMethodAndClassNodeVisitor.php b/packages/NodeTypeResolver/NodeVisitor/FunctionMethodAndClassNodeVisitor.php index 7f8d47569f5..a65bbb3eae5 100644 --- a/packages/NodeTypeResolver/NodeVisitor/FunctionMethodAndClassNodeVisitor.php +++ b/packages/NodeTypeResolver/NodeVisitor/FunctionMethodAndClassNodeVisitor.php @@ -1,7 +1,6 @@ classLike = null; $this->className = null; $this->classMethod = null; - return null; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PhpParser\Node $node) : ?\PhpParser\Node { $this->processClass($node); $this->processMethod($node); - return $node; } - - public function leaveNode(Node $node) + public function leaveNode(\PhpParser\Node $node) { - if ($node instanceof ClassLike) { - $classLike = array_pop($this->classStack); + if ($node instanceof \PhpParser\Node\Stmt\ClassLike) { + $classLike = \array_pop($this->classStack); $this->setClassNodeAndName($classLike); } - - if ($node instanceof ClassMethod) { - $this->classMethod = array_pop($this->methodStack); + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { + $this->classMethod = \array_pop($this->methodStack); } - return null; } - - private function processClass(Node $node): void + private function processClass(\PhpParser\Node $node) : void { - if ($node instanceof ClassLike) { + if ($node instanceof \PhpParser\Node\Stmt\ClassLike) { $this->classStack[] = $this->classLike; $this->setClassNodeAndName($node); } - - $node->setAttribute(AttributeKey::CLASS_NODE, $this->classLike); - $node->setAttribute(AttributeKey::CLASS_NAME, $this->className); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE, $this->classLike); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME, $this->className); } - - private function processMethod(Node $node): void + private function processMethod(\PhpParser\Node $node) : void { - if ($node instanceof ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { $this->methodStack[] = $this->classMethod; - $this->classMethod = $node; } - - $node->setAttribute(AttributeKey::METHOD_NODE, $this->classMethod); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE, $this->classMethod); } - - private function setClassNodeAndName(?ClassLike $classLike): void + private function setClassNodeAndName(?\PhpParser\Node\Stmt\ClassLike $classLike) : void { $this->classLike = $classLike; - if (! $classLike instanceof ClassLike || $classLike->name === null) { + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike || $classLike->name === null) { $this->className = null; - } elseif (property_exists($classLike, 'namespacedName')) { + } elseif (\property_exists($classLike, 'namespacedName')) { $this->className = $classLike->namespacedName->toString(); } else { $this->className = (string) $classLike->name; diff --git a/packages/NodeTypeResolver/NodeVisitor/NamespaceNodeVisitor.php b/packages/NodeTypeResolver/NodeVisitor/NamespaceNodeVisitor.php index bbb05cb1e61..cd700d1132a 100644 --- a/packages/NodeTypeResolver/NodeVisitor/NamespaceNodeVisitor.php +++ b/packages/NodeTypeResolver/NodeVisitor/NamespaceNodeVisitor.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; } - /** * @param Node[] $nodes * @return Node[]|null */ - public function beforeTraverse(array $nodes): ?array + public function beforeTraverse(array $nodes) : ?array { // init basic use nodes for non-namespaced code /** @var Use_[] $uses */ - $uses = $this->betterNodeFinder->findInstanceOf($nodes, Use_::class); + $uses = $this->betterNodeFinder->findInstanceOf($nodes, \PhpParser\Node\Stmt\Use_::class); $this->useNodes = $uses; - return null; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof Namespace_) { + if ($node instanceof \PhpParser\Node\Stmt\Namespace_) { /** @var Use_[] $uses */ - $uses = $this->betterNodeFinder->findInstanceOf($node, Use_::class); + $uses = $this->betterNodeFinder->findInstanceOf($node, \PhpParser\Node\Stmt\Use_::class); $this->useNodes = $uses; } - - $node->setAttribute(AttributeKey::USE_NODES, $this->useNodes); - + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::USE_NODES, $this->useNodes); return $node; } } diff --git a/packages/NodeTypeResolver/NodeVisitor/StatementNodeVisitor.php b/packages/NodeTypeResolver/NodeVisitor/StatementNodeVisitor.php index 456347b4b4d..0752dbc87c8 100644 --- a/packages/NodeTypeResolver/NodeVisitor/StatementNodeVisitor.php +++ b/packages/NodeTypeResolver/NodeVisitor/StatementNodeVisitor.php @@ -1,68 +1,51 @@ previousStmt = null; - return null; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PhpParser\Node $node) : ?\PhpParser\Node { - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Node) { - if (! $node instanceof Stmt) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node) { + if (!$node instanceof \PhpParser\Node\Stmt) { return null; } - - $node->setAttribute(AttributeKey::PREVIOUS_STATEMENT, $this->previousStmt); - $node->setAttribute(AttributeKey::CURRENT_STATEMENT, $node); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT, $this->previousStmt); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT, $node); $this->previousStmt = $node; } - - if (property_exists($node, 'stmts')) { + if (\property_exists($node, 'stmts')) { $previous = $node; foreach ((array) $node->stmts as $stmt) { - $stmt->setAttribute(AttributeKey::PREVIOUS_STATEMENT, $previous); - $stmt->setAttribute(AttributeKey::CURRENT_STATEMENT, $stmt); + $stmt->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT, $previous); + $stmt->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT, $stmt); $previous = $stmt; } } - - $currentStmt = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); - - if ($parent && ! $currentStmt) { - $node->setAttribute( - AttributeKey::PREVIOUS_STATEMENT, - $parent->getAttribute(AttributeKey::PREVIOUS_STATEMENT) - ); - - $node->setAttribute( - AttributeKey::CURRENT_STATEMENT, - $parent->getAttribute(AttributeKey::CURRENT_STATEMENT) - ); + $currentStmt = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); + if ($parent && !$currentStmt) { + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT, $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT)); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT, $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT)); } - return null; } } diff --git a/packages/NodeTypeResolver/PHPStan/Collector/TraitNodeScopeCollector.php b/packages/NodeTypeResolver/PHPStan/Collector/TraitNodeScopeCollector.php index e18fa10b5ba..58b2d777c9f 100644 --- a/packages/NodeTypeResolver/PHPStan/Collector/TraitNodeScopeCollector.php +++ b/packages/NodeTypeResolver/PHPStan/Collector/TraitNodeScopeCollector.php @@ -1,58 +1,46 @@ */ private $scopeByTraitNodeHash = []; - /** * @var BetterStandardPrinter */ private $betterStandardPrinter; - - public function __construct(BetterStandardPrinter $betterStandardPrinter) + public function __construct(\Rector\Core\PhpParser\Printer\BetterStandardPrinter $betterStandardPrinter) { $this->betterStandardPrinter = $betterStandardPrinter; } - - public function addForTraitAndNode(string $traitName, Node $node, Scope $scope): void + public function addForTraitAndNode(string $traitName, \PhpParser\Node $node, \PHPStan\Analyser\Scope $scope) : void { - if ($node instanceof VirtualNode) { + if ($node instanceof \PHPStan\Node\VirtualNode) { return; } - $traitNodeHash = $this->createHash($traitName, $node); - // probably set from another class if (isset($this->scopeByTraitNodeHash[$traitNodeHash])) { return; } - $this->scopeByTraitNodeHash[$traitNodeHash] = $scope; } - - public function getScopeForTraitAndNode(string $traitName, Node $node): ?Scope + public function getScopeForTraitAndNode(string $traitName, \PhpParser\Node $node) : ?\PHPStan\Analyser\Scope { $traitNodeHash = $this->createHash($traitName, $node); - return $this->scopeByTraitNodeHash[$traitNodeHash] ?? null; } - - private function createHash(string $traitName, Node $node): string + private function createHash(string $traitName, \PhpParser\Node $node) : string { $printedNode = $this->betterStandardPrinter->print($node); - - return sha1($traitName . $printedNode); + return \sha1($traitName . $printedNode); } } diff --git a/packages/NodeTypeResolver/PHPStan/Scope/NodeVisitor/RemoveDeepChainMethodCallNodeVisitor.php b/packages/NodeTypeResolver/PHPStan/Scope/NodeVisitor/RemoveDeepChainMethodCallNodeVisitor.php index 4ca794186e0..1033da8eac8 100644 --- a/packages/NodeTypeResolver/PHPStan/Scope/NodeVisitor/RemoveDeepChainMethodCallNodeVisitor.php +++ b/packages/NodeTypeResolver/PHPStan/Scope/NodeVisitor/RemoveDeepChainMethodCallNodeVisitor.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; - $this->nestedChainMethodCallLimit = (int) $parameterProvider->provideParameter( - Option::NESTED_CHAIN_METHOD_CALL_LIMIT - ); + $this->nestedChainMethodCallLimit = (int) $parameterProvider->provideParameter(\Rector\Core\Configuration\Option::NESTED_CHAIN_METHOD_CALL_LIMIT); } - - public function enterNode(Node $node): ?int + public function enterNode(\PhpParser\Node $node) : ?int { - if (! $node instanceof Expression) { + if (!$node instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - if ($node->expr instanceof MethodCall && $node->expr->var instanceof MethodCall) { - $nestedChainMethodCalls = $this->betterNodeFinder->findInstanceOf([$node->expr], MethodCall::class); - if (count($nestedChainMethodCalls) > $this->nestedChainMethodCallLimit) { + if ($node->expr instanceof \PhpParser\Node\Expr\MethodCall && $node->expr->var instanceof \PhpParser\Node\Expr\MethodCall) { + $nestedChainMethodCalls = $this->betterNodeFinder->findInstanceOf([$node->expr], \PhpParser\Node\Expr\MethodCall::class); + if (\count($nestedChainMethodCalls) > $this->nestedChainMethodCallLimit) { $this->removingExpression = $node; - - return NodeTraverser::DONT_TRAVERSE_CHILDREN; + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CHILDREN; } } - return null; } - /** * @return Nop|Node */ - public function leaveNode(Node $node) + public function leaveNode(\PhpParser\Node $node) { if ($node === $this->removingExpression) { // keep any node, so we don't remove it permanently - $nop = new Nop(); + $nop = new \PhpParser\Node\Stmt\Nop(); $nop->setAttributes($node->getAttributes()); return $nop; } - return $node; } } diff --git a/packages/NodeTypeResolver/PHPStan/Scope/PHPStanNodeScopeResolver.php b/packages/NodeTypeResolver/PHPStan/Scope/PHPStanNodeScopeResolver.php index bf1472914cc..2f7c5428e98 100644 --- a/packages/NodeTypeResolver/PHPStan/Scope/PHPStanNodeScopeResolver.php +++ b/packages/NodeTypeResolver/PHPStan/Scope/PHPStanNodeScopeResolver.php @@ -1,10 +1,9 @@ scopeFactory = $scopeFactory; $this->nodeScopeResolver = $nodeScopeResolver; $this->reflectionProvider = $reflectionProvider; @@ -111,153 +89,123 @@ final class PHPStanNodeScopeResolver $this->configuration = $configuration; $this->symfonyStyle = $symfonyStyle; } - /** * @param Node[] $nodes * @return Node[] */ - public function processNodes(array $nodes, SmartFileInfo $smartFileInfo): array + public function processNodes(array $nodes, \Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : array { $this->removeDeepChainMethodCallNodes($nodes); - $scope = $this->scopeFactory->createFromFile($smartFileInfo); - $this->dependentFiles = []; - // skip chain method calls, performance issue: https://github.com/phpstan/phpstan/issues/254 - $nodeCallback = function (Node $node, Scope $scope): void { + $nodeCallback = function (\PhpParser\Node $node, \PHPStan\Analyser\Scope $scope) : void { // traversing trait inside class that is using it scope (from referenced) - the trait traversed by Rector is different (directly from parsed file) if ($scope->isInTrait()) { /** @var ClassReflection $classReflection */ $classReflection = $scope->getTraitReflection(); $traitName = $classReflection->getName(); $this->traitNodeScopeCollector->addForTraitAndNode($traitName, $node, $scope); - return; } - // the class reflection is resolved AFTER entering to class node // so we need to get it from the first after this one - if ($node instanceof Class_ || $node instanceof Interface_) { + if ($node instanceof \PhpParser\Node\Stmt\Class_ || $node instanceof \PhpParser\Node\Stmt\Interface_) { /** @var Scope $scope */ $scope = $this->resolveClassOrInterfaceScope($node, $scope); } - // special case for unreachable nodes - if ($node instanceof UnreachableStatementNode) { + if ($node instanceof \PHPStan\Node\UnreachableStatementNode) { $originalNode = $node->getOriginalStatement(); - $originalNode->setAttribute(AttributeKey::IS_UNREACHABLE, true); - $originalNode->setAttribute(AttributeKey::SCOPE, $scope); + $originalNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_UNREACHABLE, \true); + $originalNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE, $scope); } else { - $node->setAttribute(AttributeKey::SCOPE, $scope); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE, $scope); } }; - foreach ($nodes as $node) { $this->resolveDependentFiles($node, $scope); } - /** @var MutatingScope $scope */ $this->nodeScopeResolver->processNodes($nodes, $scope, $nodeCallback); - $this->reportCacheDebugAndSaveDependentFiles($smartFileInfo, $this->dependentFiles); - return $nodes; } - /** * @param Node[] $nodes */ - private function removeDeepChainMethodCallNodes(array $nodes): void + private function removeDeepChainMethodCallNodes(array $nodes) : void { - $nodeTraverser = new NodeTraverser(); + $nodeTraverser = new \PhpParser\NodeTraverser(); $nodeTraverser->addVisitor($this->removeDeepChainMethodCallNodeVisitor); $nodeTraverser->traverse($nodes); } - /** * @param Class_|Interface_ $classLike */ - private function resolveClassOrInterfaceScope(ClassLike $classLike, Scope $scope): Scope + private function resolveClassOrInterfaceScope(\PhpParser\Node\Stmt\ClassLike $classLike, \PHPStan\Analyser\Scope $scope) : \PHPStan\Analyser\Scope { $className = $this->resolveClassName($classLike); - // is anonymous class? - not possible to enter it since PHPStan 0.12.33, see https://github.com/phpstan/phpstan-src/commit/e87fb0ec26f9c8552bbeef26a868b1e5d8185e91 - if ($classLike instanceof Class_ && Strings::match($className, self::ANONYMOUS_CLASS_START_REGEX)) { + if ($classLike instanceof \PhpParser\Node\Stmt\Class_ && \RectorPrefix20210509\Nette\Utils\Strings::match($className, self::ANONYMOUS_CLASS_START_REGEX)) { $classReflection = $this->reflectionProvider->getAnonymousClassReflection($classLike, $scope); - } elseif (! $this->reflectionProvider->hasClass($className)) { + } elseif (!$this->reflectionProvider->hasClass($className)) { return $scope; } else { $classReflection = $this->reflectionProvider->getClass($className); } - /** @var MutatingScope $scope */ return $scope->enterClass($classReflection); } - - private function resolveDependentFiles(Node $node, MutatingScope $mutatingScope): void + private function resolveDependentFiles(\PhpParser\Node $node, \PHPStan\Analyser\MutatingScope $mutatingScope) : void { - if (! $this->configuration->isCacheEnabled()) { + if (!$this->configuration->isCacheEnabled()) { return; } - try { $dependentFiles = $this->dependencyResolver->resolveDependencies($node, $mutatingScope); foreach ($dependentFiles as $dependentFile) { $this->dependentFiles[] = $dependentFile; } - } catch (AnalysedCodeException $analysedCodeException) { + } catch (\PHPStan\AnalysedCodeException $analysedCodeException) { // @ignoreException } } - /** * @param string[] $dependentFiles */ - private function reportCacheDebugAndSaveDependentFiles(SmartFileInfo $smartFileInfo, array $dependentFiles): void + private function reportCacheDebugAndSaveDependentFiles(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo, array $dependentFiles) : void { - if (! $this->configuration->isCacheEnabled()) { + if (!$this->configuration->isCacheEnabled()) { return; } - $this->reportCacheDebug($smartFileInfo, $dependentFiles); - // save for cache $this->changedFilesDetector->addFileWithDependencies($smartFileInfo, $dependentFiles); } - /** * @param Class_|Interface_|Trait_ $classLike */ - private function resolveClassName(ClassLike $classLike): string + private function resolveClassName(\PhpParser\Node\Stmt\ClassLike $classLike) : string { - if (property_exists($classLike, 'namespacedName')) { + if (\property_exists($classLike, 'namespacedName')) { return (string) $classLike->namespacedName; } - if ($classLike->name === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - return $classLike->name->toString(); } - /** * @param string[] $dependentFiles */ - private function reportCacheDebug(SmartFileInfo $smartFileInfo, array $dependentFiles): void + private function reportCacheDebug(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo, array $dependentFiles) : void { - if (! $this->configuration->isCacheDebug()) { + if (!$this->configuration->isCacheDebug()) { return; } - $message = sprintf( - '[debug] %d dependencies for "%s" file', - count($dependentFiles), - $smartFileInfo->getRealPath() - ); - + $message = \sprintf('[debug] %d dependencies for "%s" file', \count($dependentFiles), $smartFileInfo->getRealPath()); $this->symfonyStyle->note($message); - if ($dependentFiles !== []) { $this->symfonyStyle->listing($dependentFiles); } diff --git a/packages/NodeTypeResolver/PHPStan/Scope/ScopeFactory.php b/packages/NodeTypeResolver/PHPStan/Scope/ScopeFactory.php index 436b441f58e..42059486a3a 100644 --- a/packages/NodeTypeResolver/PHPStan/Scope/ScopeFactory.php +++ b/packages/NodeTypeResolver/PHPStan/Scope/ScopeFactory.php @@ -1,29 +1,25 @@ phpStanScopeFactory = $phpStanScopeFactory; } - - public function createFromFile(SmartFileInfo $fileInfo): MutatingScope + public function createFromFile(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo) : \PHPStan\Analyser\MutatingScope { - $scopeContext = ScopeContext::create($fileInfo->getRealPath()); + $scopeContext = \PHPStan\Analyser\ScopeContext::create($fileInfo->getRealPath()); return $this->phpStanScopeFactory->create($scopeContext); } } diff --git a/packages/NodeTypeResolver/PHPStan/Type/StaticTypeAnalyzer.php b/packages/NodeTypeResolver/PHPStan/Type/StaticTypeAnalyzer.php index 321fef3553c..9a4ba27b577 100644 --- a/packages/NodeTypeResolver/PHPStan/Type/StaticTypeAnalyzer.php +++ b/packages/NodeTypeResolver/PHPStan/Type/StaticTypeAnalyzer.php @@ -1,7 +1,6 @@ isAlwaysTruableArrayType($type); } - if ($this->isNullable($type)) { - return false; + return \false; } - // always trueish - if ($type instanceof ObjectType) { - return true; + if ($type instanceof \PHPStan\Type\ObjectType) { + return \true; } - - if ($type instanceof ConstantScalarType && ! $type instanceof NullType) { + if ($type instanceof \PHPStan\Type\ConstantScalarType && !$type instanceof \PHPStan\Type\NullType) { return (bool) $type->getValue(); } - if ($this->isScalarType($type)) { - return false; + return \false; } - return $this->isAlwaysTruableUnionType($type); } - - private function isNullable(Type $type): bool + private function isNullable(\PHPStan\Type\Type $type) : bool { - if (! $type instanceof UnionType) { - return false; + if (!$type instanceof \PHPStan\Type\UnionType) { + return \false; } - foreach ($type->getTypes() as $unionedType) { - if ($unionedType instanceof NullType) { - return true; + if ($unionedType instanceof \PHPStan\Type\NullType) { + return \true; } } - - return false; + return \false; } - - private function isScalarType(Type $type): bool + private function isScalarType(\PHPStan\Type\Type $type) : bool { - if ($type instanceof NullType) { - return true; + if ($type instanceof \PHPStan\Type\NullType) { + return \true; } - - return $type instanceof BooleanType || $type instanceof StringType || $type instanceof IntegerType || $type instanceof FloatType; + return $type instanceof \PHPStan\Type\BooleanType || $type instanceof \PHPStan\Type\StringType || $type instanceof \PHPStan\Type\IntegerType || $type instanceof \PHPStan\Type\FloatType; } - - private function isAlwaysTruableUnionType(Type $type): bool + private function isAlwaysTruableUnionType(\PHPStan\Type\Type $type) : bool { - if (! $type instanceof UnionType) { - return false; + if (!$type instanceof \PHPStan\Type\UnionType) { + return \false; } - foreach ($type->getTypes() as $unionedType) { - if (! $this->isAlwaysTruableType($unionedType)) { - return false; + if (!$this->isAlwaysTruableType($unionedType)) { + return \false; } } - - return true; + return \true; } - - private function isAlwaysTruableArrayType(ArrayType $arrayType): bool + private function isAlwaysTruableArrayType(\PHPStan\Type\ArrayType $arrayType) : bool { $itemType = $arrayType->getItemType(); - return $itemType instanceof ConstantScalarType && $itemType->getValue(); + return $itemType instanceof \PHPStan\Type\ConstantScalarType && $itemType->getValue(); } } diff --git a/packages/NodeTypeResolver/PHPStan/Type/TypeFactory.php b/packages/NodeTypeResolver/PHPStan/Type/TypeFactory.php index 65bf978ec9d..87389c9a99f 100644 --- a/packages/NodeTypeResolver/PHPStan/Type/TypeFactory.php +++ b/packages/NodeTypeResolver/PHPStan/Type/TypeFactory.php @@ -1,7 +1,6 @@ unionTypeFactory = $unionTypeFactory; } - /** * @param Type[] $types */ - public function createMixedPassedOrUnionTypeAndKeepConstant(array $types): Type + public function createMixedPassedOrUnionTypeAndKeepConstant(array $types) : \PHPStan\Type\Type { $types = $this->unwrapUnionedTypes($types); - $types = $this->uniquateTypes($types, true); - + $types = $this->uniquateTypes($types, \true); return $this->createUnionOrSingleType($types); } - /** * @param Type[] $types */ - public function createMixedPassedOrUnionType(array $types): Type + public function createMixedPassedOrUnionType(array $types) : \PHPStan\Type\Type { $types = $this->unwrapUnionedTypes($types); $types = $this->uniquateTypes($types); - return $this->createUnionOrSingleType($types); } - /** * @param Type[] $types * @return Type[] */ - public function uniquateTypes(array $types, bool $keepConstant = false): array + public function uniquateTypes(array $types, bool $keepConstant = \false) : array { $uniqueTypes = []; foreach ($types as $type) { - if (! $keepConstant) { + if (!$keepConstant) { $type = $this->removeValueFromConstantType($type); } - - if ($type instanceof ShortenedObjectType) { - $type = new FullyQualifiedObjectType($type->getFullyQualifiedName()); + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType) { + $type = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($type->getFullyQualifiedName()); } - - if ($type instanceof ObjectType && ! $type instanceof GenericObjectType && ! $type instanceof AliasedObjectType && $type->getClassName() !== 'Iterator') { - $type = new FullyQualifiedObjectType($type->getClassName()); + if ($type instanceof \PHPStan\Type\ObjectType && !$type instanceof \PHPStan\Type\Generic\GenericObjectType && !$type instanceof \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType && $type->getClassName() !== 'Iterator') { + $type = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($type->getClassName()); } - - $typeHash = md5($type->describe(VerbosityLevel::cache())); + $typeHash = \md5($type->describe(\PHPStan\Type\VerbosityLevel::cache())); $uniqueTypes[$typeHash] = $type; } - // re-index - return array_values($uniqueTypes); + return \array_values($uniqueTypes); } - /** * @param Type[] $types * @return Type[] */ - private function unwrapUnionedTypes(array $types): array + private function unwrapUnionedTypes(array $types) : array { // unwrap union types $unwrappedTypes = []; foreach ($types as $type) { - $flattenTypes = TypeUtils::flattenTypes($type); - + $flattenTypes = \PHPStan\Type\TypeUtils::flattenTypes($type); foreach ($flattenTypes as $flattenType) { - if ($flattenType instanceof ConstantArrayType) { - $unwrappedTypes = array_merge($unwrappedTypes, $this->unwrapConstantArrayTypes($flattenType)); + if ($flattenType instanceof \PHPStan\Type\Constant\ConstantArrayType) { + $unwrappedTypes = \array_merge($unwrappedTypes, $this->unwrapConstantArrayTypes($flattenType)); } else { $unwrappedTypes[] = $flattenType; } } } - return $unwrappedTypes; } - /** * @param Type[] $types */ - private function createUnionOrSingleType(array $types): Type + private function createUnionOrSingleType(array $types) : \PHPStan\Type\Type { if ($types === []) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - if (count($types) === 1) { + if (\count($types) === 1) { return $types[0]; } - return $this->unionTypeFactory->createUnionObjectType($types); } - - private function removeValueFromConstantType(Type $type): Type + private function removeValueFromConstantType(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { // remove values from constant types - if ($type instanceof ConstantFloatType) { - return new FloatType(); + if ($type instanceof \PHPStan\Type\Constant\ConstantFloatType) { + return new \PHPStan\Type\FloatType(); } - - if ($type instanceof ConstantStringType) { - return new StringType(); + if ($type instanceof \PHPStan\Type\Constant\ConstantStringType) { + return new \PHPStan\Type\StringType(); } - - if ($type instanceof ConstantIntegerType) { - return new IntegerType(); + if ($type instanceof \PHPStan\Type\Constant\ConstantIntegerType) { + return new \PHPStan\Type\IntegerType(); } - - if ($type instanceof ConstantBooleanType) { - return new BooleanType(); + if ($type instanceof \PHPStan\Type\Constant\ConstantBooleanType) { + return new \PHPStan\Type\BooleanType(); } - return $type; } - /** * @return Type[] */ - private function unwrapConstantArrayTypes(ConstantArrayType $constantArrayType): array + private function unwrapConstantArrayTypes(\PHPStan\Type\Constant\ConstantArrayType $constantArrayType) : array { $unwrappedTypes = []; - - $flattenKeyTypes = TypeUtils::flattenTypes($constantArrayType->getKeyType()); - $flattenItemTypes = TypeUtils::flattenTypes($constantArrayType->getItemType()); - + $flattenKeyTypes = \PHPStan\Type\TypeUtils::flattenTypes($constantArrayType->getKeyType()); + $flattenItemTypes = \PHPStan\Type\TypeUtils::flattenTypes($constantArrayType->getItemType()); foreach ($flattenItemTypes as $position => $nestedFlattenItemType) { /** @var Type|null $nestedFlattenKeyType */ $nestedFlattenKeyType = $flattenKeyTypes[$position] ?? null; if ($nestedFlattenKeyType === null) { - $nestedFlattenKeyType = new MixedType(); + $nestedFlattenKeyType = new \PHPStan\Type\MixedType(); } - - $unwrappedTypes[] = new ArrayType($nestedFlattenKeyType, $nestedFlattenItemType); + $unwrappedTypes[] = new \PHPStan\Type\ArrayType($nestedFlattenKeyType, $nestedFlattenItemType); } - return $unwrappedTypes; } } diff --git a/packages/NodeTypeResolver/PHPStan/TypeHasher.php b/packages/NodeTypeResolver/PHPStan/TypeHasher.php index 49e745fd91d..b939493fc2d 100644 --- a/packages/NodeTypeResolver/PHPStan/TypeHasher.php +++ b/packages/NodeTypeResolver/PHPStan/TypeHasher.php @@ -1,7 +1,6 @@ createTypeHash($firstType) === $this->createTypeHash($secondType); } - - private function createTypeHash(Type $type): string + private function createTypeHash(\PHPStan\Type\Type $type) : string { - if ($type instanceof MixedType) { - return serialize($type) . $type->isExplicitMixed(); + if ($type instanceof \PHPStan\Type\MixedType) { + return \serialize($type) . $type->isExplicitMixed(); } - - if ($type instanceof ArrayType) { + if ($type instanceof \PHPStan\Type\ArrayType) { return $this->createTypeHash($type->getItemType()) . $this->createTypeHash($type->getKeyType()) . '[]'; } - - if ($type instanceof GenericObjectType) { - return $type->describe(VerbosityLevel::precise()); + if ($type instanceof \PHPStan\Type\Generic\GenericObjectType) { + return $type->describe(\PHPStan\Type\VerbosityLevel::precise()); } - - if ($type instanceof TypeWithClassName) { + if ($type instanceof \PHPStan\Type\TypeWithClassName) { return $this->resolveUniqueTypeWithClassNameHash($type); } - - if ($type instanceof ConstantType) { - return get_class($type) . $type->getValue(); + if ($type instanceof \PHPStan\Type\ConstantType) { + return \get_class($type) . $type->getValue(); } - - if ($type instanceof UnionType) { + if ($type instanceof \PHPStan\Type\UnionType) { return $this->createUnionTypeHash($type); } - - return $type->describe(VerbosityLevel::value()); + return $type->describe(\PHPStan\Type\VerbosityLevel::value()); } - - private function resolveUniqueTypeWithClassNameHash(TypeWithClassName $typeWithClassName): string + private function resolveUniqueTypeWithClassNameHash(\PHPStan\Type\TypeWithClassName $typeWithClassName) : string { - if ($typeWithClassName instanceof ShortenedObjectType) { + if ($typeWithClassName instanceof \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType) { return $typeWithClassName->getFullyQualifiedName(); } - - if ($typeWithClassName instanceof AliasedObjectType) { + if ($typeWithClassName instanceof \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType) { return $typeWithClassName->getFullyQualifiedClass(); } - return $typeWithClassName->getClassName(); } - - private function createUnionTypeHash(UnionType $unionType): string + private function createUnionTypeHash(\PHPStan\Type\UnionType $unionType) : string { - $sortedTypes = UnionTypeHelper::sortTypes($unionType->getTypes()); - $sortedUnionType = new UnionType($sortedTypes); - - $booleanType = new BooleanType(); + $sortedTypes = \PHPStan\Type\UnionTypeHelper::sortTypes($unionType->getTypes()); + $sortedUnionType = new \PHPStan\Type\UnionType($sortedTypes); + $booleanType = new \PHPStan\Type\BooleanType(); if ($booleanType->isSuperTypeOf($unionType)->yes()) { - return $booleanType->describe(VerbosityLevel::precise()); + return $booleanType->describe(\PHPStan\Type\VerbosityLevel::precise()); } - $normalizedUnionType = clone $sortedUnionType; - // change alias to non-alias - $normalizedUnionType = TypeTraverser::map( - $normalizedUnionType, - function (Type $type, callable $callable): Type { - if (! $type instanceof AliasedObjectType) { - return $callable($type); - } - - return new FullyQualifiedObjectType($type->getFullyQualifiedClass()); + $normalizedUnionType = \PHPStan\Type\TypeTraverser::map($normalizedUnionType, function (\PHPStan\Type\Type $type, callable $callable) : Type { + if (!$type instanceof \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType) { + return $callable($type); } - ); - - return $normalizedUnionType->describe(VerbosityLevel::cache()); + return new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($type->getFullyQualifiedClass()); + }); + return $normalizedUnionType->describe(\PHPStan\Type\VerbosityLevel::cache()); } } diff --git a/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockClassRenamer.php b/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockClassRenamer.php index d77836a7a21..9900e821516 100644 --- a/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockClassRenamer.php +++ b/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockClassRenamer.php @@ -1,46 +1,37 @@ classRenamePhpDocNodeVisitor = $classRenamePhpDocNodeVisitor; $this->renamingPhpDocNodeVisitorFactory = $renamingPhpDocNodeVisitorFactory; } - /** * @param OldToNewType[] $oldToNewTypes */ - public function renamePhpDocType(PhpDocInfo $phpDocInfo, array $oldToNewTypes): void + public function renamePhpDocType(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, array $oldToNewTypes) : void { if ($oldToNewTypes === []) { return; } - $phpDocNodeTraverser = $this->renamingPhpDocNodeVisitorFactory->create(); $this->classRenamePhpDocNodeVisitor->setOldToNewTypes($oldToNewTypes); - $phpDocNodeTraverser->traverse($phpDocInfo->getPhpDocNode()); } } diff --git a/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockNameImporter.php b/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockNameImporter.php index c1ae2af1c10..81e68bc3d7f 100644 --- a/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockNameImporter.php +++ b/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockNameImporter.php @@ -1,42 +1,33 @@ nameImportingPhpDocNodeVisitor = $nameImportingPhpDocNodeVisitor; $this->importingPhpDocNodeTraverserFactory = $importingPhpDocNodeTraverserFactory; } - - public function importNames(PhpDocNode $phpDocNode, Node $node): void + public function importNames(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode $phpDocNode, \PhpParser\Node $node) : void { if ($phpDocNode->children === []) { return; } - $this->nameImportingPhpDocNodeVisitor->setCurrentNode($node); - $phpDocNodeTraverser = $this->importingPhpDocNodeTraverserFactory->create(); $phpDocNodeTraverser->traverse($phpDocNode); } diff --git a/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockTagReplacer.php b/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockTagReplacer.php index 75a443a3e81..eeba076a3e0 100644 --- a/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockTagReplacer.php +++ b/packages/NodeTypeResolver/PhpDoc/NodeAnalyzer/DocBlockTagReplacer.php @@ -1,43 +1,36 @@ annotationNaming = $annotationNaming; } - - public function replaceTagByAnother(PhpDocInfo $phpDocInfo, string $oldTag, string $newTag): void + public function replaceTagByAnother(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, string $oldTag, string $newTag) : void { $oldTag = $this->annotationNaming->normalizeName($oldTag); $newTag = $this->annotationNaming->normalizeName($newTag); - $phpDocNode = $phpDocInfo->getPhpDocNode(); foreach ($phpDocNode->children as $key => $phpDocChildNode) { - if (! $phpDocChildNode instanceof PhpDocTagNode) { + if (!$phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { continue; } - if ($phpDocChildNode->name !== $oldTag) { continue; } - unset($phpDocNode->children[$key]); - $phpDocNode->children[] = new PhpDocTagNode($newTag, new GenericTagValueNode('')); + $phpDocNode->children[] = new \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode($newTag, new \PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode('')); } } } diff --git a/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/ImportingPhpDocNodeTraverserFactory.php b/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/ImportingPhpDocNodeTraverserFactory.php index 671e31d92fb..0da20ab9b74 100644 --- a/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/ImportingPhpDocNodeTraverserFactory.php +++ b/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/ImportingPhpDocNodeTraverserFactory.php @@ -1,29 +1,24 @@ nameImportingPhpDocNodeVisitor = $nameImportingPhpDocNodeVisitor; } - - public function create(): PhpDocNodeTraverser + public function create() : \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser { - $phpDocNodeTraverser = new PhpDocNodeTraverser(); + $phpDocNodeTraverser = new \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser(); $phpDocNodeTraverser->addPhpDocNodeVisitor($this->nameImportingPhpDocNodeVisitor); - return $phpDocNodeTraverser; } } diff --git a/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/RenamingPhpDocNodeVisitorFactory.php b/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/RenamingPhpDocNodeVisitorFactory.php index 79e9055c21a..9ba98db683f 100644 --- a/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/RenamingPhpDocNodeVisitorFactory.php +++ b/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/RenamingPhpDocNodeVisitorFactory.php @@ -1,29 +1,24 @@ classRenamePhpDocNodeVisitor = $classRenamePhpDocNodeVisitor; } - - public function create(): PhpDocNodeTraverser + public function create() : \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser { - $phpDocNodeTraverser = new PhpDocNodeTraverser(); + $phpDocNodeTraverser = new \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser(); $phpDocNodeTraverser->addPhpDocNodeVisitor($this->classRenamePhpDocNodeVisitor); - return $phpDocNodeTraverser; } } diff --git a/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/UnderscorePhpDocNodeTraverserFactory.php b/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/UnderscorePhpDocNodeTraverserFactory.php index 2d03ca01267..59a7fe6bfea 100644 --- a/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/UnderscorePhpDocNodeTraverserFactory.php +++ b/packages/NodeTypeResolver/PhpDoc/PhpDocNodeTraverser/UnderscorePhpDocNodeTraverserFactory.php @@ -1,29 +1,24 @@ underscoreRenamePhpDocNodeVisitor = $underscoreRenamePhpDocNodeVisitor; } - - public function create(): PhpDocNodeTraverser + public function create() : \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser { - $phpDocNodeTraverser = new PhpDocNodeTraverser(); + $phpDocNodeTraverser = new \RectorPrefix20210509\Symplify\SimplePhpDocParser\PhpDocNodeTraverser(); $phpDocNodeTraverser->addPhpDocNodeVisitor($this->underscoreRenamePhpDocNodeVisitor); - return $phpDocNodeTraverser; } } diff --git a/packages/NodeTypeResolver/PhpDoc/PhpDocTypeRenamer.php b/packages/NodeTypeResolver/PhpDoc/PhpDocTypeRenamer.php index 55b0fea8c3f..948b039a044 100644 --- a/packages/NodeTypeResolver/PhpDoc/PhpDocTypeRenamer.php +++ b/packages/NodeTypeResolver/PhpDoc/PhpDocTypeRenamer.php @@ -1,7 +1,6 @@ underscoreRenamePhpDocNodeVisitor = $underscoreRenamePhpDocNodeVisitor; $this->underscorePhpDocNodeTraverserFactory = $underscorePhpDocNodeTraverserFactory; } - - public function changeUnderscoreType( - PhpDocInfo $phpDocInfo, - Node $node, - PseudoNamespaceToNamespace $pseudoNamespaceToNamespace - ): void { + public function changeUnderscoreType(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \PhpParser\Node $node, \Rector\Renaming\ValueObject\PseudoNamespaceToNamespace $pseudoNamespaceToNamespace) : void + { $phpDocNode = $phpDocInfo->getPhpDocNode(); - $this->underscoreRenamePhpDocNodeVisitor->setPseudoNamespaceToNamespace($pseudoNamespaceToNamespace); $this->underscoreRenamePhpDocNodeVisitor->setCurrentPhpParserNode($node); - $phpDocNodeTraverser = $this->underscorePhpDocNodeTraverserFactory->create(); $phpDocNodeTraverser->traverse($phpDocNode); } diff --git a/packages/NodeTypeResolver/PhpDocNodeVisitor/ClassRenamePhpDocNodeVisitor.php b/packages/NodeTypeResolver/PhpDocNodeVisitor/ClassRenamePhpDocNodeVisitor.php index f873a38a2be..8b4ee9702fd 100644 --- a/packages/NodeTypeResolver/PhpDocNodeVisitor/ClassRenamePhpDocNodeVisitor.php +++ b/packages/NodeTypeResolver/PhpDocNodeVisitor/ClassRenamePhpDocNodeVisitor.php @@ -1,7 +1,6 @@ staticTypeMapper = $staticTypeMapper; $this->currentNodeProvider = $currentNodeProvider; } - - public function beforeTraverse(Node $node): void + public function beforeTraverse(\PHPStan\PhpDocParser\Ast\Node $node) : void { if ($this->oldToNewTypes === []) { - throw new ShouldNotHappenException('Configure "$oldToNewClasses" first'); + throw new \Rector\Core\Exception\ShouldNotHappenException('Configure "$oldToNewClasses" first'); } } - - public function enterNode(Node $node): ?Node + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) : ?\PHPStan\PhpDocParser\Ast\Node { - if (! $node instanceof IdentifierTypeNode) { + if (!$node instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode) { return null; } - $phpParserNode = $this->currentNodeProvider->getNode(); - if (! $phpParserNode instanceof \PhpParser\Node) { - throw new ShouldNotHappenException(); + if (!$phpParserNode instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $staticType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType($node, $phpParserNode); - // make sure to compare FQNs - if ($staticType instanceof ShortenedObjectType) { - $staticType = new ObjectType($staticType->getFullyQualifiedName()); + if ($staticType instanceof \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType) { + $staticType = new \PHPStan\Type\ObjectType($staticType->getFullyQualifiedName()); } - foreach ($this->oldToNewTypes as $oldToNewType) { - if (! $staticType->equals($oldToNewType->getOldType())) { + if (!$staticType->equals($oldToNewType->getOldType())) { continue; } - $newTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPHPStanPhpDocTypeNode($oldToNewType->getNewType()); - - $parentType = $node->getAttribute(PhpDocAttributeKey::PARENT); - if ($parentType instanceof TypeNode) { + $parentType = $node->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::PARENT); + if ($parentType instanceof \PHPStan\PhpDocParser\Ast\Type\TypeNode) { // mirror attributes - $newTypeNode->setAttribute(PhpDocAttributeKey::PARENT, $parentType); + $newTypeNode->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::PARENT, $parentType); } - return $newTypeNode; } - return null; } - /** * @param OldToNewType[] $oldToNewTypes */ - public function setOldToNewTypes(array $oldToNewTypes): void + public function setOldToNewTypes(array $oldToNewTypes) : void { $this->oldToNewTypes = $oldToNewTypes; } diff --git a/packages/NodeTypeResolver/PhpDocNodeVisitor/NameImportingPhpDocNodeVisitor.php b/packages/NodeTypeResolver/PhpDocNodeVisitor/NameImportingPhpDocNodeVisitor.php index 8fa31168229..287453e2143 100644 --- a/packages/NodeTypeResolver/PhpDocNodeVisitor/NameImportingPhpDocNodeVisitor.php +++ b/packages/NodeTypeResolver/PhpDocNodeVisitor/NameImportingPhpDocNodeVisitor.php @@ -1,7 +1,6 @@ staticTypeMapper = $staticTypeMapper; $this->parameterProvider = $parameterProvider; $this->classNameImportSkipper = $classNameImportSkipper; $this->useNodesToAddCollector = $useNodesToAddCollector; } - - public function beforeTraverse(Node $node): void + public function beforeTraverse(\PHPStan\PhpDocParser\Ast\Node $node) : void { if ($this->currentPhpParserNode === null) { - throw new ShouldNotHappenException('Set "$currentPhpParserNode" first'); + throw new \Rector\Core\Exception\ShouldNotHappenException('Set "$currentPhpParserNode" first'); } } - - public function enterNode(Node $node): ?Node + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) : ?\PHPStan\PhpDocParser\Ast\Node { - if (! $node instanceof IdentifierTypeNode) { + if (!$node instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode) { return null; } - - $staticType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType( - $node, - $this->currentPhpParserNode - ); - if (! $staticType instanceof FullyQualifiedObjectType) { + $staticType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType($node, $this->currentPhpParserNode); + if (!$staticType instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType) { return null; } - // Importing root namespace classes (like \DateTime) is optional if ($this->shouldSkipShortClassName($staticType)) { return null; } - return $this->processFqnNameImport($this->currentPhpParserNode, $node, $staticType); } - - public function setCurrentNode(PhpParserNode $phpParserNode): void + public function setCurrentNode(\PhpParser\Node $phpParserNode) : void { $this->currentPhpParserNode = $phpParserNode; } - - private function processFqnNameImport( - PhpParserNode $phpParserNode, - IdentifierTypeNode $identifierTypeNode, - FullyQualifiedObjectType $fullyQualifiedObjectType - ): ?IdentifierTypeNode { - if ($this->classNameImportSkipper->shouldSkipNameForFullyQualifiedObjectType( - $phpParserNode, - $fullyQualifiedObjectType - )) { + private function processFqnNameImport(\PhpParser\Node $phpParserNode, \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode $identifierTypeNode, \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType) : ?\PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode + { + if ($this->classNameImportSkipper->shouldSkipNameForFullyQualifiedObjectType($phpParserNode, $fullyQualifiedObjectType)) { return $identifierTypeNode; } - - $parent = $identifierTypeNode->getAttribute(PhpDocAttributeKey::PARENT); - if ($parent instanceof TemplateTagValueNode) { + $parent = $identifierTypeNode->getAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::PARENT); + if ($parent instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode) { // might break return null; } - // should skip because its already used if ($this->useNodesToAddCollector->isShortImported($phpParserNode, $fullyQualifiedObjectType)) { if ($this->useNodesToAddCollector->isImportShortable($phpParserNode, $fullyQualifiedObjectType)) { - $newNode = new IdentifierTypeNode($fullyQualifiedObjectType->getShortName()); + $newNode = new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode($fullyQualifiedObjectType->getShortName()); if ($newNode->name !== $identifierTypeNode->name) { return $newNode; } return $identifierTypeNode; } - return $identifierTypeNode; } - $this->useNodesToAddCollector->addUseImport($phpParserNode, $fullyQualifiedObjectType); - - $newNode = new IdentifierTypeNode($fullyQualifiedObjectType->getShortName()); + $newNode = new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode($fullyQualifiedObjectType->getShortName()); if ($newNode->name !== $identifierTypeNode->name) { return $newNode; } return $identifierTypeNode; } - - private function shouldSkipShortClassName(FullyQualifiedObjectType $fullyQualifiedObjectType): bool + private function shouldSkipShortClassName(\Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType) : bool { - $importShortClasses = $this->parameterProvider->provideBoolParameter(Option::IMPORT_SHORT_CLASSES); + $importShortClasses = $this->parameterProvider->provideBoolParameter(\Rector\Core\Configuration\Option::IMPORT_SHORT_CLASSES); if ($importShortClasses) { - return false; + return \false; } - - return substr_count($fullyQualifiedObjectType->getClassName(), '\\') === 0; + return \substr_count($fullyQualifiedObjectType->getClassName(), '\\') === 0; } } diff --git a/packages/NodeTypeResolver/PhpDocNodeVisitor/UnderscoreRenamePhpDocNodeVisitor.php b/packages/NodeTypeResolver/PhpDocNodeVisitor/UnderscoreRenamePhpDocNodeVisitor.php index 951a2d114f2..b928d6f4fde 100644 --- a/packages/NodeTypeResolver/PhpDocNodeVisitor/UnderscoreRenamePhpDocNodeVisitor.php +++ b/packages/NodeTypeResolver/PhpDocNodeVisitor/UnderscoreRenamePhpDocNodeVisitor.php @@ -1,104 +1,78 @@ staticTypeMapper = $staticTypeMapper; } - - public function beforeTraverse(Node $node): void + public function beforeTraverse(\PHPStan\PhpDocParser\Ast\Node $node) : void { if ($this->pseudoNamespaceToNamespace === null) { - throw new ShouldNotHappenException('Set PseudoNamespaceToNamespace first'); + throw new \Rector\Core\Exception\ShouldNotHappenException('Set PseudoNamespaceToNamespace first'); } - - if (! $this->currentPhpParserNode instanceof \PhpParser\Node) { - throw new ShouldNotHappenException('Set "$currentPhpParserNode" first'); + if (!$this->currentPhpParserNode instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException('Set "$currentPhpParserNode" first'); } } - - public function enterNode(Node $node): ?Node + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) : ?\PHPStan\PhpDocParser\Ast\Node { - if (! $node instanceof IdentifierTypeNode) { + if (!$node instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode) { return null; } - if ($this->shouldSkip($node, $this->currentPhpParserNode, $this->pseudoNamespaceToNamespace)) { return null; } - /** @var IdentifierTypeNode $node */ - $staticType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType( - $node, - $this->currentPhpParserNode - ); - if (! $staticType instanceof ObjectType) { + $staticType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType($node, $this->currentPhpParserNode); + if (!$staticType instanceof \PHPStan\Type\ObjectType) { return null; } - // change underscore to \\ - $slashedName = '\\' . Strings::replace($staticType->getClassName(), '#_#', '\\'); - return new IdentifierTypeNode($slashedName); + $slashedName = '\\' . \RectorPrefix20210509\Nette\Utils\Strings::replace($staticType->getClassName(), '#_#', '\\'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode($slashedName); } - - public function setPseudoNamespaceToNamespace(PseudoNamespaceToNamespace $pseudoNamespaceToNamespace): void + public function setPseudoNamespaceToNamespace(\Rector\Renaming\ValueObject\PseudoNamespaceToNamespace $pseudoNamespaceToNamespace) : void { $this->pseudoNamespaceToNamespace = $pseudoNamespaceToNamespace; } - - public function setCurrentPhpParserNode(\PhpParser\Node $node): void + public function setCurrentPhpParserNode(\PhpParser\Node $node) : void { $this->currentPhpParserNode = $node; } - - private function shouldSkip( - IdentifierTypeNode $identifierTypeNode, - \PhpParser\Node $phpParserNode, - PseudoNamespaceToNamespace $pseudoNamespaceToNamespace - ): bool { - $staticType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType( - $identifierTypeNode, - $phpParserNode - ); - - if (! $staticType instanceof ObjectType) { - return true; + private function shouldSkip(\PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode $identifierTypeNode, \PhpParser\Node $phpParserNode, \Rector\Renaming\ValueObject\PseudoNamespaceToNamespace $pseudoNamespaceToNamespace) : bool + { + $staticType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType($identifierTypeNode, $phpParserNode); + if (!$staticType instanceof \PHPStan\Type\ObjectType) { + return \true; } - - if (! Strings::startsWith($staticType->getClassName(), $pseudoNamespaceToNamespace->getNamespacePrefix())) { - return true; + if (!\RectorPrefix20210509\Nette\Utils\Strings::startsWith($staticType->getClassName(), $pseudoNamespaceToNamespace->getNamespacePrefix())) { + return \true; } - // excluded? - return in_array($staticType->getClassName(), $pseudoNamespaceToNamespace->getExcludedClasses(), true); + return \in_array($staticType->getClassName(), $pseudoNamespaceToNamespace->getExcludedClasses(), \true); } } diff --git a/packages/NodeTypeResolver/Reflection/BetterReflection/RectorBetterReflectionSourceLocatorFactory.php b/packages/NodeTypeResolver/Reflection/BetterReflection/RectorBetterReflectionSourceLocatorFactory.php index 44403158df8..ed310e70b27 100644 --- a/packages/NodeTypeResolver/Reflection/BetterReflection/RectorBetterReflectionSourceLocatorFactory.php +++ b/packages/NodeTypeResolver/Reflection/BetterReflection/RectorBetterReflectionSourceLocatorFactory.php @@ -1,42 +1,33 @@ betterReflectionSourceLocatorFactory = $betterReflectionSourceLocatorFactory; $this->intermediateSourceLocator = $intermediateSourceLocator; } - - public function create(): MemoizingSourceLocator + public function create() : \PHPStan\BetterReflection\SourceLocator\Type\MemoizingSourceLocator { $phpStanSourceLocator = $this->betterReflectionSourceLocatorFactory->create(); - // make PHPStan first source locator, so we avoid parsing every single file - huge performance hit! - $aggregateSourceLocator = new AggregateSourceLocator([$phpStanSourceLocator, $this->intermediateSourceLocator]); - + $aggregateSourceLocator = new \PHPStan\BetterReflection\SourceLocator\Type\AggregateSourceLocator([$phpStanSourceLocator, $this->intermediateSourceLocator]); // important for cache - return new MemoizingSourceLocator($aggregateSourceLocator); + return new \PHPStan\BetterReflection\SourceLocator\Type\MemoizingSourceLocator($aggregateSourceLocator); } } diff --git a/packages/NodeTypeResolver/Reflection/BetterReflection/SourceLocator/IntermediateSourceLocator.php b/packages/NodeTypeResolver/Reflection/BetterReflection/SourceLocator/IntermediateSourceLocator.php index 66b6defd297..5e320857ca1 100644 --- a/packages/NodeTypeResolver/Reflection/BetterReflection/SourceLocator/IntermediateSourceLocator.php +++ b/packages/NodeTypeResolver/Reflection/BetterReflection/SourceLocator/IntermediateSourceLocator.php @@ -1,7 +1,6 @@ sourceLocatorProviders = $sourceLocatorProviders; } - - public function locateIdentifier(Reflector $reflector, Identifier $identifier): ?Reflection + public function locateIdentifier(\PHPStan\BetterReflection\Reflector\Reflector $reflector, \PHPStan\BetterReflection\Identifier\Identifier $identifier) : ?\PHPStan\BetterReflection\Reflection\Reflection { foreach ($this->sourceLocatorProviders as $sourceLocatorProvider) { $sourceLocator = $sourceLocatorProvider->provide(); - $reflection = $sourceLocator->locateIdentifier($reflector, $identifier); - if ($reflection instanceof Reflection) { + if ($reflection instanceof \PHPStan\BetterReflection\Reflection\Reflection) { return $reflection; } } - return null; } - /** * Find all identifiers of a type * @return Reflection[] */ - public function locateIdentifiersByType(Reflector $reflector, IdentifierType $identifierType): array + public function locateIdentifiersByType(\PHPStan\BetterReflection\Reflector\Reflector $reflector, \PHPStan\BetterReflection\Identifier\IdentifierType $identifierType) : array { foreach ($this->sourceLocatorProviders as $sourceLocatorProvider) { $sourceLocator = $sourceLocatorProvider->provide(); - $reflections = $sourceLocator->locateIdentifiersByType($reflector, $identifierType); if ($reflections !== []) { return $reflections; } } - return []; } } diff --git a/packages/NodeTypeResolver/Reflection/BetterReflection/SourceLocatorProvider/DynamicSourceLocatorProvider.php b/packages/NodeTypeResolver/Reflection/BetterReflection/SourceLocatorProvider/DynamicSourceLocatorProvider.php index 9ce82a94294..98321cf8776 100644 --- a/packages/NodeTypeResolver/Reflection/BetterReflection/SourceLocatorProvider/DynamicSourceLocatorProvider.php +++ b/packages/NodeTypeResolver/Reflection/BetterReflection/SourceLocatorProvider/DynamicSourceLocatorProvider.php @@ -1,7 +1,6 @@ */ private $filesByDirectory = []; - /** * @var FileNodesFetcher */ private $fileNodesFetcher; - /** * @var SourceLocator|null */ private $cachedSourceLocator; - - public function __construct(FileNodesFetcher $fileNodesFetcher) + public function __construct(\PHPStan\Reflection\BetterReflection\SourceLocator\FileNodesFetcher $fileNodesFetcher) { $this->fileNodesFetcher = $fileNodesFetcher; } - - public function setFileInfo(SmartFileInfo $fileInfo): void + public function setFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo) : void { $this->files = [$fileInfo->getRealPath()]; } - /** * @param string[] $files */ - public function addFiles(array $files): void + public function addFiles(array $files) : void { - $this->files = array_merge($this->files, $files); + $this->files = \array_merge($this->files, $files); } - - public function provide(): SourceLocator + public function provide() : \PHPStan\BetterReflection\SourceLocator\Type\SourceLocator { // do not cache for PHPUnit, as in test every fixture is different - $isPHPUnitRun = StaticPHPUnitEnvironment::isPHPUnitRun(); - - if ($this->cachedSourceLocator && $isPHPUnitRun === false) { + $isPHPUnitRun = \Rector\Testing\PHPUnit\StaticPHPUnitEnvironment::isPHPUnitRun(); + if ($this->cachedSourceLocator && $isPHPUnitRun === \false) { return $this->cachedSourceLocator; } - $sourceLocators = []; foreach ($this->files as $file) { - $sourceLocators[] = new OptimizedSingleFileSourceLocator($this->fileNodesFetcher, $file); + $sourceLocators[] = new \PHPStan\Reflection\BetterReflection\SourceLocator\OptimizedSingleFileSourceLocator($this->fileNodesFetcher, $file); } - foreach ($this->filesByDirectory as $files) { - $sourceLocators[] = new OptimizedDirectorySourceLocator($this->fileNodesFetcher, $files); + $sourceLocators[] = new \PHPStan\Reflection\BetterReflection\SourceLocator\OptimizedDirectorySourceLocator($this->fileNodesFetcher, $files); } - - $this->cachedSourceLocator = new AggregateSourceLocator($sourceLocators); - + $this->cachedSourceLocator = new \PHPStan\BetterReflection\SourceLocator\Type\AggregateSourceLocator($sourceLocators); return $this->cachedSourceLocator; } - /** * @param string[] $files */ - public function addFilesByDirectory(string $directory, array $files): void + public function addFilesByDirectory(string $directory, array $files) : void { $this->filesByDirectory[$directory] = $files; } diff --git a/packages/NodeTypeResolver/TypeAnalyzer/ArrayTypeAnalyzer.php b/packages/NodeTypeResolver/TypeAnalyzer/ArrayTypeAnalyzer.php index f0a884ca809..fea65e14149 100644 --- a/packages/NodeTypeResolver/TypeAnalyzer/ArrayTypeAnalyzer.php +++ b/packages/NodeTypeResolver/TypeAnalyzer/ArrayTypeAnalyzer.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->pregMatchTypeCorrector = $pregMatchTypeCorrector; $this->nodeNameResolver = $nodeNameResolver; } - - public function isArrayType(Node $node): bool + public function isArrayType(\PhpParser\Node $node) : bool { $nodeStaticType = $this->nodeTypeResolver->resolve($node); - $nodeStaticType = $this->pregMatchTypeCorrector->correct($node, $nodeStaticType); if ($this->isIntersectionArrayType($nodeStaticType)) { - return true; + return \true; } - // PHPStan false positive, when variable has type[] docblock, but default array is missing - if (($node instanceof PropertyFetch || $node instanceof StaticPropertyFetch) && ! $this->isPropertyFetchWithArrayDefault( - $node - )) { - return false; + if (($node instanceof \PhpParser\Node\Expr\PropertyFetch || $node instanceof \PhpParser\Node\Expr\StaticPropertyFetch) && !$this->isPropertyFetchWithArrayDefault($node)) { + return \false; } - - if ($nodeStaticType instanceof MixedType) { + if ($nodeStaticType instanceof \PHPStan\Type\MixedType) { if ($nodeStaticType->isExplicitMixed()) { - return false; + return \false; } - if ($this->isPropertyFetchWithArrayDefault($node)) { - return true; + return \true; } } - - return $nodeStaticType instanceof ArrayType; + return $nodeStaticType instanceof \PHPStan\Type\ArrayType; } - - private function isIntersectionArrayType(Type $nodeType): bool + private function isIntersectionArrayType(\PHPStan\Type\Type $nodeType) : bool { - if (! $nodeType instanceof IntersectionType) { - return false; + if (!$nodeType instanceof \PHPStan\Type\IntersectionType) { + return \false; } - foreach ($nodeType->getTypes() as $intersectionNodeType) { - if ($intersectionNodeType instanceof ArrayType) { + if ($intersectionNodeType instanceof \PHPStan\Type\ArrayType) { continue; } - if ($intersectionNodeType instanceof HasOffsetType) { + if ($intersectionNodeType instanceof \PHPStan\Type\Accessory\HasOffsetType) { continue; } - if ($intersectionNodeType instanceof NonEmptyArrayType) { + if ($intersectionNodeType instanceof \PHPStan\Type\Accessory\NonEmptyArrayType) { continue; } - return false; + return \false; } - - return true; + return \true; } - /** * phpstan bug workaround - https://phpstan.org/r/0443f283-244c-42b8-8373-85e7deb3504c */ - private function isPropertyFetchWithArrayDefault(Node $node): bool + private function isPropertyFetchWithArrayDefault(\PhpParser\Node $node) : bool { - if (! $node instanceof PropertyFetch && ! $node instanceof StaticPropertyFetch) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\PropertyFetch && !$node instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { + return \false; } - /** @var Class_|Trait_|Interface_|null $classLike */ - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if ($classLike instanceof Interface_) { - return false; + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if ($classLike instanceof \PhpParser\Node\Stmt\Interface_) { + return \false; } if ($classLike === null) { - return false; + return \false; } - $propertyName = $this->nodeNameResolver->getName($node->name); if ($propertyName === null) { - return false; + return \false; } - $property = $classLike->getProperty($propertyName); if ($property !== null) { $propertyProperty = $property->props[0]; - return $propertyProperty->default instanceof Array_; + return $propertyProperty->default instanceof \PhpParser\Node\Expr\Array_; } - // also possible 3rd party vendor - if ($node instanceof PropertyFetch) { + if ($node instanceof \PhpParser\Node\Expr\PropertyFetch) { $propertyOwnerStaticType = $this->nodeTypeResolver->resolve($node->var); } else { $propertyOwnerStaticType = $this->nodeTypeResolver->resolve($node->class); } - if ($propertyOwnerStaticType instanceof ThisType) { - return false; + if ($propertyOwnerStaticType instanceof \PHPStan\Type\ThisType) { + return \false; } - return $propertyOwnerStaticType instanceof TypeWithClassName; + return $propertyOwnerStaticType instanceof \PHPStan\Type\TypeWithClassName; } } diff --git a/packages/NodeTypeResolver/TypeAnalyzer/CountableTypeAnalyzer.php b/packages/NodeTypeResolver/TypeAnalyzer/CountableTypeAnalyzer.php index aaf99fef858..9ce4c9e6102 100644 --- a/packages/NodeTypeResolver/TypeAnalyzer/CountableTypeAnalyzer.php +++ b/packages/NodeTypeResolver/TypeAnalyzer/CountableTypeAnalyzer.php @@ -1,63 +1,46 @@ arrayTypeAnalyzer = $arrayTypeAnalyzer; $this->pregMatchTypeCorrector = $pregMatchTypeCorrector; $this->nodeTypeResolver = $nodeTypeResolver; - - $this->countableObjectTypes = [ - new ObjectType('Countable'), - new ObjectType('SimpleXMLElement'), - new ObjectType('ResourceBundle'), - ]; + $this->countableObjectTypes = [new \PHPStan\Type\ObjectType('Countable'), new \PHPStan\Type\ObjectType('SimpleXMLElement'), new \PHPStan\Type\ObjectType('ResourceBundle')]; } - - public function isCountableType(Node $node): bool + public function isCountableType(\PhpParser\Node $node) : bool { $nodeType = $this->nodeTypeResolver->resolve($node); $nodeType = $this->pregMatchTypeCorrector->correct($node, $nodeType); - foreach ($this->countableObjectTypes as $countableObjectType) { if ($countableObjectType->isSuperTypeOf($nodeType)->yes()) { - return true; + return \true; } } - return $this->arrayTypeAnalyzer->isArrayType($node); } } diff --git a/packages/NodeTypeResolver/TypeAnalyzer/StringTypeAnalyzer.php b/packages/NodeTypeResolver/TypeAnalyzer/StringTypeAnalyzer.php index aea187fe1c4..44cf8daedb8 100644 --- a/packages/NodeTypeResolver/TypeAnalyzer/StringTypeAnalyzer.php +++ b/packages/NodeTypeResolver/TypeAnalyzer/StringTypeAnalyzer.php @@ -1,43 +1,36 @@ nodeTypeResolver = $nodeTypeResolver; } - - public function isStringOrUnionStringOnlyType(Node $node): bool + public function isStringOrUnionStringOnlyType(\PhpParser\Node $node) : bool { $nodeType = $this->nodeTypeResolver->getStaticType($node); - if ($nodeType instanceof StringType) { - return true; + if ($nodeType instanceof \PHPStan\Type\StringType) { + return \true; } - - if ($nodeType instanceof UnionType) { + if ($nodeType instanceof \PHPStan\Type\UnionType) { foreach ($nodeType->getTypes() as $singleType) { - if ($singleType->isSuperTypeOf(new StringType())->no()) { - return false; + if ($singleType->isSuperTypeOf(new \PHPStan\Type\StringType())->no()) { + return \false; } } - - return true; + return \true; } - - return false; + return \false; } } diff --git a/packages/NodeTypeResolver/TypeComparator/ArrayTypeComparator.php b/packages/NodeTypeResolver/TypeComparator/ArrayTypeComparator.php index 5eabceb82f6..e701b4ace02 100644 --- a/packages/NodeTypeResolver/TypeComparator/ArrayTypeComparator.php +++ b/packages/NodeTypeResolver/TypeComparator/ArrayTypeComparator.php @@ -1,7 +1,6 @@ unionTypeCommonTypeNarrower = $unionTypeCommonTypeNarrower; } - - public function isSubtype(ArrayType $checkedType, ArrayType $mainType): bool + public function isSubtype(\PHPStan\Type\ArrayType $checkedType, \PHPStan\Type\ArrayType $mainType) : bool { - if (! $checkedType instanceof ConstantArrayType && ! $mainType instanceof ConstantArrayType) { - return $mainType->isSuperTypeOf($checkedType) - ->yes(); + if (!$checkedType instanceof \PHPStan\Type\Constant\ConstantArrayType && !$mainType instanceof \PHPStan\Type\Constant\ConstantArrayType) { + return $mainType->isSuperTypeOf($checkedType)->yes(); } - $checkedKeyType = $checkedType->getKeyType(); $mainKeyType = $mainType->getKeyType(); - $mainKeyType = $this->narrowArrayKeysUnionType($mainKeyType); - $checkedKeyType = $this->narrowArrayKeysUnionType($checkedKeyType); - if (! $mainKeyType instanceof MixedType && $mainKeyType->isSuperTypeOf($checkedKeyType)->yes()) { - return true; + if (!$mainKeyType instanceof \PHPStan\Type\MixedType && $mainKeyType->isSuperTypeOf($checkedKeyType)->yes()) { + return \true; } - $checkedItemType = $checkedType->getItemType(); - if ($checkedItemType instanceof UnionType) { + if ($checkedItemType instanceof \PHPStan\Type\UnionType) { $checkedItemType = $this->unionTypeCommonTypeNarrower->narrowToGenericClassStringType($checkedItemType); } - $mainItemType = $mainType->getItemType(); - if ($mainItemType instanceof UnionType) { + if ($mainItemType instanceof \PHPStan\Type\UnionType) { $mainItemType = $this->unionTypeCommonTypeNarrower->narrowToGenericClassStringType($mainItemType); } - - return $checkedItemType->isSuperTypeOf($mainItemType) - ->yes(); + return $checkedItemType->isSuperTypeOf($mainItemType)->yes(); } - /** * Native array order can be treated as mixed type */ - private function narrowArrayKeysUnionType(Type $type): Type + private function narrowArrayKeysUnionType(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - if (! $type instanceof UnionType) { + if (!$type instanceof \PHPStan\Type\UnionType) { return $type; } - foreach ($type->getTypes() as $key => $unionedType) { - if (! $unionedType instanceof ConstantIntegerType) { + if (!$unionedType instanceof \PHPStan\Type\Constant\ConstantIntegerType) { return $type; } - if ($key === $unionedType->getValue()) { continue; } - return $type; } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } } diff --git a/packages/NodeTypeResolver/TypeComparator/ScalarTypeComparator.php b/packages/NodeTypeResolver/TypeComparator/ScalarTypeComparator.php index 24bd4c602a2..f6254cfc787 100644 --- a/packages/NodeTypeResolver/TypeComparator/ScalarTypeComparator.php +++ b/packages/NodeTypeResolver/TypeComparator/ScalarTypeComparator.php @@ -1,7 +1,6 @@ typeHasher = $typeHasher; $this->typeNormalizer = $typeNormalizer; $this->staticTypeMapper = $staticTypeMapper; @@ -69,181 +55,138 @@ final class TypeComparator $this->scalarTypeComparator = $scalarTypeComparator; $this->typeFactory = $typeFactory; } - - public function areTypesEqual(Type $firstType, Type $secondType): bool + public function areTypesEqual(\PHPStan\Type\Type $firstType, \PHPStan\Type\Type $secondType) : bool { if ($this->scalarTypeComparator->areEqualScalar($firstType, $secondType)) { - return true; + return \true; } - // aliases and types if ($this->areAliasedObjectMatchingFqnObject($firstType, $secondType)) { - return true; + return \true; } - if ($this->areArrayUnionConstantEqualTypes($firstType, $secondType)) { - return true; + return \true; } - $firstType = $this->typeNormalizer->normalizeArrayOfUnionToUnionArray($firstType); $secondType = $this->typeNormalizer->normalizeArrayOfUnionToUnionArray($secondType); - if ($this->typeHasher->areTypesEqual($firstType, $secondType)) { - return true; + return \true; } - // is template of return $this->areArrayTypeWithSingleObjectChildToParent($firstType, $secondType); } - - public function arePhpParserAndPhpStanPhpDocTypesEqual( - Node $phpParserNode, - TypeNode $phpStanDocTypeNode, - Node $node - ): bool { + public function arePhpParserAndPhpStanPhpDocTypesEqual(\PhpParser\Node $phpParserNode, \PHPStan\PhpDocParser\Ast\Type\TypeNode $phpStanDocTypeNode, \PhpParser\Node $node) : bool + { $phpParserNodeType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($phpParserNode); - $phpStanDocType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType( - $phpStanDocTypeNode, - $node - ); - + $phpStanDocType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType($phpStanDocTypeNode, $node); // normalize bool union types $phpParserNodeType = $this->normalizeConstantBooleanType($phpParserNodeType); $phpStanDocType = $this->normalizeConstantBooleanType($phpStanDocType); - return $this->areTypesEqual($phpParserNodeType, $phpStanDocType); } - - public function isSubtype(Type $checkedType, Type $mainType): bool + public function isSubtype(\PHPStan\Type\Type $checkedType, \PHPStan\Type\Type $mainType) : bool { - if ($mainType instanceof MixedType) { - return false; + if ($mainType instanceof \PHPStan\Type\MixedType) { + return \false; } - - if (! $mainType instanceof ArrayType) { - return $mainType->isSuperTypeOf($checkedType) - ->yes(); + if (!$mainType instanceof \PHPStan\Type\ArrayType) { + return $mainType->isSuperTypeOf($checkedType)->yes(); } - - if (! $checkedType instanceof ArrayType) { - return $mainType->isSuperTypeOf($checkedType) - ->yes(); + if (!$checkedType instanceof \PHPStan\Type\ArrayType) { + return $mainType->isSuperTypeOf($checkedType)->yes(); } - return $this->arrayTypeComparator->isSubtype($checkedType, $mainType); } - - private function areAliasedObjectMatchingFqnObject(Type $firstType, Type $secondType): bool + private function areAliasedObjectMatchingFqnObject(\PHPStan\Type\Type $firstType, \PHPStan\Type\Type $secondType) : bool { - if ($firstType instanceof AliasedObjectType && $secondType instanceof ObjectType && $firstType->getFullyQualifiedClass() === $secondType->getClassName()) { - return true; + if ($firstType instanceof \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType && $secondType instanceof \PHPStan\Type\ObjectType && $firstType->getFullyQualifiedClass() === $secondType->getClassName()) { + return \true; } - if (! $secondType instanceof AliasedObjectType) { - return false; + if (!$secondType instanceof \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType) { + return \false; } - if (! $firstType instanceof ObjectType) { - return false; + if (!$firstType instanceof \PHPStan\Type\ObjectType) { + return \false; } return $secondType->getFullyQualifiedClass() === $firstType->getClassName(); } - /** * E.g. class A extends B, class B → A[] is subtype of B[] → keep A[] */ - private function areArrayTypeWithSingleObjectChildToParent(Type $firstType, Type $secondType): bool + private function areArrayTypeWithSingleObjectChildToParent(\PHPStan\Type\Type $firstType, \PHPStan\Type\Type $secondType) : bool { - if (! $firstType instanceof ArrayType) { - return false; + if (!$firstType instanceof \PHPStan\Type\ArrayType) { + return \false; } - if (! $secondType instanceof ArrayType) { - return false; + if (!$secondType instanceof \PHPStan\Type\ArrayType) { + return \false; } - $firstArrayItemType = $firstType->getItemType(); $secondArrayItemType = $secondType->getItemType(); - if ($this->isMutualObjectSubtypes($firstArrayItemType, $secondArrayItemType)) { - return true; + return \true; } - - if (! $firstArrayItemType instanceof GenericClassStringType) { - return false; + if (!$firstArrayItemType instanceof \PHPStan\Type\Generic\GenericClassStringType) { + return \false; } - - if (! $secondArrayItemType instanceof GenericClassStringType) { - return false; + if (!$secondArrayItemType instanceof \PHPStan\Type\Generic\GenericClassStringType) { + return \false; } - // @todo resolve later better with template map, @see https://github.com/symplify/symplify/pull/3034/commits/4f6be8b87e52117b1aa1613b9b689ae958a9d6f4 - return $firstArrayItemType->getGenericType() instanceof ObjectType && $secondArrayItemType->getGenericType() instanceof ObjectType; + return $firstArrayItemType->getGenericType() instanceof \PHPStan\Type\ObjectType && $secondArrayItemType->getGenericType() instanceof \PHPStan\Type\ObjectType; } - - private function isMutualObjectSubtypes(Type $firstArrayItemType, Type $secondArrayItemType): bool + private function isMutualObjectSubtypes(\PHPStan\Type\Type $firstArrayItemType, \PHPStan\Type\Type $secondArrayItemType) : bool { - if ($firstArrayItemType instanceof ObjectType && $secondArrayItemType instanceof ObjectType) { + if ($firstArrayItemType instanceof \PHPStan\Type\ObjectType && $secondArrayItemType instanceof \PHPStan\Type\ObjectType) { if ($firstArrayItemType->isSuperTypeOf($secondArrayItemType)->yes()) { - return true; + return \true; } - if ($secondArrayItemType->isSuperTypeOf($firstArrayItemType)->yes()) { - return true; + return \true; } } - - return false; + return \false; } - - private function normalizeSingleUnionType(Type $type): Type + private function normalizeSingleUnionType(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - if ($type instanceof UnionType) { + if ($type instanceof \PHPStan\Type\UnionType) { $uniqueTypes = $this->typeFactory->uniquateTypes($type->getTypes()); - if (count($uniqueTypes) === 1) { + if (\count($uniqueTypes) === 1) { return $uniqueTypes[0]; } } - return $type; } - - private function areArrayUnionConstantEqualTypes(Type $firstType, Type $secondType): bool + private function areArrayUnionConstantEqualTypes(\PHPStan\Type\Type $firstType, \PHPStan\Type\Type $secondType) : bool { - if (! $firstType instanceof ArrayType) { - return false; + if (!$firstType instanceof \PHPStan\Type\ArrayType) { + return \false; } - - if (! $secondType instanceof ArrayType) { - return false; + if (!$secondType instanceof \PHPStan\Type\ArrayType) { + return \false; } - $firstKeyType = $this->normalizeSingleUnionType($firstType->getKeyType()); $secondKeyType = $this->normalizeSingleUnionType($secondType->getKeyType()); - // mixed and integer type are mutual replaceable in practise - if ($firstKeyType instanceof MixedType) { - $firstKeyType = new IntegerType(); + if ($firstKeyType instanceof \PHPStan\Type\MixedType) { + $firstKeyType = new \PHPStan\Type\IntegerType(); } - - if ($secondKeyType instanceof MixedType) { - $secondKeyType = new IntegerType(); + if ($secondKeyType instanceof \PHPStan\Type\MixedType) { + $secondKeyType = new \PHPStan\Type\IntegerType(); } - - if (! $this->areTypesEqual($firstKeyType, $secondKeyType)) { - return false; + if (!$this->areTypesEqual($firstKeyType, $secondKeyType)) { + return \false; } - $firstArrayType = $this->normalizeSingleUnionType($firstType->getItemType()); $secondArrayType = $this->normalizeSingleUnionType($secondType->getItemType()); - return $this->areTypesEqual($firstArrayType, $secondArrayType); } - - private function normalizeConstantBooleanType(Type $type): Type + private function normalizeConstantBooleanType(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - return TypeTraverser::map($type, function (Type $type, callable $callable): Type { - if ($type instanceof ConstantBooleanType) { - return new BooleanType(); + return \PHPStan\Type\TypeTraverser::map($type, function (\PHPStan\Type\Type $type, callable $callable) : Type { + if ($type instanceof \PHPStan\Type\Constant\ConstantBooleanType) { + return new \PHPStan\Type\BooleanType(); } - return $callable($type); }); } diff --git a/packages/NodeTypeResolver/ValueObject/OldToNewType.php b/packages/NodeTypeResolver/ValueObject/OldToNewType.php index 38f8b4dd902..c4699afabfa 100644 --- a/packages/NodeTypeResolver/ValueObject/OldToNewType.php +++ b/packages/NodeTypeResolver/ValueObject/OldToNewType.php @@ -1,35 +1,29 @@ oldType = $oldType; $this->newType = $newType; } - - public function getOldType(): Type + public function getOldType() : \PHPStan\Type\Type { return $this->oldType; } - - public function getNewType(): Type + public function getNewType() : \PHPStan\Type\Type { return $this->newType; } diff --git a/packages/PHPStanStaticTypeMapper/Contract/PHPStanStaticTypeMapperAwareInterface.php b/packages/PHPStanStaticTypeMapper/Contract/PHPStanStaticTypeMapperAwareInterface.php index fcfe36d21be..388235f93e9 100644 --- a/packages/PHPStanStaticTypeMapper/Contract/PHPStanStaticTypeMapperAwareInterface.php +++ b/packages/PHPStanStaticTypeMapper/Contract/PHPStanStaticTypeMapperAwareInterface.php @@ -1,12 +1,10 @@ */ - public function getNodeClass(): string; - - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode; - + public function getNodeClass() : string; + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode; /** * @return Name|NullableType|UnionType|null */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node; + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node; } diff --git a/packages/PHPStanStaticTypeMapper/DoctrineTypeAnalyzer.php b/packages/PHPStanStaticTypeMapper/DoctrineTypeAnalyzer.php index a4b3f29debb..945e99ebd92 100644 --- a/packages/PHPStanStaticTypeMapper/DoctrineTypeAnalyzer.php +++ b/packages/PHPStanStaticTypeMapper/DoctrineTypeAnalyzer.php @@ -1,47 +1,39 @@ getTypes() as $unionedType) { if ($this->isCollectionObjectType($unionedType)) { - $hasDoctrineCollectionType = true; + $hasDoctrineCollectionType = \true; } - - if ($unionedType instanceof ArrayType) { + if ($unionedType instanceof \PHPStan\Type\ArrayType) { $arrayType = $unionedType; } } - - if (! $hasDoctrineCollectionType) { - return false; + if (!$hasDoctrineCollectionType) { + return \false; } - return $arrayType !== null; } - - private function isCollectionObjectType(Type $type): bool + private function isCollectionObjectType(\PHPStan\Type\Type $type) : bool { - if (! $type instanceof TypeWithClassName) { - return false; + if (!$type instanceof \PHPStan\Type\TypeWithClassName) { + return \false; } - - return $type->getClassName() === 'Doctrine\Common\Collections\Collection'; + return $type->getClassName() === 'Doctrine\\Common\\Collections\\Collection'; } } diff --git a/packages/PHPStanStaticTypeMapper/PHPStanStaticTypeMapper.php b/packages/PHPStanStaticTypeMapper/PHPStanStaticTypeMapper.php index b3ed21634c2..fa13d6af19b 100644 --- a/packages/PHPStanStaticTypeMapper/PHPStanStaticTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/PHPStanStaticTypeMapper.php @@ -1,7 +1,6 @@ setPHPStanStaticTypeMapper($this); } } - $this->typeMappers = $typeMappers; } - - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { foreach ($this->typeMappers as $typeMapper) { - if (! is_a($type, $typeMapper->getNodeClass(), true)) { + if (!\is_a($type, $typeMapper->getNodeClass(), \true)) { continue; } - return $typeMapper->mapToPHPStanPhpDocTypeNode($type); } - - throw new NotImplementedYetException(__METHOD__ . ' for ' . get_class($type)); + throw new \Rector\Core\Exception\NotImplementedYetException(__METHOD__ . ' for ' . \get_class($type)); } - /** * @return Name|NullableType|PhpParserUnionType|null */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { foreach ($this->typeMappers as $typeMapper) { - if (! is_a($type, $typeMapper->getNodeClass(), true)) { + if (!\is_a($type, $typeMapper->getNodeClass(), \true)) { continue; } - return $typeMapper->mapToPhpParserNode($type, $kind); } - - throw new NotImplementedYetException(__METHOD__ . ' for ' . get_class($type)); + throw new \Rector\Core\Exception\NotImplementedYetException(__METHOD__ . ' for ' . \get_class($type)); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeAnalyzer/BoolUnionTypeAnalyzer.php b/packages/PHPStanStaticTypeMapper/TypeAnalyzer/BoolUnionTypeAnalyzer.php index 9644de6b7b7..38324e1897e 100644 --- a/packages/PHPStanStaticTypeMapper/TypeAnalyzer/BoolUnionTypeAnalyzer.php +++ b/packages/PHPStanStaticTypeMapper/TypeAnalyzer/BoolUnionTypeAnalyzer.php @@ -1,42 +1,35 @@ getTypes() as $unionedType) { - if (! $unionedType instanceof BooleanType) { - return false; + if (!$unionedType instanceof \PHPStan\Type\BooleanType) { + return \false; } } - - return true; + return \true; } - - public function isNullableBoolUnionType(UnionType $unionType): bool + public function isNullableBoolUnionType(\PHPStan\Type\UnionType $unionType) : bool { - $hasNullable = false; + $hasNullable = \false; foreach ($unionType->getTypes() as $unionedType) { - if ($unionedType instanceof NullType) { - $hasNullable = true; + if ($unionedType instanceof \PHPStan\Type\NullType) { + $hasNullable = \true; continue; } - - if ($unionedType instanceof BooleanType) { + if ($unionedType instanceof \PHPStan\Type\BooleanType) { continue; } - - return false; + return \false; } - return $hasNullable; } } diff --git a/packages/PHPStanStaticTypeMapper/TypeAnalyzer/UnionTypeAnalyzer.php b/packages/PHPStanStaticTypeMapper/TypeAnalyzer/UnionTypeAnalyzer.php index 3d92c248b6f..8e2cdc2b072 100644 --- a/packages/PHPStanStaticTypeMapper/TypeAnalyzer/UnionTypeAnalyzer.php +++ b/packages/PHPStanStaticTypeMapper/TypeAnalyzer/UnionTypeAnalyzer.php @@ -1,7 +1,6 @@ getTypes() as $unionedType) { - if ($unionedType instanceof IterableType) { - $hasIterable = true; + if ($unionedType instanceof \PHPStan\Type\IterableType) { + $hasIterable = \true; continue; } - - if ($unionedType instanceof ArrayType) { - $hasArray = true; + if ($unionedType instanceof \PHPStan\Type\ArrayType) { + $hasArray = \true; continue; } - - if ($unionedType instanceof NullType) { - $isNullableType = true; + if ($unionedType instanceof \PHPStan\Type\NullType) { + $isNullableType = \true; continue; } - - if ($unionedType instanceof ObjectType && $unionedType->getClassName() === Traversable::class) { - $hasIterable = true; + if ($unionedType instanceof \PHPStan\Type\ObjectType && $unionedType->getClassName() === \Traversable::class) { + $hasIterable = \true; continue; } - return null; } - - return new UnionTypeAnalysis($isNullableType, $hasIterable, $hasArray); + return new \Rector\PHPStanStaticTypeMapper\ValueObject\UnionTypeAnalysis($isNullableType, $hasIterable, $hasArray); } - - public function hasTypeClassNameOnly(UnionType $unionType): bool + public function hasTypeClassNameOnly(\PHPStan\Type\UnionType $unionType) : bool { foreach ($unionType->getTypes() as $unionedType) { - if (! $unionedType instanceof TypeWithClassName) { - return false; + if (!$unionedType instanceof \PHPStan\Type\TypeWithClassName) { + return \false; } } - - return true; + return \true; } - - public function hasObjectWithoutClassType(UnionType $unionType): bool + public function hasObjectWithoutClassType(\PHPStan\Type\UnionType $unionType) : bool { $types = $unionType->getTypes(); foreach ($types as $type) { - if ($type instanceof ObjectWithoutClassType) { - return true; + if ($type instanceof \PHPStan\Type\ObjectWithoutClassType) { + return \true; } } - - return false; + return \false; } - - public function hasObjectWithoutClassTypeWithOnlyFullyQualifiedObjectType(UnionType $unionType): bool + public function hasObjectWithoutClassTypeWithOnlyFullyQualifiedObjectType(\PHPStan\Type\UnionType $unionType) : bool { $types = $unionType->getTypes(); foreach ($types as $type) { - if ($type instanceof ObjectWithoutClassType) { + if ($type instanceof \PHPStan\Type\ObjectWithoutClassType) { continue; } - - if (! $type instanceof FullyQualifiedObjectType) { - return false; + if (!$type instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType) { + return \false; } } - - return true; + return \true; } - - public function isScalar(UnionType $unionType): bool + public function isScalar(\PHPStan\Type\UnionType $unionType) : bool { $types = $unionType->getTypes(); - - if (count($types) !== 4) { - return false; + if (\count($types) !== 4) { + return \false; } - foreach ($types as $type) { - if ($type instanceof StringType) { + if ($type instanceof \PHPStan\Type\StringType) { continue; } - if ($type instanceof FloatType) { + if ($type instanceof \PHPStan\Type\FloatType) { continue; } - if ($type instanceof IntegerType) { + if ($type instanceof \PHPStan\Type\IntegerType) { continue; } - if ($type instanceof BooleanType) { + if ($type instanceof \PHPStan\Type\BooleanType) { continue; } - return false; + return \false; } - - return true; + return \true; } } diff --git a/packages/PHPStanStaticTypeMapper/TypeAnalyzer/UnionTypeCommonTypeNarrower.php b/packages/PHPStanStaticTypeMapper/TypeAnalyzer/UnionTypeCommonTypeNarrower.php index 47b954fa6f2..6b19c11fe8d 100644 --- a/packages/PHPStanStaticTypeMapper/TypeAnalyzer/UnionTypeCommonTypeNarrower.php +++ b/packages/PHPStanStaticTypeMapper/TypeAnalyzer/UnionTypeCommonTypeNarrower.php @@ -1,7 +1,6 @@ |class-string<\PHPStan\PhpDocParser\Ast\Node>|class-string>> */ - private const PRIORITY_TYPES = [ - ClassLike::class => [ClassLike::class], - FunctionLike::class => [FunctionLike::class], - BinaryOp::class => [BinaryOp::class, Expr::class], - Expr::class => [Node::class, Expr::class], - Stmt::class => [Node::class, Stmt::class], - PhpDocTagValueNode::class => [PhpDocTagValueNode::class, \PHPStan\PhpDocParser\Ast\Node::class], - Node::class => [Node::class], - RectorInterface::class => [RectorInterface::class], - ]; - + private const PRIORITY_TYPES = [\PhpParser\Node\Stmt\ClassLike::class => [\PhpParser\Node\Stmt\ClassLike::class], \PhpParser\Node\FunctionLike::class => [\PhpParser\Node\FunctionLike::class], \PhpParser\Node\Expr\BinaryOp::class => [\PhpParser\Node\Expr\BinaryOp::class, \PhpParser\Node\Expr::class], \PhpParser\Node\Expr::class => [\PhpParser\Node::class, \PhpParser\Node\Expr::class], \PhpParser\Node\Stmt::class => [\PhpParser\Node::class, \PhpParser\Node\Stmt::class], \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode::class => [\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode::class, \PHPStan\PhpDocParser\Ast\Node::class], \PhpParser\Node::class => [\PhpParser\Node::class], \Rector\Core\Contract\Rector\RectorInterface::class => [\Rector\Core\Contract\Rector\RectorInterface::class]]; /** * @var GenericClassStringTypeCorrector */ private $genericClassStringTypeCorrector; - /** * @var ReflectionProvider */ private $reflectionProvider; - - public function __construct( - GenericClassStringTypeCorrector $genericClassStringTypeCorrector, - ReflectionProvider $reflectionProvider - ) { + public function __construct(\Rector\NodeTypeResolver\NodeTypeCorrector\GenericClassStringTypeCorrector $genericClassStringTypeCorrector, \PHPStan\Reflection\ReflectionProvider $reflectionProvider) + { $this->genericClassStringTypeCorrector = $genericClassStringTypeCorrector; $this->reflectionProvider = $reflectionProvider; } - - public function narrowToSharedObjectType(UnionType $unionType): ?ObjectType + public function narrowToSharedObjectType(\PHPStan\Type\UnionType $unionType) : ?\PHPStan\Type\ObjectType { $sharedTypes = $this->narrowToSharedTypes($unionType); - if ($sharedTypes !== []) { foreach (self::PRIORITY_TYPES as $winningType => $groupTypes) { - $intersectedGroupTypes = array_intersect($groupTypes, $sharedTypes); + $intersectedGroupTypes = \array_intersect($groupTypes, $sharedTypes); if ($intersectedGroupTypes === $groupTypes) { - return new ObjectType($winningType); + return new \PHPStan\Type\ObjectType($winningType); } } - $firstSharedType = $sharedTypes[0]; - return new ObjectType($firstSharedType); + return new \PHPStan\Type\ObjectType($firstSharedType); } - return null; } - /** * @return GenericClassStringType|UnionType */ - public function narrowToGenericClassStringType(UnionType $unionType): Type + public function narrowToGenericClassStringType(\PHPStan\Type\UnionType $unionType) : \PHPStan\Type\Type { $availableTypes = []; - foreach ($unionType->getTypes() as $unionedType) { - if ($unionedType instanceof ConstantStringType) { + if ($unionedType instanceof \PHPStan\Type\Constant\ConstantStringType) { $unionedType = $this->genericClassStringTypeCorrector->correct($unionedType); } - - if (! $unionedType instanceof GenericClassStringType) { + if (!$unionedType instanceof \PHPStan\Type\Generic\GenericClassStringType) { return $unionType; } - $genericClassStrings = []; - if ($unionedType->getGenericType() instanceof ObjectType) { + if ($unionedType->getGenericType() instanceof \PHPStan\Type\ObjectType) { $parentClassReflections = $this->resolveClassParentClassesAndInterfaces($unionedType->getGenericType()); foreach ($parentClassReflections as $parentClassReflection) { $genericClassStrings[] = $parentClassReflection->getName(); } } - $availableTypes[] = $genericClassStrings; } - $genericClassStringType = $this->createGenericClassStringType($availableTypes); - if ($genericClassStringType instanceof GenericClassStringType) { + if ($genericClassStringType instanceof \PHPStan\Type\Generic\GenericClassStringType) { return $genericClassStringType; } - return $unionType; } - /** * @return string[] */ - private function narrowToSharedTypes(UnionType $unionType): array + private function narrowToSharedTypes(\PHPStan\Type\UnionType $unionType) : array { $availableTypes = []; - foreach ($unionType->getTypes() as $unionedType) { - if (! $unionedType instanceof ObjectType) { + if (!$unionedType instanceof \PHPStan\Type\ObjectType) { return []; } - $typeClassReflections = $this->resolveClassParentClassesAndInterfaces($unionedType); $typeClassNames = []; - foreach ($typeClassReflections as $typeClassReflection) { $typeClassNames[] = $typeClassReflection->getName(); } - if ($typeClassNames === []) { continue; } - $availableTypes[] = $typeClassNames; } - return $this->narrowAvailableTypes($availableTypes); } - /** * @return ClassReflection[] */ - private function resolveClassParentClassesAndInterfaces(ObjectType $objectType): array + private function resolveClassParentClassesAndInterfaces(\PHPStan\Type\ObjectType $objectType) : array { - if (! $this->reflectionProvider->hasClass($objectType->getClassName())) { + if (!$this->reflectionProvider->hasClass($objectType->getClassName())) { return []; } - $classReflection = $this->reflectionProvider->getClass($objectType->getClassName()); - // put earliest interfaces first - $implementedInterfaceClassReflections = array_reverse($classReflection->getInterfaces()); - + $implementedInterfaceClassReflections = \array_reverse($classReflection->getInterfaces()); /** @var ClassReflection[] $parentClassAndInterfaceReflections */ - $parentClassAndInterfaceReflections = array_merge( - $implementedInterfaceClassReflections, - $classReflection->getParents() - ); - + $parentClassAndInterfaceReflections = \array_merge($implementedInterfaceClassReflections, $classReflection->getParents()); return $this->filterOutNativeClassReflections($parentClassAndInterfaceReflections); } - /** * @param string[][] $availableTypes * @return string[] */ - private function narrowAvailableTypes(array $availableTypes): array + private function narrowAvailableTypes(array $availableTypes) : array { - if (count($availableTypes) < 2) { + if (\count($availableTypes) < 2) { return []; } - /** @var string[] $sharedTypes */ - $sharedTypes = array_intersect(...$availableTypes); - return array_values($sharedTypes); + $sharedTypes = \array_intersect(...$availableTypes); + return \array_values($sharedTypes); } - /** * @param string[][] $availableTypes */ - private function createGenericClassStringType(array $availableTypes): ?GenericClassStringType + private function createGenericClassStringType(array $availableTypes) : ?\PHPStan\Type\Generic\GenericClassStringType { $sharedTypes = $this->narrowAvailableTypes($availableTypes); - if ($sharedTypes !== []) { foreach (self::PRIORITY_TYPES as $winningType => $groupTypes) { - $intersectedGroupTypes = array_intersect($groupTypes, $sharedTypes); + $intersectedGroupTypes = \array_intersect($groupTypes, $sharedTypes); if ($intersectedGroupTypes === $groupTypes) { - return new GenericClassStringType(new ObjectType($winningType)); + return new \PHPStan\Type\Generic\GenericClassStringType(new \PHPStan\Type\ObjectType($winningType)); } } - $firstSharedType = $sharedTypes[0]; - return new GenericClassStringType(new ObjectType($firstSharedType)); + return new \PHPStan\Type\Generic\GenericClassStringType(new \PHPStan\Type\ObjectType($firstSharedType)); } - return null; } - /** * @param ClassReflection[] $classReflections * @return ClassReflection[] */ - private function filterOutNativeClassReflections(array $classReflections): array + private function filterOutNativeClassReflections(array $classReflections) : array { - return array_filter($classReflections, function (ClassReflection $classReflection): bool { - return ! $classReflection->isBuiltin(); + return \array_filter($classReflections, function (\PHPStan\Reflection\ClassReflection $classReflection) : bool { + return !$classReflection->isBuiltin(); }); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/ArrayTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/ArrayTypeMapper.php index 7ac075882a1..63d7ededf8c 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/ArrayTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/ArrayTypeMapper.php @@ -1,7 +1,6 @@ phpStanStaticTypeMapper = $phpStanStaticTypeMapper; $this->unionTypeCommonTypeNarrower = $unionTypeCommonTypeNarrower; $this->reflectionProvider = $reflectionProvider; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return ArrayType::class; + return \PHPStan\Type\ArrayType::class; } - /** * @param ArrayType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { $itemType = $type->getItemType(); - - if ($itemType instanceof UnionType && ! $type instanceof ConstantArrayType) { + if ($itemType instanceof \PHPStan\Type\UnionType && !$type instanceof \PHPStan\Type\Constant\ConstantArrayType) { return $this->createArrayTypeNodeFromUnionType($itemType); } - - if ($itemType instanceof ArrayType && $this->isGenericArrayCandidate($itemType)) { - return $this->createGenericArrayType($type, true); + if ($itemType instanceof \PHPStan\Type\ArrayType && $this->isGenericArrayCandidate($itemType)) { + return $this->createGenericArrayType($type, \true); } - if ($this->isGenericArrayCandidate($type)) { - return $this->createGenericArrayType($type, true); + return $this->createGenericArrayType($type, \true); } - $narrowedTypeNode = $this->narrowConstantArrayTypeOfUnionType($type, $itemType); - if ($narrowedTypeNode instanceof TypeNode) { + if ($narrowedTypeNode instanceof \PHPStan\PhpDocParser\Ast\Type\TypeNode) { return $narrowedTypeNode; } - $itemTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($itemType); - - return new SpacingAwareArrayTypeNode($itemTypeNode); + return new \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode($itemTypeNode); } - /** * @param ArrayType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - return new Name('array'); + return new \PhpParser\Node\Name('array'); } - - private function createArrayTypeNodeFromUnionType(UnionType $unionType): SpacingAwareArrayTypeNode + private function createArrayTypeNodeFromUnionType(\PHPStan\Type\UnionType $unionType) : \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode { $unionedArrayType = []; foreach ($unionType->getTypes() as $unionedType) { $typeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($unionedType); $unionedArrayType[(string) $typeNode] = $typeNode; } - - if (count($unionedArrayType) > 1) { - return new SpacingAwareArrayTypeNode(new BracketsAwareUnionTypeNode($unionedArrayType)); + if (\count($unionedArrayType) > 1) { + return new \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode(new \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareUnionTypeNode($unionedArrayType)); } - /** @var TypeNode $arrayType */ - $arrayType = array_shift($unionedArrayType); - return new SpacingAwareArrayTypeNode($arrayType); + $arrayType = \array_shift($unionedArrayType); + return new \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode($arrayType); } - - private function isGenericArrayCandidate(ArrayType $arrayType): bool + private function isGenericArrayCandidate(\PHPStan\Type\ArrayType $arrayType) : bool { - if ($arrayType->getKeyType() instanceof MixedType) { - return false; + if ($arrayType->getKeyType() instanceof \PHPStan\Type\MixedType) { + return \false; } - if ($this->isClassStringArrayType($arrayType)) { - return true; + return \true; } - // skip simple arrays, like "string[]", from converting to obvious "array" if ($this->isIntegerKeyAndNonNestedArray($arrayType)) { - return false; + return \false; } - - if ($arrayType->getKeyType() instanceof NeverType) { - return false; + if ($arrayType->getKeyType() instanceof \PHPStan\Type\NeverType) { + return \false; } - // make sure the integer key type is not natural/implicit array int keys $keysArrayType = $arrayType->getKeysArray(); - if (! $keysArrayType instanceof ConstantArrayType) { - return true; + if (!$keysArrayType instanceof \PHPStan\Type\Constant\ConstantArrayType) { + return \true; } - foreach ($keysArrayType->getValueTypes() as $key => $keyType) { - if (! $keyType instanceof ConstantIntegerType) { - return true; + if (!$keyType instanceof \PHPStan\Type\Constant\ConstantIntegerType) { + return \true; } - if ($key !== $keyType->getValue()) { - return true; + return \true; } } - - return false; + return \false; } - - private function createGenericArrayType(ArrayType $arrayType, bool $withKey = false): GenericTypeNode + private function createGenericArrayType(\PHPStan\Type\ArrayType $arrayType, bool $withKey = \false) : \PHPStan\PhpDocParser\Ast\Type\GenericTypeNode { $itemTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($arrayType->getItemType()); - $identifierTypeNode = new IdentifierTypeNode('array'); - + $identifierTypeNode = new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('array'); // is class-string[] list only if ($this->isClassStringArrayType($arrayType)) { - $withKey = false; + $withKey = \false; } - if ($withKey) { $keyTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($arrayType->getKeyType()); $genericTypes = [$keyTypeNode, $itemTypeNode]; } else { $genericTypes = [$itemTypeNode]; } - // @see https://github.com/phpstan/phpdoc-parser/blob/98a088b17966bdf6ee25c8a4b634df313d8aa531/tests/PHPStan/Parser/PhpDocParserTest.php#L2692-L2696 - foreach ($genericTypes as $genericType) { /** @var \PHPStan\PhpDocParser\Ast\Node $genericType */ $genericType->setAttribute(self::HAS_GENERIC_TYPE_PARENT, $withKey); } - $identifierTypeNode->setAttribute(self::HAS_GENERIC_TYPE_PARENT, $withKey); - return new GenericTypeNode($identifierTypeNode, $genericTypes); + return new \PHPStan\PhpDocParser\Ast\Type\GenericTypeNode($identifierTypeNode, $genericTypes); } - - private function isIntegerKeyAndNonNestedArray(ArrayType $arrayType): bool + private function isIntegerKeyAndNonNestedArray(\PHPStan\Type\ArrayType $arrayType) : bool { - if (! $arrayType->getKeyType() instanceof IntegerType) { - return false; + if (!$arrayType->getKeyType() instanceof \PHPStan\Type\IntegerType) { + return \false; } - - return ! $arrayType->getItemType() instanceof ArrayType; + return !$arrayType->getItemType() instanceof \PHPStan\Type\ArrayType; } - - private function narrowConstantArrayTypeOfUnionType(ArrayType $arrayType, Type $itemType): ?TypeNode + private function narrowConstantArrayTypeOfUnionType(\PHPStan\Type\ArrayType $arrayType, \PHPStan\Type\Type $itemType) : ?\PHPStan\PhpDocParser\Ast\Type\TypeNode { - if ($arrayType instanceof ConstantArrayType && $itemType instanceof UnionType) { + if ($arrayType instanceof \PHPStan\Type\Constant\ConstantArrayType && $itemType instanceof \PHPStan\Type\UnionType) { $narrowedItemType = $this->unionTypeCommonTypeNarrower->narrowToSharedObjectType($itemType); - if ($narrowedItemType instanceof ObjectType) { + if ($narrowedItemType instanceof \PHPStan\Type\ObjectType) { $itemTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($narrowedItemType); - return new SpacingAwareArrayTypeNode($itemTypeNode); + return new \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode($itemTypeNode); } - $narrowedItemType = $this->unionTypeCommonTypeNarrower->narrowToGenericClassStringType($itemType); - if ($narrowedItemType instanceof GenericClassStringType) { + if ($narrowedItemType instanceof \PHPStan\Type\Generic\GenericClassStringType) { return $this->createTypeNodeFromGenericClassStringType($narrowedItemType); } } - return null; } - - private function createTypeNodeFromGenericClassStringType( - GenericClassStringType $genericClassStringType - ): TypeNode { - $genericType = $genericClassStringType->getGenericType(); - if ($genericType instanceof ObjectType && ! $this->reflectionProvider->hasClass($genericType->getClassName())) { - return new IdentifierTypeNode($genericType->getClassName()); - } - - $itemTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($genericClassStringType); - - return new GenericTypeNode(new IdentifierTypeNode('array'), [$itemTypeNode]); - } - - private function isClassStringArrayType(ArrayType $arrayType): bool + private function createTypeNodeFromGenericClassStringType(\PHPStan\Type\Generic\GenericClassStringType $genericClassStringType) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - if ($arrayType->getKeyType() instanceof MixedType) { - return $arrayType->getItemType() instanceof GenericClassStringType; + $genericType = $genericClassStringType->getGenericType(); + if ($genericType instanceof \PHPStan\Type\ObjectType && !$this->reflectionProvider->hasClass($genericType->getClassName())) { + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode($genericType->getClassName()); } - - if ($arrayType->getKeyType() instanceof ConstantIntegerType) { - return $arrayType->getItemType() instanceof GenericClassStringType; + $itemTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($genericClassStringType); + return new \PHPStan\PhpDocParser\Ast\Type\GenericTypeNode(new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('array'), [$itemTypeNode]); + } + private function isClassStringArrayType(\PHPStan\Type\ArrayType $arrayType) : bool + { + if ($arrayType->getKeyType() instanceof \PHPStan\Type\MixedType) { + return $arrayType->getItemType() instanceof \PHPStan\Type\Generic\GenericClassStringType; } - - return false; + if ($arrayType->getKeyType() instanceof \PHPStan\Type\Constant\ConstantIntegerType) { + return $arrayType->getItemType() instanceof \PHPStan\Type\Generic\GenericClassStringType; + } + return \false; } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/BooleanTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/BooleanTypeMapper.php index 208b8da7dd8..15e83b5b1fc 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/BooleanTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/BooleanTypeMapper.php @@ -1,7 +1,6 @@ phpVersionProvider = $phpVersionProvider; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return BooleanType::class; + return \PHPStan\Type\BooleanType::class; } - /** * @param BooleanType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { if ($this->isFalseBooleanTypeWithUnion($type)) { - return new IdentifierTypeNode('false'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('false'); } - - return new IdentifierTypeNode('bool'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('bool'); } - /** * @param BooleanType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::SCALAR_TYPES)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SCALAR_TYPES)) { return null; } - if ($this->isFalseBooleanTypeWithUnion($type)) { - return new Name('false'); + return new \PhpParser\Node\Name('false'); } - - return new Name('bool'); + return new \PhpParser\Node\Name('bool'); } - - private function isFalseBooleanTypeWithUnion(Type $type): bool + private function isFalseBooleanTypeWithUnion(\PHPStan\Type\Type $type) : bool { - if (! $type instanceof ConstantBooleanType) { - return false; + if (!$type instanceof \PHPStan\Type\Constant\ConstantBooleanType) { + return \false; } - if ($type->getValue()) { - return false; + return \false; } - - return $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::UNION_TYPES); + return $this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::UNION_TYPES); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/CallableTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/CallableTypeMapper.php index d050ee5a277..79382d11f8a 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/CallableTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/CallableTypeMapper.php @@ -1,7 +1,6 @@ phpStanStaticTypeMapper = $phpStanStaticTypeMapper; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return CallableType::class; + return \PHPStan\Type\CallableType::class; } - /** * @param CallableType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { $returnTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($type->getReturnType()); - - return new SpacingAwareCallableTypeNode(new IdentifierTypeNode('callable'), [], $returnTypeNode); + return new \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareCallableTypeNode(new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('callable'), [], $returnTypeNode); } - /** * @param CallableType|ClosureType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { if ($kind === 'property') { return null; } - - return new Name('callable'); + return new \PhpParser\Node\Name('callable'); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/ClassStringTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/ClassStringTypeMapper.php index 7e46eb22a59..2274209702a 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/ClassStringTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/ClassStringTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return ClassStringType::class; + return \PHPStan\Type\ClassStringType::class; } - /** * @param ClassStringType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - $attributeAwareIdentifierTypeNode = new IdentifierTypeNode('class-string'); - - if ($type instanceof GenericClassStringType) { + $attributeAwareIdentifierTypeNode = new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('class-string'); + if ($type instanceof \PHPStan\Type\Generic\GenericClassStringType) { $genericType = $type->getGenericType(); - if ($genericType instanceof ObjectType) { + if ($genericType instanceof \PHPStan\Type\ObjectType) { $className = $genericType->getClassName(); $className = $this->normalizeType($className); - $genericType = new ObjectType($className); + $genericType = new \PHPStan\Type\ObjectType($className); } - $genericTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($genericType); - return new GenericTypeNode($attributeAwareIdentifierTypeNode, [$genericTypeNode]); + return new \PHPStan\PhpDocParser\Ast\Type\GenericTypeNode($attributeAwareIdentifierTypeNode, [$genericTypeNode]); } - return $attributeAwareIdentifierTypeNode; } - /** * @param ClassStringType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { return null; } - - public function setPHPStanStaticTypeMapper(PHPStanStaticTypeMapper $phpStanStaticTypeMapper): void + public function setPHPStanStaticTypeMapper(\Rector\PHPStanStaticTypeMapper\PHPStanStaticTypeMapper $phpStanStaticTypeMapper) : void { $this->phpStanStaticTypeMapper = $phpStanStaticTypeMapper; } - - private function normalizeType(string $classType): string + private function normalizeType(string $classType) : string { - if (is_a($classType, Expr::class, true)) { - return Expr::class; + if (\is_a($classType, \PhpParser\Node\Expr::class, \true)) { + return \PhpParser\Node\Expr::class; } - - if (is_a($classType, Node::class, true)) { - return Node::class; + if (\is_a($classType, \PhpParser\Node::class, \true)) { + return \PhpParser\Node::class; } - return $classType; } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/ClosureTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/ClosureTypeMapper.php index 5dc0b3758b9..39d370d4b51 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/ClosureTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/ClosureTypeMapper.php @@ -1,7 +1,6 @@ callableTypeMapper = $callableTypeMapper; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return ClosureType::class; + return \PHPStan\Type\ClosureType::class; } - /** * @param ClosureType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - $identifierTypeNode = new IdentifierTypeNode($type->getClassName()); - + $identifierTypeNode = new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode($type->getClassName()); $returnDocTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($type->getReturnType()); - - return new SpacingAwareCallableTypeNode($identifierTypeNode, [], $returnDocTypeNode); + return new \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareCallableTypeNode($identifierTypeNode, [], $returnDocTypeNode); } - /** * @param ClosureType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { return $this->callableTypeMapper->mapToPhpParserNode($type, $kind); } - - public function setPHPStanStaticTypeMapper(PHPStanStaticTypeMapper $phpStanStaticTypeMapper): void + public function setPHPStanStaticTypeMapper(\Rector\PHPStanStaticTypeMapper\PHPStanStaticTypeMapper $phpStanStaticTypeMapper) : void { $this->phpStanStaticTypeMapper = $phpStanStaticTypeMapper; } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/FloatTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/FloatTypeMapper.php index 96ce4ee62b3..42f226ad6db 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/FloatTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/FloatTypeMapper.php @@ -1,7 +1,6 @@ phpVersionProvider = $phpVersionProvider; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return FloatType::class; + return \PHPStan\Type\FloatType::class; } - /** * @param FloatType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode('float'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('float'); } - /** * @param FloatType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::SCALAR_TYPES)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SCALAR_TYPES)) { return null; } - - return new Name('float'); + return new \PhpParser\Node\Name('float'); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/HasOffsetTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/HasOffsetTypeMapper.php index 62f1186f751..11c64543f7c 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/HasOffsetTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/HasOffsetTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return HasOffsetType::class; + return \PHPStan\Type\Accessory\HasOffsetType::class; } - /** * @param HasOffsetType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new ArrayTypeNode(new IdentifierTypeNode('mixed')); + return new \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode(new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('mixed')); } - /** * @param HasOffsetType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/IntegerTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/IntegerTypeMapper.php index 3c9ec9959e2..98d0b7df9df 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/IntegerTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/IntegerTypeMapper.php @@ -1,7 +1,6 @@ phpVersionProvider = $phpVersionProvider; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return IntegerType::class; + return \PHPStan\Type\IntegerType::class; } - /** * @param IntegerType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode('int'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('int'); } - /** * @param IntegerType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::SCALAR_TYPES)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SCALAR_TYPES)) { return null; } - - return new Name('int'); + return new \PhpParser\Node\Name('int'); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/IntersectionTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/IntersectionTypeMapper.php index 810fd6de8f0..cd8fa8f5d56 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/IntersectionTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/IntersectionTypeMapper.php @@ -1,7 +1,6 @@ phpStanStaticTypeMapper = $phpStanStaticTypeMapper; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return IntersectionType::class; + return \PHPStan\Type\IntersectionType::class; } - /** * @param IntersectionType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { $intersectionTypesNodes = []; - foreach ($type->getTypes() as $intersectionedType) { $intersectionTypesNodes[] = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($intersectionedType); } - - $intersectionTypesNodes = array_unique($intersectionTypesNodes); - - return new BracketsAwareIntersectionTypeNode($intersectionTypesNodes); + $intersectionTypesNodes = \array_unique($intersectionTypesNodes); + return new \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareIntersectionTypeNode($intersectionTypesNodes); } - /** * @param IntersectionType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { // intersection types in PHP are not yet supported return null; diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/IterableTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/IterableTypeMapper.php index e70d2207968..8ec861071ea 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/IterableTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/IterableTypeMapper.php @@ -1,7 +1,6 @@ phpStanStaticTypeMapper = $phpStanStaticTypeMapper; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return IterableType::class; + return \PHPStan\Type\IterableType::class; } - /** * @param IterableType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { $itemTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($type->getItemType()); - if ($itemTypeNode instanceof UnionTypeNode) { + if ($itemTypeNode instanceof \PHPStan\PhpDocParser\Ast\Type\UnionTypeNode) { return $this->convertUnionArrayTypeNodesToArrayTypeOfUnionTypeNodes($itemTypeNode); } - - return new SpacingAwareArrayTypeNode($itemTypeNode); + return new \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode($itemTypeNode); } - /** * @param IterableType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - return new Name('iterable'); + return new \PhpParser\Node\Name('iterable'); } - - private function convertUnionArrayTypeNodesToArrayTypeOfUnionTypeNodes( - UnionTypeNode $unionTypeNode - ): BracketsAwareUnionTypeNode { + private function convertUnionArrayTypeNodesToArrayTypeOfUnionTypeNodes(\PHPStan\PhpDocParser\Ast\Type\UnionTypeNode $unionTypeNode) : \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareUnionTypeNode + { $unionedArrayType = []; foreach ($unionTypeNode->types as $unionedType) { - if ($unionedType instanceof UnionTypeNode) { + if ($unionedType instanceof \PHPStan\PhpDocParser\Ast\Type\UnionTypeNode) { foreach ($unionedType->types as $key => $subUnionedType) { - $unionedType->types[$key] = new ArrayTypeNode($subUnionedType); + $unionedType->types[$key] = new \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode($subUnionedType); } - $unionedArrayType[] = $unionedType; continue; } - - $unionedArrayType[] = new ArrayTypeNode($unionedType); + $unionedArrayType[] = new \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode($unionedType); } - - return new BracketsAwareUnionTypeNode($unionedArrayType); + return new \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareUnionTypeNode($unionedArrayType); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/MixedTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/MixedTypeMapper.php index 1787be306d2..d04d47153f2 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/MixedTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/MixedTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return MixedType::class; + return \PHPStan\Type\MixedType::class; } - /** * @param MixedType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode('mixed'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('mixed'); } - /** * @param MixedType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { return null; } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/NeverTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/NeverTypeMapper.php index 426b2210f4e..6629bb4543e 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/NeverTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/NeverTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return NeverType::class; + return \PHPStan\Type\NeverType::class; } - /** * @param NeverType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode('mixed'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('mixed'); } - /** * @param NeverType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { return null; } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/NonEmptyArrayTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/NonEmptyArrayTypeMapper.php index ac9b233e545..10efb032456 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/NonEmptyArrayTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/NonEmptyArrayTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return NonEmptyArrayType::class; + return \PHPStan\Type\Accessory\NonEmptyArrayType::class; } - /** * @param NonEmptyArrayType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new SpacingAwareArrayTypeNode(new IdentifierTypeNode('mixed')); + return new \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode(new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('mixed')); } - /** * @param NonEmptyArrayType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - return new Name('array'); + return new \PhpParser\Node\Name('array'); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/NullTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/NullTypeMapper.php index b68dd8b36c9..b4816bf8aa1 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/NullTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/NullTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return NullType::class; + return \PHPStan\Type\NullType::class; } - /** * @param NullType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode('null'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('null'); } - /** * @param NullType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - if ($kind !== TypeKind::KIND_PROPERTY) { + if ($kind !== \Rector\PHPStanStaticTypeMapper\ValueObject\TypeKind::KIND_PROPERTY) { return null; } - - return new Name('null'); + return new \PhpParser\Node\Name('null'); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/ObjectTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/ObjectTypeMapper.php index 2972991e7ad..43e640af5a7 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/ObjectTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/ObjectTypeMapper.php @@ -1,10 +1,9 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return ObjectType::class; + return \PHPStan\Type\ObjectType::class; } - /** * @param ObjectType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - if ($type instanceof ShortenedObjectType) { - return new IdentifierTypeNode($type->getClassName()); + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType) { + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode($type->getClassName()); } - - if ($type instanceof AliasedObjectType) { - return new IdentifierTypeNode($type->getClassName()); + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType) { + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode($type->getClassName()); } - - if ($type instanceof GenericObjectType) { + if ($type instanceof \PHPStan\Type\Generic\GenericObjectType) { return $this->mapGenericObjectType($type); } - - return new IdentifierTypeNode('\\' . $type->getClassName()); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('\\' . $type->getClassName()); } - /** * @param ObjectType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - if ($type instanceof SelfObjectType) { - return new Name('self'); + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\SelfObjectType) { + return new \PhpParser\Node\Name('self'); } - - if ($type instanceof ShortenedObjectType) { - return new FullyQualified($type->getFullyQualifiedName()); + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType) { + return new \PhpParser\Node\Name\FullyQualified($type->getFullyQualifiedName()); } - - if ($type instanceof AliasedObjectType) { - return new Name($type->getClassName()); + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType) { + return new \PhpParser\Node\Name($type->getClassName()); } - - if ($type instanceof FullyQualifiedObjectType) { - return new FullyQualified($type->getClassName()); + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType) { + return new \PhpParser\Node\Name\FullyQualified($type->getClassName()); } - - if (! $type instanceof GenericObjectType) { + if (!$type instanceof \PHPStan\Type\Generic\GenericObjectType) { // fallback - return new FullyQualified($type->getClassName()); + return new \PhpParser\Node\Name\FullyQualified($type->getClassName()); } - if ($type->getClassName() === 'iterable') { // fallback - return new Name('iterable'); + return new \PhpParser\Node\Name('iterable'); } - if ($type->getClassName() !== 'object') { // fallback - return new FullyQualified($type->getClassName()); + return new \PhpParser\Node\Name\FullyQualified($type->getClassName()); } - - return new Name('object'); + return new \PhpParser\Node\Name('object'); } - - public function setPHPStanStaticTypeMapper(PHPStanStaticTypeMapper $phpStanStaticTypeMapper): void + public function setPHPStanStaticTypeMapper(\Rector\PHPStanStaticTypeMapper\PHPStanStaticTypeMapper $phpStanStaticTypeMapper) : void { $this->phpStanStaticTypeMapper = $phpStanStaticTypeMapper; } - - private function mapGenericObjectType(GenericObjectType $genericObjectType): TypeNode + private function mapGenericObjectType(\PHPStan\Type\Generic\GenericObjectType $genericObjectType) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { $name = $this->resolveGenericObjectTypeName($genericObjectType); - $identifierTypeNode = new IdentifierTypeNode($name); - + $identifierTypeNode = new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode($name); $genericTypeNodes = []; foreach ($genericObjectType->getTypes() as $key => $genericType) { // mixed type on 1st item in iterator has no value - if ($name === 'Iterator' && $genericType instanceof MixedType && $key === 0) { + if ($name === 'Iterator' && $genericType instanceof \PHPStan\Type\MixedType && $key === 0) { continue; } - $typeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($genericType); $genericTypeNodes[] = $typeNode; } - if ($genericTypeNodes === []) { return $identifierTypeNode; } - - return new GenericTypeNode($identifierTypeNode, $genericTypeNodes); + return new \PHPStan\PhpDocParser\Ast\Type\GenericTypeNode($identifierTypeNode, $genericTypeNodes); } - - private function resolveGenericObjectTypeName(GenericObjectType $genericObjectType): string + private function resolveGenericObjectTypeName(\PHPStan\Type\Generic\GenericObjectType $genericObjectType) : string { - if ($genericObjectType instanceof FullyQualifiedGenericObjectType) { + if ($genericObjectType instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedGenericObjectType) { return '\\' . $genericObjectType->getClassName(); } - - if (Strings::contains($genericObjectType->getClassName(), '\\')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($genericObjectType->getClassName(), '\\')) { return '\\' . $genericObjectType->getClassName(); } - return $genericObjectType->getClassName(); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/ObjectWithoutClassTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/ObjectWithoutClassTypeMapper.php index 413cef93c45..d30d282928e 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/ObjectWithoutClassTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/ObjectWithoutClassTypeMapper.php @@ -1,7 +1,6 @@ phpVersionProvider = $phpVersionProvider; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return ObjectWithoutClassType::class; + return \PHPStan\Type\ObjectWithoutClassType::class; } - /** * @param ObjectWithoutClassType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - if ($type instanceof TemplateObjectWithoutClassType) { - $attributeAwareIdentifierTypeNode = new IdentifierTypeNode($type->getName()); - return new EmptyGenericTypeNode($attributeAwareIdentifierTypeNode); + if ($type instanceof \PHPStan\Type\Generic\TemplateObjectWithoutClassType) { + $attributeAwareIdentifierTypeNode = new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode($type->getName()); + return new \Rector\BetterPhpDocParser\ValueObject\Type\EmptyGenericTypeNode($attributeAwareIdentifierTypeNode); } - - return new IdentifierTypeNode('object'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('object'); } - /** * @param ObjectWithoutClassType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { $subtractedType = $type->getSubtractedType(); if ($subtractedType !== null) { return $this->phpStanStaticTypeMapper->mapToPhpParserNode($subtractedType); } - - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::OBJECT_TYPE)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::OBJECT_TYPE)) { return null; } - - return new Name('object'); + return new \PhpParser\Node\Name('object'); } - - public function setPHPStanStaticTypeMapper(PHPStanStaticTypeMapper $phpStanStaticTypeMapper): void + public function setPHPStanStaticTypeMapper(\Rector\PHPStanStaticTypeMapper\PHPStanStaticTypeMapper $phpStanStaticTypeMapper) : void { $this->phpStanStaticTypeMapper = $phpStanStaticTypeMapper; } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/ParentStaticTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/ParentStaticTypeMapper.php index d8c650beaa8..3337bafbf4a 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/ParentStaticTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/ParentStaticTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return ParentStaticType::class; + return \Rector\StaticTypeMapper\ValueObject\Type\ParentStaticType::class; } - /** * @param ParentStaticType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode('parent'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('parent'); } - /** * @param ParentStaticType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - return new Name('parent'); + return new \PhpParser\Node\Name('parent'); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/ResourceTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/ResourceTypeMapper.php index 06c87526544..aa143128306 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/ResourceTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/ResourceTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return ResourceType::class; + return \PHPStan\Type\ResourceType::class; } - /** * @param ResourceType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode('resource'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('resource'); } - /** * @param ResourceType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { return null; } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/SelfObjectTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/SelfObjectTypeMapper.php index 94976559ff0..ba0b678e0fc 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/SelfObjectTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/SelfObjectTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return SelfObjectType::class; + return \Rector\StaticTypeMapper\ValueObject\Type\SelfObjectType::class; } - /** * @param SelfObjectType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode('self'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('self'); } - /** * @param SelfObjectType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - return new Name('self'); + return new \PhpParser\Node\Name('self'); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/StaticTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/StaticTypeMapper.php index 7447a463a40..a6b154099c0 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/StaticTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/StaticTypeMapper.php @@ -1,7 +1,6 @@ phpVersionProvider = $phpVersionProvider; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return StaticType::class; + return \PHPStan\Type\StaticType::class; } - /** * @param StaticType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new ThisTypeNode(); + return new \PHPStan\PhpDocParser\Ast\Type\ThisTypeNode(); } - /** * @param StaticType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - if ($type instanceof ThisType) { + if ($type instanceof \PHPStan\Type\ThisType) { // @todo wait for PHPStan to differentiate between self/static - if ($this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::STATIC_RETURN_TYPE)) { - return new Name('static'); + if ($this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::STATIC_RETURN_TYPE)) { + return new \PhpParser\Node\Name('static'); } - - return new Name('self'); + return new \PhpParser\Node\Name('self'); } - return null; } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/StrictMixedTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/StrictMixedTypeMapper.php index c9bab9b17b4..09d5da1b3f1 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/StrictMixedTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/StrictMixedTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return StrictMixedType::class; + return \PHPStan\Type\StrictMixedType::class; } - /** * @param StrictMixedType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode(self::MIXED); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode(self::MIXED); } - /** * @param StrictMixedType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - return new Name(self::MIXED); + return new \PhpParser\Node\Name(self::MIXED); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/StringTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/StringTypeMapper.php index 99430eee26e..2282426df32 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/StringTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/StringTypeMapper.php @@ -1,7 +1,6 @@ phpVersionProvider = $phpVersionProvider; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return StringType::class; + return \PHPStan\Type\StringType::class; } - /** * @param StringType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode('string'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('string'); } - - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::SCALAR_TYPES)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SCALAR_TYPES)) { return null; } - - return new Name('string'); + return new \PhpParser\Node\Name('string'); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/ThisTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/ThisTypeMapper.php index 5387925ad30..c14734b29cc 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/ThisTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/ThisTypeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeClass(): string + public function getNodeClass() : string { - return ThisType::class; + return \PHPStan\Type\ThisType::class; } - /** * @param ThisType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new ThisTypeNode(); + return new \PHPStan\PhpDocParser\Ast\Type\ThisTypeNode(); } - /** * @param ThisType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - return new Name('self'); + return new \PhpParser\Node\Name('self'); } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/TypeWithClassNameTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/TypeWithClassNameTypeMapper.php index 8cacaa83448..84352c5fa55 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/TypeWithClassNameTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/TypeWithClassNameTypeMapper.php @@ -1,7 +1,6 @@ stringTypeMapper = $stringTypeMapper; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return TypeWithClassName::class; + return \PHPStan\Type\TypeWithClassName::class; } - /** * @param TypeWithClassName $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode('string-class'); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('string-class'); } - /** * @param TypeWithClassName $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { return $this->stringTypeMapper->mapToPhpParserNode($type, $kind); } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/UnionTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/UnionTypeMapper.php index 7b81cec260c..cee1d46b1a2 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/UnionTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/UnionTypeMapper.php @@ -1,7 +1,6 @@ phpVersionProvider = $phpVersionProvider; $this->unionTypeAnalyzer = $unionTypeAnalyzer; $this->doctrineTypeAnalyzer = $doctrineTypeAnalyzer; $this->boolUnionTypeAnalyzer = $boolUnionTypeAnalyzer; $this->unionTypeCommonTypeNarrower = $unionTypeCommonTypeNarrower; } - /** * @required */ - public function autowireUnionTypeMapper(PHPStanStaticTypeMapper $phpStanStaticTypeMapper): void + public function autowireUnionTypeMapper(\Rector\PHPStanStaticTypeMapper\PHPStanStaticTypeMapper $phpStanStaticTypeMapper) : void { $this->phpStanStaticTypeMapper = $phpStanStaticTypeMapper; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return UnionType::class; + return \PHPStan\Type\UnionType::class; } - /** * @param UnionType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { $unionTypesNodes = []; $skipIterable = $this->shouldSkipIterable($type); - foreach ($type->getTypes() as $unionedType) { - if ($unionedType instanceof IterableType && $skipIterable) { + if ($unionedType instanceof \PHPStan\Type\IterableType && $skipIterable) { continue; } - $unionTypesNodes[] = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($unionedType); } - - $unionTypesNodes = array_unique($unionTypesNodes); - return new BracketsAwareUnionTypeNode($unionTypesNodes); + $unionTypesNodes = \array_unique($unionTypesNodes); + return new \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareUnionTypeNode($unionTypesNodes); } - /** * @param UnionType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { $arrayNode = $this->matchArrayTypes($type); if ($arrayNode !== null) { return $arrayNode; } - - if ($this->boolUnionTypeAnalyzer->isNullableBoolUnionType( - $type - ) && ! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::UNION_TYPES)) { - return new NullableType(new Name('bool')); + if ($this->boolUnionTypeAnalyzer->isNullableBoolUnionType($type) && !$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::UNION_TYPES)) { + return new \PhpParser\Node\NullableType(new \PhpParser\Node\Name('bool')); } - - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::UNION_TYPES) && $this->isFalseBoolUnion( - $type - )) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::UNION_TYPES) && $this->isFalseBoolUnion($type)) { // return new Bool - return new Name('bool'); + return new \PhpParser\Node\Name('bool'); } - // special case for nullable $nullabledType = $this->matchTypeForNullableUnionType($type); - if (! $nullabledType instanceof Type) { + if (!$nullabledType instanceof \PHPStan\Type\Type) { // use first unioned type in case of unioned object types return $this->matchTypeForUnionedObjectTypes($type); } - // void cannot be nullable - if ($nullabledType instanceof VoidType) { + if ($nullabledType instanceof \PHPStan\Type\VoidType) { return null; } - $nullabledTypeNode = $this->phpStanStaticTypeMapper->mapToPhpParserNode($nullabledType); - if (! $nullabledTypeNode instanceof Node) { + if (!$nullabledTypeNode instanceof \PhpParser\Node) { return null; } - - if ($nullabledTypeNode instanceof NullableType) { + if ($nullabledTypeNode instanceof \PhpParser\Node\NullableType) { return $nullabledTypeNode; } - - if ($nullabledTypeNode instanceof PhpParserUnionType) { - throw new ShouldNotHappenException(); + if ($nullabledTypeNode instanceof \PhpParser\Node\UnionType) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - return new NullableType($nullabledTypeNode); + return new \PhpParser\Node\NullableType($nullabledTypeNode); } - - private function shouldSkipIterable(UnionType $unionType): bool + private function shouldSkipIterable(\PHPStan\Type\UnionType $unionType) : bool { $unionTypeAnalysis = $this->unionTypeAnalyzer->analyseForNullableAndIterable($unionType); - if (! $unionTypeAnalysis instanceof UnionTypeAnalysis) { - return false; + if (!$unionTypeAnalysis instanceof \Rector\PHPStanStaticTypeMapper\ValueObject\UnionTypeAnalysis) { + return \false; } - if (! $unionTypeAnalysis->hasIterable()) { - return false; + if (!$unionTypeAnalysis->hasIterable()) { + return \false; } return $unionTypeAnalysis->hasArray(); } - /** * @return Name|NullableType|null */ - private function matchArrayTypes(UnionType $unionType): ?Node + private function matchArrayTypes(\PHPStan\Type\UnionType $unionType) : ?\PhpParser\Node { $unionTypeAnalysis = $this->unionTypeAnalyzer->analyseForNullableAndIterable($unionType); - if (! $unionTypeAnalysis instanceof UnionTypeAnalysis) { + if (!$unionTypeAnalysis instanceof \Rector\PHPStanStaticTypeMapper\ValueObject\UnionTypeAnalysis) { return null; } - $type = $unionTypeAnalysis->hasIterable() ? 'iterable' : 'array'; if ($unionTypeAnalysis->isNullableType()) { - return new NullableType($type); + return new \PhpParser\Node\NullableType($type); } - - return new Name($type); + return new \PhpParser\Node\Name($type); } - - private function matchTypeForNullableUnionType(UnionType $unionType): ?Type + private function matchTypeForNullableUnionType(\PHPStan\Type\UnionType $unionType) : ?\PHPStan\Type\Type { - if (count($unionType->getTypes()) !== 2) { + if (\count($unionType->getTypes()) !== 2) { return null; } - $firstType = $unionType->getTypes()[0]; $secondType = $unionType->getTypes()[1]; - - if ($firstType instanceof NullType) { + if ($firstType instanceof \PHPStan\Type\NullType) { return $secondType; } - - if ($secondType instanceof NullType) { + if ($secondType instanceof \PHPStan\Type\NullType) { return $firstType; } - return null; } - /** * @return Name|FullyQualified|PhpParserUnionType|null */ - private function matchTypeForUnionedObjectTypes(UnionType $unionType): ?Node + private function matchTypeForUnionedObjectTypes(\PHPStan\Type\UnionType $unionType) : ?\PhpParser\Node { $phpParserUnionType = $this->matchPhpParserUnionType($unionType); if ($phpParserUnionType !== null) { - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::UNION_TYPES)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::UNION_TYPES)) { // maybe all one type? if ($this->boolUnionTypeAnalyzer->isBoolUnionType($unionType)) { - return new Name('bool'); + return new \PhpParser\Node\Name('bool'); } - return null; } - return $phpParserUnionType; } - if ($this->boolUnionTypeAnalyzer->isBoolUnionType($unionType)) { - return new Name('bool'); + return new \PhpParser\Node\Name('bool'); } - // the type should be compatible with all other types, e.g. A extends B, B $compatibleObjectType = $this->resolveCompatibleObjectCandidate($unionType); - if (! $compatibleObjectType instanceof ObjectType) { + if (!$compatibleObjectType instanceof \PHPStan\Type\ObjectType) { return null; } - - return new FullyQualified($compatibleObjectType->getClassName()); + return new \PhpParser\Node\Name\FullyQualified($compatibleObjectType->getClassName()); } - - private function matchPhpParserUnionType(UnionType $unionType): ?PhpParserUnionType + private function matchPhpParserUnionType(\PHPStan\Type\UnionType $unionType) : ?\PhpParser\Node\UnionType { - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::UNION_TYPES)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::UNION_TYPES)) { return null; } - $phpParserUnionedTypes = []; - foreach ($unionType->getTypes() as $unionedType) { // void type is not allowed in union - if ($unionedType instanceof VoidType) { + if ($unionedType instanceof \PHPStan\Type\VoidType) { return null; } - /** @var Identifier|Name|null $phpParserNode */ $phpParserNode = $this->phpStanStaticTypeMapper->mapToPhpParserNode($unionedType); if ($phpParserNode === null) { return null; } - $phpParserUnionedTypes[] = $phpParserNode; } - - return new PhpParserUnionType($phpParserUnionedTypes); + return new \PhpParser\Node\UnionType($phpParserUnionedTypes); } - - private function resolveCompatibleObjectCandidate(UnionType $unionType): ?TypeWithClassName + private function resolveCompatibleObjectCandidate(\PHPStan\Type\UnionType $unionType) : ?\PHPStan\Type\TypeWithClassName { if ($this->doctrineTypeAnalyzer->isDoctrineCollectionWithIterableUnionType($unionType)) { - return new ObjectType('Doctrine\Common\Collections\Collection'); + return new \PHPStan\Type\ObjectType('Doctrine\\Common\\Collections\\Collection'); } - - if (! $this->unionTypeAnalyzer->hasTypeClassNameOnly($unionType)) { + if (!$this->unionTypeAnalyzer->hasTypeClassNameOnly($unionType)) { return null; } - $sharedTypeWithClassName = $this->matchTwoObjectTypes($unionType); - if ($sharedTypeWithClassName instanceof TypeWithClassName) { + if ($sharedTypeWithClassName instanceof \PHPStan\Type\TypeWithClassName) { return $this->correctObjectType($sharedTypeWithClassName); } // find least common denominator return $this->unionTypeCommonTypeNarrower->narrowToSharedObjectType($unionType); } - - private function matchTwoObjectTypes(UnionType $unionType): ?TypeWithClassName + private function matchTwoObjectTypes(\PHPStan\Type\UnionType $unionType) : ?\PHPStan\Type\TypeWithClassName { /** @var TypeWithClassName $unionedType */ foreach ($unionType->getTypes() as $unionedType) { /** @var TypeWithClassName $nestedUnionedType */ foreach ($unionType->getTypes() as $nestedUnionedType) { - if (! $this->areTypeWithClassNamesRelated($unionedType, $nestedUnionedType)) { + if (!$this->areTypeWithClassNamesRelated($unionedType, $nestedUnionedType)) { continue 2; } } - return $unionedType; } - return null; } - - private function areTypeWithClassNamesRelated(TypeWithClassName $firstType, TypeWithClassName $secondType): bool + private function areTypeWithClassNamesRelated(\PHPStan\Type\TypeWithClassName $firstType, \PHPStan\Type\TypeWithClassName $secondType) : bool { - if ($firstType->accepts($secondType, false)->yes()) { - return true; + if ($firstType->accepts($secondType, \false)->yes()) { + return \true; } - - return $secondType->accepts($firstType, false) - ->yes(); + return $secondType->accepts($firstType, \false)->yes(); } - - private function correctObjectType(TypeWithClassName $typeWithClassName): TypeWithClassName + private function correctObjectType(\PHPStan\Type\TypeWithClassName $typeWithClassName) : \PHPStan\Type\TypeWithClassName { - if ($typeWithClassName->getClassName() === NodeAbstract::class) { - return new ObjectType('PhpParser\Node'); + if ($typeWithClassName->getClassName() === \PhpParser\NodeAbstract::class) { + return new \PHPStan\Type\ObjectType('PhpParser\\Node'); } - - if ($typeWithClassName->getClassName() === AbstractRector::class) { - return new ObjectType('Rector\Core\Contract\Rector\RectorInterface'); + if ($typeWithClassName->getClassName() === \Rector\Core\Rector\AbstractRector::class) { + return new \PHPStan\Type\ObjectType('Rector\\Core\\Contract\\Rector\\RectorInterface'); } - return $typeWithClassName; } - - private function isFalseBoolUnion(UnionType $unionType): bool + private function isFalseBoolUnion(\PHPStan\Type\UnionType $unionType) : bool { - if (count($unionType->getTypes()) !== 2) { - return false; + if (\count($unionType->getTypes()) !== 2) { + return \false; } - foreach ($unionType->getTypes() as $unionedType) { - if ($unionedType instanceof ConstantBooleanType) { + if ($unionedType instanceof \PHPStan\Type\Constant\ConstantBooleanType) { continue; } - - return false; + return \false; } - - return true; + return \true; } } diff --git a/packages/PHPStanStaticTypeMapper/TypeMapper/VoidTypeMapper.php b/packages/PHPStanStaticTypeMapper/TypeMapper/VoidTypeMapper.php index 311d7a26612..8d6ff390194 100644 --- a/packages/PHPStanStaticTypeMapper/TypeMapper/VoidTypeMapper.php +++ b/packages/PHPStanStaticTypeMapper/TypeMapper/VoidTypeMapper.php @@ -1,7 +1,6 @@ phpVersionProvider = $phpVersionProvider; } - /** * @return class-string */ - public function getNodeClass(): string + public function getNodeClass() : string { - return VoidType::class; + return \PHPStan\Type\VoidType::class; } - /** * @param VoidType $type */ - public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode + public function mapToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $type) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { - return new IdentifierTypeNode(self::VOID); + return new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode(self::VOID); } - /** * @param VoidType $type */ - public function mapToPhpParserNode(Type $type, ?string $kind = null): ?Node + public function mapToPhpParserNode(\PHPStan\Type\Type $type, ?string $kind = null) : ?\PhpParser\Node { - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::VOID_TYPE)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::VOID_TYPE)) { return null; } - - if (in_array($kind, ['param', 'property'], true)) { + if (\in_array($kind, ['param', 'property'], \true)) { return null; } - - return new Name(self::VOID); + return new \PhpParser\Node\Name(self::VOID); } } diff --git a/packages/PHPStanStaticTypeMapper/Utils/TypeUnwrapper.php b/packages/PHPStanStaticTypeMapper/Utils/TypeUnwrapper.php index ff501be7dab..f14f1b72b7d 100644 --- a/packages/PHPStanStaticTypeMapper/Utils/TypeUnwrapper.php +++ b/packages/PHPStanStaticTypeMapper/Utils/TypeUnwrapper.php @@ -1,7 +1,6 @@ unionTypeFactory = $unionTypeFactory; } - /** * E.g. null|ClassType → ClassType */ - public function unwrapNullableType(Type $type): Type + public function unwrapNullableType(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - return TypeCombinator::removeNull($type); + return \PHPStan\Type\TypeCombinator::removeNull($type); } - - public function unwrapFirstObjectTypeFromUnionType(Type $type): Type + public function unwrapFirstObjectTypeFromUnionType(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - if (! $type instanceof UnionType) { + if (!$type instanceof \PHPStan\Type\UnionType) { return $type; } - foreach ($type->getTypes() as $unionedType) { - if (! $unionedType instanceof TypeWithClassName) { + if (!$unionedType instanceof \PHPStan\Type\TypeWithClassName) { continue; } - return $unionedType; } - return $type; } - - public function removeNullTypeFromUnionType(UnionType $unionType): UnionType + public function removeNullTypeFromUnionType(\PHPStan\Type\UnionType $unionType) : \PHPStan\Type\UnionType { $unionedTypesWithoutNullType = []; - foreach ($unionType->getTypes() as $type) { - if ($type instanceof UnionType) { + if ($type instanceof \PHPStan\Type\UnionType) { continue; } - $unionedTypesWithoutNullType[] = $type; } - return $this->unionTypeFactory->createUnionObjectType($unionedTypesWithoutNullType); } } diff --git a/packages/PHPStanStaticTypeMapper/ValueObject/TypeKind.php b/packages/PHPStanStaticTypeMapper/ValueObject/TypeKind.php index 513359d3b4f..322bf55786a 100644 --- a/packages/PHPStanStaticTypeMapper/ValueObject/TypeKind.php +++ b/packages/PHPStanStaticTypeMapper/ValueObject/TypeKind.php @@ -1,7 +1,6 @@ isNullableType = $isNullableType; $this->hasIterable = $hasIterable; $this->hasArray = $hasArray; } - - public function isNullableType(): bool + public function isNullableType() : bool { return $this->isNullableType; } - - public function hasIterable(): bool + public function hasIterable() : bool { return $this->hasIterable; } - - public function hasArray(): bool + public function hasArray() : bool { return $this->hasArray; } diff --git a/packages/PhpAttribute/Printer/PhpAttributeGroupFactory.php b/packages/PhpAttribute/Printer/PhpAttributeGroupFactory.php index 5a84a885a42..69534776b52 100644 --- a/packages/PhpAttribute/Printer/PhpAttributeGroupFactory.php +++ b/packages/PhpAttribute/Printer/PhpAttributeGroupFactory.php @@ -1,7 +1,6 @@ getAttributeClass()); - $attribute = new Attribute($fullyQualified); - return new AttributeGroup([$attribute]); + $fullyQualified = new \PhpParser\Node\Name\FullyQualified($annotationToAttribute->getAttributeClass()); + $attribute = new \PhpParser\Node\Attribute($fullyQualified); + return new \PhpParser\Node\AttributeGroup([$attribute]); } - - public function create( - DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode, - AnnotationToAttribute $annotationToAttribute - ): AttributeGroup { - $fullyQualified = new FullyQualified($annotationToAttribute->getAttributeClass()); - + public function create(\Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode, \Rector\Php80\ValueObject\AnnotationToAttribute $annotationToAttribute) : \PhpParser\Node\AttributeGroup + { + $fullyQualified = new \PhpParser\Node\Name\FullyQualified($annotationToAttribute->getAttributeClass()); $values = $doctrineAnnotationTagValueNode->getValuesWithExplicitSilentAndWithoutQuotes(); - $args = $this->createArgsFromItems($values); - - $attribute = new Attribute($fullyQualified, $args); - return new AttributeGroup([$attribute]); + $attribute = new \PhpParser\Node\Attribute($fullyQualified, $args); + return new \PhpParser\Node\AttributeGroup([$attribute]); } - /** * @param mixed[] $items * @return Arg[] */ - private function createArgsFromItems(array $items, ?string $silentKey = null): array + private function createArgsFromItems(array $items, ?string $silentKey = null) : array { $args = []; - if ($silentKey !== null && isset($items[$silentKey])) { - $silentValue = BuilderHelpers::normalizeValue($items[$silentKey]); - $args[] = new Arg($silentValue); + $silentValue = \PhpParser\BuilderHelpers::normalizeValue($items[$silentKey]); + $args[] = new \PhpParser\Node\Arg($silentValue); unset($items[$silentKey]); } - foreach ($items as $key => $value) { $value = $this->normalizeNodeValue($value); - $value = BuilderHelpers::normalizeValue($value); - - $args[] = $this->isArrayArguments($items) - ? new Arg($value, false, false, [], new Identifier($key)) - : new Arg($value) - ; + $value = \PhpParser\BuilderHelpers::normalizeValue($value); + $args[] = $this->isArrayArguments($items) ? new \PhpParser\Node\Arg($value, \false, \false, [], new \PhpParser\Node\Identifier($key)) : new \PhpParser\Node\Arg($value); } - return $args; } - /** * @param mixed[] $items */ - private function isArrayArguments(array $items): bool + private function isArrayArguments(array $items) : bool { - foreach (array_keys($items) as $key) { - if (! is_int($key)) { - return true; + foreach (\array_keys($items) as $key) { + if (!\is_int($key)) { + return \true; } } - - return false; + return \false; } - /** * @param mixed $value * @return bool|float|int|string|array */ private function normalizeNodeValue($value) { - if ($value instanceof ConstExprIntegerNode) { + if ($value instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode) { return (int) $value->value; } - - if ($value instanceof ConstantFloatType) { + if ($value instanceof \PHPStan\Type\Constant\ConstantFloatType) { return $value->getValue(); } - - if ($value instanceof ConstantBooleanType) { + if ($value instanceof \PHPStan\Type\Constant\ConstantBooleanType) { return $value->getValue(); } - - if ($value instanceof ConstExprTrueNode) { - return true; + if ($value instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode) { + return \true; } - - if ($value instanceof ConstExprFalseNode) { - return false; + if ($value instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode) { + return \false; } - - if ($value instanceof CurlyListNode) { - return array_map(function ($node) { + if ($value instanceof \Rector\BetterPhpDocParser\ValueObject\PhpDoc\DoctrineAnnotation\CurlyListNode) { + return \array_map(function ($node) { return $this->normalizeNodeValue($node); }, $value->getValuesWithExplicitSilentAndWithoutQuotes()); } - - if ($value instanceof Node) { + if ($value instanceof \PHPStan\PhpDocParser\Ast\Node) { return (string) $value; } - return $value; } } diff --git a/packages/PostRector/Application/PostFileProcessor.php b/packages/PostRector/Application/PostFileProcessor.php index fb74ced53de..d7cfee0bd2e 100644 --- a/packages/PostRector/Application/PostFileProcessor.php +++ b/packages/PostRector/Application/PostFileProcessor.php @@ -1,7 +1,6 @@ postRectors = $this->sortByPriority($postRectors); $this->skipper = $skipper; $this->currentRectorProvider = $currentRectorProvider; $this->currentFileProvider = $currentFileProvider; } - /** * @param Stmt[] $nodes * @return Stmt[] */ - public function traverse(array $nodes): array + public function traverse(array $nodes) : array { foreach ($this->postRectors as $postRector) { if ($this->shouldSkipPostRector($postRector)) { continue; } - $this->currentRectorProvider->changeCurrentRector($postRector); - - $nodeTraverser = new NodeTraverser(); + $nodeTraverser = new \PhpParser\NodeTraverser(); $nodeTraverser->addVisitor($postRector); $nodes = $nodeTraverser->traverse($nodes); } - return $nodes; } - /** * @param PostRectorInterface[] $postRectors * @return PostRectorInterface[] */ - private function sortByPriority(array $postRectors): array + private function sortByPriority(array $postRectors) : array { $postRectorsByPriority = []; - foreach ($postRectors as $postRector) { if (isset($postRectorsByPriority[$postRector->getPriority()])) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $postRectorsByPriority[$postRector->getPriority()] = $postRector; } - - krsort($postRectorsByPriority); - + \krsort($postRectorsByPriority); return $postRectorsByPriority; } - - private function shouldSkipPostRector(PostRectorInterface $postRector): bool + private function shouldSkipPostRector(\Rector\PostRector\Contract\Rector\PostRectorInterface $postRector) : bool { $file = $this->currentFileProvider->getFile(); - if (! $file instanceof File) { - return false; + if (!$file instanceof \Rector\Core\ValueObject\Application\File) { + return \false; } - $smartFileInfo = $file->getSmartFileInfo(); return $this->skipper->shouldSkipElementAndFileInfo($postRector, $smartFileInfo); } diff --git a/packages/PostRector/Collector/NodesToAddCollector.php b/packages/PostRector/Collector/NodesToAddCollector.php index d4d70190ccf..8f33674885c 100644 --- a/packages/PostRector/Collector/NodesToAddCollector.php +++ b/packages/PostRector/Collector/NodesToAddCollector.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->rectorChangeCollector = $rectorChangeCollector; $this->betterStandardPrinter = $betterStandardPrinter; } - - public function isActive(): bool + public function isActive() : bool { return $this->nodesToAddAfter !== [] || $this->nodesToAddBefore !== []; } - - public function addNodeBeforeNode(Node $addedNode, Node $positionNode): void + public function addNodeBeforeNode(\PhpParser\Node $addedNode, \PhpParser\Node $positionNode) : void { if ($positionNode->getAttributes() === []) { - $message = sprintf('Switch arguments in "%s()" method', __METHOD__); - throw new ShouldNotHappenException($message); + $message = \sprintf('Switch arguments in "%s()" method', __METHOD__); + throw new \Rector\Core\Exception\ShouldNotHappenException($message); } - $position = $this->resolveNearestExpressionPosition($positionNode); $this->nodesToAddBefore[$position][] = $this->wrapToExpression($addedNode); - $this->rectorChangeCollector->notifyNodeFileInfo($positionNode); } - /** * @param Node[] $addedNodes */ - public function addNodesAfterNode(array $addedNodes, Node $positionNode): void + public function addNodesAfterNode(array $addedNodes, \PhpParser\Node $positionNode) : void { $position = $this->resolveNearestExpressionPosition($positionNode); foreach ($addedNodes as $addedNode) { // prevent fluent method weird indent - $addedNode->setAttribute(AttributeKey::ORIGINAL_NODE, null); + $addedNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); $this->nodesToAddAfter[$position][] = $this->wrapToExpression($addedNode); } - $this->rectorChangeCollector->notifyNodeFileInfo($positionNode); } - - public function addNodeAfterNode(Node $addedNode, Node $positionNode): void + public function addNodeAfterNode(\PhpParser\Node $addedNode, \PhpParser\Node $positionNode) : void { $position = $this->resolveNearestExpressionPosition($positionNode); $this->nodesToAddAfter[$position][] = $this->wrapToExpression($addedNode); - $this->rectorChangeCollector->notifyNodeFileInfo($positionNode); } - /** * @return Stmt[] */ - public function getNodesToAddAfterNode(Node $node): array + public function getNodesToAddAfterNode(\PhpParser\Node $node) : array { - $position = spl_object_hash($node); + $position = \spl_object_hash($node); return $this->nodesToAddAfter[$position] ?? []; } - /** * @return Stmt[] */ - public function getNodesToAddBeforeNode(Node $node): array + public function getNodesToAddBeforeNode(\PhpParser\Node $node) : array { - $position = spl_object_hash($node); + $position = \spl_object_hash($node); return $this->nodesToAddBefore[$position] ?? []; } - - public function clearNodesToAddAfter(Node $node): void + public function clearNodesToAddAfter(\PhpParser\Node $node) : void { - $objectHash = spl_object_hash($node); + $objectHash = \spl_object_hash($node); unset($this->nodesToAddAfter[$objectHash]); } - - public function clearNodesToAddBefore(Node $node): void + public function clearNodesToAddBefore(\PhpParser\Node $node) : void { - $objectHash = spl_object_hash($node); + $objectHash = \spl_object_hash($node); unset($this->nodesToAddBefore[$objectHash]); } - /** * @param Node[] $newNodes */ - public function addNodesBeforeNode(array $newNodes, Node $positionNode): void + public function addNodesBeforeNode(array $newNodes, \PhpParser\Node $positionNode) : void { foreach ($newNodes as $newNode) { $this->addNodeBeforeNode($newNode, $positionNode); } - $this->rectorChangeCollector->notifyNodeFileInfo($positionNode); } - - private function resolveNearestExpressionPosition(Node $node): string + private function resolveNearestExpressionPosition(\PhpParser\Node $node) : string { - if ($node instanceof Expression || $node instanceof Stmt) { - return spl_object_hash($node); + if ($node instanceof \PhpParser\Node\Stmt\Expression || $node instanceof \PhpParser\Node\Stmt) { + return \spl_object_hash($node); } - - $currentStmt = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); - if ($currentStmt instanceof Stmt) { - return spl_object_hash($currentStmt); + $currentStmt = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); + if ($currentStmt instanceof \PhpParser\Node\Stmt) { + return \spl_object_hash($currentStmt); } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Return_) { - return spl_object_hash($parent); + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Stmt\Return_) { + return \spl_object_hash($parent); } - - $foundNode = $this->betterNodeFinder->findParentTypes($node, [Expression::class, Stmt::class]); - - if (! $foundNode instanceof Stmt) { + $foundNode = $this->betterNodeFinder->findParentTypes($node, [\PhpParser\Node\Stmt\Expression::class, \PhpParser\Node\Stmt::class]); + if (!$foundNode instanceof \PhpParser\Node\Stmt) { $printedNode = $this->betterStandardPrinter->print($node); - $errorMessage = sprintf('Could not find parent Stmt of "%s" node', $printedNode); - throw new ShouldNotHappenException($errorMessage); + $errorMessage = \sprintf('Could not find parent Stmt of "%s" node', $printedNode); + throw new \Rector\Core\Exception\ShouldNotHappenException($errorMessage); } - - return spl_object_hash($foundNode); + return \spl_object_hash($foundNode); } - /** * @param Expr|Stmt $node */ - private function wrapToExpression(Node $node): Stmt + private function wrapToExpression(\PhpParser\Node $node) : \PhpParser\Node\Stmt { - return $node instanceof Stmt ? $node : new Expression($node); + return $node instanceof \PhpParser\Node\Stmt ? $node : new \PhpParser\Node\Stmt\Expression($node); } } diff --git a/packages/PostRector/Collector/NodesToRemoveCollector.php b/packages/PostRector/Collector/NodesToRemoveCollector.php index 09f9f777e59..ee1e518cfe5 100644 --- a/packages/PostRector/Collector/NodesToRemoveCollector.php +++ b/packages/PostRector/Collector/NodesToRemoveCollector.php @@ -1,7 +1,6 @@ affectedFilesCollector = $affectedFilesCollector; $this->breakingRemovalGuard = $breakingRemovalGuard; $this->betterNodeFinder = $betterNodeFinder; $this->nodeComparator = $nodeComparator; $this->currentFileProvider = $currentFileProvider; } - - public function addNodeToRemove(Node $node): void + public function addNodeToRemove(\PhpParser\Node $node) : void { /** Node|null $parentNode */ - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); if ($parentNode !== null && $this->isUsedInArg($node, $parentNode)) { return; } - // chain call: "->method()->another()" $this->ensureIsNotPartOfChainMethodCall($node); - - if (! $node instanceof Expression && $parentNode instanceof Expression) { + if (!$node instanceof \PhpParser\Node\Stmt\Expression && $parentNode instanceof \PhpParser\Node\Stmt\Expression) { // only expressions can be removed $node = $parentNode; } else { $this->breakingRemovalGuard->ensureNodeCanBeRemove($node); } - $file = $this->currentFileProvider->getFile(); - // /** @var SmartFileInfo|null $fileInfo */ if ($file !== null) { $this->affectedFilesCollector->addFile($file); } - /** @var Stmt $node */ $this->nodesToRemove[] = $node; } - - public function isNodeRemoved(Node $node): bool + public function isNodeRemoved(\PhpParser\Node $node) : bool { - return in_array($node, $this->nodesToRemove, true); + return \in_array($node, $this->nodesToRemove, \true); } - - public function isActive(): bool + public function isActive() : bool { return $this->getCount() > 0; } - - public function getCount(): int + public function getCount() : int { - return count($this->nodesToRemove); + return \count($this->nodesToRemove); } - /** * @return Node[] */ - public function getNodesToRemove(): array + public function getNodesToRemove() : array { return $this->nodesToRemove; } - - public function unset(int $key): void + public function unset(int $key) : void { unset($this->nodesToRemove[$key]); } - - private function isUsedInArg(Node $node, Node $parentNode): bool + private function isUsedInArg(\PhpParser\Node $node, \PhpParser\Node $parentNode) : bool { - if (! $node instanceof Param) { - return false; + if (!$node instanceof \PhpParser\Node\Param) { + return \false; } - - if (! $parentNode instanceof ClassMethod) { - return false; + if (!$parentNode instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - $paramVariable = $node->var; - if ($paramVariable instanceof Variable) { - return (bool) $this->betterNodeFinder->findFirst((array) $parentNode->stmts, function (Node $variable) use ( - $paramVariable - ): bool { - if (! $this->nodeComparator->areNodesEqual($variable, $paramVariable)) { - return false; + if ($paramVariable instanceof \PhpParser\Node\Expr\Variable) { + return (bool) $this->betterNodeFinder->findFirst((array) $parentNode->stmts, function (\PhpParser\Node $variable) use($paramVariable) : bool { + if (!$this->nodeComparator->areNodesEqual($variable, $paramVariable)) { + return \false; } - - $hasArgParent = (bool) $this->betterNodeFinder->findParentType($variable, Arg::class); - if (! $hasArgParent) { - return false; + $hasArgParent = (bool) $this->betterNodeFinder->findParentType($variable, \PhpParser\Node\Arg::class); + if (!$hasArgParent) { + return \false; } - - return ! (bool) $this->betterNodeFinder->findParentType($variable, StaticCall::class); + return !(bool) $this->betterNodeFinder->findParentType($variable, \PhpParser\Node\Expr\StaticCall::class); }); } - - return false; + return \false; } - - private function ensureIsNotPartOfChainMethodCall(Node $node): void + private function ensureIsNotPartOfChainMethodCall(\PhpParser\Node $node) : void { - if (! $node instanceof MethodCall) { + if (!$node instanceof \PhpParser\Node\Expr\MethodCall) { return; } - - if (! $node->var instanceof MethodCall) { + if (!$node->var instanceof \PhpParser\Node\Expr\MethodCall) { return; } - - throw new ShouldNotHappenException( - 'Chain method calls cannot be removed this way. It would remove the whole tree of calls. Remove them manually by creating new parent node with no following method.' - ); + throw new \Rector\Core\Exception\ShouldNotHappenException('Chain method calls cannot be removed this way. It would remove the whole tree of calls. Remove them manually by creating new parent node with no following method.'); } } diff --git a/packages/PostRector/Collector/NodesToReplaceCollector.php b/packages/PostRector/Collector/NodesToReplaceCollector.php index e653089b0ad..4d554b76fb4 100644 --- a/packages/PostRector/Collector/NodesToReplaceCollector.php +++ b/packages/PostRector/Collector/NodesToReplaceCollector.php @@ -1,33 +1,28 @@ nodesToReplace[] = [$node, $replaceWith]; } - - public function isActive(): bool + public function isActive() : bool { return $this->nodesToReplace !== []; } - /** * @return Node[][] */ - public function getNodes(): array + public function getNodes() : array { return $this->nodesToReplace; } diff --git a/packages/PostRector/Collector/PropertyToAddCollector.php b/packages/PostRector/Collector/PropertyToAddCollector.php index 70e7f9fd4e8..badc1fcc73d 100644 --- a/packages/PostRector/Collector/PropertyToAddCollector.php +++ b/packages/PostRector/Collector/PropertyToAddCollector.php @@ -1,7 +1,6 @@ > */ private $constantsByClass = []; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var array */ private $propertiesByClass = []; - /** * @var array> */ private $propertiesWithoutConstructorByClass = []; - /** * @var RectorChangeCollector */ private $rectorChangeCollector; - - public function __construct(NodeNameResolver $nodeNameResolver, RectorChangeCollector $rectorChangeCollector) + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\ChangesReporting\Collector\RectorChangeCollector $rectorChangeCollector) { $this->nodeNameResolver = $nodeNameResolver; $this->rectorChangeCollector = $rectorChangeCollector; } - - public function isActive(): bool + public function isActive() : bool { if ($this->propertiesByClass !== []) { - return true; + return \true; } - if ($this->propertiesWithoutConstructorByClass !== []) { - return true; + return \true; } - return $this->constantsByClass !== []; } - - public function addPropertyToClass( - Class_ $class, - string $propertyName, - ?Type $propertyType, - int $propertyFlags - ): void { - $uniqueHash = spl_object_hash($class); - $this->propertiesByClass[$uniqueHash][] = new PropertyMetadata($propertyName, $propertyType, $propertyFlags); + public function addPropertyToClass(\PhpParser\Node\Stmt\Class_ $class, string $propertyName, ?\PHPStan\Type\Type $propertyType, int $propertyFlags) : void + { + $uniqueHash = \spl_object_hash($class); + $this->propertiesByClass[$uniqueHash][] = new \Rector\PostRector\ValueObject\PropertyMetadata($propertyName, $propertyType, $propertyFlags); } - - public function addConstantToClass(Class_ $class, ClassConst $classConst): void + public function addConstantToClass(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt\ClassConst $classConst) : void { $constantName = $this->nodeNameResolver->getName($classConst); - $this->constantsByClass[spl_object_hash($class)][$constantName] = $classConst; - + $this->constantsByClass[\spl_object_hash($class)][$constantName] = $classConst; $this->rectorChangeCollector->notifyNodeFileInfo($class); } - - public function addPropertyWithoutConstructorToClass( - string $propertyName, - ?Type $propertyType, - Class_ $class - ): void { - $this->propertiesWithoutConstructorByClass[spl_object_hash($class)][$propertyName] = $propertyType; - + public function addPropertyWithoutConstructorToClass(string $propertyName, ?\PHPStan\Type\Type $propertyType, \PhpParser\Node\Stmt\Class_ $class) : void + { + $this->propertiesWithoutConstructorByClass[\spl_object_hash($class)][$propertyName] = $propertyType; $this->rectorChangeCollector->notifyNodeFileInfo($class); } - /** * @return ClassConst[] */ - public function getConstantsByClass(Class_ $class): array + public function getConstantsByClass(\PhpParser\Node\Stmt\Class_ $class) : array { - $classHash = spl_object_hash($class); + $classHash = \spl_object_hash($class); return $this->constantsByClass[$classHash] ?? []; } - /** * @return PropertyMetadata[] */ - public function getPropertiesByClass(Class_ $class): array + public function getPropertiesByClass(\PhpParser\Node\Stmt\Class_ $class) : array { - $classHash = spl_object_hash($class); + $classHash = \spl_object_hash($class); return $this->propertiesByClass[$classHash] ?? []; } - /** * @return array */ - public function getPropertiesWithoutConstructorByClass(Class_ $class): array + public function getPropertiesWithoutConstructorByClass(\PhpParser\Node\Stmt\Class_ $class) : array { - $classHash = spl_object_hash($class); + $classHash = \spl_object_hash($class); return $this->propertiesWithoutConstructorByClass[$classHash] ?? []; } } diff --git a/packages/PostRector/Collector/UseNodesToAddCollector.php b/packages/PostRector/Collector/UseNodesToAddCollector.php index fec64200037..b658331a9c4 100644 --- a/packages/PostRector/Collector/UseNodesToAddCollector.php +++ b/packages/PostRector/Collector/UseNodesToAddCollector.php @@ -1,7 +1,6 @@ currentFileProvider = $currentFileProvider; } - - public function isActive(): bool + public function isActive() : bool { return $this->useImportTypesInFilePath !== [] || $this->functionUseImportTypesInFilePath !== []; } - /** * @param FullyQualifiedObjectType|AliasedObjectType $objectType */ - public function addUseImport(Node $positionNode, ObjectType $objectType): void + public function addUseImport(\PhpParser\Node $positionNode, \PHPStan\Type\ObjectType $objectType) : void { $file = $this->currentFileProvider->getFile(); $smartFileInfo = $file->getSmartFileInfo(); - $this->useImportTypesInFilePath[$smartFileInfo->getRealPath()][] = $objectType; } - - public function addFunctionUseImport(Node $node, FullyQualifiedObjectType $fullyQualifiedObjectType): void + public function addFunctionUseImport(\PhpParser\Node $node, \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType) : void { $file = $this->currentFileProvider->getFile(); $smartFileInfo = $file->getSmartFileInfo(); - $this->functionUseImportTypesInFilePath[$smartFileInfo->getRealPath()][] = $fullyQualifiedObjectType; } - - public function removeShortUse(Node $node, string $shortUse): void + public function removeShortUse(\PhpParser\Node $node, string $shortUse) : void { $file = $this->currentFileProvider->getFile(); - if (! $file instanceof File) { + if (!$file instanceof \Rector\Core\ValueObject\Application\File) { return; } - $smartFileInfo = $file->getSmartFileInfo(); - $this->removedShortUsesInFilePath[$smartFileInfo->getRealPath()][] = $shortUse; } - - public function clear(SmartFileInfo $smartFileInfo): void + public function clear(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : void { // clear applied imports, so isActive() doesn't return any false positives unset($this->useImportTypesInFilePath[$smartFileInfo->getRealPath()], $this->functionUseImportTypesInFilePath[$smartFileInfo->getRealPath()]); } - /** * @return AliasedObjectType[]|FullyQualifiedObjectType[] */ - public function getUseImportTypesByNode(Node $node): array + public function getUseImportTypesByNode(\PhpParser\Node $node) : array { $filePath = $this->getRealPathFromNode(); - $objectTypes = $this->useImportTypesInFilePath[$filePath] ?? []; - /** @var Use_[] $useNodes */ - $useNodes = (array) $node->getAttribute(AttributeKey::USE_NODES); + $useNodes = (array) $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::USE_NODES); foreach ($useNodes as $useNode) { foreach ($useNode->uses as $useUse) { if ($useUse->alias === null) { - $objectTypes[] = new FullyQualifiedObjectType((string) $useUse->name); + $objectTypes[] = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType((string) $useUse->name); } else { - $objectTypes[] = new AliasedObjectType($useUse->alias->toString(), (string) $useUse->name); + $objectTypes[] = new \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType($useUse->alias->toString(), (string) $useUse->name); } } } - return $objectTypes; } - - public function hasImport(Node $node, FullyQualifiedObjectType $fullyQualifiedObjectType): bool + public function hasImport(\PhpParser\Node $node, \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType) : bool { $useImports = $this->getUseImportTypesByNode($node); - foreach ($useImports as $useImport) { if ($useImport->equals($fullyQualifiedObjectType)) { - return true; + return \true; } } - - return false; + return \false; } - - public function isShortImported(Node $node, FullyQualifiedObjectType $fullyQualifiedObjectType): bool + public function isShortImported(\PhpParser\Node $node, \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType) : bool { $filePath = $this->getRealPathFromNode(); if ($filePath === null) { - return false; + return \false; } - $shortName = $fullyQualifiedObjectType->getShortName(); - if ($this->isShortClassImported($filePath, $shortName)) { - return true; + return \true; } - $fileFunctionUseImportTypes = $this->functionUseImportTypesInFilePath[$filePath] ?? []; foreach ($fileFunctionUseImportTypes as $fileFunctionUseImportType) { if ($fileFunctionUseImportType->getShortName() === $fullyQualifiedObjectType->getShortName()) { - return true; + return \true; } } - - return false; + return \false; } - - public function isImportShortable(Node $node, FullyQualifiedObjectType $fullyQualifiedObjectType): bool + public function isImportShortable(\PhpParser\Node $node, \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType) : bool { $filePath = $this->getRealPathFromNode(); - $fileUseImportTypes = $this->useImportTypesInFilePath[$filePath] ?? []; - foreach ($fileUseImportTypes as $fileUseImportType) { if ($fullyQualifiedObjectType->equals($fileUseImportType)) { - return true; + return \true; } } - $functionImports = $this->functionUseImportTypesInFilePath[$filePath] ?? []; foreach ($functionImports as $functionImport) { if ($fullyQualifiedObjectType->equals($functionImport)) { - return true; + return \true; } } - - return false; + return \false; } - /** * @return AliasedObjectType[]|FullyQualifiedObjectType[] */ - public function getObjectImportsByFileInfo(SmartFileInfo $smartFileInfo): array + public function getObjectImportsByFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : array { return $this->useImportTypesInFilePath[$smartFileInfo->getRealPath()] ?? []; } - /** * @return FullyQualifiedObjectType[] */ - public function getFunctionImportsByFileInfo(SmartFileInfo $smartFileInfo): array + public function getFunctionImportsByFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : array { return $this->functionUseImportTypesInFilePath[$smartFileInfo->getRealPath()] ?? []; } - /** * @return string[] */ - public function getShortUsesByFileInfo(SmartFileInfo $smartFileInfo): array + public function getShortUsesByFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : array { return $this->removedShortUsesInFilePath[$smartFileInfo->getRealPath()] ?? []; } - - private function getRealPathFromNode(): ?string + private function getRealPathFromNode() : ?string { $file = $this->currentFileProvider->getFile(); - if (! $file instanceof File) { + if (!$file instanceof \Rector\Core\ValueObject\Application\File) { return null; } - $smartFileInfo = $file->getSmartFileInfo(); - return $smartFileInfo->getRealPath(); } - - private function isShortClassImported(string $filePath, string $shortName): bool + private function isShortClassImported(string $filePath, string $shortName) : bool { $fileUseImports = $this->useImportTypesInFilePath[$filePath] ?? []; - foreach ($fileUseImports as $fileUseImport) { if ($fileUseImport->getShortName() === $shortName) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/PostRector/Contract/Collector/NodeCollectorInterface.php b/packages/PostRector/Contract/Collector/NodeCollectorInterface.php index e19fd4c4a1f..abf9703fd60 100644 --- a/packages/PostRector/Contract/Collector/NodeCollectorInterface.php +++ b/packages/PostRector/Contract/Collector/NodeCollectorInterface.php @@ -1,10 +1,9 @@ nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; $this->propertyToAddCollector = $propertyToAddCollector; $this->rectorChangeCollector = $rectorChangeCollector; $this->propertyNaming = $propertyNaming; } - - public function addPropertyToCollector(Property $property): void + public function addPropertyToCollector(\PhpParser\Node\Stmt\Property $property) : void { - $classNode = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classNode instanceof Class_) { + $classNode = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classNode instanceof \PhpParser\Node\Stmt\Class_) { return; } - $propertyType = $this->nodeTypeResolver->resolve($property); - // use first type - hard assumption @todo improve - if ($propertyType instanceof UnionType) { + if ($propertyType instanceof \PHPStan\Type\UnionType) { $propertyType = $propertyType->getTypes()[0]; } - $propertyName = $this->nodeNameResolver->getName($property); $this->addConstructorDependencyToClass($classNode, $propertyType, $propertyName, $property->flags); } - - public function addConstructorDependencyToClass( - Class_ $class, - Type $propertyType, - string $propertyName, - int $propertyFlags = 0 - ): void { + public function addConstructorDependencyToClass(\PhpParser\Node\Stmt\Class_ $class, \PHPStan\Type\Type $propertyType, string $propertyName, int $propertyFlags = 0) : void + { $this->propertyToAddCollector->addPropertyToClass($class, $propertyName, $propertyType, $propertyFlags); $this->rectorChangeCollector->notifyNodeFileInfo($class); } - - public function addServiceConstructorDependencyToClass(Class_ $class, ObjectType $objectType): void + public function addServiceConstructorDependencyToClass(\PhpParser\Node\Stmt\Class_ $class, \PHPStan\Type\ObjectType $objectType) : void { $propertyName = $this->propertyNaming->fqnToVariableName($objectType); $this->addConstructorDependencyToClass($class, $objectType, $propertyName); diff --git a/packages/PostRector/NodeAnalyzer/NetteInjectDetector.php b/packages/PostRector/NodeAnalyzer/NetteInjectDetector.php index 9e5d4b6c333..4b1a07af578 100644 --- a/packages/PostRector/NodeAnalyzer/NetteInjectDetector.php +++ b/packages/PostRector/NodeAnalyzer/NetteInjectDetector.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->reflectionProvider = $reflectionProvider; } - - public function isNetteInjectPreferred(Class_ $class): bool + public function isNetteInjectPreferred(\PhpParser\Node\Stmt\Class_ $class) : bool { if ($this->isInjectPropertyAlreadyInTheClass($class)) { - return true; + return \true; } - return $this->hasParentClassConstructor($class); } - - private function isInjectPropertyAlreadyInTheClass(Class_ $class): bool + private function isInjectPropertyAlreadyInTheClass(\PhpParser\Node\Stmt\Class_ $class) : bool { foreach ($class->getProperties() as $property) { - if (! $property->isPublic()) { + if (!$property->isPublic()) { continue; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); if ($phpDocInfo->hasByName('inject')) { - return true; + return \true; } } - - return false; + return \false; } - - private function hasParentClassConstructor(Class_ $class): bool + private function hasParentClassConstructor(\PhpParser\Node\Stmt\Class_ $class) : bool { $className = $this->nodeNameResolver->getName($class); if ($className === null) { - return false; + return \false; } - - if (! $this->reflectionProvider->hasClass($className)) { - return false; + if (!$this->reflectionProvider->hasClass($className)) { + return \false; } - $classReflection = $this->reflectionProvider->getClass($className); - if (! $classReflection->isSubclassOf('Nette\Application\IPresenter')) { - return false; + if (!$classReflection->isSubclassOf('Nette\\Application\\IPresenter')) { + return \false; } - // has no parent class if ($class->extends === null) { - return false; + return \false; } - $parentClass = $this->nodeNameResolver->getName($class->extends); // is not the nette class - we don't care about that - if ($parentClass === 'Nette\Application\UI\Presenter') { - return false; + if ($parentClass === 'Nette\\Application\\UI\\Presenter') { + return \false; } - // prefer local constructor $classReflection = $this->reflectionProvider->getClass($className); - - if ($classReflection->hasMethod(MethodName::CONSTRUCT)) { + if ($classReflection->hasMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT)) { $constructorReflectionMethod = $classReflection->getConstructor(); $declaringClass = $constructorReflectionMethod->getDeclaringClass(); - // be sure its local constructor if ($declaringClass->getName() === $className) { - return false; + return \false; } } - $classReflection = $this->reflectionProvider->getClass($parentClass); - return $classReflection->hasMethod(MethodName::CONSTRUCT); + return $classReflection->hasMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); } } diff --git a/packages/PostRector/Rector/AbstractPostRector.php b/packages/PostRector/Rector/AbstractPostRector.php index 6890062e6f0..43524dc88a2 100644 --- a/packages/PostRector/Rector/AbstractPostRector.php +++ b/packages/PostRector/Rector/AbstractPostRector.php @@ -1,12 +1,10 @@ renamedClassesCollector = $renamedClassesCollector; $this->classRenamer = $classRenamer; } - - public function getPriority(): int + public function getPriority() : int { // must be run before name importing, so new names are imported return 650; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PhpParser\Node $node) : ?\PhpParser\Node { $oldToNewClasses = $this->renamedClassesCollector->getOldToNewClasses(); if ($oldToNewClasses === []) { return $node; } - return $this->classRenamer->renameNode($node, $oldToNewClasses); } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Rename references for classes that were renamed during Rector run', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Rename references for classes that were renamed during Rector run', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' function (OriginalClass $someClass) { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' function (RenamedClass $someClass) { } CODE_SAMPLE - ), - ]); +)]); } } diff --git a/packages/PostRector/Rector/NameImportingPostRector.php b/packages/PostRector/Rector/NameImportingPostRector.php index 032dc0ced5c..cdc5d1bbd3a 100644 --- a/packages/PostRector/Rector/NameImportingPostRector.php +++ b/packages/PostRector/Rector/NameImportingPostRector.php @@ -1,7 +1,6 @@ parameterProvider = $parameterProvider; $this->nameImporter = $nameImporter; $this->docBlockNameImporter = $docBlockNameImporter; @@ -71,40 +55,31 @@ final class NameImportingPostRector extends AbstractPostRector $this->nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PhpParser\Node $node) : ?\PhpParser\Node { - $autoImportNames = $this->parameterProvider->provideParameter(Option::AUTO_IMPORT_NAMES); - if (! $autoImportNames) { + $autoImportNames = $this->parameterProvider->provideParameter(\Rector\Core\Configuration\Option::AUTO_IMPORT_NAMES); + if (!$autoImportNames) { return null; } - - if ($node instanceof Name) { + if ($node instanceof \PhpParser\Node\Name) { return $this->processNodeName($node); } - - $importDocBlocks = (bool) $this->parameterProvider->provideParameter(Option::IMPORT_DOC_BLOCKS); - if (! $importDocBlocks) { + $importDocBlocks = (bool) $this->parameterProvider->provideParameter(\Rector\Core\Configuration\Option::IMPORT_DOC_BLOCKS); + if (!$importDocBlocks) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); $this->docBlockNameImporter->importNames($phpDocInfo->getPhpDocNode(), $node); - return $node; } - - public function getPriority(): int + public function getPriority() : int { // this must run after NodeRemovingPostRector, sine renamed use imports can block next import return 600; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Imports fully qualified names', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Imports fully qualified names', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run(App\AnotherClass $anotherClass) @@ -112,8 +87,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use App\AnotherClass; class SomeClass @@ -123,34 +97,26 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - - private function processNodeName(Name $name): ?Node + private function processNodeName(\PhpParser\Node\Name $name) : ?\PhpParser\Node { if ($name->isSpecialClassName()) { return $name; } - $importName = $this->nodeNameResolver->getName($name); - - if (! is_callable($importName)) { + if (!\is_callable($importName)) { return $this->nameImporter->importName($name); } - - if (substr_count($name->toCodeString(), '\\') <= 1) { + if (\substr_count($name->toCodeString(), '\\') <= 1) { return $this->nameImporter->importName($name); } - - if (! $this->classNameImportSkipper->isFoundInUse($name)) { + if (!$this->classNameImportSkipper->isFoundInUse($name)) { return $this->nameImporter->importName($name); } - - if ($this->reflectionProvider->hasFunction(new Name($name->getLast()), null)) { + if ($this->reflectionProvider->hasFunction(new \PhpParser\Node\Name($name->getLast()), null)) { return $this->nameImporter->importName($name); } - return null; } } diff --git a/packages/PostRector/Rector/NodeAddingPostRector.php b/packages/PostRector/Rector/NodeAddingPostRector.php index 7bd1b99e329..f2709c967c2 100644 --- a/packages/PostRector/Rector/NodeAddingPostRector.php +++ b/packages/PostRector/Rector/NodeAddingPostRector.php @@ -1,14 +1,12 @@ someCall(); * - $value = this->someNewCall(); // added expression */ -final class NodeAddingPostRector extends AbstractPostRector +final class NodeAddingPostRector extends \Rector\PostRector\Rector\AbstractPostRector { /** * @var NodesToAddCollector */ private $nodesToAddCollector; - - public function __construct(NodesToAddCollector $nodesToAddCollector) + public function __construct(\Rector\PostRector\Collector\NodesToAddCollector $nodesToAddCollector) { $this->nodesToAddCollector = $nodesToAddCollector; } - - public function getPriority(): int + public function getPriority() : int { return 1000; } - /** * @return array|Node */ - public function leaveNode(Node $node) + public function leaveNode(\PhpParser\Node $node) { $newNodes = [$node]; - $nodesToAddAfter = $this->nodesToAddCollector->getNodesToAddAfterNode($node); if ($nodesToAddAfter !== []) { $this->nodesToAddCollector->clearNodesToAddAfter($node); - $newNodes = array_merge($newNodes, $nodesToAddAfter); + $newNodes = \array_merge($newNodes, $nodesToAddAfter); } - $nodesToAddBefore = $this->nodesToAddCollector->getNodesToAddBeforeNode($node); if ($nodesToAddBefore !== []) { $this->nodesToAddCollector->clearNodesToAddBefore($node); - $newNodes = array_merge($nodesToAddBefore, $newNodes); + $newNodes = \array_merge($nodesToAddBefore, $newNodes); } - if ($newNodes === [$node]) { return $node; } - return $newNodes; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Add nodes on weird positions', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add nodes on weird positions', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -78,8 +64,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -90,7 +75,6 @@ class SomeClass } } CODE_SAMPLE - ), ] - ); +)]); } } diff --git a/packages/PostRector/Rector/NodeRemovingPostRector.php b/packages/PostRector/Rector/NodeRemovingPostRector.php index 8b7939f39e7..04b811e1a20 100644 --- a/packages/PostRector/Rector/NodeRemovingPostRector.php +++ b/packages/PostRector/Rector/NodeRemovingPostRector.php @@ -1,7 +1,6 @@ nodesToRemoveCollector = $nodesToRemoveCollector; $this->nodeFactory = $nodeFactory; $this->nodeNameResolver = $nodeNameResolver; } - - public function getPriority(): int + public function getPriority() : int { return 800; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->nodesToRemoveCollector->isActive()) { + if (!$this->nodesToRemoveCollector->isActive()) { return null; } - // special case for fluent methods foreach ($this->nodesToRemoveCollector->getNodesToRemove() as $key => $nodeToRemove) { - if (! $node instanceof MethodCall) { + if (!$node instanceof \PhpParser\Node\Expr\MethodCall) { continue; } - - if (! $nodeToRemove instanceof MethodCall) { + if (!$nodeToRemove instanceof \PhpParser\Node\Expr\MethodCall) { continue; } - // replace chain method call by non-chain method call - if (! $this->isChainMethodCallNodeToBeRemoved($node, $nodeToRemove)) { + if (!$this->isChainMethodCallNodeToBeRemoved($node, $nodeToRemove)) { continue; } - $this->nodesToRemoveCollector->unset($key); - $methodName = $this->nodeNameResolver->getName($node->name); - /** @var MethodCall $nestedMethodCall */ $nestedMethodCall = $node->var; - /** @var string $methodName */ return $this->nodeFactory->createMethodCall($nestedMethodCall->var, $methodName, $node->args); } - - if (! $node instanceof BinaryOp) { + if (!$node instanceof \PhpParser\Node\Expr\BinaryOp) { return null; } - return $this->removePartOfBinaryOp($node); } - /** * @return int|Node */ - public function leaveNode(Node $node) + public function leaveNode(\PhpParser\Node $node) { foreach ($this->nodesToRemoveCollector->getNodesToRemove() as $key => $nodeToRemove) { - $nodeToRemoveParent = $nodeToRemove->getAttribute(AttributeKey::PARENT_NODE); - if ($nodeToRemoveParent instanceof BinaryOp) { + $nodeToRemoveParent = $nodeToRemove->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($nodeToRemoveParent instanceof \PhpParser\Node\Expr\BinaryOp) { continue; } - if ($node === $nodeToRemove) { $this->nodesToRemoveCollector->unset($key); - - return NodeTraverser::REMOVE_NODE; + return \PhpParser\NodeTraverser::REMOVE_NODE; } } - return $node; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove nodes from weird positions', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove nodes from weird positions', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -124,8 +96,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -134,47 +105,37 @@ class SomeClass } } CODE_SAMPLE - ), ] - ); +)]); } - - private function isChainMethodCallNodeToBeRemoved( - MethodCall $mainMethodCall, - MethodCall $toBeRemovedMethodCall - ): bool { - if (! $mainMethodCall->var instanceof MethodCall) { - return false; + private function isChainMethodCallNodeToBeRemoved(\PhpParser\Node\Expr\MethodCall $mainMethodCall, \PhpParser\Node\Expr\MethodCall $toBeRemovedMethodCall) : bool + { + if (!$mainMethodCall->var instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } if ($toBeRemovedMethodCall !== $mainMethodCall->var) { - return false; + return \false; } - $methodName = $this->nodeNameResolver->getName($mainMethodCall->name); - return $methodName !== null; } - - private function removePartOfBinaryOp(BinaryOp $binaryOp): ?Node + private function removePartOfBinaryOp(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\PhpParser\Node { // handle left/right binary remove, e.g. "true && false" → remove false → "true" foreach ($this->nodesToRemoveCollector->getNodesToRemove() as $key => $nodeToRemove) { // remove node - $nodeToRemoveParentNode = $nodeToRemove->getAttribute(AttributeKey::PARENT_NODE); - if (! $nodeToRemoveParentNode instanceof BinaryOp) { + $nodeToRemoveParentNode = $nodeToRemove->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$nodeToRemoveParentNode instanceof \PhpParser\Node\Expr\BinaryOp) { continue; } - if ($binaryOp->left === $nodeToRemove) { $this->nodesToRemoveCollector->unset($key); return $binaryOp->right; } - if ($binaryOp->right === $nodeToRemove) { $this->nodesToRemoveCollector->unset($key); return $binaryOp->left; } } - return null; } } diff --git a/packages/PostRector/Rector/NodeToReplacePostRector.php b/packages/PostRector/Rector/NodeToReplacePostRector.php index 8090ea0a84f..fa59ca3a42f 100644 --- a/packages/PostRector/Rector/NodeToReplacePostRector.php +++ b/packages/PostRector/Rector/NodeToReplacePostRector.php @@ -1,49 +1,38 @@ nodesToReplaceCollector = $nodesToReplaceCollector; } - - public function getPriority(): int + public function getPriority() : int { return 1100; } - - public function leaveNode(Node $node): ?Node + public function leaveNode(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->nodesToReplaceCollector->getNodes() as [$nodeToFind, $replacement]) { if ($node === $nodeToFind) { return $replacement; } } - return null; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Replaces nodes on weird positions', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces nodes on weird positions', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -52,8 +41,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -62,7 +50,6 @@ class SomeClass } } CODE_SAMPLE - ), ] - ); +)]); } } diff --git a/packages/PostRector/Rector/PropertyAddingPostRector.php b/packages/PostRector/Rector/PropertyAddingPostRector.php index 9c178d4d1ab..9b9d5bdbc73 100644 --- a/packages/PostRector/Rector/PropertyAddingPostRector.php +++ b/packages/PostRector/Rector/PropertyAddingPostRector.php @@ -1,7 +1,6 @@ classDependencyManipulator = $classDependencyManipulator; $this->classInsertManipulator = $classInsertManipulator; $this->propertyToAddCollector = $propertyToAddCollector; $this->netteInjectDetector = $netteInjectDetector; $this->classAnalyzer = $classAnalyzer; } - - public function getPriority(): int + public function getPriority() : int { return 900; } - - public function enterNode(Node $node): ?Node + public function enterNode(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node instanceof Class_) { + if (!$node instanceof \PhpParser\Node\Stmt\Class_) { return null; } if ($this->classAnalyzer->isAnonymousClass($node)) { @@ -74,17 +60,11 @@ final class PropertyAddingPostRector extends AbstractPostRector $this->addConstants($node); $this->addProperties($node); $this->addPropertiesWithoutConstructor($node); - return $node; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Add dependency properties', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add dependency properties', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -93,8 +73,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { private $value; @@ -104,40 +83,30 @@ class SomeClass } } CODE_SAMPLE - ), ] - ); +)]); } - - private function addConstants(Class_ $class): void + private function addConstants(\PhpParser\Node\Stmt\Class_ $class) : void { $constants = $this->propertyToAddCollector->getConstantsByClass($class); - foreach ($constants as $constantName => $nodeConst) { $this->classInsertManipulator->addConstantToClass($class, $constantName, $nodeConst); } } - - private function addProperties(Class_ $class): void + private function addProperties(\PhpParser\Node\Stmt\Class_ $class) : void { $propertiesMetadatas = $this->propertyToAddCollector->getPropertiesByClass($class); - $isNetteInjectPreferred = $this->netteInjectDetector->isNetteInjectPreferred($class); - foreach ($propertiesMetadatas as $propertyMetadata) { - if (! $isNetteInjectPreferred) { + if (!$isNetteInjectPreferred) { $this->classDependencyManipulator->addConstructorDependency($class, $propertyMetadata); } else { $this->classDependencyManipulator->addInjectProperty($class, $propertyMetadata); } } } - - private function addPropertiesWithoutConstructor(Class_ $class): void + private function addPropertiesWithoutConstructor(\PhpParser\Node\Stmt\Class_ $class) : void { - $propertiesWithoutConstructor = $this->propertyToAddCollector->getPropertiesWithoutConstructorByClass( - $class - ); - + $propertiesWithoutConstructor = $this->propertyToAddCollector->getPropertiesWithoutConstructorByClass($class); foreach ($propertiesWithoutConstructor as $propertyName => $propertyType) { $this->classInsertManipulator->addPropertyToClass($class, $propertyName, $propertyType); } diff --git a/packages/PostRector/Rector/UseAddingPostRector.php b/packages/PostRector/Rector/UseAddingPostRector.php index 78d6b890340..32c24aaf927 100644 --- a/packages/PostRector/Rector/UseAddingPostRector.php +++ b/packages/PostRector/Rector/UseAddingPostRector.php @@ -1,10 +1,9 @@ useImportsAdder = $useImportsAdder; $this->betterNodeFinder = $betterNodeFinder; $this->useImportsRemover = $useImportsRemover; @@ -65,73 +51,56 @@ final class UseAddingPostRector extends AbstractPostRector $this->useNodesToAddCollector = $useNodesToAddCollector; $this->currentFileProvider = $currentFileProvider; } - /** * @param Stmt[] $nodes * @return Stmt[] */ - public function beforeTraverse(array $nodes): array + public function beforeTraverse(array $nodes) : ?array { // no nodes → just return if ($nodes === []) { return $nodes; } - $file = $this->currentFileProvider->getFile(); $smartFileInfo = $file->getSmartFileInfo(); - $useImportTypes = $this->useNodesToAddCollector->getObjectImportsByFileInfo($smartFileInfo); $functionUseImportTypes = $this->useNodesToAddCollector->getFunctionImportsByFileInfo($smartFileInfo); $removedShortUses = $this->useNodesToAddCollector->getShortUsesByFileInfo($smartFileInfo); - // nothing to import or remove if ($useImportTypes === [] && $functionUseImportTypes === [] && $removedShortUses === []) { return $nodes; } - /** @var FullyQualifiedObjectType[] $useImportTypes */ $useImportTypes = $this->typeFactory->uniquateTypes($useImportTypes); - $this->useNodesToAddCollector->clear($smartFileInfo); - // A. has namespace? add under it - $namespace = $this->betterNodeFinder->findFirstInstanceOf($nodes, Namespace_::class); - if ($namespace instanceof Namespace_) { + $namespace = $this->betterNodeFinder->findFirstInstanceOf($nodes, \PhpParser\Node\Stmt\Namespace_::class); + if ($namespace instanceof \PhpParser\Node\Stmt\Namespace_) { // first clean $this->useImportsRemover->removeImportsFromNamespace($namespace, $removedShortUses); // then add, to prevent adding + removing false positive of same short use $this->useImportsAdder->addImportsToNamespace($namespace, $useImportTypes, $functionUseImportTypes); - return $nodes; } - $firstNode = $nodes[0]; - if ($firstNode instanceof FileWithoutNamespace) { + if ($firstNode instanceof \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace) { $nodes = $firstNode->stmts; } - // B. no namespace? add in the top // first clean $nodes = $this->useImportsRemover->removeImportsFromStmts($nodes, $removedShortUses); $useImportTypes = $this->filterOutNonNamespacedNames($useImportTypes); // then add, to prevent adding + removing false positive of same short use - return $this->useImportsAdder->addImportsToStmts($nodes, $useImportTypes, $functionUseImportTypes); } - - public function getPriority(): int + public function getPriority() : int { // must be after name importing return 500; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Add unique use imports collected during Rector run', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add unique use imports collected during Rector run', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run(AnotherClass $anotherClass) @@ -139,8 +108,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use App\AnotherClass; class SomeClass @@ -150,27 +118,22 @@ class SomeClass } } CODE_SAMPLE - ), ] - ); +)]); } - /** * Prevents * @param FullyQualifiedObjectType[] $useImportTypes * @return FullyQualifiedObjectType[] */ - private function filterOutNonNamespacedNames(array $useImportTypes): array + private function filterOutNonNamespacedNames(array $useImportTypes) : array { $namespacedUseImportTypes = []; - foreach ($useImportTypes as $useImportType) { - if (! Strings::contains($useImportType->getClassName(), '\\')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($useImportType->getClassName(), '\\')) { continue; } - $namespacedUseImportTypes[] = $useImportType; } - return $namespacedUseImportTypes; } } diff --git a/packages/PostRector/ValueObject/PropertyMetadata.php b/packages/PostRector/ValueObject/PropertyMetadata.php index b3d42592c2c..98615178d50 100644 --- a/packages/PostRector/ValueObject/PropertyMetadata.php +++ b/packages/PostRector/ValueObject/PropertyMetadata.php @@ -1,46 +1,38 @@ name = $name; $this->type = $type; $this->flags = $flags; } - - public function getName(): string + public function getName() : string { return $this->name; } - - public function getType(): ?Type + public function getType() : ?\PHPStan\Type\Type { return $this->type; } - - public function getFlags(): int + public function getFlags() : int { return $this->flags; } diff --git a/packages/ReadWrite/Contract/ReadNodeAnalyzerInterface.php b/packages/ReadWrite/Contract/ReadNodeAnalyzerInterface.php index a00f86ead5a..43b7e746f2d 100644 --- a/packages/ReadWrite/Contract/ReadNodeAnalyzerInterface.php +++ b/packages/ReadWrite/Contract/ReadNodeAnalyzerInterface.php @@ -1,14 +1,11 @@ > */ private $referencePositionsByFunctionName = []; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var ReflectionProvider */ private $reflectionProvider; - /** * @var PrivatesAccessor */ private $privatesAccessor; - - public function __construct( - NodeNameResolver $nodeNameResolver, - ReflectionProvider $reflectionProvider, - PrivatesAccessor $privatesAccessor - ) { + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \PHPStan\Reflection\ReflectionProvider $reflectionProvider, \RectorPrefix20210509\Symplify\PackageBuilder\Reflection\PrivatesAccessor $privatesAccessor) + { $this->nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; $this->privatesAccessor = $privatesAccessor; } - - public function isReadArg(Arg $arg): bool + public function isReadArg(\PhpParser\Node\Arg $arg) : bool { - $parentParent = $arg->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentParent instanceof FuncCall) { - return true; + $parentParent = $arg->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentParent instanceof \PhpParser\Node\Expr\FuncCall) { + return \true; } - $functionNameString = $this->nodeNameResolver->getName($parentParent); if ($functionNameString === null) { - return true; + return \true; } - - $functionName = new Name($functionNameString); - $argScope = $arg->getAttribute(AttributeKey::SCOPE); - - if (! $this->reflectionProvider->hasFunction($functionName, $argScope)) { + $functionName = new \PhpParser\Node\Name($functionNameString); + $argScope = $arg->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$this->reflectionProvider->hasFunction($functionName, $argScope)) { // we don't know - return true; + return \true; } - $functionReflection = $this->reflectionProvider->getFunction($functionName, $argScope); - $referenceParametersPositions = $this->resolveFunctionReferencePositions($functionReflection); if ($referenceParametersPositions === []) { // no reference always only write - return true; + return \true; } - $argumentPosition = $this->getArgumentPosition($parentParent, $arg); - return ! in_array($argumentPosition, $referenceParametersPositions, true); + return !\in_array($argumentPosition, $referenceParametersPositions, \true); } - /** * @return int[] */ - private function resolveFunctionReferencePositions(FunctionReflection $functionReflection): array + private function resolveFunctionReferencePositions(\PHPStan\Reflection\FunctionReflection $functionReflection) : array { if (isset($this->referencePositionsByFunctionName[$functionReflection->getName()])) { return $this->referencePositionsByFunctionName[$functionReflection->getName()]; } - // this is needed, as native function reflection does not have access to referenced parameters - if ($functionReflection instanceof NativeFunctionReflection) { - $nativeFunctionReflection = new ReflectionFunction($functionReflection->getName()); + if ($functionReflection instanceof \PHPStan\Reflection\Native\NativeFunctionReflection) { + $nativeFunctionReflection = new \ReflectionFunction($functionReflection->getName()); } else { $nativeFunctionReflection = $this->privatesAccessor->getPrivateProperty($functionReflection, 'reflection'); } - $referencePositions = []; /** @var int $position */ foreach ($nativeFunctionReflection->getParameters() as $position => $reflectionParameter) { - if (! $reflectionParameter->isPassedByReference()) { + if (!$reflectionParameter->isPassedByReference()) { continue; } - $referencePositions[] = $position; } - $this->referencePositionsByFunctionName[$functionReflection->getName()] = $referencePositions; - return $referencePositions; } - - private function getArgumentPosition(FuncCall $funcCall, Arg $desiredArg): int + private function getArgumentPosition(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Arg $desiredArg) : int { foreach ($funcCall->args as $position => $arg) { if ($arg !== $desiredArg) { continue; } - return $position; } - - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } } diff --git a/packages/ReadWrite/NodeAnalyzer/ReadExprAnalyzer.php b/packages/ReadWrite/NodeAnalyzer/ReadExprAnalyzer.php index 080a08d483a..afd0aa216e6 100644 --- a/packages/ReadWrite/NodeAnalyzer/ReadExprAnalyzer.php +++ b/packages/ReadWrite/NodeAnalyzer/ReadExprAnalyzer.php @@ -1,20 +1,17 @@ readNodeAnalyzers = $readNodeAnalyzers; } - /** * Is the value read or used for read purpose (at least, not only) */ - public function isExprRead(Expr $expr): bool + public function isExprRead(\PhpParser\Node\Expr $expr) : bool { foreach ($this->readNodeAnalyzers as $readNodeAnalyzer) { - if (! $readNodeAnalyzer->supports($expr)) { + if (!$readNodeAnalyzer->supports($expr)) { continue; } - return $readNodeAnalyzer->isRead($expr); } - - throw new NotImplementedYetException(get_class($expr)); + throw new \Rector\Core\Exception\NotImplementedYetException(\get_class($expr)); } } diff --git a/packages/ReadWrite/NodeAnalyzer/ReadWritePropertyAnalyzer.php b/packages/ReadWrite/NodeAnalyzer/ReadWritePropertyAnalyzer.php index 5be483df048..34c402c9724 100644 --- a/packages/ReadWrite/NodeAnalyzer/ReadWritePropertyAnalyzer.php +++ b/packages/ReadWrite/NodeAnalyzer/ReadWritePropertyAnalyzer.php @@ -1,7 +1,6 @@ variableToConstantGuard = $variableToConstantGuard; $this->assignManipulator = $assignManipulator; $this->readExprAnalyzer = $readExprAnalyzer; $this->betterNodeFinder = $betterNodeFinder; } - /** * @param PropertyFetch|StaticPropertyFetch $node */ - public function isRead(Node $node): bool + public function isRead(\PhpParser\Node $node) : bool { - Assert::isAnyOf($node, [PropertyFetch::class, StaticPropertyFetch::class]); - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Node) { - throw new ShouldNotHappenException(); + \RectorPrefix20210509\Webmozart\Assert\Assert::isAnyOf($node, [\PhpParser\Node\Expr\PropertyFetch::class, \PhpParser\Node\Expr\StaticPropertyFetch::class]); + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $parent = $this->unwrapPostPreIncDec($parent); - - if ($parent instanceof Arg) { + if ($parent instanceof \PhpParser\Node\Arg) { $readArg = $this->variableToConstantGuard->isReadArg($parent); if ($readArg) { - return true; + return \true; } } - - if ($parent instanceof ArrayDimFetch && $parent->dim === $node && $this->isNotInsideIssetUnset($parent)) { + if ($parent instanceof \PhpParser\Node\Expr\ArrayDimFetch && $parent->dim === $node && $this->isNotInsideIssetUnset($parent)) { return $this->isArrayDimFetchRead($parent); } - - return ! $this->assignManipulator->isLeftPartOfAssign($node); + return !$this->assignManipulator->isLeftPartOfAssign($node); } - - private function unwrapPostPreIncDec(Node $node): Node + private function unwrapPostPreIncDec(\PhpParser\Node $node) : \PhpParser\Node { - if ($node instanceof PreInc || $node instanceof PreDec || $node instanceof PostInc || $node instanceof PostDec) { - $node = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $node instanceof Node) { - throw new ShouldNotHappenException(); + if ($node instanceof \PhpParser\Node\Expr\PreInc || $node instanceof \PhpParser\Node\Expr\PreDec || $node instanceof \PhpParser\Node\Expr\PostInc || $node instanceof \PhpParser\Node\Expr\PostDec) { + $node = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$node instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } } - return $node; } - - private function isNotInsideIssetUnset(ArrayDimFetch $arrayDimFetch): bool + private function isNotInsideIssetUnset(\PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : bool { - return ! (bool) $this->betterNodeFinder->findParentTypes($arrayDimFetch, [Isset_::class, Unset_::class]); + return !(bool) $this->betterNodeFinder->findParentTypes($arrayDimFetch, [\PhpParser\Node\Expr\Isset_::class, \PhpParser\Node\Stmt\Unset_::class]); } - - private function isArrayDimFetchRead(ArrayDimFetch $arrayDimFetch): bool + private function isArrayDimFetchRead(\PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : bool { - $parentParent = $arrayDimFetch->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentParent instanceof Node) { - throw new ShouldNotHappenException(); + $parentParent = $arrayDimFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentParent instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - if (! $this->assignManipulator->isLeftPartOfAssign($arrayDimFetch)) { - return false; + if (!$this->assignManipulator->isLeftPartOfAssign($arrayDimFetch)) { + return \false; } - - if ($arrayDimFetch->var instanceof ArrayDimFetch) { - return true; + if ($arrayDimFetch->var instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + return \true; } - // the array dim fetch is assing here only; but the variable might be used later if ($this->readExprAnalyzer->isExprRead($arrayDimFetch->var)) { - return true; + return \true; } - - return ! $this->assignManipulator->isLeftPartOfAssign($arrayDimFetch); + return !$this->assignManipulator->isLeftPartOfAssign($arrayDimFetch); } } diff --git a/packages/ReadWrite/NodeFinder/NodeUsageFinder.php b/packages/ReadWrite/NodeFinder/NodeUsageFinder.php index c6688586d38..894ac205129 100644 --- a/packages/ReadWrite/NodeFinder/NodeUsageFinder.php +++ b/packages/ReadWrite/NodeFinder/NodeUsageFinder.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; $this->nodeRepository = $nodeRepository; $this->scopeAwareNodeFinder = $scopeAwareNodeFinder; $this->nodeComparator = $nodeComparator; } - /** * @param Node[] $nodes * @return Variable[] */ - public function findVariableUsages(array $nodes, Variable $variable): array + public function findVariableUsages(array $nodes, \PhpParser\Node\Expr\Variable $variable) : array { $variableName = $this->nodeNameResolver->getName($variable); if ($variableName === null) { return []; } - - return $this->betterNodeFinder->find($nodes, function (Node $node) use ($variable, $variableName): bool { - if (! $node instanceof Variable) { - return false; + return $this->betterNodeFinder->find($nodes, function (\PhpParser\Node $node) use($variable, $variableName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - if ($node === $variable) { - return false; + return \false; } - return $this->nodeNameResolver->isName($node, $variableName); }); } - /** * @return PropertyFetch[] */ - public function findPropertyFetchUsages(PropertyFetch $desiredPropertyFetch): array + public function findPropertyFetchUsages(\PhpParser\Node\Expr\PropertyFetch $desiredPropertyFetch) : array { $propertyFetches = $this->nodeRepository->findPropertyFetchesByPropertyFetch($desiredPropertyFetch); - $propertyFetchesWithoutPropertyFetch = []; foreach ($propertyFetches as $propertyFetch) { if ($propertyFetch === $desiredPropertyFetch) { continue; } - $propertyFetchesWithoutPropertyFetch[] = $propertyFetch; } - return $propertyFetchesWithoutPropertyFetch; } - - public function findPreviousForeachNodeUsage(Foreach_ $foreach, Expr $expr): ?Node + public function findPreviousForeachNodeUsage(\PhpParser\Node\Stmt\Foreach_ $foreach, \PhpParser\Node\Expr $expr) : ?\PhpParser\Node { - return $this->scopeAwareNodeFinder->findParent($foreach, function (Node $node) use ($expr): bool { + return $this->scopeAwareNodeFinder->findParent($foreach, function (\PhpParser\Node $node) use($expr) : bool { // skip itself if ($node === $expr) { - return false; + return \false; } - return $this->nodeComparator->areNodesEqual($node, $expr); - }, [Foreach_::class]); + }, [\PhpParser\Node\Stmt\Foreach_::class]); } } diff --git a/packages/ReadWrite/ReadNodeAnalyzer/PropertyFetchReadNodeAnalyzer.php b/packages/ReadWrite/ReadNodeAnalyzer/PropertyFetchReadNodeAnalyzer.php index 8e16c3f01d3..c13c63d8046 100644 --- a/packages/ReadWrite/ReadNodeAnalyzer/PropertyFetchReadNodeAnalyzer.php +++ b/packages/ReadWrite/ReadNodeAnalyzer/PropertyFetchReadNodeAnalyzer.php @@ -1,49 +1,42 @@ readExprAnalyzer = $readExprAnalyzer; $this->nodeUsageFinder = $nodeUsageFinder; } - - public function supports(Node $node): bool + public function supports(\PhpParser\Node $node) : bool { - return $node instanceof PropertyFetch; + return $node instanceof \PhpParser\Node\Expr\PropertyFetch; } - /** * @param PropertyFetch $node */ - public function isRead(Node $node): bool + public function isRead(\PhpParser\Node $node) : bool { $propertyFetchUsages = $this->nodeUsageFinder->findPropertyFetchUsages($node); foreach ($propertyFetchUsages as $propertyFetchUsage) { if ($this->readExprAnalyzer->isReadContext($propertyFetchUsage)) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/ReadWrite/ReadNodeAnalyzer/ReadExprAnalyzer.php b/packages/ReadWrite/ReadNodeAnalyzer/ReadExprAnalyzer.php index 399fa6661b7..0d32c651e89 100644 --- a/packages/ReadWrite/ReadNodeAnalyzer/ReadExprAnalyzer.php +++ b/packages/ReadWrite/ReadNodeAnalyzer/ReadExprAnalyzer.php @@ -1,7 +1,6 @@ getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Return_) { - return true; + $parent = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Stmt\Return_) { + return \true; } - - if ($parent instanceof Arg) { - return true; + if ($parent instanceof \PhpParser\Node\Arg) { + return \true; } - - if ($parent instanceof ArrayDimFetch) { - $parentParent = $parent->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentParent instanceof Assign) { - return true; + if ($parent instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + $parentParent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentParent instanceof \PhpParser\Node\Expr\Assign) { + return \true; } - return $parentParent->var !== $parent; } - // assume it's used by default - return ! $parent instanceof Expression; + return !$parent instanceof \PhpParser\Node\Stmt\Expression; } } diff --git a/packages/ReadWrite/ReadNodeAnalyzer/VariableReadNodeAnalyzer.php b/packages/ReadWrite/ReadNodeAnalyzer/VariableReadNodeAnalyzer.php index 95de9db719e..fbd670533f1 100644 --- a/packages/ReadWrite/ReadNodeAnalyzer/VariableReadNodeAnalyzer.php +++ b/packages/ReadWrite/ReadNodeAnalyzer/VariableReadNodeAnalyzer.php @@ -1,7 +1,6 @@ parentScopeFinder = $parentScopeFinder; $this->nodeUsageFinder = $nodeUsageFinder; $this->readExprAnalyzer = $readExprAnalyzer; } - - public function supports(Node $node): bool + public function supports(\PhpParser\Node $node) : bool { - return $node instanceof Variable; + return $node instanceof \PhpParser\Node\Expr\Variable; } - /** * @param Variable $node */ - public function isRead(Node $node): bool + public function isRead(\PhpParser\Node $node) : bool { $parentScope = $this->parentScopeFinder->find($node); if ($parentScope === null) { - return false; + return \false; } - $variableUsages = $this->nodeUsageFinder->findVariableUsages((array) $parentScope->stmts, $node); foreach ($variableUsages as $variableUsage) { if ($this->readExprAnalyzer->isReadContext($variableUsage)) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/Set/Contract/SetListInterface.php b/packages/Set/Contract/SetListInterface.php index 22d48b8d49a..3bd243907c7 100644 --- a/packages/Set/Contract/SetListInterface.php +++ b/packages/Set/Contract/SetListInterface.php @@ -1,7 +1,6 @@ */ - public function getNodeType(): string; - - public function mapToPHPStanType(TypeNode $typeNode, Node $node, NameScope $nameScope): Type; + public function getNodeType() : string; + public function mapToPHPStanType(\PHPStan\PhpDocParser\Ast\Type\TypeNode $typeNode, \PhpParser\Node $node, \PHPStan\Analyser\NameScope $nameScope) : \PHPStan\Type\Type; } diff --git a/packages/StaticTypeMapper/Contract/PhpParser/PhpParserNodeMapperInterface.php b/packages/StaticTypeMapper/Contract/PhpParser/PhpParserNodeMapperInterface.php index 4e956b4c3a5..e202251bbd1 100644 --- a/packages/StaticTypeMapper/Contract/PhpParser/PhpParserNodeMapperInterface.php +++ b/packages/StaticTypeMapper/Contract/PhpParser/PhpParserNodeMapperInterface.php @@ -1,18 +1,15 @@ */ - public function getNodeType(): string; - - public function mapToPHPStan(Node $node): Type; + public function getNodeType() : string; + public function mapToPHPStan(\PhpParser\Node $node) : \PHPStan\Type\Type; } diff --git a/packages/StaticTypeMapper/Mapper/PhpParserNodeMapper.php b/packages/StaticTypeMapper/Mapper/PhpParserNodeMapper.php index 47986843793..3d595dff3ac 100644 --- a/packages/StaticTypeMapper/Mapper/PhpParserNodeMapper.php +++ b/packages/StaticTypeMapper/Mapper/PhpParserNodeMapper.php @@ -1,7 +1,6 @@ phpParserNodeMappers = $phpParserNodeMappers; } - - public function mapToPHPStanType(Node $node): Type + public function mapToPHPStanType(\PhpParser\Node $node) : \PHPStan\Type\Type { foreach ($this->phpParserNodeMappers as $phpParserNodeMapper) { - if (! is_a($node, $phpParserNodeMapper->getNodeType())) { + if (!\is_a($node, $phpParserNodeMapper->getNodeType())) { continue; } - // do not let Expr collect all the types // note: can be solve later with priorities on mapper interface, making this last - if ($phpParserNodeMapper->getNodeType() !== Expr::class) { + if ($phpParserNodeMapper->getNodeType() !== \PhpParser\Node\Expr::class) { return $phpParserNodeMapper->mapToPHPStan($node); } - - if (! $node instanceof String_) { + if (!$node instanceof \PhpParser\Node\Scalar\String_) { return $phpParserNodeMapper->mapToPHPStan($node); } } - - throw new NotImplementedYetException(get_class($node)); + throw new \Rector\Core\Exception\NotImplementedYetException(\get_class($node)); } } diff --git a/packages/StaticTypeMapper/Mapper/ScalarStringToTypeMapper.php b/packages/StaticTypeMapper/Mapper/ScalarStringToTypeMapper.php index 2739e8b9c94..fd6754a41f6 100644 --- a/packages/StaticTypeMapper/Mapper/ScalarStringToTypeMapper.php +++ b/packages/StaticTypeMapper/Mapper/ScalarStringToTypeMapper.php @@ -1,10 +1,9 @@ , string[]> */ - private const SCALAR_NAME_BY_TYPE = [ - StringType::class => ['string'], - FloatType::class => ['float', 'real', 'double'], - IntegerType::class => ['int', 'integer'], - BooleanType::class => ['bool', 'boolean'], - NullType::class => ['null'], - VoidType::class => ['void'], - ResourceType::class => ['resource'], - CallableType::class => ['callback', 'callable'], - ObjectWithoutClassType::class => ['object'], - ]; - - public function mapScalarStringToType(string $scalarName): Type + private const SCALAR_NAME_BY_TYPE = [\PHPStan\Type\StringType::class => ['string'], \PHPStan\Type\FloatType::class => ['float', 'real', 'double'], \PHPStan\Type\IntegerType::class => ['int', 'integer'], \PHPStan\Type\BooleanType::class => ['bool', 'boolean'], \PHPStan\Type\NullType::class => ['null'], \PHPStan\Type\VoidType::class => ['void'], \PHPStan\Type\ResourceType::class => ['resource'], \PHPStan\Type\CallableType::class => ['callback', 'callable'], \PHPStan\Type\ObjectWithoutClassType::class => ['object']]; + public function mapScalarStringToType(string $scalarName) : \PHPStan\Type\Type { - $loweredScalarName = Strings::lower($scalarName); - + $loweredScalarName = \RectorPrefix20210509\Nette\Utils\Strings::lower($scalarName); if ($loweredScalarName === 'false') { - return new ConstantBooleanType(false); + return new \PHPStan\Type\Constant\ConstantBooleanType(\false); } - if ($loweredScalarName === 'true') { - return new ConstantBooleanType(true); + return new \PHPStan\Type\Constant\ConstantBooleanType(\true); } - foreach (self::SCALAR_NAME_BY_TYPE as $objectType => $scalarNames) { - if (! in_array($loweredScalarName, $scalarNames, true)) { + if (!\in_array($loweredScalarName, $scalarNames, \true)) { continue; } - return new $objectType(); } - if ($loweredScalarName === 'array') { - return new ArrayType(new MixedType(), new MixedType()); + return new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); } - if ($loweredScalarName === 'iterable') { - return new IterableType(new MixedType(), new MixedType()); + return new \PHPStan\Type\IterableType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); } - if ($loweredScalarName === 'mixed') { - return new MixedType(true); + return new \PHPStan\Type\MixedType(\true); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } } diff --git a/packages/StaticTypeMapper/Naming/NameScopeFactory.php b/packages/StaticTypeMapper/Naming/NameScopeFactory.php index 9ecd5fa4c17..de99db94a40 100644 --- a/packages/StaticTypeMapper/Naming/NameScopeFactory.php +++ b/packages/StaticTypeMapper/Naming/NameScopeFactory.php @@ -1,7 +1,6 @@ phpDocInfoFactory = $phpDocInfoFactory; } - - public function createNameScopeFromNodeWithoutTemplateTypes(Node $node): NameScope + public function createNameScopeFromNodeWithoutTemplateTypes(\PhpParser\Node $node) : \PHPStan\Analyser\NameScope { - $scope = $node->getAttribute(AttributeKey::SCOPE); - $namespace = $scope instanceof Scope ? $scope->getNamespace() : null; - + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + $namespace = $scope instanceof \PHPStan\Analyser\Scope ? $scope->getNamespace() : null; /** @var Use_[] $useNodes */ - $useNodes = (array) $node->getAttribute(AttributeKey::USE_NODES); - + $useNodes = (array) $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::USE_NODES); $uses = $this->resolveUseNamesByAlias($useNodes); - $className = $node->getAttribute(AttributeKey::CLASS_NAME); - - return new NameScope($namespace, $uses, $className); + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + return new \PHPStan\Analyser\NameScope($namespace, $uses, $className); } - - public function createNameScopeFromNode(Node $node): NameScope + public function createNameScopeFromNode(\PhpParser\Node $node) : \PHPStan\Analyser\NameScope { $nameScope = $this->createNameScopeFromNodeWithoutTemplateTypes($node); $templateTypeMap = $this->templateTemplateTypeMap($node); - - return new NameScope( - $nameScope->getNamespace(), - $nameScope->getUses(), - $nameScope->getClassName(), - null, - $templateTypeMap - ); + return new \PHPStan\Analyser\NameScope($nameScope->getNamespace(), $nameScope->getUses(), $nameScope->getClassName(), null, $templateTypeMap); } - - public function setStaticTypeMapper(StaticTypeMapper $staticTypeMapper): void + public function setStaticTypeMapper(\Rector\StaticTypeMapper\StaticTypeMapper $staticTypeMapper) : void { $this->staticTypeMapper = $staticTypeMapper; } - /** * @param Use_[] $useNodes * @return array */ - private function resolveUseNamesByAlias(array $useNodes): array + private function resolveUseNamesByAlias(array $useNodes) : array { $useNamesByAlias = []; - foreach ($useNodes as $useNode) { foreach ($useNode->uses as $useUse) { /** @var UseUse $useUse */ - $aliasName = $useUse->getAlias() - ->name; - + $aliasName = $useUse->getAlias()->name; $useName = $useUse->name->toString(); - if (! is_string($useName)) { - throw new ShouldNotHappenException(); + if (!\is_string($useName)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - // uses must be lowercase, as PHPStan lowercases it - $lowercasedAliasName = strtolower($aliasName); - + $lowercasedAliasName = \strtolower($aliasName); $useNamesByAlias[$lowercasedAliasName] = $useName; } } - return $useNamesByAlias; } - - private function templateTemplateTypeMap(Node $node): TemplateTypeMap + private function templateTemplateTypeMap(\PhpParser\Node $node) : \PHPStan\Type\Generic\TemplateTypeMap { $nodeTemplateTypes = $this->resolveTemplateTypesFromNode($node); - - $class = $node->getAttribute(AttributeKey::CLASS_NODE); + $class = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); $classTemplateTypes = []; - if ($class instanceof ClassLike) { + if ($class instanceof \PhpParser\Node\Stmt\ClassLike) { $classTemplateTypes = $this->resolveTemplateTypesFromNode($class); } - - $templateTypes = array_merge($nodeTemplateTypes, $classTemplateTypes); - return new TemplateTypeMap($templateTypes); + $templateTypes = \array_merge($nodeTemplateTypes, $classTemplateTypes); + return new \PHPStan\Type\Generic\TemplateTypeMap($templateTypes); } - /** * @return Type[] */ - private function resolveTemplateTypesFromNode(Node $node): array + private function resolveTemplateTypesFromNode(\PhpParser\Node $node) : array { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - $templateTypes = []; - foreach ($phpDocInfo->getTemplateTagValueNodes() as $templateTagValueNode) { $phpstanType = $this->staticTypeMapper->mapPHPStanPhpDocTypeToPHPStanType($templateTagValueNode, $node); $templateTypes[$templateTagValueNode->name] = $phpstanType; } - return $templateTypes; } } diff --git a/packages/StaticTypeMapper/PhpDoc/PhpDocTypeMapper.php b/packages/StaticTypeMapper/PhpDoc/PhpDocTypeMapper.php index f4e47c0bff7..9641cb0c9cb 100644 --- a/packages/StaticTypeMapper/PhpDoc/PhpDocTypeMapper.php +++ b/packages/StaticTypeMapper/PhpDoc/PhpDocTypeMapper.php @@ -1,7 +1,6 @@ phpDocTypeMappers = $phpDocTypeMappers; $this->typeNodeResolver = $typeNodeResolver; } - - public function mapToPHPStanType(TypeNode $typeNode, Node $node, NameScope $nameScope): Type + public function mapToPHPStanType(\PHPStan\PhpDocParser\Ast\Type\TypeNode $typeNode, \PhpParser\Node $node, \PHPStan\Analyser\NameScope $nameScope) : \PHPStan\Type\Type { foreach ($this->phpDocTypeMappers as $phpDocTypeMapper) { - if (! is_a($typeNode, $phpDocTypeMapper->getNodeType())) { + if (!\is_a($typeNode, $phpDocTypeMapper->getNodeType())) { continue; } - return $phpDocTypeMapper->mapToPHPStanType($typeNode, $node, $nameScope); } - // fallback to PHPStan resolver return $this->typeNodeResolver->resolve($typeNode, $nameScope); } diff --git a/packages/StaticTypeMapper/PhpDocParser/IdentifierTypeMapper.php b/packages/StaticTypeMapper/PhpDocParser/IdentifierTypeMapper.php index cd591ce9854..7baeb5482e1 100644 --- a/packages/StaticTypeMapper/PhpDocParser/IdentifierTypeMapper.php +++ b/packages/StaticTypeMapper/PhpDocParser/IdentifierTypeMapper.php @@ -1,7 +1,6 @@ scalarStringToTypeMapper = $scalarStringToTypeMapper; $this->objectTypeSpecifier = $objectTypeSpecifier; $this->parentClassScopeResolver = $parentClassScopeResolver; } - /** * @return class-string */ - public function getNodeType(): string + public function getNodeType() : string { - return IdentifierTypeNode::class; + return \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode::class; } - /** * @param IdentifierTypeNode $typeNode */ - public function mapToPHPStanType(TypeNode $typeNode, Node $node, NameScope $nameScope): Type + public function mapToPHPStanType(\PHPStan\PhpDocParser\Ast\Type\TypeNode $typeNode, \PhpParser\Node $node, \PHPStan\Analyser\NameScope $nameScope) : \PHPStan\Type\Type { $type = $this->scalarStringToTypeMapper->mapScalarStringToType($typeNode->name); - if (! $type instanceof MixedType) { + if (!$type instanceof \PHPStan\Type\MixedType) { return $type; } - if ($type->isExplicitMixed()) { return $type; } - - $loweredName = strtolower($typeNode->name); - + $loweredName = \strtolower($typeNode->name); if ($loweredName === 'class-string') { - return new ClassStringType(); + return new \PHPStan\Type\ClassStringType(); } - if ($loweredName === 'self') { return $this->mapSelf($node); } - if ($loweredName === 'parent') { return $this->mapParent($node); } - if ($loweredName === 'static') { return $this->mapStatic($node); } - if ($loweredName === 'iterable') { - return new IterableType(new MixedType(), new MixedType()); + return new \PHPStan\Type\IterableType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); } - - $objectType = new ObjectType($typeNode->name); - + $objectType = new \PHPStan\Type\ObjectType($typeNode->name); return $this->objectTypeSpecifier->narrowToFullyQualifiedOrAliasedObjectType($node, $objectType); } - - private function mapSelf(Node $node): SubtractableType + private function mapSelf(\PhpParser\Node $node) : \PHPStan\Type\SubtractableType { /** @var string|null $className */ - $className = $node->getAttribute(AttributeKey::CLASS_NAME); + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { // self outside the class, e.g. in a function - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - return new SelfObjectType($className); + return new \Rector\StaticTypeMapper\ValueObject\Type\SelfObjectType($className); } - - private function mapParent(Node $node): Type + private function mapParent(\PhpParser\Node $node) : \PHPStan\Type\Type { $parentClassName = $this->parentClassScopeResolver->resolveParentClassName($node); if ($parentClassName !== null) { - return new ParentStaticType($parentClassName); + return new \Rector\StaticTypeMapper\ValueObject\Type\ParentStaticType($parentClassName); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - private function mapStatic(Node $node): Type + private function mapStatic(\PhpParser\Node $node) : \PHPStan\Type\Type { /** @var string|null $className */ - $className = $node->getAttribute(AttributeKey::CLASS_NAME); + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - return new StaticType($className); + return new \PHPStan\Type\StaticType($className); } } diff --git a/packages/StaticTypeMapper/PhpDocParser/UnionTypeMapper.php b/packages/StaticTypeMapper/PhpDocParser/UnionTypeMapper.php index f92aeb3ef81..61652c92371 100644 --- a/packages/StaticTypeMapper/PhpDocParser/UnionTypeMapper.php +++ b/packages/StaticTypeMapper/PhpDocParser/UnionTypeMapper.php @@ -1,7 +1,6 @@ typeFactory = $typeFactory; } - /** * @return class-string */ - public function getNodeType(): string + public function getNodeType() : string { - return UnionTypeNode::class; + return \PHPStan\PhpDocParser\Ast\Type\UnionTypeNode::class; } - /** * @required */ - public function autowireUnionTypeMapper(PhpDocTypeMapper $phpDocTypeMapper): void + public function autowireUnionTypeMapper(\Rector\StaticTypeMapper\PhpDoc\PhpDocTypeMapper $phpDocTypeMapper) : void { $this->phpDocTypeMapper = $phpDocTypeMapper; } - /** * @param UnionTypeNode $typeNode */ - public function mapToPHPStanType(TypeNode $typeNode, Node $node, NameScope $nameScope): Type + public function mapToPHPStanType(\PHPStan\PhpDocParser\Ast\Type\TypeNode $typeNode, \PhpParser\Node $node, \PHPStan\Analyser\NameScope $nameScope) : \PHPStan\Type\Type { $unionedTypes = []; foreach ($typeNode->types as $unionedTypeNode) { $unionedTypes[] = $this->phpDocTypeMapper->mapToPHPStanType($unionedTypeNode, $node, $nameScope); } - // to prevent missing class error, e.g. in tests return $this->typeFactory->createMixedPassedOrUnionTypeAndKeepConstant($unionedTypes); } diff --git a/packages/StaticTypeMapper/PhpParser/ExprNodeMapper.php b/packages/StaticTypeMapper/PhpParser/ExprNodeMapper.php index bf18bce9265..31724253091 100644 --- a/packages/StaticTypeMapper/PhpParser/ExprNodeMapper.php +++ b/packages/StaticTypeMapper/PhpParser/ExprNodeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeType(): string + public function getNodeType() : string { - return Expr::class; + return \PhpParser\Node\Expr::class; } - /** * @param Expr $node */ - public function mapToPHPStan(Node $node): Type + public function mapToPHPStan(\PhpParser\Node $node) : \PHPStan\Type\Type { - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return new MixedType(); + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return new \PHPStan\Type\MixedType(); } - return $scope->getType($node); } } diff --git a/packages/StaticTypeMapper/PhpParser/FullyQualifiedNodeMapper.php b/packages/StaticTypeMapper/PhpParser/FullyQualifiedNodeMapper.php index a88286d4868..224dcf34f8b 100644 --- a/packages/StaticTypeMapper/PhpParser/FullyQualifiedNodeMapper.php +++ b/packages/StaticTypeMapper/PhpParser/FullyQualifiedNodeMapper.php @@ -1,10 +1,9 @@ */ - public function getNodeType(): string + public function getNodeType() : string { - return FullyQualified::class; + return \PhpParser\Node\Name\FullyQualified::class; } - /** * @param FullyQualified $node */ - public function mapToPHPStan(Node $node): Type + public function mapToPHPStan(\PhpParser\Node $node) : \PHPStan\Type\Type { - $originalName = (string) $node->getAttribute(AttributeKey::ORIGINAL_NAME); + $originalName = (string) $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NAME); $fullyQualifiedName = $node->toString(); - // is aliased? if ($this->isAliasedName($originalName, $fullyQualifiedName)) { - return new AliasedObjectType($originalName, $fullyQualifiedName); + return new \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType($originalName, $fullyQualifiedName); } - - return new FullyQualifiedObjectType($fullyQualifiedName); + return new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($fullyQualifiedName); } - - private function isAliasedName(string $originalName, string $fullyQualifiedName): bool + private function isAliasedName(string $originalName, string $fullyQualifiedName) : bool { if ($originalName === '') { - return false; + return \false; } - if ($originalName === $fullyQualifiedName) { - return false; + return \false; } - - return ! Strings::endsWith($fullyQualifiedName, '\\' . $originalName); + return !\RectorPrefix20210509\Nette\Utils\Strings::endsWith($fullyQualifiedName, '\\' . $originalName); } } diff --git a/packages/StaticTypeMapper/PhpParser/IdentifierNodeMapper.php b/packages/StaticTypeMapper/PhpParser/IdentifierNodeMapper.php index a80cfc599e7..55ff3311115 100644 --- a/packages/StaticTypeMapper/PhpParser/IdentifierNodeMapper.php +++ b/packages/StaticTypeMapper/PhpParser/IdentifierNodeMapper.php @@ -1,7 +1,6 @@ scalarStringToTypeMapper = $scalarStringToTypeMapper; } - /** * @return class-string */ - public function getNodeType(): string + public function getNodeType() : string { - return Identifier::class; + return \PhpParser\Node\Identifier::class; } - /** * @param Identifier $node */ - public function mapToPHPStan(Node $node): Type + public function mapToPHPStan(\PhpParser\Node $node) : \PHPStan\Type\Type { return $this->scalarStringToTypeMapper->mapScalarStringToType($node->name); } diff --git a/packages/StaticTypeMapper/PhpParser/NameNodeMapper.php b/packages/StaticTypeMapper/PhpParser/NameNodeMapper.php index 2372329f27d..9924b61c2ca 100644 --- a/packages/StaticTypeMapper/PhpParser/NameNodeMapper.php +++ b/packages/StaticTypeMapper/PhpParser/NameNodeMapper.php @@ -1,7 +1,6 @@ renamedClassesCollector = $renamedClassesCollector; $this->reflectionProvider = $reflectionProvider; } - /** * @return class-string */ - public function getNodeType(): string + public function getNodeType() : string { - return Name::class; + return \PhpParser\Node\Name::class; } - /** * @param Name $node */ - public function mapToPHPStan(Node $node): Type + public function mapToPHPStan(\PhpParser\Node $node) : \PHPStan\Type\Type { $name = $node->toString(); if ($this->isExistingClass($name)) { - return new FullyQualifiedObjectType($name); + return new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($name); } - - if (in_array($name, ['static', 'self'], true)) { + if (\in_array($name, ['static', 'self'], \true)) { return $this->createClassReferenceType($node, $name); } - return $this->createScalarType($name); } - - private function isExistingClass(string $name): bool + private function isExistingClass(string $name) : bool { if ($this->reflectionProvider->hasClass($name)) { - return true; + return \true; } - // to be existing class names $oldToNewClasses = $this->renamedClassesCollector->getOldToNewClasses(); - - return in_array($name, $oldToNewClasses, true); + return \in_array($name, $oldToNewClasses, \true); } - - private function createClassReferenceType(Name $name, string $reference): Type + private function createClassReferenceType(\PhpParser\Node\Name $name, string $reference) : \PHPStan\Type\Type { - $className = $name->getAttribute(AttributeKey::CLASS_NAME); + $className = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - if ($reference === 'static') { - return new StaticType($className); + return new \PHPStan\Type\StaticType($className); } - if ($this->reflectionProvider->hasClass($className)) { $classReflection = $this->reflectionProvider->getClass($className); - return new ThisType($classReflection); + return new \PHPStan\Type\ThisType($classReflection); } - - return new ThisType($className); + return new \PHPStan\Type\ThisType($className); } - - private function createScalarType(string $name): Type + private function createScalarType(string $name) : \PHPStan\Type\Type { if ($name === 'array') { - return new ArrayType(new MixedType(), new MixedType()); + return new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); } - if ($name === 'int') { - return new IntegerType(); + return new \PHPStan\Type\IntegerType(); } - if ($name === 'float') { - return new FloatType(); + return new \PHPStan\Type\FloatType(); } - if ($name === 'string') { - return new StringType(); + return new \PHPStan\Type\StringType(); } - if ($name === 'false') { - return new ConstantBooleanType(false); + return new \PHPStan\Type\Constant\ConstantBooleanType(\false); } - if ($name === 'bool') { - return new BooleanType(); + return new \PHPStan\Type\BooleanType(); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } } diff --git a/packages/StaticTypeMapper/PhpParser/NullableTypeNodeMapper.php b/packages/StaticTypeMapper/PhpParser/NullableTypeNodeMapper.php index 15c3d2538d2..05e25e7f9b5 100644 --- a/packages/StaticTypeMapper/PhpParser/NullableTypeNodeMapper.php +++ b/packages/StaticTypeMapper/PhpParser/NullableTypeNodeMapper.php @@ -1,7 +1,6 @@ typeFactory = $typeFactory; } - /** * @required */ - public function autowireNullableTypeNodeMapper(PhpParserNodeMapper $phpParserNodeMapper): void + public function autowireNullableTypeNodeMapper(\Rector\StaticTypeMapper\Mapper\PhpParserNodeMapper $phpParserNodeMapper) : void { $this->phpParserNodeMapper = $phpParserNodeMapper; } - /** * @return class-string */ - public function getNodeType(): string + public function getNodeType() : string { - return NullableType::class; + return \PhpParser\Node\NullableType::class; } - /** * @param NullableType $node */ - public function mapToPHPStan(Node $node): Type + public function mapToPHPStan(\PhpParser\Node $node) : \PHPStan\Type\Type { $types = []; $types[] = $this->phpParserNodeMapper->mapToPHPStanType($node->type); - $types[] = new NullType(); - + $types[] = new \PHPStan\Type\NullType(); return $this->typeFactory->createMixedPassedOrUnionType($types); } } diff --git a/packages/StaticTypeMapper/PhpParser/StringNodeMapper.php b/packages/StaticTypeMapper/PhpParser/StringNodeMapper.php index dcc7e55003e..4b7a29c1f96 100644 --- a/packages/StaticTypeMapper/PhpParser/StringNodeMapper.php +++ b/packages/StaticTypeMapper/PhpParser/StringNodeMapper.php @@ -1,7 +1,6 @@ */ - public function getNodeType(): string + public function getNodeType() : string { - return String_::class; + return \PhpParser\Node\Scalar\String_::class; } - /** * @param String_ $node */ - public function mapToPHPStan(Node $node): Type + public function mapToPHPStan(\PhpParser\Node $node) : \PHPStan\Type\Type { - return new StringType(); + return new \PHPStan\Type\StringType(); } } diff --git a/packages/StaticTypeMapper/PhpParser/UnionTypeNodeMapper.php b/packages/StaticTypeMapper/PhpParser/UnionTypeNodeMapper.php index ceff60543a2..9eb3113bb6d 100644 --- a/packages/StaticTypeMapper/PhpParser/UnionTypeNodeMapper.php +++ b/packages/StaticTypeMapper/PhpParser/UnionTypeNodeMapper.php @@ -1,7 +1,6 @@ typeFactory = $typeFactory; } - /** * @required */ - public function autowireUnionTypeNodeMapper(PhpParserNodeMapper $phpParserNodeMapper): void + public function autowireUnionTypeNodeMapper(\Rector\StaticTypeMapper\Mapper\PhpParserNodeMapper $phpParserNodeMapper) : void { $this->phpParserNodeMapper = $phpParserNodeMapper; } - /** * @return class-string */ - public function getNodeType(): string + public function getNodeType() : string { - return UnionType::class; + return \PhpParser\Node\UnionType::class; } - /** * @param UnionType $node */ - public function mapToPHPStan(Node $node): Type + public function mapToPHPStan(\PhpParser\Node $node) : \PHPStan\Type\Type { $types = []; foreach ($node->types as $unionedType) { $types[] = $this->phpParserNodeMapper->mapToPHPStanType($unionedType); } - return $this->typeFactory->createMixedPassedOrUnionType($types); } } diff --git a/packages/StaticTypeMapper/StaticTypeMapper.php b/packages/StaticTypeMapper/StaticTypeMapper.php index 1cf8fd59632..c473d2adf72 100644 --- a/packages/StaticTypeMapper/StaticTypeMapper.php +++ b/packages/StaticTypeMapper/StaticTypeMapper.php @@ -1,7 +1,6 @@ PHPStan <=> PHPStan doc <=> string type nodes between all possible formats * @see \Rector\Tests\NodeTypeResolver\StaticTypeMapper\StaticTypeMapperTest @@ -34,87 +32,65 @@ final class StaticTypeMapper * @var PHPStanStaticTypeMapper */ private $phpStanStaticTypeMapper; - /** * @var PhpParserNodeMapper */ private $phpParserNodeMapper; - /** * @var PhpDocTypeMapper */ private $phpDocTypeMapper; - /** * @var NameScopeFactory */ private $nameScopeFactory; - - public function __construct( - NameScopeFactory $nameScopeFactory, - PHPStanStaticTypeMapper $phpStanStaticTypeMapper, - PhpDocTypeMapper $phpDocTypeMapper, - PhpParserNodeMapper $phpParserNodeMapper - ) { + public function __construct(\Rector\StaticTypeMapper\Naming\NameScopeFactory $nameScopeFactory, \Rector\PHPStanStaticTypeMapper\PHPStanStaticTypeMapper $phpStanStaticTypeMapper, \Rector\StaticTypeMapper\PhpDoc\PhpDocTypeMapper $phpDocTypeMapper, \Rector\StaticTypeMapper\Mapper\PhpParserNodeMapper $phpParserNodeMapper) + { $this->phpStanStaticTypeMapper = $phpStanStaticTypeMapper; $this->phpParserNodeMapper = $phpParserNodeMapper; $this->phpDocTypeMapper = $phpDocTypeMapper; $this->nameScopeFactory = $nameScopeFactory; - $this->nameScopeFactory->setStaticTypeMapper($this); } - - public function mapPHPStanTypeToPHPStanPhpDocTypeNode(Type $phpStanType): TypeNode + public function mapPHPStanTypeToPHPStanPhpDocTypeNode(\PHPStan\Type\Type $phpStanType) : \PHPStan\PhpDocParser\Ast\Type\TypeNode { return $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($phpStanType); } - /** * @return Name|NullableType|PhpParserUnionType|null */ - public function mapPHPStanTypeToPhpParserNode(Type $phpStanType, ?string $kind = null): ?Node + public function mapPHPStanTypeToPhpParserNode(\PHPStan\Type\Type $phpStanType, ?string $kind = null) : ?\PhpParser\Node { return $this->phpStanStaticTypeMapper->mapToPhpParserNode($phpStanType, $kind); } - - public function mapPhpParserNodePHPStanType(Node $node): Type + public function mapPhpParserNodePHPStanType(\PhpParser\Node $node) : \PHPStan\Type\Type { return $this->phpParserNodeMapper->mapToPHPStanType($node); } - - public function mapPHPStanPhpDocTypeToPHPStanType(PhpDocTagValueNode $phpDocTagValueNode, Node $node): Type + public function mapPHPStanPhpDocTypeToPHPStanType(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode $phpDocTagValueNode, \PhpParser\Node $node) : \PHPStan\Type\Type { - if ($phpDocTagValueNode instanceof TemplateTagValueNode) { + if ($phpDocTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode) { // special case $nameScope = $this->nameScopeFactory->createNameScopeFromNodeWithoutTemplateTypes($node); if ($phpDocTagValueNode->bound === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - return $this->phpDocTypeMapper->mapToPHPStanType($phpDocTagValueNode->bound, $node, $nameScope); } - - if ($phpDocTagValueNode instanceof ReturnTagValueNode || $phpDocTagValueNode instanceof ParamTagValueNode || $phpDocTagValueNode instanceof VarTagValueNode || $phpDocTagValueNode instanceof ThrowsTagValueNode) { + if ($phpDocTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode || $phpDocTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode || $phpDocTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode || $phpDocTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ThrowsTagValueNode) { return $this->mapPHPStanPhpDocTypeNodeToPHPStanType($phpDocTagValueNode->type, $node); } - - throw new NotImplementedYetException(__METHOD__ . ' for ' . get_class($phpDocTagValueNode)); + throw new \Rector\Core\Exception\NotImplementedYetException(__METHOD__ . ' for ' . \get_class($phpDocTagValueNode)); } - - public function mapPHPStanPhpDocTypeNodeToPHPStanType(TypeNode $typeNode, Node $node): Type + public function mapPHPStanPhpDocTypeNodeToPHPStanType(\PHPStan\PhpDocParser\Ast\Type\TypeNode $typeNode, \PhpParser\Node $node) : \PHPStan\Type\Type { $nameScope = $this->nameScopeFactory->createNameScopeFromNode($node); return $this->phpDocTypeMapper->mapToPHPStanType($typeNode, $node, $nameScope); } - - public function mapPHPStanPhpDocTypeNodeToPHPStanTypeWithTemplateTypeMap( - TypeNode $typeNode, - Node $node, - TemplateTypeMap $templateTypeMap - ): Type { + public function mapPHPStanPhpDocTypeNodeToPHPStanTypeWithTemplateTypeMap(\PHPStan\PhpDocParser\Ast\Type\TypeNode $typeNode, \PhpParser\Node $node, \PHPStan\Type\Generic\TemplateTypeMap $templateTypeMap) : \PHPStan\Type\Type + { $nameScope = $this->nameScopeFactory->createNameScopeFromNode($node); $nameScope = $nameScope->withTemplateTypeMap($templateTypeMap); - return $this->phpDocTypeMapper->mapToPHPStanType($typeNode, $node, $nameScope); } } diff --git a/packages/StaticTypeMapper/TypeFactory/UnionTypeFactory.php b/packages/StaticTypeMapper/TypeFactory/UnionTypeFactory.php index 1f4e2404a5f..b6e539c8cb3 100644 --- a/packages/StaticTypeMapper/TypeFactory/UnionTypeFactory.php +++ b/packages/StaticTypeMapper/TypeFactory/UnionTypeFactory.php @@ -1,36 +1,30 @@ newInstanceWithoutConstructor(); - - $privatesAccessor = new PrivatesAccessor(); + $privatesAccessor = new \RectorPrefix20210509\Symplify\PackageBuilder\Reflection\PrivatesAccessor(); $privatesAccessor->setPrivateProperty($unionType, 'types', $objectTypes); - return $unionType; } } diff --git a/packages/StaticTypeMapper/ValueObject/Type/AliasedObjectType.php b/packages/StaticTypeMapper/ValueObject/Type/AliasedObjectType.php index 19b341e8140..9d738779151 100644 --- a/packages/StaticTypeMapper/ValueObject/Type/AliasedObjectType.php +++ b/packages/StaticTypeMapper/ValueObject/Type/AliasedObjectType.php @@ -1,49 +1,41 @@ fullyQualifiedClass = $fullyQualifiedClass; } - - public function getFullyQualifiedClass(): string + public function getFullyQualifiedClass() : string { return $this->fullyQualifiedClass; } - - public function getUseNode(): Use_ + public function getUseNode() : \PhpParser\Node\Stmt\Use_ { - $name = new Name($this->fullyQualifiedClass); - $useUse = new UseUse($name, $this->getClassName()); - return new Use_([$useUse]); + $name = new \PhpParser\Node\Name($this->fullyQualifiedClass); + $useUse = new \PhpParser\Node\Stmt\UseUse($name, $this->getClassName()); + return new \PhpParser\Node\Stmt\Use_([$useUse]); } - - public function getShortName(): string + public function getShortName() : string { return $this->getClassName(); } - /** * @param AliasedObjectType|FullyQualifiedObjectType $comparedObjectType */ - public function areShortNamesEqual(ObjectType $comparedObjectType): bool + public function areShortNamesEqual(\PHPStan\Type\ObjectType $comparedObjectType) : bool { return $this->getShortName() === $comparedObjectType->getShortName(); } diff --git a/packages/StaticTypeMapper/ValueObject/Type/FullyQualifiedGenericObjectType.php b/packages/StaticTypeMapper/ValueObject/Type/FullyQualifiedGenericObjectType.php index 4d98289a97e..b0a2e69f682 100644 --- a/packages/StaticTypeMapper/ValueObject/Type/FullyQualifiedGenericObjectType.php +++ b/packages/StaticTypeMapper/ValueObject/Type/FullyQualifiedGenericObjectType.php @@ -1,11 +1,9 @@ getShortName(), $this->getClassName()); + return new \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType($this->getShortName(), $this->getClassName()); } - /** * @param AliasedObjectType|FullyQualifiedObjectType $comparedObjectType */ - public function areShortNamesEqual(ObjectType $comparedObjectType): bool + public function areShortNamesEqual(\PHPStan\Type\ObjectType $comparedObjectType) : bool { return $this->getShortName() === $comparedObjectType->getShortName(); } - - public function getShortName(): string + public function getShortName() : string { - if (! Strings::contains($this->getClassName(), '\\')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($this->getClassName(), '\\')) { return $this->getClassName(); } - - return (string) Strings::after($this->getClassName(), '\\', -1); + return (string) \RectorPrefix20210509\Nette\Utils\Strings::after($this->getClassName(), '\\', -1); } - - public function getShortNameNode(): Name + public function getShortNameNode() : \PhpParser\Node\Name { - $name = new Name($this->getShortName()); - $name->setAttribute(AttributeKey::VIRTUAL_NODE, true); - + $name = new \PhpParser\Node\Name($this->getShortName()); + $name->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::VIRTUAL_NODE, \true); return $name; } - - public function getUseNode(): Use_ + public function getUseNode() : \PhpParser\Node\Stmt\Use_ { - $name = new Name($this->getClassName()); - $useUse = new UseUse($name); - - $name->setAttribute(AttributeKey::PARENT_NODE, $useUse); - - return new Use_([$useUse]); + $name = new \PhpParser\Node\Name($this->getClassName()); + $useUse = new \PhpParser\Node\Stmt\UseUse($name); + $name->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE, $useUse); + return new \PhpParser\Node\Stmt\Use_([$useUse]); } - - public function getFunctionUseNode(): Use_ + public function getFunctionUseNode() : \PhpParser\Node\Stmt\Use_ { - $name = new Name($this->getClassName()); - $useUse = new UseUse($name, null, Use_::TYPE_FUNCTION); - - $name->setAttribute(AttributeKey::PARENT_NODE, $useUse); - - return new Use_([$useUse]); + $name = new \PhpParser\Node\Name($this->getClassName()); + $useUse = new \PhpParser\Node\Stmt\UseUse($name, null, \PhpParser\Node\Stmt\Use_::TYPE_FUNCTION); + $name->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE, $useUse); + return new \PhpParser\Node\Stmt\Use_([$useUse]); } - - public function getShortNameLowered(): string + public function getShortNameLowered() : string { - return strtolower($this->getShortName()); + return \strtolower($this->getShortName()); } - - public function getClassNameLowered(): string + public function getClassNameLowered() : string { - return strtolower($this->getClassName()); + return \strtolower($this->getClassName()); } } diff --git a/packages/StaticTypeMapper/ValueObject/Type/ParentStaticType.php b/packages/StaticTypeMapper/ValueObject/Type/ParentStaticType.php index ab95077abc7..0a8157e3be1 100644 --- a/packages/StaticTypeMapper/ValueObject/Type/ParentStaticType.php +++ b/packages/StaticTypeMapper/ValueObject/Type/ParentStaticType.php @@ -1,11 +1,9 @@ fullyQualifiedName = $fullyQualifiedName; } - - public function isSuperTypeOf(Type $type): TrinaryLogic + public function isSuperTypeOf(\PHPStan\Type\Type $type) : \PHPStan\TrinaryLogic { - $fullyQualifiedObjectType = new ObjectType($this->fullyQualifiedName); + $fullyQualifiedObjectType = new \PHPStan\Type\ObjectType($this->fullyQualifiedName); return $fullyQualifiedObjectType->isSuperTypeOf($type); } - - public function getShortName(): string + public function getShortName() : string { return $this->getClassName(); } - /** * @return class-string */ - public function getFullyQualifiedName(): string + public function getFullyQualifiedName() : string { return $this->fullyQualifiedName; } diff --git a/packages/Testing/Contract/ConfigFileAwareInterface.php b/packages/Testing/Contract/ConfigFileAwareInterface.php index 46a672ee498..e442e82dd3b 100644 --- a/packages/Testing/Contract/ConfigFileAwareInterface.php +++ b/packages/Testing/Contract/ConfigFileAwareInterface.php @@ -1,10 +1,9 @@ provideConfigFilePath()); - $rectorConfigsResolver = new RectorConfigsResolver(); - + @\ini_set('memory_limit', '-1'); + $configFileInfo = new \Symplify\SmartFileSystem\SmartFileInfo($this->provideConfigFilePath()); + $rectorConfigsResolver = new \Rector\Core\Bootstrap\RectorConfigsResolver(); $configFileInfos = $rectorConfigsResolver->resolveFromConfigFileInfo($configFileInfo); $this->bootFromConfigFileInfos($configFileInfos); - - $this->applicationFileProcessor = $this->getService(ApplicationFileProcessor::class); - $this->parameterProvider = $this->getService(ParameterProvider::class); - $this->dynamicSourceLocatorProvider = $this->getService(DynamicSourceLocatorProvider::class); - - $this->removedAndAddedFilesCollector = $this->getService(RemovedAndAddedFilesCollector::class); + $this->applicationFileProcessor = $this->getService(\Rector\Core\Application\ApplicationFileProcessor::class); + $this->parameterProvider = $this->getService(\RectorPrefix20210509\Symplify\PackageBuilder\Parameter\ParameterProvider::class); + $this->dynamicSourceLocatorProvider = $this->getService(\Rector\NodeTypeResolver\Reflection\BetterReflection\SourceLocatorProvider\DynamicSourceLocatorProvider::class); + $this->removedAndAddedFilesCollector = $this->getService(\Rector\Core\Application\FileSystem\RemovedAndAddedFilesCollector::class); $this->removedAndAddedFilesCollector->reset(); - /** @var AdditionalAutoloader $additionalAutoloader */ - $additionalAutoloader = $this->getService(AdditionalAutoloader::class); + $additionalAutoloader = $this->getService(\Rector\Core\Autoloading\AdditionalAutoloader::class); $additionalAutoloader->autoloadPaths(); - /** @var BootstrapFilesIncluder $bootstrapFilesIncluder */ - $bootstrapFilesIncluder = $this->getService(BootstrapFilesIncluder::class); + $bootstrapFilesIncluder = $this->getService(\Rector\Core\Autoloading\BootstrapFilesIncluder::class); $bootstrapFilesIncluder->includeBootstrapFiles(); - /** @var Configuration $configuration */ - $configuration = $this->getService(Configuration::class); - $configuration->setIsDryRun(true); + $configuration = $this->getService(\Rector\Core\Configuration\Configuration::class); + $configuration->setIsDryRun(\true); } - - public function provideConfigFilePath(): string + public function provideConfigFilePath() : string { // must be implemented return ''; } - /** * @return Iterator */ - protected function yieldFilesFromDirectory(string $directory, string $suffix = '*.php.inc'): Iterator + protected function yieldFilesFromDirectory(string $directory, string $suffix = '*.php.inc') : \Iterator { - return StaticFixtureFinder::yieldDirectoryExclusively($directory, $suffix); + return \RectorPrefix20210509\Symplify\EasyTesting\DataProvider\StaticFixtureFinder::yieldDirectoryExclusively($directory, $suffix); } - - protected function doTestFileInfo(SmartFileInfo $fixtureFileInfo): void + protected function doTestFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $fixtureFileInfo) : void { - $inputFileInfoAndExpectedFileInfo = StaticFixtureSplitter::splitFileInfoToLocalInputAndExpectedFileInfos( - $fixtureFileInfo - ); - + $inputFileInfoAndExpectedFileInfo = \RectorPrefix20210509\Symplify\EasyTesting\StaticFixtureSplitter::splitFileInfoToLocalInputAndExpectedFileInfos($fixtureFileInfo); $inputFileInfo = $inputFileInfoAndExpectedFileInfo->getInputFileInfo(); $this->originalTempFileInfo = $inputFileInfo; - $expectedFileInfo = $inputFileInfoAndExpectedFileInfo->getExpectedFileInfo(); $this->doTestFileMatchesExpectedContent($inputFileInfo, $expectedFileInfo, $fixtureFileInfo); } - - protected function getFixtureTempDirectory(): string + protected function getFixtureTempDirectory() : string { - return sys_get_temp_dir() . '/_temp_fixture_easy_testing'; + return \sys_get_temp_dir() . '/_temp_fixture_easy_testing'; } - - private function doTestFileMatchesExpectedContent( - SmartFileInfo $originalFileInfo, - SmartFileInfo $expectedFileInfo, - SmartFileInfo $fixtureFileInfo - ): void { - $this->parameterProvider->changeParameter(Option::SOURCE, [$originalFileInfo->getRealPath()]); - + private function doTestFileMatchesExpectedContent(\Symplify\SmartFileSystem\SmartFileInfo $originalFileInfo, \Symplify\SmartFileSystem\SmartFileInfo $expectedFileInfo, \Symplify\SmartFileSystem\SmartFileInfo $fixtureFileInfo) : void + { + $this->parameterProvider->changeParameter(\Rector\Core\Configuration\Option::SOURCE, [$originalFileInfo->getRealPath()]); $changedContent = $this->processFileInfo($originalFileInfo); - // file is removed, we cannot compare it if ($this->removedAndAddedFilesCollector->isFileRemoved($originalFileInfo)) { return; } - $relativeFilePathFromCwd = $fixtureFileInfo->getRelativeFilePathFromCwd(); - try { $this->assertStringEqualsFile($expectedFileInfo->getRealPath(), $changedContent, $relativeFilePathFromCwd); - } catch (ExpectationFailedException $expectationFailedException) { - StaticFixtureUpdater::updateFixtureContent($originalFileInfo, $changedContent, $fixtureFileInfo); + } catch (\RectorPrefix20210509\PHPUnit\Framework\ExpectationFailedException $expectationFailedException) { + \RectorPrefix20210509\Symplify\EasyTesting\DataProvider\StaticFixtureUpdater::updateFixtureContent($originalFileInfo, $changedContent, $fixtureFileInfo); $contents = $expectedFileInfo->getContents(); - // make sure we don't get a diff in which every line is different (because of differences in EOL) $contents = $this->normalizeNewlines($contents); - // if not exact match, check the regex version (useful for generated hashes/uuids in the code) $this->assertStringMatchesFormat($contents, $changedContent, $relativeFilePathFromCwd); } } - - private function normalizeNewlines(string $string): string + private function normalizeNewlines(string $string) : string { - return Strings::replace($string, '#\r\n|\r|\n#', "\n"); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($string, '#\\r\\n|\\r|\\n#', "\n"); } - - private function processFileInfo(SmartFileInfo $fileInfo): string + private function processFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo) : string { $this->dynamicSourceLocatorProvider->setFileInfo($fileInfo); - // needed for PHPStan, because the analyzed file is just created in /temp - need for trait and similar deps /** @var NodeScopeResolver $nodeScopeResolver */ - $nodeScopeResolver = $this->getService(NodeScopeResolver::class); + $nodeScopeResolver = $this->getService(\PHPStan\Analyser\NodeScopeResolver::class); $nodeScopeResolver->setAnalysedFiles([$fileInfo->getRealPath()]); - - $file = new File($fileInfo, $fileInfo->getContents()); + $file = new \Rector\Core\ValueObject\Application\File($fileInfo, $fileInfo->getContents()); $this->applicationFileProcessor->run([$file]); - return $file->getFileContent(); } } diff --git a/packages/Testing/PHPUnit/AbstractTestCase.php b/packages/Testing/PHPUnit/AbstractTestCase.php index d2d5bb10cb9..df4427805c2 100644 --- a/packages/Testing/PHPUnit/AbstractTestCase.php +++ b/packages/Testing/PHPUnit/AbstractTestCase.php @@ -1,51 +1,43 @@ */ private static $kernelsByHash = []; - /** * @var ContainerInterface */ private static $currentContainer; - - protected function boot(): void + protected function boot() : void { $this->bootFromConfigFileInfos([]); } - /** * @param SmartFileInfo[] $configFileInfos */ - protected function bootFromConfigFileInfos(array $configFileInfos): void + protected function bootFromConfigFileInfos(array $configFileInfos) : void { $configsHash = $this->createConfigsHash($configFileInfos); - if (isset(self::$kernelsByHash[$configsHash])) { $rectorKernel = self::$kernelsByHash[$configsHash]; self::$currentContainer = $rectorKernel->getContainer(); } else { - $rectorKernel = new RectorKernel('test_' . $configsHash, true, $configFileInfos); + $rectorKernel = new \Rector\Core\HttpKernel\RectorKernel('test_' . $configsHash, \true, $configFileInfos); $rectorKernel->boot(); - self::$kernelsByHash[$configsHash] = $rectorKernel; self::$currentContainer = $rectorKernel->getContainer(); } } - /** * Syntax-sugar to remove static * @@ -53,25 +45,22 @@ abstract class AbstractTestCase extends TestCase * @param class-string $type * @return T */ - protected function getService(string $type): object + protected function getService(string $type) : object { if (self::$currentContainer === null) { - throw new ShouldNotHappenException('First, create container with "bootWithConfigFileInfos([...])"'); + throw new \Rector\Core\Exception\ShouldNotHappenException('First, create container with "bootWithConfigFileInfos([...])"'); } - return self::$currentContainer->get($type); } - /** * @param SmartFileInfo[] $configFileInfos */ - private function createConfigsHash(array $configFileInfos): string + private function createConfigsHash(array $configFileInfos) : string { $configHash = ''; foreach ($configFileInfos as $configFileInfo) { - $configHash .= md5_file($configFileInfo->getRealPath()); + $configHash .= \md5_file($configFileInfo->getRealPath()); } - return $configHash; } } diff --git a/packages/Testing/PHPUnit/Behavior/MovingFilesTrait.php b/packages/Testing/PHPUnit/Behavior/MovingFilesTrait.php index 44a9eb9a6e9..b369ea5da3a 100644 --- a/packages/Testing/PHPUnit/Behavior/MovingFilesTrait.php +++ b/packages/Testing/PHPUnit/Behavior/MovingFilesTrait.php @@ -1,81 +1,61 @@ removedAndAddedFilesCollector->isFileRemoved($smartFileInfo); $this->assertFalse($hasFileInfo); } - - protected function assertFileWasAdded(AddedFileWithContent $addedFileWithContent): void + protected function assertFileWasAdded(\Rector\FileSystemRector\ValueObject\AddedFileWithContent $addedFileWithContent) : void { $this->assertFilesWereAdded([$addedFileWithContent]); } - - protected function assertFileWasRemoved(SmartFileInfo $smartFileInfo): void + protected function assertFileWasRemoved(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : void { $isFileRemoved = $this->removedAndAddedFilesCollector->isFileRemoved($smartFileInfo); $this->assertTrue($isFileRemoved); } - /** * @param AddedFileWithContent[] $expectedAddedFileWithContents */ - protected function assertFilesWereAdded(array $expectedAddedFileWithContents): void + protected function assertFilesWereAdded(array $expectedAddedFileWithContents) : void { - Assert::allIsAOf($expectedAddedFileWithContents, AddedFileWithContent::class); - sort($expectedAddedFileWithContents); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsAOf($expectedAddedFileWithContents, \Rector\FileSystemRector\ValueObject\AddedFileWithContent::class); + \sort($expectedAddedFileWithContents); $addedFilePathsWithContents = $this->resolveAddedFilePathsWithContents(); - sort($addedFilePathsWithContents); - + \sort($addedFilePathsWithContents); // there should be at least some added files - Assert::notEmpty($addedFilePathsWithContents); - + \RectorPrefix20210509\Webmozart\Assert\Assert::notEmpty($addedFilePathsWithContents); foreach ($addedFilePathsWithContents as $key => $addedFilePathWithContent) { $expectedFilePathWithContent = $expectedAddedFileWithContents[$key]; - - $this->assertSame( - $expectedFilePathWithContent->getFilePath(), - $addedFilePathWithContent->getFilePath() - ); - - $this->assertSame( - $expectedFilePathWithContent->getFileContent(), - $addedFilePathWithContent->getFileContent() - ); + $this->assertSame($expectedFilePathWithContent->getFilePath(), $addedFilePathWithContent->getFilePath()); + $this->assertSame($expectedFilePathWithContent->getFileContent(), $addedFilePathWithContent->getFileContent()); } } - /** * @return AddedFileWithContent[] */ - private function resolveAddedFilePathsWithContents(): array + private function resolveAddedFilePathsWithContents() : array { $addedFilePathsWithContents = $this->removedAndAddedFilesCollector->getAddedFilesWithContent(); - $addedFilesWithNodes = $this->removedAndAddedFilesCollector->getAddedFilesWithNodes(); - foreach ($addedFilesWithNodes as $addedFileWithNode) { - $nodesWithFileDestinationPrinter = $this->getService(NodesWithFileDestinationPrinter::class); + $nodesWithFileDestinationPrinter = $this->getService(\Rector\Core\PhpParser\Printer\NodesWithFileDestinationPrinter::class); $fileContent = $nodesWithFileDestinationPrinter->printNodesWithFileDestination($addedFileWithNode); - $addedFilePathsWithContents[] = new AddedFileWithContent($addedFileWithNode->getFilePath(), $fileContent); + $addedFilePathsWithContents[] = new \Rector\FileSystemRector\ValueObject\AddedFileWithContent($addedFileWithNode->getFilePath(), $fileContent); } - return $addedFilePathsWithContents; } } diff --git a/packages/Testing/PHPUnit/StaticPHPUnitEnvironment.php b/packages/Testing/PHPUnit/StaticPHPUnitEnvironment.php index 0237c4973a8..da1427dad91 100644 --- a/packages/Testing/PHPUnit/StaticPHPUnitEnvironment.php +++ b/packages/Testing/PHPUnit/StaticPHPUnitEnvironment.php @@ -1,7 +1,6 @@ parameterProvider = $parameterProvider; $this->parser = $parser; $this->nodeScopeAndMetadataDecorator = $nodeScopeAndMetadataDecorator; $this->betterNodeFinder = $betterNodeFinder; } - /** * @return Node[] */ - public function parseFileToDecoratedNodes(string $file): array + public function parseFileToDecoratedNodes(string $file) : array { // autoload file require_once $file; - - $smartFileInfo = new SmartFileInfo($file); - $this->parameterProvider->changeParameter(Option::SOURCE, [$file]); - + $smartFileInfo = new \Symplify\SmartFileSystem\SmartFileInfo($file); + $this->parameterProvider->changeParameter(\Rector\Core\Configuration\Option::SOURCE, [$file]); $nodes = $this->parser->parseFileInfo($smartFileInfo); - - $file = new File($smartFileInfo, $smartFileInfo->getContents()); + $file = new \Rector\Core\ValueObject\Application\File($smartFileInfo, $smartFileInfo->getContents()); return $this->nodeScopeAndMetadataDecorator->decorateNodesFromFile($file, $nodes, $smartFileInfo); } - /** * @template T of Node * @param class-string $nodeClass * @return Node[] */ - public function parseFileToDecoratedNodesAndFindNodesByType(string $file, string $nodeClass): array + public function parseFileToDecoratedNodesAndFindNodesByType(string $file, string $nodeClass) : array { $nodes = $this->parseFileToDecoratedNodes($file); return $this->betterNodeFinder->findInstanceOf($nodes, $nodeClass); diff --git a/packages/Testing/ValueObject/InputFilePathWithExpectedFile.php b/packages/Testing/ValueObject/InputFilePathWithExpectedFile.php index f6839116567..e04dba8342d 100644 --- a/packages/Testing/ValueObject/InputFilePathWithExpectedFile.php +++ b/packages/Testing/ValueObject/InputFilePathWithExpectedFile.php @@ -1,36 +1,30 @@ inputFilePath = $inputFilePath; $this->addedFileWithContent = $addedFileWithContent; } - - public function getInputFileInfo(): SmartFileInfo + public function getInputFileInfo() : \Symplify\SmartFileSystem\SmartFileInfo { - return new SmartFileInfo($this->inputFilePath); + return new \Symplify\SmartFileSystem\SmartFileInfo($this->inputFilePath); } - - public function getAddedFileWithContent(): AddedFileWithContent + public function getAddedFileWithContent() : \Rector\FileSystemRector\ValueObject\AddedFileWithContent { return $this->addedFileWithContent; } diff --git a/packages/VendorLocker/Contract/NodeVendorLockerInterface.php b/packages/VendorLocker/Contract/NodeVendorLockerInterface.php index 8d48221b426..7143d080c47 100644 --- a/packages/VendorLocker/Contract/NodeVendorLockerInterface.php +++ b/packages/VendorLocker/Contract/NodeVendorLockerInterface.php @@ -1,12 +1,10 @@ nodeNameResolver = $nodeNameResolver; } - - public function isVendorLocked(ClassMethod $classMethod): bool + public function isVendorLocked(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { if ($classMethod->isMagic()) { - return true; + return \true; } - - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - $methodName = $this->nodeNameResolver->getName($classMethod); foreach ($classReflection->getAncestors() as $ancestorClassReflection) { // skip self if ($ancestorClassReflection === $classReflection) { continue; } - // parent type if ($ancestorClassReflection->hasNativeMethod($methodName)) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/VendorLocker/NodeVendorLocker/ClassMethodReturnTypeOverrideGuard.php b/packages/VendorLocker/NodeVendorLocker/ClassMethodReturnTypeOverrideGuard.php index 7a4fcce9f99..bc8731eb38f 100644 --- a/packages/VendorLocker/NodeVendorLocker/ClassMethodReturnTypeOverrideGuard.php +++ b/packages/VendorLocker/NodeVendorLocker/ClassMethodReturnTypeOverrideGuard.php @@ -1,7 +1,6 @@ > */ - private const CHAOTIC_CLASS_METHOD_NAMES = [ - 'PhpParser\NodeVisitor' => ['enterNode', 'leaveNode', 'beforeTraverse', 'afterTraverse'], - ]; - + private const CHAOTIC_CLASS_METHOD_NAMES = ['PhpParser\\NodeVisitor' => ['enterNode', 'leaveNode', 'beforeTraverse', 'afterTraverse']]; /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var ReflectionProvider */ private $reflectionProvider; - /** * @var FamilyRelationsAnalyzer */ private $familyRelationsAnalyzer; - /** * @var BetterNodeFinder */ private $betterNodeFinder; - - public function __construct( - NodeNameResolver $nodeNameResolver, - ReflectionProvider $reflectionProvider, - FamilyRelationsAnalyzer $familyRelationsAnalyzer, - BetterNodeFinder $betterNodeFinder - ) { + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \PHPStan\Reflection\ReflectionProvider $reflectionProvider, \Rector\FamilyTree\Reflection\FamilyRelationsAnalyzer $familyRelationsAnalyzer, \Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder) + { $this->nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; $this->familyRelationsAnalyzer = $familyRelationsAnalyzer; $this->betterNodeFinder = $betterNodeFinder; } - - public function shouldSkipClassMethod(ClassMethod $classMethod): bool + public function shouldSkipClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { // 1. skip magic methods if ($classMethod->isMagic()) { - return true; + return \true; } - // 2. skip chaotic contract class methods if ($this->shouldSkipChaoticClassMethods($classMethod)) { - return true; + return \true; } - - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - throw new ShouldNotHappenException(); + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $childrenClassReflections = $this->familyRelationsAnalyzer->getChildrenOfClassReflection($classReflection); if ($childrenClassReflections === []) { - return false; + return \false; } - if ($this->hasClassMethodExprReturn($classMethod)) { - return false; + return \false; } - return $classMethod->returnType === null; } - - public function shouldSkipClassMethodOldTypeWithNewType(Type $oldType, Type $newType): bool + public function shouldSkipClassMethodOldTypeWithNewType(\PHPStan\Type\Type $oldType, \PHPStan\Type\Type $newType) : bool { - if ($oldType instanceof MixedType) { - return false; + if ($oldType instanceof \PHPStan\Type\MixedType) { + return \false; } - // new generic string type is more advanced than old array type if ($this->isFirstArrayTypeMoreAdvanced($oldType, $newType)) { - return false; + return \false; } - - return $oldType->isSuperTypeOf($newType) - ->yes(); + return $oldType->isSuperTypeOf($newType)->yes(); } - - private function shouldSkipChaoticClassMethods(ClassMethod $classMethod): bool + private function shouldSkipChaoticClassMethods(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { /** @var string|null $className */ - $className = $classMethod->getAttribute(AttributeKey::CLASS_NAME); + $className = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { - return false; + return \false; } - - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - foreach (self::CHAOTIC_CLASS_METHOD_NAMES as $chaoticClass => $chaoticMethodNames) { - if (! $this->reflectionProvider->hasClass($chaoticClass)) { + if (!$this->reflectionProvider->hasClass($chaoticClass)) { continue; } - $chaoticClassReflection = $this->reflectionProvider->getClass($chaoticClass); - if (! $classReflection->isSubclassOf($chaoticClassReflection->getName())) { + if (!$classReflection->isSubclassOf($chaoticClassReflection->getName())) { continue; } - return $this->nodeNameResolver->isNames($classMethod, $chaoticMethodNames); } - - return false; + return \false; } - - private function hasClassMethodExprReturn(ClassMethod $classMethod): bool + private function hasClassMethodExprReturn(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - return (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (Node $node): bool { - if (! $node instanceof Return_) { - return false; + return (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Stmt\Return_) { + return \false; } - - return $node->expr instanceof Expr; + return $node->expr instanceof \PhpParser\Node\Expr; }); } - - private function isFirstArrayTypeMoreAdvanced(Type $oldType, Type $newType): bool + private function isFirstArrayTypeMoreAdvanced(\PHPStan\Type\Type $oldType, \PHPStan\Type\Type $newType) : bool { - if (! $oldType instanceof ArrayType) { - return false; + if (!$oldType instanceof \PHPStan\Type\ArrayType) { + return \false; } - - if (! $newType instanceof ArrayType) { - return false; + if (!$newType instanceof \PHPStan\Type\ArrayType) { + return \false; } - - if (! $oldType->getItemType() instanceof StringType) { - return false; + if (!$oldType->getItemType() instanceof \PHPStan\Type\StringType) { + return \false; } - - return $newType->getItemType() instanceof GenericClassStringType; + return $newType->getItemType() instanceof \PHPStan\Type\Generic\GenericClassStringType; } } diff --git a/packages/VendorLocker/NodeVendorLocker/ClassMethodReturnVendorLockResolver.php b/packages/VendorLocker/NodeVendorLocker/ClassMethodReturnVendorLockResolver.php index 92751d1cd27..2a64a418abb 100644 --- a/packages/VendorLocker/NodeVendorLocker/ClassMethodReturnVendorLockResolver.php +++ b/packages/VendorLocker/NodeVendorLocker/ClassMethodReturnVendorLockResolver.php @@ -1,7 +1,6 @@ methodReflectionContractAnalyzer = $methodReflectionContractAnalyzer; $this->nodeNameResolver = $nodeNameResolver; } - - public function isVendorLocked(ClassMethod $classMethod): bool + public function isVendorLocked(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - - if (count($classReflection->getAncestors()) === 1) { - return false; + if (\count($classReflection->getAncestors()) === 1) { + return \false; } - $methodName = $this->nodeNameResolver->getName($classMethod); if ($this->isVendorLockedByParentClass($classReflection, $methodName)) { - return true; + return \true; } - if ($classReflection->isTrait()) { - return false; + return \false; } - return $this->methodReflectionContractAnalyzer->hasInterfaceContract($classReflection, $methodName); } - - private function isVendorLockedByParentClass(ClassReflection $classReflection, string $methodName): bool + private function isVendorLockedByParentClass(\PHPStan\Reflection\ClassReflection $classReflection, string $methodName) : bool { foreach ($classReflection->getParents() as $parentClassReflections) { - if (! $parentClassReflections->hasMethod($methodName)) { + if (!$parentClassReflections->hasMethod($methodName)) { continue; } - $parentClassMethodReflection = $parentClassReflections->getNativeMethod($methodName); $parametersAcceptor = $parentClassMethodReflection->getVariants()[0]; - if (! $parametersAcceptor instanceof FunctionVariantWithPhpDocs) { + if (!$parametersAcceptor instanceof \PHPStan\Reflection\FunctionVariantWithPhpDocs) { continue; } - // here we count only on strict types, not on docs - return ! $parametersAcceptor->getNativeReturnType() instanceof MixedType; + return !$parametersAcceptor->getNativeReturnType() instanceof \PHPStan\Type\MixedType; } - - return false; + return \false; } } diff --git a/packages/VendorLocker/NodeVendorLocker/ClassMethodVendorLockResolver.php b/packages/VendorLocker/NodeVendorLocker/ClassMethodVendorLockResolver.php index ecfed7f4c61..74402e4defb 100644 --- a/packages/VendorLocker/NodeVendorLocker/ClassMethodVendorLockResolver.php +++ b/packages/VendorLocker/NodeVendorLocker/ClassMethodVendorLockResolver.php @@ -1,7 +1,6 @@ methodReflectionContractAnalyzer = $methodReflectionContractAnalyzer; $this->nodeNameResolver = $nodeNameResolver; } - /** * Checks for: * - interface required methods @@ -40,37 +33,30 @@ final class ClassMethodVendorLockResolver * Prevent: * - removing class methods, that breaks the code */ - public function isRemovalVendorLocked(ClassMethod $classMethod): bool + public function isRemovalVendorLocked(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { $classMethodName = $this->nodeNameResolver->getName($classMethod); - /** @var Scope $scope */ - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - if ($this->methodReflectionContractAnalyzer->hasInterfaceContract($classReflection, $classMethodName)) { - return true; + return \true; } - foreach ($classReflection->getParents() as $parentClassReflection) { - if (! $parentClassReflection->hasMethod($classMethodName)) { + if (!$parentClassReflection->hasMethod($classMethodName)) { continue; } - $methodReflection = $parentClassReflection->getNativeMethod($classMethodName); - if (! $methodReflection instanceof PhpMethodReflection) { + if (!$methodReflection instanceof \PHPStan\Reflection\Php\PhpMethodReflection) { continue; } - if ($methodReflection->isAbstract()) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/VendorLocker/NodeVendorLocker/PropertyTypeVendorLockResolver.php b/packages/VendorLocker/NodeVendorLocker/PropertyTypeVendorLockResolver.php index 48b283548e1..3c8453e57fd 100644 --- a/packages/VendorLocker/NodeVendorLocker/PropertyTypeVendorLockResolver.php +++ b/packages/VendorLocker/NodeVendorLocker/PropertyTypeVendorLockResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->familyRelationsAnalyzer = $familyRelationsAnalyzer; } - - public function isVendorLocked(Property $property): bool + public function isVendorLocked(\PhpParser\Node\Stmt\Property $property) : bool { - $scope = $property->getAttribute(AttributeKey::SCOPE); + $scope = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); // possibly trait - if (! $scope instanceof Scope) { - return true; + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \true; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - - if (count($classReflection->getAncestors()) === 1) { - return false; + if (\count($classReflection->getAncestors()) === 1) { + return \false; } - /** @var string $propertyName */ $propertyName = $this->nodeNameResolver->getName($property); - if ($this->isParentClassLocked($classReflection, $propertyName)) { - return true; + return \true; } - return $this->isChildClassLocked($property, $classReflection, $propertyName); } - - private function isParentClassLocked(ClassReflection $classReflection, string $propertyName): bool + private function isParentClassLocked(\PHPStan\Reflection\ClassReflection $classReflection, string $propertyName) : bool { // extract to some "inherited parent method" service foreach ($classReflection->getParents() as $parentClassReflection) { if ($parentClassReflection->hasProperty($propertyName)) { // validate type is conflicting // parent class property in external scope → it's not ok - return true; + return \true; } } - - return false; + return \false; } - - private function isChildClassLocked( - Property $property, - ClassReflection $classReflection, - string $propertyName - ): bool { - if (! $classReflection->isClass()) { - return false; + private function isChildClassLocked(\PhpParser\Node\Stmt\Property $property, \PHPStan\Reflection\ClassReflection $classReflection, string $propertyName) : bool + { + if (!$classReflection->isClass()) { + return \false; } - // is child class locked? if ($property->isPrivate()) { - return false; + return \false; } - $childClassReflections = $this->familyRelationsAnalyzer->getChildrenOfClassReflection($classReflection); - foreach ($childClassReflections as $childClassReflection) { - if (! $childClassReflection->hasProperty($propertyName)) { + if (!$childClassReflection->hasProperty($propertyName)) { continue; } - $propertyReflection = $childClassReflection->getNativeProperty($propertyName); - // ensure the property is not in the parent class $propertyReflectionDeclaringClass = $propertyReflection->getDeclaringClass(); if ($propertyReflectionDeclaringClass->getName() === $childClassReflection->getName()) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/VendorLocker/NodeVendorLocker/PropertyVisibilityVendorLockResolver.php b/packages/VendorLocker/NodeVendorLocker/PropertyVisibilityVendorLockResolver.php index f6e02296144..515a62247e4 100644 --- a/packages/VendorLocker/NodeVendorLocker/PropertyVisibilityVendorLockResolver.php +++ b/packages/VendorLocker/NodeVendorLocker/PropertyVisibilityVendorLockResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->familyRelationsAnalyzer = $familyRelationsAnalyzer; } - /** * Checks for: * - child classes required properties @@ -37,54 +32,44 @@ final class PropertyVisibilityVendorLockResolver * Prevents: * - changing visibility conflicting with children */ - public function isParentLockedProperty(Property $property): bool + public function isParentLockedProperty(\PhpParser\Node\Stmt\Property $property) : bool { $classReflection = $this->resolveClassReflection($property); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - $propertyName = $this->nodeNameResolver->getName($property); - foreach ($classReflection->getParents() as $parentClassReflection) { if ($parentClassReflection->hasProperty($propertyName)) { - return true; + return \true; } } - - return false; + return \false; } - - public function isChildLockedProperty(Property $property): bool + public function isChildLockedProperty(\PhpParser\Node\Stmt\Property $property) : bool { $classReflection = $this->resolveClassReflection($property); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - $propertyName = $this->nodeNameResolver->getName($property); - $childrenClassReflections = $this->familyRelationsAnalyzer->getChildrenOfClassReflection($classReflection); foreach ($childrenClassReflections as $childClassReflection) { if ($childClassReflection === $classReflection) { continue; } - if ($childClassReflection->hasProperty($propertyName)) { - return true; + return \true; } } - - return false; + return \false; } - - private function resolveClassReflection(Node $node): ?ClassReflection + private function resolveClassReflection(\PhpParser\Node $node) : ?\PHPStan\Reflection\ClassReflection { - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - return $scope->getClassReflection(); } } diff --git a/packages/VendorLocker/Reflection/MethodReflectionContractAnalyzer.php b/packages/VendorLocker/Reflection/MethodReflectionContractAnalyzer.php index 1ecd3202acc..861c217065f 100644 --- a/packages/VendorLocker/Reflection/MethodReflectionContractAnalyzer.php +++ b/packages/VendorLocker/Reflection/MethodReflectionContractAnalyzer.php @@ -1,21 +1,18 @@ getInterfaces() as $interfaceReflection) { if ($interfaceReflection->hasMethod($methodName)) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/VendorLocker/VendorLockResolver.php b/packages/VendorLocker/VendorLockResolver.php index 1e9e921113e..484a0c8a8df 100644 --- a/packages/VendorLocker/VendorLockResolver.php +++ b/packages/VendorLocker/VendorLockResolver.php @@ -1,7 +1,6 @@ classMethodReturnVendorLockResolver = $classMethodReturnVendorLockResolver; $this->classMethodParamVendorLockResolver = $classMethodParamVendorLockResolver; $this->propertyTypeVendorLockResolver = $propertyTypeVendorLockResolver; $this->classMethodVendorLockResolver = $classMethodVendorLockResolver; } - - public function isClassMethodParamLockedIn(Node $node): bool + public function isClassMethodParamLockedIn(\PhpParser\Node $node) : bool { - if (! $node instanceof ClassMethod) { - return false; + if (!$node instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - return $this->classMethodParamVendorLockResolver->isVendorLocked($node); } - - public function isReturnChangeVendorLockedIn(ClassMethod $classMethod): bool + public function isReturnChangeVendorLockedIn(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { return $this->classMethodReturnVendorLockResolver->isVendorLocked($classMethod); } - - public function isPropertyTypeChangeVendorLockedIn(Property $property): bool + public function isPropertyTypeChangeVendorLockedIn(\PhpParser\Node\Stmt\Property $property) : bool { return $this->propertyTypeVendorLockResolver->isVendorLocked($property); } - - public function isClassMethodRemovalVendorLocked(ClassMethod $classMethod): bool + public function isClassMethodRemovalVendorLocked(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { return $this->classMethodVendorLockResolver->isRemovalVendorLocked($classMethod); } diff --git a/preload.php b/preload.php index e8f4ee062dd..51cc8b57935 100644 --- a/preload.php +++ b/preload.php @@ -2,243 +2,243 @@ declare(strict_types = 1); -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/FnTokenEmulator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/TokenEmulator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/NumericLiteralSeparatorEmulator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReverseEmulator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/FlexibleDocStringEmulator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/MatchTokenEmulator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/KeywordEmulator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/CoaleseEqualTokenEmulator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/NullsafeTokenEmulator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/AttributeEmulator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/Emulative.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/JsonDecoder.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Arg.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Variable.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ShellExec.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Closure.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrowFunction.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Print_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ErrorSuppress.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ClosureUse.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/StaticPropertyFetch.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PreInc.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/StaticCall.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Include_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Instanceof_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ConstFetch.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/MethodCall.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayDimFetch.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/UnaryPlus.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayItem.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Assign.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Throw_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ClassConstFetch.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/NullsafeMethodCall.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/NullsafePropertyFetch.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Match_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Exit_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Eval_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignRef.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PostDec.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Empty_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Clone_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BitwiseNot.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/YieldFrom.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Error.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Unset_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Double.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/String_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Object_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Array_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Int_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Bool_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PreDec.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Isset_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PropertyFetch.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/FuncCall.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/New_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Array_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Coalesce.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Div.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Plus.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseOr.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Concat.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/ShiftLeft.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseAnd.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/ShiftRight.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Mul.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseXor.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Minus.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Pow.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Mod.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/UnaryMinus.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/List_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Yield_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Ternary.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BooleanNot.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PostInc.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Coalesce.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Equal.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalXor.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Greater.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BooleanAnd.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/SmallerOrEqual.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Div.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Plus.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseOr.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/NotEqual.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Concat.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalOr.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/ShiftLeft.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Spaceship.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseAnd.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/ShiftRight.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalAnd.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Mul.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseXor.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BooleanOr.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Minus.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/GreaterOrEqual.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Identical.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Pow.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Smaller.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/NotIdentical.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Mod.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/VarLikeIdentifier.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/MatchArm.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/AttributeGroup.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/NullableType.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Identifier.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Name/Relative.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Name/FullyQualified.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Const_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Attribute.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/LNumber.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/DNumber.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Function_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Trait_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Line.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/File.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Namespace_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Class_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Dir.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Method.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Encapsed.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/String_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/EncapsedStringPart.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Name.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/UnionType.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Param.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/GroupUse.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Unset_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Goto_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUse.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Function_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/While_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Global_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TryCatch.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Static_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/If_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/InlineHTML.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Foreach_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Break_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/StaticVar.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Trait_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassMethod.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/UseUse.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Property.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Throw_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Label.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Else_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Return_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Declare_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ElseIf_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Namespace_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Do_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Const_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassLike.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassConst.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Finally_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Expression.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Use_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Class_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Interface_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Case_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/HaltCompiler.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Nop.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Continue_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Switch_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/PropertyProperty.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation/Precedence.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation/Alias.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/DeclareDeclare.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/For_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Catch_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Echo_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/FunctionLike.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Parser.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/NameResolver.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/CloningVisitor.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/NodeConnectingVisitor.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/FirstFindingVisitor.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/FindingVisitor.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/ParentConnectingVisitor.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Parser/Multiple.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Parser/Tokens.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Parser/Php5.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Parser/Php7.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeTraverser.php'; require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeDumper.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NameContext.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeFinder.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinterAbstract.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Internal/DiffElem.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Internal/Differ.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Internal/TokenStream.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Internal/PrintableNewAnonClassNode.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinter/Standard.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ConstExprEvaluator.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Throwing.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Collecting.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ParserAbstract.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitorAbstract.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Comment/Doc.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/TraitUse.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Function_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Trait_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Property.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Namespace_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Use_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Class_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Interface_.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Declaration.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Param.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/TraitUseAdaptation.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/FunctionLike.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Method.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Comment.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeTraverserInterface.php'; require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ConstExprEvaluationException.php'; require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/BuilderFactory.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/BuilderHelpers.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Error.php'; -require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ParserFactory.php'; require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeAbstract.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinter/Standard.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ConstExprEvaluator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitorAbstract.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Comment.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Internal/PrintableNewAnonClassNode.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Internal/TokenStream.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Internal/DiffElem.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Internal/Differ.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ParserFactory.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/BuilderFactory.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Throwing.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Collecting.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeFinder.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Declaration.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Method.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Function_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Property.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Namespace_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/TraitUse.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Param.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/TraitUseAdaptation.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Class_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/FunctionLike.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Trait_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Use_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Builder/Interface_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Error.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Parser.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/BuilderHelpers.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinterAbstract.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeTraverser.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeTraverserInterface.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NameContext.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Comment/Doc.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/FlexibleDocStringEmulator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/CoaleseEqualTokenEmulator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/MatchTokenEmulator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/NumericLiteralSeparatorEmulator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/ReverseEmulator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/FnTokenEmulator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/NullsafeTokenEmulator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/AttributeEmulator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/TokenEmulator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator/KeywordEmulator.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer/Emulative.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ParserAbstract.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Parser/Tokens.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Parser/Multiple.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Parser/Php5.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Parser/Php7.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Lexer.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/File.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Line.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Method.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Function_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Namespace_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Dir.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Class_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst/Trait_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/DNumber.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/EncapsedStringPart.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/LNumber.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/Encapsed.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/String_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Name/FullyQualified.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Name/Relative.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/MatchArm.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/NullableType.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/UnionType.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Name.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Const_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Param.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Identifier.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation/Alias.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation/Precedence.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Foreach_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Expression.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Return_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/StaticVar.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Function_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Static_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Property.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Finally_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Namespace_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Const_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Global_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Goto_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/UseUse.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUse.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/PropertyProperty.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/For_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Echo_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Declare_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdaptation.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/GroupUse.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Class_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Case_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/InlineHTML.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Switch_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Do_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ElseIf_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Break_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Nop.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Else_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Throw_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Trait_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Catch_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassMethod.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Continue_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/While_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Use_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/DeclareDeclare.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Unset_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TryCatch.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Interface_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/If_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassConst.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/ClassLike.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/Label.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/HaltCompiler.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Yield_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/StaticPropertyFetch.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PostInc.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ErrorSuppress.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Instanceof_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ClosureUse.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/FuncCall.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/New_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrowFunction.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Div.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseXor.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BooleanAnd.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalAnd.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Coalesce.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseOr.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/NotIdentical.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Mod.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Pow.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/ShiftLeft.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalXor.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BooleanOr.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/SmallerOrEqual.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Equal.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/GreaterOrEqual.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Identical.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Minus.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/LogicalOr.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Concat.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Mul.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/BitwiseAnd.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Spaceship.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Plus.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Smaller.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/Greater.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/NotEqual.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp/ShiftRight.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Exit_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PropertyFetch.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BooleanNot.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Div.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseXor.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Coalesce.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseOr.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Mod.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Pow.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/ShiftLeft.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Minus.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Concat.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Mul.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/BitwiseAnd.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/Plus.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp/ShiftRight.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Isset_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Empty_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/MethodCall.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PreInc.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignRef.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ConstFetch.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Assign.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/YieldFrom.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PostDec.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Eval_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Print_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/UnaryMinus.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Ternary.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Match_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Include_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/PreDec.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Int_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Object_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Double.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Bool_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Array_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/String_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast/Unset_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/List_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/NullsafePropertyFetch.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BitwiseNot.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Error.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Variable.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Array_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Throw_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/UnaryPlus.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ClassConstFetch.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/StaticCall.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/NullsafeMethodCall.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Clone_.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Closure.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayItem.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ShellExec.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/ArrayDimFetch.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/FunctionLike.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/AttributeGroup.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Expr.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Attribute.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/Arg.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node/VarLikeIdentifier.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/JsonDecoder.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/NodeConnectingVisitor.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/ParentConnectingVisitor.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/FirstFindingVisitor.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/CloningVisitor.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/FindingVisitor.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor/NameResolver.php'; +require_once __DIR__ . '/vendor/nikic/php-parser/lib/PhpParser/Node.php'; +require_once __DIR__ . '/vendor/symplify/symfony-php-config/src/Exception/ValueObjectException.php'; require_once __DIR__ . '/vendor/symplify/symfony-php-config/src/Reflection/ArgumentAndParameterFactory.php'; require_once __DIR__ . '/vendor/symplify/symfony-php-config/src/ValueObjectInliner.php'; -require_once __DIR__ . '/vendor/symplify/symfony-php-config/src/Exception/ValueObjectException.php'; diff --git a/rules/Arguments/NodeAnalyzer/ArgumentAddingScope.php b/rules/Arguments/NodeAnalyzer/ArgumentAddingScope.php index 444e7e13146..7b6dde88fd6 100644 --- a/rules/Arguments/NodeAnalyzer/ArgumentAddingScope.php +++ b/rules/Arguments/NodeAnalyzer/ArgumentAddingScope.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; } - /** * @param MethodCall|StaticCall $expr */ - public function isInCorrectScope(Expr $expr, ArgumentAdder $argumentAdder): bool + public function isInCorrectScope(\PhpParser\Node\Expr $expr, \Rector\Arguments\ValueObject\ArgumentAdder $argumentAdder) : bool { if ($argumentAdder->getScope() === null) { - return true; + return \true; } - $scope = $argumentAdder->getScope(); - if ($expr instanceof StaticCall) { - if (! $expr->class instanceof Name) { - return false; + if ($expr instanceof \PhpParser\Node\Expr\StaticCall) { + if (!$expr->class instanceof \PhpParser\Node\Name) { + return \false; } - if ($this->nodeNameResolver->isName($expr->class, 'parent')) { return $scope === self::SCOPE_PARENT_CALL; } - return $scope === self::SCOPE_METHOD_CALL; } - // MethodCall return $scope === self::SCOPE_METHOD_CALL; } diff --git a/rules/Arguments/Rector/ClassMethod/ArgumentAdderRector.php b/rules/Arguments/Rector/ClassMethod/ArgumentAdderRector.php index 64dd037df71..f8b48e64c3d 100644 --- a/rules/Arguments/Rector/ClassMethod/ArgumentAdderRector.php +++ b/rules/Arguments/Rector/ClassMethod/ArgumentAdderRector.php @@ -1,7 +1,6 @@ argumentAddingScope = $argumentAddingScope; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - $exampleConfiguration = [ - self::ADDED_ARGUMENTS => [ - new ArgumentAdder('SomeExampleClass', 'someMethod', 0, 'someArgument', true, 'SomeType'), - ], - ]; - - return new RuleDefinition( - 'This Rector adds new default arguments in calls of defined methods and class types.', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + $exampleConfiguration = [self::ADDED_ARGUMENTS => [new \Rector\Arguments\ValueObject\ArgumentAdder('SomeExampleClass', 'someMethod', 0, 'someArgument', \true, 'SomeType')]]; + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('This Rector adds new default arguments in calls of defined methods and class types.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' $someObject = new SomeExampleClass; $someObject->someMethod(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someObject = new SomeExampleClass; $someObject->someMethod(true); CODE_SAMPLE - , - $exampleConfiguration - ), - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' +, $exampleConfiguration), new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class MyCustomClass extends SomeExampleClass { public function someMethod() @@ -85,8 +65,7 @@ class MyCustomClass extends SomeExampleClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class MyCustomClass extends SomeExampleClass { public function someMethod($value = true) @@ -94,175 +73,138 @@ class MyCustomClass extends SomeExampleClass } } CODE_SAMPLE - , - $exampleConfiguration - ), - ] - ); +, $exampleConfiguration)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class, StaticCall::class, ClassMethod::class]; + return [\PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param MethodCall|StaticCall|ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->addedArguments as $addedArgument) { - if (! $this->isObjectTypeMatch($node, $addedArgument->getObjectType())) { + if (!$this->isObjectTypeMatch($node, $addedArgument->getObjectType())) { continue; } - - if (! $this->isName($node->name, $addedArgument->getMethod())) { + if (!$this->isName($node->name, $addedArgument->getMethod())) { continue; } - $this->processPositionWithDefaultValues($node, $addedArgument); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $addedArguments = $configuration[self::ADDED_ARGUMENTS] ?? []; - Assert::allIsInstanceOf($addedArguments, ArgumentAdder::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($addedArguments, \Rector\Arguments\ValueObject\ArgumentAdder::class); $this->addedArguments = $addedArguments; } - /** * @param MethodCall|StaticCall|ClassMethod $node */ - private function isObjectTypeMatch(Node $node, ObjectType $objectType): bool + private function isObjectTypeMatch(\PhpParser\Node $node, \PHPStan\Type\ObjectType $objectType) : bool { - if ($node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { return $this->isObjectType($node->var, $objectType); } - - if ($node instanceof StaticCall) { + if ($node instanceof \PhpParser\Node\Expr\StaticCall) { return $this->isObjectType($node->class, $objectType); } - // ClassMethod /** @var Class_|null $classLike */ - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); // anonymous class - if (! $classLike instanceof Class_) { - return false; + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } - return $this->isObjectType($classLike, $objectType); } - /** * @param ClassMethod|MethodCall|StaticCall $node */ - private function processPositionWithDefaultValues(Node $node, ArgumentAdder $argumentAdder): void + private function processPositionWithDefaultValues(\PhpParser\Node $node, \Rector\Arguments\ValueObject\ArgumentAdder $argumentAdder) : void { if ($this->shouldSkipParameter($node, $argumentAdder)) { return; } - $defaultValue = $argumentAdder->getArgumentDefaultValue(); $argumentType = $argumentAdder->getArgumentType(); - $position = $argumentAdder->getPosition(); - - if ($node instanceof ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { $this->addClassMethodParam($node, $argumentAdder, $defaultValue, $argumentType, $position); - } elseif ($node instanceof StaticCall) { + } elseif ($node instanceof \PhpParser\Node\Expr\StaticCall) { $this->processStaticCall($node, $position, $argumentAdder); } else { - $arg = new Arg(BuilderHelpers::normalizeValue($defaultValue)); + $arg = new \PhpParser\Node\Arg(\PhpParser\BuilderHelpers::normalizeValue($defaultValue)); if (isset($node->args[$position])) { return; } - $node->args[$position] = $arg; } } - /** * @param ClassMethod|MethodCall|StaticCall $node */ - private function shouldSkipParameter(Node $node, ArgumentAdder $argumentAdder): bool + private function shouldSkipParameter(\PhpParser\Node $node, \Rector\Arguments\ValueObject\ArgumentAdder $argumentAdder) : bool { $position = $argumentAdder->getPosition(); $argumentName = $argumentAdder->getArgumentName(); - if ($argumentName === null) { - return true; + return \true; } - - if ($node instanceof ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { // already added? - if (! isset($node->params[$position])) { - return false; + if (!isset($node->params[$position])) { + return \false; } - return $this->isName($node->params[$position], $argumentName); } - // already added? - if (! isset($node->args[$position])) { + if (!isset($node->args[$position])) { // is correct scope? - return ! $this->argumentAddingScope->isInCorrectScope($node, $argumentAdder); + return !$this->argumentAddingScope->isInCorrectScope($node, $argumentAdder); } - if (! $this->isName($node->args[$position], $argumentName)) { + if (!$this->isName($node->args[$position], $argumentName)) { // is correct scope? - return ! $this->argumentAddingScope->isInCorrectScope($node, $argumentAdder); + return !$this->argumentAddingScope->isInCorrectScope($node, $argumentAdder); } - return true; + return \true; } - /** * @param mixed $defaultValue */ - private function addClassMethodParam( - ClassMethod $classMethod, - ArgumentAdder $argumentAdder, - $defaultValue, - ?string $type, - int $position - ): void { - $argumentName = $argumentAdder->getArgumentName(); - if ($argumentName === null) { - throw new ShouldNotHappenException(); - } - - $param = new Param(new Variable($argumentName), BuilderHelpers::normalizeValue($defaultValue)); - if ($type) { - $param->type = ctype_upper($type[0]) ? new FullyQualified($type) : new Identifier($type); - } - - $classMethod->params[$position] = $param; - } - - private function processStaticCall(StaticCall $staticCall, int $position, ArgumentAdder $argumentAdder): void + private function addClassMethodParam(\PhpParser\Node\Stmt\ClassMethod $classMethod, \Rector\Arguments\ValueObject\ArgumentAdder $argumentAdder, $defaultValue, ?string $type, int $position) : void { $argumentName = $argumentAdder->getArgumentName(); if ($argumentName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - if (! $staticCall->class instanceof Name) { + $param = new \PhpParser\Node\Param(new \PhpParser\Node\Expr\Variable($argumentName), \PhpParser\BuilderHelpers::normalizeValue($defaultValue)); + if ($type) { + $param->type = \ctype_upper($type[0]) ? new \PhpParser\Node\Name\FullyQualified($type) : new \PhpParser\Node\Identifier($type); + } + $classMethod->params[$position] = $param; + } + private function processStaticCall(\PhpParser\Node\Expr\StaticCall $staticCall, int $position, \Rector\Arguments\ValueObject\ArgumentAdder $argumentAdder) : void + { + $argumentName = $argumentAdder->getArgumentName(); + if ($argumentName === null) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); + } + if (!$staticCall->class instanceof \PhpParser\Node\Name) { return; } - - if (! $this->isName($staticCall->class, 'parent')) { + if (!$this->isName($staticCall->class, 'parent')) { return; } - - $staticCall->args[$position] = new Arg(new Variable($argumentName)); + $staticCall->args[$position] = new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\Variable($argumentName)); } } diff --git a/rules/Arguments/Rector/ClassMethod/ArgumentDefaultValueReplacerRector.php b/rules/Arguments/Rector/ClassMethod/ArgumentDefaultValueReplacerRector.php index 7b2f53df04e..3e13ca65d9f 100644 --- a/rules/Arguments/Rector/ClassMethod/ArgumentDefaultValueReplacerRector.php +++ b/rules/Arguments/Rector/ClassMethod/ArgumentDefaultValueReplacerRector.php @@ -1,10 +1,9 @@ someMethod(SomeClass::OLD_CONSTANT); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someObject = new SomeClass; $someObject->someMethod(false);' CODE_SAMPLE - , - [ - self::REPLACED_ARGUMENTS => [ - new ArgumentDefaultValueReplacer( - 'SomeExampleClass', - 'someMethod', - 0, - 'SomeClass::OLD_CONSTANT', - false - ), - ], - ] - ), - ] - ); +, [self::REPLACED_ARGUMENTS => [new \Rector\Arguments\ValueObject\ArgumentDefaultValueReplacer('SomeExampleClass', 'someMethod', 0, 'SomeClass::OLD_CONSTANT', \false)]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class, StaticCall::class, ClassMethod::class]; + return [\PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param MethodCall|StaticCall|ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->replacedArguments as $replacedArgument) { - if (! $this->nodeTypeResolver->isMethodStaticCallOrClassMethodObjectType( - $node, - $replacedArgument->getObjectType() - )) { + if (!$this->nodeTypeResolver->isMethodStaticCallOrClassMethodObjectType($node, $replacedArgument->getObjectType())) { continue; } - - if (! $this->isName($node->name, $replacedArgument->getMethod())) { + if (!$this->isName($node->name, $replacedArgument->getMethod())) { continue; } - $this->processReplaces($node, $replacedArgument); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $replacedArguments = $configuration[self::REPLACED_ARGUMENTS] ?? []; - Assert::allIsInstanceOf($replacedArguments, ArgumentDefaultValueReplacer::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($replacedArguments, \Rector\Arguments\ValueObject\ArgumentDefaultValueReplacer::class); $this->replacedArguments = $replacedArguments; } - /** * @param MethodCall|StaticCall|ClassMethod $node */ - private function processReplaces(Node $node, ArgumentDefaultValueReplacer $argumentDefaultValueReplacer): ?Node + private function processReplaces(\PhpParser\Node $node, \Rector\Arguments\ValueObject\ArgumentDefaultValueReplacer $argumentDefaultValueReplacer) : ?\PhpParser\Node { - if ($node instanceof ClassMethod) { - if (! isset($node->params[$argumentDefaultValueReplacer->getPosition()])) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { + if (!isset($node->params[$argumentDefaultValueReplacer->getPosition()])) { return null; } } elseif (isset($node->args[$argumentDefaultValueReplacer->getPosition()])) { $this->processArgs($node, $argumentDefaultValueReplacer); } - return $node; } - /** * @param MethodCall|StaticCall $expr */ - private function processArgs(Expr $expr, ArgumentDefaultValueReplacer $argumentDefaultValueReplacer): void + private function processArgs(\PhpParser\Node\Expr $expr, \Rector\Arguments\ValueObject\ArgumentDefaultValueReplacer $argumentDefaultValueReplacer) : void { $position = $argumentDefaultValueReplacer->getPosition(); - $argValue = $this->valueResolver->getValue($expr->args[$position]->value); - - if (is_scalar( - $argumentDefaultValueReplacer->getValueBefore() - ) && $argValue === $argumentDefaultValueReplacer->getValueBefore()) { + if (\is_scalar($argumentDefaultValueReplacer->getValueBefore()) && $argValue === $argumentDefaultValueReplacer->getValueBefore()) { $expr->args[$position] = $this->normalizeValueToArgument($argumentDefaultValueReplacer->getValueAfter()); - } elseif (is_array($argumentDefaultValueReplacer->getValueBefore())) { + } elseif (\is_array($argumentDefaultValueReplacer->getValueBefore())) { $newArgs = $this->processArrayReplacement($expr->args, $argumentDefaultValueReplacer); - if ($newArgs) { $expr->args = $newArgs; } } } - /** * @param mixed $value */ - private function normalizeValueToArgument($value): Arg + private function normalizeValueToArgument($value) : \PhpParser\Node\Arg { // class constants → turn string to composite - if (is_string($value) && Strings::contains($value, '::')) { - [$class, $constant] = explode('::', $value); + if (\is_string($value) && \RectorPrefix20210509\Nette\Utils\Strings::contains($value, '::')) { + [$class, $constant] = \explode('::', $value); $classConstFetch = $this->nodeFactory->createClassConstFetch($class, $constant); - - return new Arg($classConstFetch); + return new \PhpParser\Node\Arg($classConstFetch); } - - return new Arg(BuilderHelpers::normalizeValue($value)); + return new \PhpParser\Node\Arg(\PhpParser\BuilderHelpers::normalizeValue($value)); } - /** * @param Arg[] $argumentNodes * @return Arg[]|null */ - private function processArrayReplacement( - array $argumentNodes, - ArgumentDefaultValueReplacer $argumentDefaultValueReplacer - ): ?array { + private function processArrayReplacement(array $argumentNodes, \Rector\Arguments\ValueObject\ArgumentDefaultValueReplacer $argumentDefaultValueReplacer) : ?array + { $argumentValues = $this->resolveArgumentValuesToBeforeRecipe($argumentNodes, $argumentDefaultValueReplacer); if ($argumentValues !== $argumentDefaultValueReplacer->getValueBefore()) { return null; } - - if (is_string($argumentDefaultValueReplacer->getValueAfter())) { - $argumentNodes[$argumentDefaultValueReplacer->getPosition()] = $this->normalizeValueToArgument( - $argumentDefaultValueReplacer->getValueAfter() - ); - + if (\is_string($argumentDefaultValueReplacer->getValueAfter())) { + $argumentNodes[$argumentDefaultValueReplacer->getPosition()] = $this->normalizeValueToArgument($argumentDefaultValueReplacer->getValueAfter()); // clear following arguments - $argumentCountToClear = count($argumentDefaultValueReplacer->getValueBefore()); + $argumentCountToClear = \count($argumentDefaultValueReplacer->getValueBefore()); for ($i = $argumentDefaultValueReplacer->getPosition() + 1; $i <= $argumentDefaultValueReplacer->getPosition() + $argumentCountToClear; ++$i) { unset($argumentNodes[$i]); } } - return $argumentNodes; } - /** * @param Arg[] $argumentNodes * @return mixed[] */ - private function resolveArgumentValuesToBeforeRecipe( - array $argumentNodes, - ArgumentDefaultValueReplacer $argumentDefaultValueReplacer - ): array { + private function resolveArgumentValuesToBeforeRecipe(array $argumentNodes, \Rector\Arguments\ValueObject\ArgumentDefaultValueReplacer $argumentDefaultValueReplacer) : array + { $argumentValues = []; - /** @var mixed[] $valueBefore */ $valueBefore = $argumentDefaultValueReplacer->getValueBefore(); - $beforeArgumentCount = count($valueBefore); - + $beforeArgumentCount = \count($valueBefore); for ($i = 0; $i < $beforeArgumentCount; ++$i) { - if (! isset($argumentNodes[$argumentDefaultValueReplacer->getPosition() + $i])) { + if (!isset($argumentNodes[$argumentDefaultValueReplacer->getPosition() + $i])) { continue; } - $nextArg = $argumentNodes[$argumentDefaultValueReplacer->getPosition() + $i]; $argumentValues[] = $this->valueResolver->getValue($nextArg->value); } - return $argumentValues; } } diff --git a/rules/Arguments/Rector/FuncCall/SwapFuncCallArgumentsRector.php b/rules/Arguments/Rector/FuncCall/SwapFuncCallArgumentsRector.php index 5a1b5ab3497..709eeb8de28 100644 --- a/rules/Arguments/Rector/FuncCall/SwapFuncCallArgumentsRector.php +++ b/rules/Arguments/Rector/FuncCall/SwapFuncCallArgumentsRector.php @@ -1,7 +1,6 @@ [new SwapFuncCallArguments('some_function', [1, 0])], - ] - ), - ]); +, [self::FUNCTION_ARGUMENT_SWAPS => [new \Rector\Arguments\ValueObject\SwapFuncCallArguments('some_function', [1, 0])]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->functionArgumentSwaps as $functionArgumentSwap) { - if (! $this->isName($node, $functionArgumentSwap->getFunction())) { + if (!$this->isName($node, $functionArgumentSwap->getFunction())) { continue; } - $newArguments = []; foreach ($functionArgumentSwap->getOrder() as $oldPosition => $newPosition) { - if (! isset($node->args[$oldPosition])) { + if (!isset($node->args[$oldPosition])) { continue; } - if (! isset($node->args[$newPosition])) { + if (!isset($node->args[$newPosition])) { continue; } $newArguments[$newPosition] = $node->args[$oldPosition]; } - foreach ($newArguments as $newPosition => $argument) { $node->args[$newPosition] = $argument; } } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $functionArgumentSwaps = $configuration[self::FUNCTION_ARGUMENT_SWAPS] ?? []; - Assert::allIsInstanceOf($functionArgumentSwaps, SwapFuncCallArguments::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($functionArgumentSwaps, \Rector\Arguments\ValueObject\SwapFuncCallArguments::class); $this->functionArgumentSwaps = $functionArgumentSwaps; } } diff --git a/rules/Arguments/Rector/MethodCall/ValueObjectWrapArgRector.php b/rules/Arguments/Rector/MethodCall/ValueObjectWrapArgRector.php index b51b37a3486..18e3f29eb23 100644 --- a/rules/Arguments/Rector/MethodCall/ValueObjectWrapArgRector.php +++ b/rules/Arguments/Rector/MethodCall/ValueObjectWrapArgRector.php @@ -1,7 +1,6 @@ [new ValueObjectWrapArg('SomeClass', 'someMethod', 0, 'Number')], - ] - ), - ]); +, [self::VALUE_OBJECT_WRAP_ARGS => [new \Rector\Arguments\ValueObject\ValueObjectWrapArg('SomeClass', 'someMethod', 0, 'Number')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->valueObjectWrapArgs as $valueObjectWrapArg) { $desiredArg = $this->matchArg($node, $valueObjectWrapArg); - if (! $desiredArg instanceof Arg) { + if (!$desiredArg instanceof \PhpParser\Node\Arg) { continue; } - $argValue = $desiredArg->value; $argValueType = $this->getStaticType($argValue); - $newObjectType = $valueObjectWrapArg->getNewType(); if ($newObjectType->isSuperTypeOf($argValueType)->yes()) { continue; } - - if ($argValueType instanceof ConstantArrayType) { + if ($argValueType instanceof \PHPStan\Type\Constant\ConstantArrayType) { return $this->refactorArray($desiredArg, $newObjectType, $node); } - $value = $desiredArg->value; - $desiredArg->value = new New_(new FullyQualified($newObjectType->getClassName()), [new Arg($value)]); - + $desiredArg->value = new \PhpParser\Node\Expr\New_(new \PhpParser\Node\Name\FullyQualified($newObjectType->getClassName()), [new \PhpParser\Node\Arg($value)]); return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->valueObjectWrapArgs = $configuration[self::VALUE_OBJECT_WRAP_ARGS] ?? []; } - - private function wrapInNewWithType(ObjectType $newObjectType, Expr $expr): New_ + private function wrapInNewWithType(\PHPStan\Type\ObjectType $newObjectType, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\New_ { - $fullyQualified = new FullyQualified($newObjectType->getClassName()); - return new New_($fullyQualified, [new Arg($expr)]); + $fullyQualified = new \PhpParser\Node\Name\FullyQualified($newObjectType->getClassName()); + return new \PhpParser\Node\Expr\New_($fullyQualified, [new \PhpParser\Node\Arg($expr)]); } - - private function refactorArray(Arg $desiredArg, ObjectType $newObjectType, MethodCall $methodCall): ?MethodCall + private function refactorArray(\PhpParser\Node\Arg $desiredArg, \PHPStan\Type\ObjectType $newObjectType, \PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node\Expr\MethodCall { - if ($desiredArg->value instanceof Array_) { + if ($desiredArg->value instanceof \PhpParser\Node\Expr\Array_) { foreach ($desiredArg->value->items as $arrayItem) { - if (! $arrayItem instanceof ArrayItem) { + if (!$arrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - $arrayItem->value = $this->wrapInNewWithType($newObjectType, $arrayItem->value); } - return $methodCall; } - return null; } - - private function matchArg(MethodCall $methodCall, ValueObjectWrapArg $valueObjectWrapArg): ?Arg + private function matchArg(\PhpParser\Node\Expr\MethodCall $methodCall, \Rector\Arguments\ValueObject\ValueObjectWrapArg $valueObjectWrapArg) : ?\PhpParser\Node\Arg { - if (! $this->isObjectType($methodCall->var, $valueObjectWrapArg->getObjectType())) { + if (!$this->isObjectType($methodCall->var, $valueObjectWrapArg->getObjectType())) { return null; } - - if (! $this->isName($methodCall->name, $valueObjectWrapArg->getMethodName())) { + if (!$this->isName($methodCall->name, $valueObjectWrapArg->getMethodName())) { return null; } - return $methodCall->args[$valueObjectWrapArg->getArgPosition()] ?? null; } } diff --git a/rules/Arguments/ValueObject/ArgumentAdder.php b/rules/Arguments/ValueObject/ArgumentAdder.php index 6001b82c602..4e9a40739cc 100644 --- a/rules/Arguments/ValueObject/ArgumentAdder.php +++ b/rules/Arguments/ValueObject/ArgumentAdder.php @@ -1,60 +1,44 @@ class = $class; $this->method = $method; $this->position = $position; @@ -63,27 +47,22 @@ final class ArgumentAdder $this->argumentType = $argumentType; $this->scope = $scope; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } - - public function getPosition(): int + public function getPosition() : int { return $this->position; } - - public function getArgumentName(): ?string + public function getArgumentName() : ?string { return $this->argumentName; } - /** * @return mixed|null */ @@ -91,13 +70,11 @@ final class ArgumentAdder { return $this->argumentDefaultValue; } - - public function getArgumentType(): ?string + public function getArgumentType() : ?string { return $this->argumentType; } - - public function getScope(): ?string + public function getScope() : ?string { return $this->scope; } diff --git a/rules/Arguments/ValueObject/ArgumentDefaultValueReplacer.php b/rules/Arguments/ValueObject/ArgumentDefaultValueReplacer.php index 0f70a5d4685..42729384502 100644 --- a/rules/Arguments/ValueObject/ArgumentDefaultValueReplacer.php +++ b/rules/Arguments/ValueObject/ArgumentDefaultValueReplacer.php @@ -1,38 +1,31 @@ valueBefore = $valueBefore; $this->valueAfter = $valueAfter; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } - - public function getPosition(): int + public function getPosition() : int { return $this->position; } - /** * @return mixed */ @@ -68,7 +57,6 @@ final class ArgumentDefaultValueReplacer { return $this->valueBefore; } - /** * @return mixed */ diff --git a/rules/Arguments/ValueObject/SwapFuncCallArguments.php b/rules/Arguments/ValueObject/SwapFuncCallArguments.php index 0ff4e123c13..815b9fb92c6 100644 --- a/rules/Arguments/ValueObject/SwapFuncCallArguments.php +++ b/rules/Arguments/ValueObject/SwapFuncCallArguments.php @@ -1,7 +1,6 @@ */ private $order = []; - /** * @param array $order */ @@ -24,16 +21,14 @@ final class SwapFuncCallArguments $this->function = $function; $this->order = $order; } - - public function getFunction(): string + public function getFunction() : string { return $this->function; } - /** * @return array */ - public function getOrder(): array + public function getOrder() : array { return $this->order; } diff --git a/rules/Arguments/ValueObject/ValueObjectWrapArg.php b/rules/Arguments/ValueObject/ValueObjectWrapArg.php index a03b1acf846..3ef7a81d419 100644 --- a/rules/Arguments/ValueObject/ValueObjectWrapArg.php +++ b/rules/Arguments/ValueObject/ValueObjectWrapArg.php @@ -1,33 +1,27 @@ objectType = $objectType; @@ -35,24 +29,20 @@ final class ValueObjectWrapArg $this->argPosition = $argPosition; $this->newType = $newType; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->objectType); + return new \PHPStan\Type\ObjectType($this->objectType); } - - public function getMethodName(): string + public function getMethodName() : string { return $this->methodName; } - - public function getArgPosition(): int + public function getArgPosition() : int { return $this->argPosition; } - - public function getNewType(): ObjectType + public function getNewType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->newType); + return new \PHPStan\Type\ObjectType($this->newType); } } diff --git a/rules/Autodiscovery/Analyzer/ValueObjectClassAnalyzer.php b/rules/Autodiscovery/Analyzer/ValueObjectClassAnalyzer.php index b1c00f1531b..58fb391e877 100644 --- a/rules/Autodiscovery/Analyzer/ValueObjectClassAnalyzer.php +++ b/rules/Autodiscovery/Analyzer/ValueObjectClassAnalyzer.php @@ -1,7 +1,6 @@ */ private $valueObjectStatusByClassName = []; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var NodeTypeResolver */ private $nodeTypeResolver; - /** * @var PhpDocInfoFactory */ private $phpDocInfoFactory; - /** * @var NodeRepository */ private $nodeRepository; - /** * @var ClassAnalyzer */ private $classAnalyzer; - - public function __construct( - NodeNameResolver $nodeNameResolver, - NodeTypeResolver $nodeTypeResolver, - PhpDocInfoFactory $phpDocInfoFactory, - NodeRepository $nodeRepository, - ClassAnalyzer $classAnalyzer - ) { + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory $phpDocInfoFactory, \Rector\NodeCollector\NodeCollector\NodeRepository $nodeRepository, \Rector\Core\NodeAnalyzer\ClassAnalyzer $classAnalyzer) + { $this->nodeNameResolver = $nodeNameResolver; $this->nodeTypeResolver = $nodeTypeResolver; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->nodeRepository = $nodeRepository; $this->classAnalyzer = $classAnalyzer; } - - public function isValueObjectClass(Class_ $class): bool + public function isValueObjectClass(\PhpParser\Node\Stmt\Class_ $class) : bool { if ($this->classAnalyzer->isAnonymousClass($class)) { - return false; + return \false; } - /** @var string $className */ $className = $this->nodeNameResolver->getName($class); - if (isset($this->valueObjectStatusByClassName[$className])) { return $this->valueObjectStatusByClassName[$className]; } - - $constructClassMethod = $class->getMethod(MethodName::CONSTRUCT); - - if (! $constructClassMethod instanceof ClassMethod) { + $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return $this->analyseWithoutConstructor($class, $className); } - // resolve constructor types foreach ($constructClassMethod->params as $param) { $paramType = $this->nodeTypeResolver->resolve($param); - if (! $paramType instanceof ObjectType) { + if (!$paramType instanceof \PHPStan\Type\ObjectType) { continue; } - // awesome! // is it services or value object? $paramTypeClass = $this->nodeRepository->findClass($paramType->getClassName()); - if (! $paramTypeClass instanceof Class_) { + if (!$paramTypeClass instanceof \PhpParser\Node\Stmt\Class_) { // not sure :/ continue; } - - if (! $this->isValueObjectClass($paramTypeClass)) { - return false; + if (!$this->isValueObjectClass($paramTypeClass)) { + return \false; } } - // if we didn't prove it's not a value object so far → fallback to true - $this->valueObjectStatusByClassName[$className] = true; - - return true; + $this->valueObjectStatusByClassName[$className] = \true; + return \true; } - - private function analyseWithoutConstructor(Class_ $class, string $className): bool + private function analyseWithoutConstructor(\PhpParser\Node\Stmt\Class_ $class, string $className) : bool { // A. has all properties with serialize? if ($this->hasAllPropertiesWithSerialize($class)) { - $this->valueObjectStatusByClassName[$className] = true; - return true; + $this->valueObjectStatusByClassName[$className] = \true; + return \true; } - // probably not a value object - $this->valueObjectStatusByClassName[$className] = false; - return false; + $this->valueObjectStatusByClassName[$className] = \false; + return \false; } - - private function hasAllPropertiesWithSerialize(Class_ $class): bool + private function hasAllPropertiesWithSerialize(\PhpParser\Node\Stmt\Class_ $class) : bool { foreach ($class->getProperties() as $property) { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); - if ($phpDocInfo->hasByAnnotationClass('JMS\Serializer\Annotation\Type')) { + if ($phpDocInfo->hasByAnnotationClass('JMS\\Serializer\\Annotation\\Type')) { continue; } - - return false; + return \false; } - - return true; + return \true; } } diff --git a/rules/Autodiscovery/Configuration/CategoryNamespaceProvider.php b/rules/Autodiscovery/Configuration/CategoryNamespaceProvider.php index 4e1f017c741..f912d203676 100644 --- a/rules/Autodiscovery/Configuration/CategoryNamespaceProvider.php +++ b/rules/Autodiscovery/Configuration/CategoryNamespaceProvider.php @@ -1,7 +1,6 @@ doctrineDocBlockResolver = $doctrineDocBlockResolver; $this->addedFileWithNodesFactory = $addedFileWithNodesFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Move entities to Entity namespace', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Move entities to Entity namespace', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' // file: app/Controller/Product.php namespace App\Controller; @@ -63,8 +53,7 @@ class Product { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' // file: app/Entity/Product.php namespace App\Entity; @@ -78,46 +67,34 @@ class Product { } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->doctrineDocBlockResolver->isDoctrineEntityClass($node)) { + if (!$this->doctrineDocBlockResolver->isDoctrineEntityClass($node)) { return null; } - // is entity in expected directory? $smartFileInfo = $this->file->getSmartFileInfo(); - if (Strings::match($smartFileInfo->getRealPath(), self::ENTITY_PATH_REGEX)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($smartFileInfo->getRealPath(), self::ENTITY_PATH_REGEX)) { return null; } - - $addedFileWithNodes = $this->addedFileWithNodesFactory->createWithDesiredGroup( - $smartFileInfo, - $this->file, - 'Entity' - ); - - if (! $addedFileWithNodes instanceof AddedFileWithNodes) { + $addedFileWithNodes = $this->addedFileWithNodesFactory->createWithDesiredGroup($smartFileInfo, $this->file, 'Entity'); + if (!$addedFileWithNodes instanceof \Rector\FileSystemRector\ValueObject\AddedFileWithNodes) { return null; } - $this->removedAndAddedFilesCollector->removeFile($smartFileInfo); $this->removedAndAddedFilesCollector->addAddedFile($addedFileWithNodes); - return null; } } diff --git a/rules/Autodiscovery/Rector/Class_/MoveServicesBySuffixToDirectoryRector.php b/rules/Autodiscovery/Rector/Class_/MoveServicesBySuffixToDirectoryRector.php index d3a616c8413..b137cc28746 100644 --- a/rules/Autodiscovery/Rector/Class_/MoveServicesBySuffixToDirectoryRector.php +++ b/rules/Autodiscovery/Rector/Class_/MoveServicesBySuffixToDirectoryRector.php @@ -1,10 +1,9 @@ expectedFileLocationResolver = $expectedFileLocationResolver; $this->addedFileWithNodesFactory = $addedFileWithNodesFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Move classes by their suffix to their own group/directory', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Move classes by their suffix to their own group/directory', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' // file: app/Entity/ProductRepository.php namespace App/Entity; @@ -66,8 +55,7 @@ class ProductRepository { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' // file: app/Repository/ProductRepository.php namespace App/Repository; @@ -76,43 +64,32 @@ class ProductRepository { } CODE_SAMPLE - , - [ - self::GROUP_NAMES_BY_SUFFIX => ['Repository'], - ] - ), - ]); +, [self::GROUP_NAMES_BY_SUFFIX => ['Repository']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $this->processGroupNamesBySuffix($this->file->getSmartFileInfo(), $this->file, $this->groupNamesBySuffix); - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $groupNamesBySuffix = $configuration[self::GROUP_NAMES_BY_SUFFIX] ?? []; - Assert::allString($groupNamesBySuffix); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allString($groupNamesBySuffix); $this->groupNamesBySuffix = $groupNamesBySuffix; } - /** * A. Match classes by suffix and move them to group namespace * @@ -122,54 +99,36 @@ CODE_SAMPLE * * @param string[] $groupNamesBySuffix */ - private function processGroupNamesBySuffix( - SmartFileInfo $smartFileInfo, - File $file, - array $groupNamesBySuffix - ): void { + private function processGroupNamesBySuffix(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo, \Rector\Core\ValueObject\Application\File $file, array $groupNamesBySuffix) : void + { foreach ($groupNamesBySuffix as $groupNames) { // has class suffix - $suffixPattern = '\w+' . $groupNames . '(Test)?\.php$'; - if (! Strings::match($smartFileInfo->getRealPath(), '#' . $suffixPattern . '#')) { + $suffixPattern = '\\w+' . $groupNames . '(Test)?\\.php$'; + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($smartFileInfo->getRealPath(), '#' . $suffixPattern . '#')) { continue; } - if ($this->isLocatedInExpectedLocation($groupNames, $suffixPattern, $smartFileInfo)) { continue; } - // file is already in the group - if (Strings::match($smartFileInfo->getPath(), '#' . $groupNames . '$#')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($smartFileInfo->getPath(), '#' . $groupNames . '$#')) { continue; } - $this->moveFileToGroupName($smartFileInfo, $this->file, $groupNames); return; } } - - private function isLocatedInExpectedLocation( - string $groupName, - string $suffixPattern, - SmartFileInfo $smartFileInfo - ): bool { - $expectedLocationFilePattern = $this->expectedFileLocationResolver->resolve($groupName, $suffixPattern); - - return (bool) Strings::match($smartFileInfo->getRealPath(), $expectedLocationFilePattern); - } - - private function moveFileToGroupName(SmartFileInfo $fileInfo, File $file, string $desiredGroupName): void + private function isLocatedInExpectedLocation(string $groupName, string $suffixPattern, \Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : bool { - $addedFileWithNodes = $this->addedFileWithNodesFactory->createWithDesiredGroup( - $fileInfo, - $this->file, - $desiredGroupName - ); - - if (! $addedFileWithNodes instanceof AddedFileWithNodes) { + $expectedLocationFilePattern = $this->expectedFileLocationResolver->resolve($groupName, $suffixPattern); + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($smartFileInfo->getRealPath(), $expectedLocationFilePattern); + } + private function moveFileToGroupName(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo, \Rector\Core\ValueObject\Application\File $file, string $desiredGroupName) : void + { + $addedFileWithNodes = $this->addedFileWithNodesFactory->createWithDesiredGroup($fileInfo, $this->file, $desiredGroupName); + if (!$addedFileWithNodes instanceof \Rector\FileSystemRector\ValueObject\AddedFileWithNodes) { return; } - $this->removedAndAddedFilesCollector->removeFile($fileInfo); $this->removedAndAddedFilesCollector->addAddedFile($addedFileWithNodes); } diff --git a/rules/Autodiscovery/Rector/Class_/MoveValueObjectsToValueObjectDirectoryRector.php b/rules/Autodiscovery/Rector/Class_/MoveValueObjectsToValueObjectDirectoryRector.php index 9177c6eb288..d221aefe60d 100644 --- a/rules/Autodiscovery/Rector/Class_/MoveValueObjectsToValueObjectDirectoryRector.php +++ b/rules/Autodiscovery/Rector/Class_/MoveValueObjectsToValueObjectDirectoryRector.php @@ -1,11 +1,10 @@ [] */ - private const COMMON_SERVICE_SUFFIXES = [ - 'Repository', 'Command', 'Mapper', 'Controller', 'Presenter', 'Factory', 'Test', 'TestCase', 'Service', - ]; - + private const COMMON_SERVICE_SUFFIXES = ['Repository', 'Command', 'Mapper', 'Controller', 'Presenter', 'Factory', 'Test', 'TestCase', 'Service']; /** * @var bool */ - private $enableValueObjectGuessing = true; - + private $enableValueObjectGuessing = \true; /** * @var class-string[] */ private $types = []; - /** * @var string[] */ private $suffixes = []; - /** * @var AddedFileWithNodesFactory */ private $addedFileWithNodesFactory; - /** * @var ValueObjectClassAnalyzer */ private $valueObjectClassAnalyzer; - - public function __construct( - AddedFileWithNodesFactory $addedFileWithNodesFactory, - ValueObjectClassAnalyzer $valueObjectClassAnalyzer - ) { + public function __construct(\Rector\FileSystemRector\ValueObjectFactory\AddedFileWithNodesFactory $addedFileWithNodesFactory, \Rector\Autodiscovery\Analyzer\ValueObjectClassAnalyzer $valueObjectClassAnalyzer) + { $this->addedFileWithNodesFactory = $addedFileWithNodesFactory; $this->valueObjectClassAnalyzer = $valueObjectClassAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Move value object to ValueObject namespace/directory', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Move value object to ValueObject namespace/directory', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' // app/Exception/Name.php class Name { @@ -103,8 +85,7 @@ class Name } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' // app/ValueObject/Name.php class Name { @@ -121,116 +102,85 @@ class Name } } CODE_SAMPLE - , - [ - self::TYPES => ['ValueObjectInterfaceClassName'], - self::SUFFIXES => ['Search'], - self::ENABLE_VALUE_OBJECT_GUESSING => true, - ] - ), - ]); +, [self::TYPES => ['ValueObjectInterfaceClassName'], self::SUFFIXES => ['Search'], self::ENABLE_VALUE_OBJECT_GUESSING => \true])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isValueObjectMatch($node)) { + if (!$this->isValueObjectMatch($node)) { return null; } - $smartFileInfo = $this->file->getSmartFileInfo(); - - $addedFileWithNodes = $this->addedFileWithNodesFactory->createWithDesiredGroup( - $smartFileInfo, - $this->file, - 'ValueObject' - ); - - if (! $addedFileWithNodes instanceof AddedFileWithNodes) { + $addedFileWithNodes = $this->addedFileWithNodesFactory->createWithDesiredGroup($smartFileInfo, $this->file, 'ValueObject'); + if (!$addedFileWithNodes instanceof \Rector\FileSystemRector\ValueObject\AddedFileWithNodes) { return null; } - $this->removedAndAddedFilesCollector->removeFile($smartFileInfo); $this->removedAndAddedFilesCollector->addAddedFile($addedFileWithNodes); - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->types = $configuration[self::TYPES] ?? []; $this->suffixes = $configuration[self::SUFFIXES] ?? []; - $this->enableValueObjectGuessing = $configuration[self::ENABLE_VALUE_OBJECT_GUESSING] ?? false; + $this->enableValueObjectGuessing = $configuration[self::ENABLE_VALUE_OBJECT_GUESSING] ?? \false; } - - private function isValueObjectMatch(Class_ $class): bool + private function isValueObjectMatch(\PhpParser\Node\Stmt\Class_ $class) : bool { if ($this->isSuffixMatch($class)) { - return true; + return \true; } - $className = $this->getName($class); if ($className === null) { - return false; + return \false; } - - $classObjectType = new ObjectType($className); - + $classObjectType = new \PHPStan\Type\ObjectType($className); foreach ($this->types as $type) { - $desiredObjectType = new ObjectType($type); + $desiredObjectType = new \PHPStan\Type\ObjectType($type); if ($desiredObjectType->isSuperTypeOf($classObjectType)->yes()) { - return true; + return \true; } } - if ($this->isKnownServiceType($className)) { - return false; + return \false; } - - if (! $this->enableValueObjectGuessing) { - return false; + if (!$this->enableValueObjectGuessing) { + return \false; } - return $this->valueObjectClassAnalyzer->isValueObjectClass($class); } - - private function isSuffixMatch(Class_ $class): bool + private function isSuffixMatch(\PhpParser\Node\Stmt\Class_ $class) : bool { - $className = $class->getAttribute(AttributeKey::CLASS_NAME); + $className = $class->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { - return false; + return \false; } - foreach ($this->suffixes as $suffix) { - if (Strings::endsWith($className, $suffix)) { - return true; + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($className, $suffix)) { + return \true; } } - - return false; + return \false; } - - private function isKnownServiceType(string $className): bool + private function isKnownServiceType(string $className) : bool { foreach (self::COMMON_SERVICE_SUFFIXES as $commonServiceSuffix) { - if (Strings::endsWith($className, $commonServiceSuffix)) { - return true; + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($className, $commonServiceSuffix)) { + return \true; } } - - return false; + return \false; } } diff --git a/rules/Autodiscovery/Rector/Interface_/MoveInterfacesToContractNamespaceDirectoryRector.php b/rules/Autodiscovery/Rector/Interface_/MoveInterfacesToContractNamespaceDirectoryRector.php index 7672e296976..305076dc1b0 100644 --- a/rules/Autodiscovery/Rector/Interface_/MoveInterfacesToContractNamespaceDirectoryRector.php +++ b/rules/Autodiscovery/Rector/Interface_/MoveInterfacesToContractNamespaceDirectoryRector.php @@ -1,7 +1,6 @@ netteControlFactoryInterfaceAnalyzer = $netteControlFactoryInterfaceAnalyzer; $this->addedFileWithNodesFactory = $addedFileWithNodesFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Move interface to "Contract" namespace', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Move interface to "Contract" namespace', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' // file: app/Exception/Rule.php namespace App\Exception; @@ -51,8 +42,7 @@ interface Rule { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' // file: app/Contract/Rule.php namespace App\Contract; @@ -61,40 +51,29 @@ interface Rule { } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Interface_::class]; + return [\PhpParser\Node\Stmt\Interface_::class]; } - /** * @param Interface_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->netteControlFactoryInterfaceAnalyzer->isComponentFactoryInterface($node)) { return null; } - - $addedFileWithNodes = $this->addedFileWithNodesFactory->createWithDesiredGroup( - $this->file->getSmartFileInfo(), - $this->file, - 'Contract' - ); - - if (! $addedFileWithNodes instanceof AddedFileWithNodes) { + $addedFileWithNodes = $this->addedFileWithNodesFactory->createWithDesiredGroup($this->file->getSmartFileInfo(), $this->file, 'Contract'); + if (!$addedFileWithNodes instanceof \Rector\FileSystemRector\ValueObject\AddedFileWithNodes) { return null; } - $this->removedAndAddedFilesCollector->removeFile($this->file->getSmartFileInfo()); $this->removedAndAddedFilesCollector->addAddedFile($addedFileWithNodes); - return null; } } diff --git a/rules/Carbon/Rector/MethodCall/ChangeCarbonSingularMethodCallToPluralRector.php b/rules/Carbon/Rector/MethodCall/ChangeCarbonSingularMethodCallToPluralRector.php index 6ee60fbf053..db1eff906bd 100644 --- a/rules/Carbon/Rector/MethodCall/ChangeCarbonSingularMethodCallToPluralRector.php +++ b/rules/Carbon/Rector/MethodCall/ChangeCarbonSingularMethodCallToPluralRector.php @@ -1,7 +1,6 @@ */ - private const SINGULAR_TO_PLURAL_NAMES = [ - 'addSecond' => 'addSeconds', - 'subSecond' => 'subSeconds', - 'addMinute' => 'addMinutes', - 'subMinute' => 'subMinutes', - 'addDay' => 'addDays', - 'subDay' => 'subDays', - 'addHour' => 'addHours', - 'subHour' => 'subHours', - 'addWeek' => 'addWeeks', - 'subWeek' => 'subWeeks', - 'addMonth' => 'addMonths', - 'subMonth' => 'subMonths', - 'addYear' => 'addYears', - 'subYear' => 'subYears', - ]; - - public function getRuleDefinition(): RuleDefinition + private const SINGULAR_TO_PLURAL_NAMES = ['addSecond' => 'addSeconds', 'subSecond' => 'subSeconds', 'addMinute' => 'addMinutes', 'subMinute' => 'subMinutes', 'addDay' => 'addDays', 'subDay' => 'subDays', 'addHour' => 'addHours', 'subHour' => 'subHours', 'addWeek' => 'addWeeks', 'subWeek' => 'subWeeks', 'addMonth' => 'addMonths', 'subMonth' => 'subMonths', 'addYear' => 'addYears', 'subYear' => 'subYears']; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change setter methods with args to their plural names on Carbon\Carbon', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change setter methods with args to their plural names on Carbon\\Carbon', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' use Carbon\Carbon; final class SomeClass @@ -55,9 +33,7 @@ final class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use Carbon\Carbon; final class SomeClass @@ -68,37 +44,30 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->args === []) { return null; } - foreach (self::SINGULAR_TO_PLURAL_NAMES as $singularName => $pluralName) { - if (! $this->isName($node->name, $singularName)) { + if (!$this->isName($node->name, $singularName)) { continue; } - - $node->name = new Identifier($pluralName); + $node->name = new \PhpParser\Node\Identifier($pluralName); return $node; } - return null; } } diff --git a/rules/Carbon/Rector/MethodCall/ChangeDiffForHumansArgsRector.php b/rules/Carbon/Rector/MethodCall/ChangeDiffForHumansArgsRector.php index 45f285fb94b..8617d42e428 100644 --- a/rules/Carbon/Rector/MethodCall/ChangeDiffForHumansArgsRector.php +++ b/rules/Carbon/Rector/MethodCall/ChangeDiffForHumansArgsRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isObjectType($node->var, new ObjectType('Carbon\Carbon'))) { + if (!$this->isObjectType($node->var, new \PHPStan\Type\ObjectType('Carbon\\Carbon'))) { return null; } - - if (! $this->isName($node->name, 'diffForHumans')) { + if (!$this->isName($node->name, 'diffForHumans')) { return null; } - - if (! isset($node->args[1])) { + if (!isset($node->args[1])) { return null; } - $secondArgValue = $node->args[1]->value; if ($this->valueResolver->isTrue($secondArgValue)) { - $node->args[1]->value = $this->nodeFactory->createClassConstFetch( - 'Carbon\CarbonInterface', - 'DIFF_ABSOLUTE' - ); + $node->args[1]->value = $this->nodeFactory->createClassConstFetch('Carbon\\CarbonInterface', 'DIFF_ABSOLUTE'); return $node; } - if ($this->valueResolver->isFalse($secondArgValue)) { - $node->args[1]->value = $this->nodeFactory->createClassConstFetch( - 'Carbon\CarbonInterface', - 'DIFF_RELATIVE_AUTO' - ); + $node->args[1]->value = $this->nodeFactory->createClassConstFetch('Carbon\\CarbonInterface', 'DIFF_RELATIVE_AUTO'); return $node; } - return null; } } diff --git a/rules/CodeQuality/CompactConverter.php b/rules/CodeQuality/CompactConverter.php index cdac341d20a..c0431ef6791 100644 --- a/rules/CodeQuality/CompactConverter.php +++ b/rules/CodeQuality/CompactConverter.php @@ -1,7 +1,6 @@ valueResolver = $valueResolver; } - - public function hasAllArgumentsNamed(FuncCall $funcCall): bool + public function hasAllArgumentsNamed(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { foreach ($funcCall->args as $arg) { /** @var string|null $variableName */ $variableName = $this->valueResolver->getValue($arg->value); - if (! is_string($variableName)) { - return false; + if (!\is_string($variableName)) { + return \false; } } - - return true; + return \true; } - - public function convertToArray(FuncCall $funcCall): Array_ + public function convertToArray(\PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\Array_ { - $array = new Array_(); - + $array = new \PhpParser\Node\Expr\Array_(); foreach ($funcCall->args as $arg) { /** @var string|null $variableName */ $variableName = $this->valueResolver->getValue($arg->value); - if (! is_string($variableName)) { - throw new ShouldNotHappenException(); + if (!\is_string($variableName)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $array->items[] = new ArrayItem(new Variable($variableName), new String_($variableName)); + $array->items[] = new \PhpParser\Node\Expr\ArrayItem(new \PhpParser\Node\Expr\Variable($variableName), new \PhpParser\Node\Scalar\String_($variableName)); } - return $array; } } diff --git a/rules/CodeQuality/Naming/MethodCallToVariableNameResolver.php b/rules/CodeQuality/Naming/MethodCallToVariableNameResolver.php index 81ce626ba27..bc9d2ca1ae6 100644 --- a/rules/CodeQuality/Naming/MethodCallToVariableNameResolver.php +++ b/rules/CodeQuality/Naming/MethodCallToVariableNameResolver.php @@ -1,10 +1,9 @@ nodeNameResolver = $nodeNameResolver; $this->expectedNameResolver = $expectedNameResolver; } - /** * @todo decouple to collector by arg type */ - public function resolveVariableName(MethodCall $methodCall): ?string + public function resolveVariableName(\PhpParser\Node\Expr\MethodCall $methodCall) : ?string { $methodCallVarName = $this->nodeNameResolver->getName($methodCall->var); $methodCallName = $this->nodeNameResolver->getName($methodCall->name); @@ -69,34 +60,28 @@ final class MethodCallToVariableNameResolver if ($methodCallName === null) { return null; } - $result = $this->getVariableName($methodCall, $methodCallVarName, $methodCallName); - if (! Strings::match($result, self::SPACE_REGEX)) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($result, self::SPACE_REGEX)) { return $result; } - return $this->getFallbackVarName($methodCallVarName, $methodCallName); } - - private function getVariableName(MethodCall $methodCall, string $methodCallVarName, string $methodCallName): string + private function getVariableName(\PhpParser\Node\Expr\MethodCall $methodCall, string $methodCallVarName, string $methodCallName) : string { $variableName = $this->expectedNameResolver->resolveForCall($methodCall); if ($methodCall->args === [] && $variableName !== null && $variableName !== $methodCallVarName) { return $variableName; } - $fallbackVarName = $this->getFallbackVarName($methodCallVarName, $methodCallName); $argValue = $methodCall->args[0]->value; - if ($argValue instanceof ClassConstFetch && $argValue->name instanceof Identifier) { + if ($argValue instanceof \PhpParser\Node\Expr\ClassConstFetch && $argValue->name instanceof \PhpParser\Node\Identifier) { return $this->getClassConstFetchVarName($argValue, $methodCallName); } - - if ($argValue instanceof String_) { + if ($argValue instanceof \PhpParser\Node\Scalar\String_) { return $this->getStringVarName($argValue, $methodCallVarName, $fallbackVarName); } - $argumentName = $this->nodeNameResolver->getName($argValue); - if (! $argValue instanceof Variable) { + if (!$argValue instanceof \PhpParser\Node\Expr\Variable) { return $fallbackVarName; } if ($argumentName === null) { @@ -105,41 +90,31 @@ final class MethodCallToVariableNameResolver if ($variableName === null) { return $fallbackVarName; } - return $argumentName . ucfirst($variableName); + return $argumentName . \ucfirst($variableName); } - - private function getFallbackVarName(string $methodCallVarName, string $methodCallName): string + private function getFallbackVarName(string $methodCallVarName, string $methodCallName) : string { - return $methodCallVarName . ucfirst($methodCallName); + return $methodCallVarName . \ucfirst($methodCallName); } - - private function getClassConstFetchVarName(ClassConstFetch $classConstFetch, string $methodCallName): string + private function getClassConstFetchVarName(\PhpParser\Node\Expr\ClassConstFetch $classConstFetch, string $methodCallName) : string { /** @var Identifier $name */ $name = $classConstFetch->name; - $argValueName = strtolower($name->toString()); - + $argValueName = \strtolower($name->toString()); if ($argValueName !== 'class') { - return Strings::replace( - $argValueName, - self::CONSTANT_REGEX, - function ($matches): string { - return strtoupper($matches[2]); - } - ); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($argValueName, self::CONSTANT_REGEX, function ($matches) : string { + return \strtoupper($matches[2]); + }); } - - if ($classConstFetch->class instanceof Name) { + if ($classConstFetch->class instanceof \PhpParser\Node\Name) { return $this->normalizeStringVariableName($methodCallName) . $classConstFetch->class->getLast(); } - return $this->normalizeStringVariableName($methodCallName); } - - private function getStringVarName(String_ $string, string $methodCallVarName, string $fallbackVarName): string + private function getStringVarName(\PhpParser\Node\Scalar\String_ $string, string $methodCallVarName, string $fallbackVarName) : string { - $normalizeStringVariableName = $this->normalizeStringVariableName($string->value . ucfirst($fallbackVarName)); - if (! Strings::match($normalizeStringVariableName, self::START_ALPHA_REGEX)) { + $normalizeStringVariableName = $this->normalizeStringVariableName($string->value . \ucfirst($fallbackVarName)); + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($normalizeStringVariableName, self::START_ALPHA_REGEX)) { return $fallbackVarName; } if ($normalizeStringVariableName === $methodCallVarName) { @@ -147,16 +122,13 @@ final class MethodCallToVariableNameResolver } return $normalizeStringVariableName; } - - private function normalizeStringVariableName(string $string): string + private function normalizeStringVariableName(string $string) : string { - if (! Strings::match($string, self::VALID_STRING_VARIABLE_REGEX)) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($string, self::VALID_STRING_VARIABLE_REGEX)) { return ''; } - - $get = str_ireplace('get', '', $string); - $by = str_ireplace('by', '', $get); - - return str_replace('-', '', $by); + $get = \str_ireplace('get', '', $string); + $by = \str_ireplace('by', '', $get); + return \str_replace('-', '', $by); } } diff --git a/rules/CodeQuality/NodeAnalyzer/ArrayCompacter.php b/rules/CodeQuality/NodeAnalyzer/ArrayCompacter.php index 5f4bd820e3c..eec88b2d1f0 100644 --- a/rules/CodeQuality/NodeAnalyzer/ArrayCompacter.php +++ b/rules/CodeQuality/NodeAnalyzer/ArrayCompacter.php @@ -1,34 +1,29 @@ items as $arrayItem) { - if (! $arrayItem instanceof ArrayItem) { + if (!$arrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - if ($arrayItem->key !== null) { continue; } - - if (! $arrayItem->value instanceof String_) { + if (!$arrayItem->value instanceof \PhpParser\Node\Scalar\String_) { continue; } - $variableName = $arrayItem->value->value; - $arrayItem->key = new String_($variableName); - $arrayItem->value = new Variable($variableName); + $arrayItem->key = new \PhpParser\Node\Scalar\String_($variableName); + $arrayItem->value = new \PhpParser\Node\Expr\Variable($variableName); } } } diff --git a/rules/CodeQuality/NodeAnalyzer/ArrayItemsAnalyzer.php b/rules/CodeQuality/NodeAnalyzer/ArrayItemsAnalyzer.php index 50d9a4b8f07..1cfd322853b 100644 --- a/rules/CodeQuality/NodeAnalyzer/ArrayItemsAnalyzer.php +++ b/rules/CodeQuality/NodeAnalyzer/ArrayItemsAnalyzer.php @@ -1,60 +1,50 @@ items as $arrayItem) { $variableName = $this->resolveStringValue($arrayItem); if ($variableName === null) { continue; } - // the variable must not be defined here if ($scope->hasVariableType($variableName)->no()) { - return false; + return \false; } } - - return true; + return \true; } - - public function hasArrayExclusiveUndefinedVariableNames(Array_ $array, Scope $scope): bool + public function hasArrayExclusiveUndefinedVariableNames(\PhpParser\Node\Expr\Array_ $array, \PHPStan\Analyser\Scope $scope) : bool { foreach ($array->items as $arrayItem) { $variableName = $this->resolveStringValue($arrayItem); if ($variableName === null) { continue; } - // the variable must not be defined here if ($scope->hasVariableType($variableName)->yes()) { - return false; + return \false; } } - - return true; + return \true; } - - private function resolveStringValue(?ArrayItem $arrayItem): ?string + private function resolveStringValue(?\PhpParser\Node\Expr\ArrayItem $arrayItem) : ?string { - if (! $arrayItem instanceof ArrayItem) { + if (!$arrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { return null; } - - if (! $arrayItem->value instanceof String_) { + if (!$arrayItem->value instanceof \PhpParser\Node\Scalar\String_) { return null; } - return $arrayItem->value->value; } } diff --git a/rules/CodeQuality/NodeAnalyzer/CallableClassMethodMatcher.php b/rules/CodeQuality/NodeAnalyzer/CallableClassMethodMatcher.php index f5a10d72d4c..c731b1794c2 100644 --- a/rules/CodeQuality/NodeAnalyzer/CallableClassMethodMatcher.php +++ b/rules/CodeQuality/NodeAnalyzer/CallableClassMethodMatcher.php @@ -1,7 +1,6 @@ valueResolver = $valueResolver; $this->nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; } - /** * @param Variable|PropertyFetch $objectExpr */ - public function match(Expr $objectExpr, String_ $string): ?PhpMethodReflection + public function match(\PhpParser\Node\Expr $objectExpr, \PhpParser\Node\Scalar\String_ $string) : ?\PHPStan\Reflection\Php\PhpMethodReflection { $methodName = $this->valueResolver->getValue($string); - if (! is_string($methodName)) { - throw new ShouldNotHappenException(); + if (!\is_string($methodName)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $objectType = $this->nodeTypeResolver->resolve($objectExpr); - - if ($objectType instanceof ThisType) { + if ($objectType instanceof \PHPStan\Type\ThisType) { $objectType = $objectType->getStaticObjectType(); } - $objectType = $this->popFirstObjectType($objectType); - - if ($objectType instanceof ObjectType) { - if (! $this->reflectionProvider->hasClass($objectType->getClassName())) { + if ($objectType instanceof \PHPStan\Type\ObjectType) { + if (!$this->reflectionProvider->hasClass($objectType->getClassName())) { return null; } - $classReflection = $this->reflectionProvider->getClass($objectType->getClassName()); - if (! $classReflection->hasMethod($methodName)) { + if (!$classReflection->hasMethod($methodName)) { return null; } - - $stringScope = $string->getAttribute(AttributeKey::SCOPE); - + $stringScope = $string->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); $methodReflection = $classReflection->getMethod($methodName, $stringScope); - if (! $methodReflection instanceof PhpMethodReflection) { + if (!$methodReflection instanceof \PHPStan\Reflection\Php\PhpMethodReflection) { return null; } - if ($this->nodeNameResolver->isName($objectExpr, 'this')) { return $methodReflection; } - // is public method of another service if ($methodReflection->isPublic()) { return $methodReflection; } } - return null; } - - private function popFirstObjectType(Type $type): Type + private function popFirstObjectType(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - if ($type instanceof UnionType) { + if ($type instanceof \PHPStan\Type\UnionType) { foreach ($type->getTypes() as $unionedType) { - if (! $unionedType instanceof ObjectType) { + if (!$unionedType instanceof \PHPStan\Type\ObjectType) { continue; } - return $unionedType; } } - return $type; } } diff --git a/rules/CodeQuality/NodeAnalyzer/ClassLikeAnalyzer.php b/rules/CodeQuality/NodeAnalyzer/ClassLikeAnalyzer.php index d816f27e8e0..916d691ceed 100644 --- a/rules/CodeQuality/NodeAnalyzer/ClassLikeAnalyzer.php +++ b/rules/CodeQuality/NodeAnalyzer/ClassLikeAnalyzer.php @@ -1,35 +1,29 @@ nodeNameResolver = $nodeNameResolver; } - /** * @return string[] */ - public function resolvePropertyNames(Class_ $class): array + public function resolvePropertyNames(\PhpParser\Node\Stmt\Class_ $class) : array { $propertyNames = []; - foreach ($class->getProperties() as $property) { $propertyNames[] = $this->nodeNameResolver->getName($property); } - return $propertyNames; } } diff --git a/rules/CodeQuality/NodeAnalyzer/ForAnalyzer.php b/rules/CodeQuality/NodeAnalyzer/ForAnalyzer.php index f989f642f6b..c87f7101ab4 100644 --- a/rules/CodeQuality/NodeAnalyzer/ForAnalyzer.php +++ b/rules/CodeQuality/NodeAnalyzer/ForAnalyzer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; $this->assignManipulator = $assignManipulator; $this->nodeComparator = $nodeComparator; } - /** * @param Expr[] $condExprs */ - public function isCondExprSmallerOrGreater(array $condExprs, string $keyValueName, string $countValueName): bool + public function isCondExprSmallerOrGreater(array $condExprs, string $keyValueName, string $countValueName) : bool { // $i < $count - if ($condExprs[0] instanceof Smaller) { - if (! $this->nodeNameResolver->isName($condExprs[0]->left, $keyValueName)) { - return false; + if ($condExprs[0] instanceof \PhpParser\Node\Expr\BinaryOp\Smaller) { + if (!$this->nodeNameResolver->isName($condExprs[0]->left, $keyValueName)) { + return \false; } - return $this->nodeNameResolver->isName($condExprs[0]->right, $countValueName); } - // $i > $count - if ($condExprs[0] instanceof Greater) { - if (! $this->nodeNameResolver->isName($condExprs[0]->left, $countValueName)) { - return false; + if ($condExprs[0] instanceof \PhpParser\Node\Expr\BinaryOp\Greater) { + if (!$this->nodeNameResolver->isName($condExprs[0]->left, $countValueName)) { + return \false; } - return $this->nodeNameResolver->isName($condExprs[0]->right, $keyValueName); } - - return false; + return \false; } - /** * @param Expr[] $loopExprs * $param */ - public function isLoopMatch(array $loopExprs, ?string $keyValueName): bool + public function isLoopMatch(array $loopExprs, ?string $keyValueName) : bool { - if (count($loopExprs) !== 1) { - return false; + if (\count($loopExprs) !== 1) { + return \false; } - if ($keyValueName === null) { - return false; + return \false; } - $prePostInc = $loopExprs[0]; - - if ($prePostInc instanceof PreInc || $prePostInc instanceof PostInc) { + if ($prePostInc instanceof \PhpParser\Node\Expr\PreInc || $prePostInc instanceof \PhpParser\Node\Expr\PostInc) { return $this->nodeNameResolver->isName($prePostInc->var, $keyValueName); } - - return false; + return \false; } - - public function isCountValueVariableUsedInsideForStatements(For_ $for, ?Expr $expr): bool + public function isCountValueVariableUsedInsideForStatements(\PhpParser\Node\Stmt\For_ $for, ?\PhpParser\Node\Expr $expr) : bool { - return (bool) $this->betterNodeFinder->findFirst( - $for->stmts, - function (Node $node) use ($expr): bool { - return $this->nodeComparator->areNodesEqual($node, $expr); + return (bool) $this->betterNodeFinder->findFirst($for->stmts, function (\PhpParser\Node $node) use($expr) : bool { + return $this->nodeComparator->areNodesEqual($node, $expr); + }); + } + public function isArrayWithKeyValueNameUnsetted(\PhpParser\Node\Stmt\For_ $for) : bool + { + return (bool) $this->betterNodeFinder->findFirst($for->stmts, function (\PhpParser\Node $node) : bool { + /** @var Node $parent */ + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Stmt\Unset_) { + return \false; } - ); + return $node instanceof \PhpParser\Node\Expr\ArrayDimFetch; + }); } - - public function isArrayWithKeyValueNameUnsetted(For_ $for): bool + public function isAssignmentWithArrayDimFetchAsVariableInsideForStatements(\PhpParser\Node\Stmt\For_ $for, string $keyValueName) : bool { - return (bool) $this->betterNodeFinder->findFirst( - $for->stmts, - function (Node $node): bool { - /** @var Node $parent */ - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Unset_) { - return false; - } - return $node instanceof ArrayDimFetch; + return (bool) $this->betterNodeFinder->findFirst($for->stmts, function (\PhpParser\Node $node) use($keyValueName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - ); - } - - public function isAssignmentWithArrayDimFetchAsVariableInsideForStatements(For_ $for, string $keyValueName): bool - { - return (bool) $this->betterNodeFinder->findFirst( - $for->stmts, - function (Node $node) use ($keyValueName): bool { - if (! $node instanceof Assign) { - return false; - } - - if (! $node->var instanceof ArrayDimFetch) { - return false; - } - - $arrayDimFetch = $node->var; - if ($arrayDimFetch->dim === null) { - return false; - } - - if (! $arrayDimFetch->dim instanceof Variable) { - return false; - } - - return $this->nodeNameResolver->isName($arrayDimFetch->dim, $keyValueName); + if (!$node->var instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + return \false; } - ); + $arrayDimFetch = $node->var; + if ($arrayDimFetch->dim === null) { + return \false; + } + if (!$arrayDimFetch->dim instanceof \PhpParser\Node\Expr\Variable) { + return \false; + } + return $this->nodeNameResolver->isName($arrayDimFetch->dim, $keyValueName); + }); } - - public function isValueVarUsedNext(For_ $for, string $iteratedVariableSingle): bool + public function isValueVarUsedNext(\PhpParser\Node\Stmt\For_ $for, string $iteratedVariableSingle) : bool { - return (bool) $this->betterNodeFinder->findFirstNext($for, function (Node $node) use ( - $iteratedVariableSingle - ): bool { - if (! $node instanceof Variable) { - return false; + return (bool) $this->betterNodeFinder->findFirstNext($for, function (\PhpParser\Node $node) use($iteratedVariableSingle) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } return $this->nodeNameResolver->isName($node, $iteratedVariableSingle); }); } - /** * @param Expr[] $condExprs */ - public function isCondExprOneOrKeyValueNameNotNull(array $condExprs, ?string $keyValueName): bool + public function isCondExprOneOrKeyValueNameNotNull(array $condExprs, ?string $keyValueName) : bool { - if (count($condExprs) !== 1) { - return true; + if (\count($condExprs) !== 1) { + return \true; } - return $keyValueName === null; } - - public function isArrayDimFetchPartOfAssignOrArgParentCount(ArrayDimFetch $arrayDimFetch): bool + public function isArrayDimFetchPartOfAssignOrArgParentCount(\PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : bool { - $parentNode = $arrayDimFetch->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Node) { - return false; + $parentNode = $arrayDimFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node) { + return \false; } - if ($this->assignManipulator->isNodePartOfAssign($parentNode)) { - return true; + return \true; } - return $this->isArgParentCount($parentNode); } - - private function isArgParentCount(Node $node): bool + private function isArgParentCount(\PhpParser\Node $node) : bool { - if (! $node instanceof Arg) { - return false; + if (!$node instanceof \PhpParser\Node\Arg) { + return \false; } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof FuncCall) { - return false; + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - return $this->nodeNameResolver->isName($parent, self::COUNT); } } diff --git a/rules/CodeQuality/NodeAnalyzer/ForeachAnalyzer.php b/rules/CodeQuality/NodeAnalyzer/ForeachAnalyzer.php index 914b5a9c6f4..2e9956b0c5a 100644 --- a/rules/CodeQuality/NodeAnalyzer/ForeachAnalyzer.php +++ b/rules/CodeQuality/NodeAnalyzer/ForeachAnalyzer.php @@ -1,7 +1,6 @@ nodeComparator = $nodeComparator; $this->forAnalyzer = $forAnalyzer; $this->nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->betterNodeFinder = $betterNodeFinder; } - /** * Matches$ * foreach ($values as $value) { * <$assigns[]> = $value; * } */ - public function matchAssignItemsOnlyForeachArrayVariable(Foreach_ $foreach): ?Expr + public function matchAssignItemsOnlyForeachArrayVariable(\PhpParser\Node\Stmt\Foreach_ $foreach) : ?\PhpParser\Node\Expr { - if (count($foreach->stmts) !== 1) { + if (\count($foreach->stmts) !== 1) { return null; } - $onlyStatement = $foreach->stmts[0]; - if ($onlyStatement instanceof Expression) { + if ($onlyStatement instanceof \PhpParser\Node\Stmt\Expression) { $onlyStatement = $onlyStatement->expr; } - - if (! $onlyStatement instanceof Assign) { + if (!$onlyStatement instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $onlyStatement->var instanceof ArrayDimFetch) { + if (!$onlyStatement->var instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return null; } - if ($onlyStatement->var->dim !== null) { return null; } - - if (! $this->nodeComparator->areNodesEqual($foreach->valueVar, $onlyStatement->expr)) { + if (!$this->nodeComparator->areNodesEqual($foreach->valueVar, $onlyStatement->expr)) { return null; } - return $onlyStatement->var->var; } - /** * @param Stmt[] $stmts */ - public function useForeachVariableInStmts( - Expr $foreachedValue, - Expr $singleValue, - array $stmts, - string $keyValueName - ): void { - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - $stmts, - function (Node $node) use ($foreachedValue, $singleValue, $keyValueName): ?Expr { - if (! $node instanceof ArrayDimFetch) { - return null; - } - - // must be the same as foreach value - if (! $this->nodeComparator->areNodesEqual($node->var, $foreachedValue)) { - return null; - } - - if ($this->forAnalyzer->isArrayDimFetchPartOfAssignOrArgParentCount($node)) { - return null; - } - - // is dim same as key value name, ...[$i] - if (! $node->dim instanceof Variable) { - return null; - } - - if (! $this->nodeNameResolver->isName($node->dim, $keyValueName)) { - return null; - } - - return $singleValue; - } - ); - } - - public function isValueVarUsed(Foreach_ $foreach, string $singularValueVarName): bool + public function useForeachVariableInStmts(\PhpParser\Node\Expr $foreachedValue, \PhpParser\Node\Expr $singleValue, array $stmts, string $keyValueName) : void { - $isUsedInStmts = (bool) $this->betterNodeFinder->findFirst($foreach->stmts, function (Node $node) use ( - $singularValueVarName - ): bool { - if (! $node instanceof Variable) { - return false; + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmts, function (\PhpParser\Node $node) use($foreachedValue, $singleValue, $keyValueName) : ?Expr { + if (!$node instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + return null; + } + // must be the same as foreach value + if (!$this->nodeComparator->areNodesEqual($node->var, $foreachedValue)) { + return null; + } + if ($this->forAnalyzer->isArrayDimFetchPartOfAssignOrArgParentCount($node)) { + return null; + } + // is dim same as key value name, ...[$i] + if (!$node->dim instanceof \PhpParser\Node\Expr\Variable) { + return null; + } + if (!$this->nodeNameResolver->isName($node->dim, $keyValueName)) { + return null; + } + return $singleValue; + }); + } + public function isValueVarUsed(\PhpParser\Node\Stmt\Foreach_ $foreach, string $singularValueVarName) : bool + { + $isUsedInStmts = (bool) $this->betterNodeFinder->findFirst($foreach->stmts, function (\PhpParser\Node $node) use($singularValueVarName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeNameResolver->isName($node, $singularValueVarName); }); - if ($isUsedInStmts) { - return true; + return \true; } - - return (bool) $this->betterNodeFinder->findFirstNext($foreach, function (Node $node) use ( - $singularValueVarName - ): bool { - if (! $node instanceof Variable) { - return false; + return (bool) $this->betterNodeFinder->findFirstNext($foreach, function (\PhpParser\Node $node) use($singularValueVarName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeNameResolver->isName($node, $singularValueVarName); }); } diff --git a/rules/CodeQuality/NodeAnalyzer/LocalPropertyAnalyzer.php b/rules/CodeQuality/NodeAnalyzer/LocalPropertyAnalyzer.php index f9964f22f24..972eb37b9cf 100644 --- a/rules/CodeQuality/NodeAnalyzer/LocalPropertyAnalyzer.php +++ b/rules/CodeQuality/NodeAnalyzer/LocalPropertyAnalyzer.php @@ -1,7 +1,6 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->classAnalyzer = $classAnalyzer; $this->nodeNameResolver = $nodeNameResolver; @@ -92,137 +73,105 @@ final class LocalPropertyAnalyzer $this->propertyFetchAnalyzer = $propertyFetchAnalyzer; $this->typeFactory = $typeFactory; } - /** * @return array */ - public function resolveFetchedPropertiesToTypesFromClass(Class_ $class): array + public function resolveFetchedPropertiesToTypesFromClass(\PhpParser\Node\Stmt\Class_ $class) : array { $fetchedLocalPropertyNameToTypes = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($class->stmts, function (Node $node) use ( - &$fetchedLocalPropertyNameToTypes - ): ?int { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($class->stmts, function (\PhpParser\Node $node) use(&$fetchedLocalPropertyNameToTypes) : ?int { // skip anonymous class scope $isAnonymousClass = $this->classAnalyzer->isAnonymousClass($node); if ($isAnonymousClass) { - return NodeTraverser::DONT_TRAVERSE_CHILDREN; + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CHILDREN; } - - if (! $node instanceof PropertyFetch) { + if (!$node instanceof \PhpParser\Node\Expr\PropertyFetch) { return null; } - - if (! $this->propertyFetchAnalyzer->isLocalPropertyFetch($node)) { + if (!$this->propertyFetchAnalyzer->isLocalPropertyFetch($node)) { return null; } - if ($this->shouldSkipPropertyFetch($node)) { return null; } - $propertyName = $this->nodeNameResolver->getName($node->name); if ($propertyName === null) { return null; } - $propertyFetchType = $this->resolvePropertyFetchType($node); $fetchedLocalPropertyNameToTypes[$propertyName][] = $propertyFetchType; - return null; }); - return $this->normalizeToSingleType($fetchedLocalPropertyNameToTypes); } - - private function shouldSkipPropertyFetch(PropertyFetch $propertyFetch): bool + private function shouldSkipPropertyFetch(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : bool { // special Laravel collection scope if ($this->shouldSkipForLaravelCollection($propertyFetch)) { - return true; + return \true; } - if ($this->isPartOfClosureBind($propertyFetch)) { - return true; + return \true; } - return $this->isPartOfClosureBindTo($propertyFetch); } - - private function resolvePropertyFetchType(PropertyFetch $propertyFetch): Type + private function resolvePropertyFetchType(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : \PHPStan\Type\Type { - $parentNode = $propertyFetch->getAttribute(AttributeKey::PARENT_NODE); - + $parentNode = $propertyFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // possible get type - if ($parentNode instanceof Assign) { + if ($parentNode instanceof \PhpParser\Node\Expr\Assign) { return $this->nodeTypeResolver->getStaticType($parentNode->expr); } - - if ($parentNode instanceof ArrayDimFetch) { + if ($parentNode instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return $this->arrayDimFetchTypeResolver->resolve($parentNode); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - /** * @param array $propertyNameToTypes * @return array */ - private function normalizeToSingleType(array $propertyNameToTypes): array + private function normalizeToSingleType(array $propertyNameToTypes) : array { // normalize types to union $propertyNameToType = []; foreach ($propertyNameToTypes as $name => $types) { $propertyNameToType[$name] = $this->typeFactory->createMixedPassedOrUnionType($types); } - return $propertyNameToType; } - - private function shouldSkipForLaravelCollection(PropertyFetch $propertyFetch): bool + private function shouldSkipForLaravelCollection(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : bool { - $staticCallOrClassMethod = $this->betterNodeFinder-> findParentTypes( - $propertyFetch, - [ClassMethod::class, StaticCall::class] - ); - - if (! $staticCallOrClassMethod instanceof StaticCall) { - return false; + $staticCallOrClassMethod = $this->betterNodeFinder->findParentTypes($propertyFetch, [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\StaticCall::class]); + if (!$staticCallOrClassMethod instanceof \PhpParser\Node\Expr\StaticCall) { + return \false; } - return $this->nodeNameResolver->isName($staticCallOrClassMethod->class, self::LARAVEL_COLLECTION_CLASS); } - /** * Local property is actually not local one, but belongs to passed object * See https://ocramius.github.io/blog/accessing-private-php-class-members-without-reflection/ */ - private function isPartOfClosureBind(PropertyFetch $propertyFetch): bool + private function isPartOfClosureBind(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : bool { - $parentStaticCall = $this->betterNodeFinder->findParentType($propertyFetch, StaticCall::class); - if (! $parentStaticCall instanceof StaticCall) { - return false; + $parentStaticCall = $this->betterNodeFinder->findParentType($propertyFetch, \PhpParser\Node\Expr\StaticCall::class); + if (!$parentStaticCall instanceof \PhpParser\Node\Expr\StaticCall) { + return \false; } - - if (! $this->nodeNameResolver->isName($parentStaticCall->class, 'Closure')) { - return true; + if (!$this->nodeNameResolver->isName($parentStaticCall->class, 'Closure')) { + return \true; } - return $this->nodeNameResolver->isName($parentStaticCall->name, 'bind'); } - - private function isPartOfClosureBindTo(PropertyFetch $propertyFetch): bool + private function isPartOfClosureBindTo(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : bool { - $parentMethodCall = $this->betterNodeFinder->findParentType($propertyFetch, MethodCall::class); - if (! $parentMethodCall instanceof MethodCall) { - return false; + $parentMethodCall = $this->betterNodeFinder->findParentType($propertyFetch, \PhpParser\Node\Expr\MethodCall::class); + if (!$parentMethodCall instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - - if (! $parentMethodCall->var instanceof Closure) { - return false; + if (!$parentMethodCall->var instanceof \PhpParser\Node\Expr\Closure) { + return \false; } - return $this->nodeNameResolver->isName($parentMethodCall->name, 'bindTo'); } } diff --git a/rules/CodeQuality/NodeFactory/AnonymousFunctionFactory.php b/rules/CodeQuality/NodeFactory/AnonymousFunctionFactory.php index 16be3d73ff6..5ad1e743ef8 100644 --- a/rules/CodeQuality/NodeFactory/AnonymousFunctionFactory.php +++ b/rules/CodeQuality/NodeFactory/AnonymousFunctionFactory.php @@ -1,7 +1,6 @@ nodeFactory = $nodeFactory; $this->nodeNameResolver = $nodeNameResolver; $this->staticTypeMapper = $staticTypeMapper; } - /** * @param Variable|PropertyFetch $expr */ - public function create(PhpMethodReflection $phpMethodReflection, Expr $expr): Closure + public function create(\PHPStan\Reflection\Php\PhpMethodReflection $phpMethodReflection, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\Closure { /** @var FunctionVariantWithPhpDocs $functionVariantWithPhpDoc */ $functionVariantWithPhpDoc = $phpMethodReflection->getVariants()[0]; - - $anonymousFunction = new Closure(); + $anonymousFunction = new \PhpParser\Node\Expr\Closure(); $newParams = $this->createParams($functionVariantWithPhpDoc->getParameters()); - $anonymousFunction->params = $newParams; - - $innerMethodCall = new MethodCall($expr, $phpMethodReflection->getName()); + $innerMethodCall = new \PhpParser\Node\Expr\MethodCall($expr, $phpMethodReflection->getName()); $innerMethodCall->args = $this->nodeFactory->createArgsFromParams($newParams); - - if (! $functionVariantWithPhpDoc->getReturnType() instanceof MixedType) { - $returnType = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode( - $functionVariantWithPhpDoc->getReturnType() - ); + if (!$functionVariantWithPhpDoc->getReturnType() instanceof \PHPStan\Type\MixedType) { + $returnType = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($functionVariantWithPhpDoc->getReturnType()); $anonymousFunction->returnType = $returnType; } - // does method return something? - - if (! $functionVariantWithPhpDoc->getReturnType() instanceof VoidType) { - $anonymousFunction->stmts[] = new Return_($innerMethodCall); + if (!$functionVariantWithPhpDoc->getReturnType() instanceof \PHPStan\Type\VoidType) { + $anonymousFunction->stmts[] = new \PhpParser\Node\Stmt\Return_($innerMethodCall); } else { - $anonymousFunction->stmts[] = new Expression($innerMethodCall); + $anonymousFunction->stmts[] = new \PhpParser\Node\Stmt\Expression($innerMethodCall); } - - if ($expr instanceof Variable && ! $this->nodeNameResolver->isName($expr, 'this')) { - $anonymousFunction->uses[] = new ClosureUse($expr); + if ($expr instanceof \PhpParser\Node\Expr\Variable && !$this->nodeNameResolver->isName($expr, 'this')) { + $anonymousFunction->uses[] = new \PhpParser\Node\Expr\ClosureUse($expr); } - return $anonymousFunction; } - /** * @param ParameterReflection[] $parameterReflections * @return Param[] */ - private function createParams(array $parameterReflections): array + private function createParams(array $parameterReflections) : array { $params = []; foreach ($parameterReflections as $parameterReflection) { - $param = new Param(new Variable($parameterReflection->getName())); - - if (! $parameterReflection->getType() instanceof MixedType) { + $param = new \PhpParser\Node\Param(new \PhpParser\Node\Expr\Variable($parameterReflection->getName())); + if (!$parameterReflection->getType() instanceof \PHPStan\Type\MixedType) { $paramType = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($parameterReflection->getType()); $param->type = $paramType; } - $params[] = $param; } - return $params; } } diff --git a/rules/CodeQuality/NodeFactory/ForeachFactory.php b/rules/CodeQuality/NodeFactory/ForeachFactory.php index 73a91faa61b..cf85264dbe5 100644 --- a/rules/CodeQuality/NodeFactory/ForeachFactory.php +++ b/rules/CodeQuality/NodeFactory/ForeachFactory.php @@ -1,7 +1,6 @@ stmts = $for->stmts; - $foreach->keyVar = new Variable($keyValueName); - + $foreach->keyVar = new \PhpParser\Node\Expr\Variable($keyValueName); return $foreach; } } diff --git a/rules/CodeQuality/NodeFactory/MissingPropertiesFactory.php b/rules/CodeQuality/NodeFactory/MissingPropertiesFactory.php index 736e7ec7e47..4d4fe724d53 100644 --- a/rules/CodeQuality/NodeFactory/MissingPropertiesFactory.php +++ b/rules/CodeQuality/NodeFactory/MissingPropertiesFactory.php @@ -1,50 +1,42 @@ nodeFactory = $nodeFactory; $this->propertyTypeDecorator = $propertyTypeDecorator; } - /** * @param array $fetchedLocalPropertyNameToTypes * @param string[] $propertyNamesToComplete * @return Property[] */ - public function create(array $fetchedLocalPropertyNameToTypes, array $propertyNamesToComplete): array + public function create(array $fetchedLocalPropertyNameToTypes, array $propertyNamesToComplete) : array { $newProperties = []; foreach ($fetchedLocalPropertyNameToTypes as $propertyName => $propertyType) { - if (! in_array($propertyName, $propertyNamesToComplete, true)) { + if (!\in_array($propertyName, $propertyNamesToComplete, \true)) { continue; } - $property = $this->nodeFactory->createPublicProperty($propertyName); $this->propertyTypeDecorator->decorateProperty($property, $propertyType); - $newProperties[] = $property; } - return $newProperties; } } diff --git a/rules/CodeQuality/NodeFactory/PropertyTypeDecorator.php b/rules/CodeQuality/NodeFactory/PropertyTypeDecorator.php index 3047b296433..e1c2f0b9a5b 100644 --- a/rules/CodeQuality/NodeFactory/PropertyTypeDecorator.php +++ b/rules/CodeQuality/NodeFactory/PropertyTypeDecorator.php @@ -1,7 +1,6 @@ phpVersionProvider = $phpVersionProvider; $this->staticTypeMapper = $staticTypeMapper; $this->phpDocTypeChanger = $phpDocTypeChanger; $this->phpDocInfoFactory = $phpDocInfoFactory; } - - public function decorateProperty(Property $property, Type $propertyType): void + public function decorateProperty(\PhpParser\Node\Stmt\Property $property, \PHPStan\Type\Type $propertyType) : void { $this->decoratePropertyWithVarDoc($property, $propertyType); $this->decoratePropertyWithType($property, $propertyType); } - - private function decoratePropertyWithVarDoc(Property $property, Type $propertyType): void + private function decoratePropertyWithVarDoc(\PhpParser\Node\Stmt\Property $property, \PHPStan\Type\Type $propertyType) : void { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); $phpDocInfo->makeMultiLined(); - if ($this->isNonMixedArrayType($propertyType)) { $this->phpDocTypeChanger->changeVarType($phpDocInfo, $propertyType); - $property->type = new Identifier('array'); + $property->type = new \PhpParser\Node\Identifier('array'); return; } - - if ($this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::TYPED_PROPERTIES)) { + if ($this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::TYPED_PROPERTIES)) { $phpParserNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($propertyType); - if (! $phpParserNode instanceof Node) { + if (!$phpParserNode instanceof \PhpParser\Node) { // fallback to doc type in PHP 7.4 $this->phpDocTypeChanger->changeVarType($phpDocInfo, $propertyType); } @@ -77,31 +63,25 @@ final class PropertyTypeDecorator $this->phpDocTypeChanger->changeVarType($phpDocInfo, $propertyType); } } - - private function decoratePropertyWithType(Property $property, Type $propertyType): void + private function decoratePropertyWithType(\PhpParser\Node\Stmt\Property $property, \PHPStan\Type\Type $propertyType) : void { - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::TYPED_PROPERTIES)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::TYPED_PROPERTIES)) { return; } - $phpParserNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($propertyType); - if (! $phpParserNode instanceof Node) { + if (!$phpParserNode instanceof \PhpParser\Node) { return; } - $property->type = $phpParserNode; } - - private function isNonMixedArrayType(Type $type): bool + private function isNonMixedArrayType(\PHPStan\Type\Type $type) : bool { - if (! $type instanceof ArrayType) { - return false; + if (!$type instanceof \PHPStan\Type\ArrayType) { + return \false; } - - if ($type->getKeyType() instanceof MixedType) { - return false; + if ($type->getKeyType() instanceof \PHPStan\Type\MixedType) { + return \false; } - - return ! $type->getItemType() instanceof MixedType; + return !$type->getItemType() instanceof \PHPStan\Type\MixedType; } } diff --git a/rules/CodeQuality/NodeManipulator/ExprBoolCaster.php b/rules/CodeQuality/NodeManipulator/ExprBoolCaster.php index 3015855e5a1..1c5dbdef6ae 100644 --- a/rules/CodeQuality/NodeManipulator/ExprBoolCaster.php +++ b/rules/CodeQuality/NodeManipulator/ExprBoolCaster.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->typeUnwrapper = $typeUnwrapper; $this->staticTypeAnalyzer = $staticTypeAnalyzer; $this->nodeFactory = $nodeFactory; } - - public function boolCastOrNullCompareIfNeeded(Expr $expr): Expr + public function boolCastOrNullCompareIfNeeded(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { - if (! $this->nodeTypeResolver->isNullableType($expr)) { - if (! $this->isBoolCastNeeded($expr)) { + if (!$this->nodeTypeResolver->isNullableType($expr)) { + if (!$this->isBoolCastNeeded($expr)) { return $expr; } - - return new Bool_($expr); + return new \PhpParser\Node\Expr\Cast\Bool_($expr); } - $exprStaticType = $this->nodeTypeResolver->getStaticType($expr); // if we remove null type, still has to be trueable - if ($exprStaticType instanceof UnionType) { + if ($exprStaticType instanceof \PHPStan\Type\UnionType) { $unionTypeWithoutNullType = $this->typeUnwrapper->removeNullTypeFromUnionType($exprStaticType); if ($this->staticTypeAnalyzer->isAlwaysTruableType($unionTypeWithoutNullType)) { - return new NotIdentical($expr, $this->nodeFactory->createNull()); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, $this->nodeFactory->createNull()); } } elseif ($this->staticTypeAnalyzer->isAlwaysTruableType($exprStaticType)) { - return new NotIdentical($expr, $this->nodeFactory->createNull()); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, $this->nodeFactory->createNull()); } - - if (! $this->isBoolCastNeeded($expr)) { + if (!$this->isBoolCastNeeded($expr)) { return $expr; } - - return new Bool_($expr); + return new \PhpParser\Node\Expr\Cast\Bool_($expr); } - - private function isBoolCastNeeded(Expr $expr): bool + private function isBoolCastNeeded(\PhpParser\Node\Expr $expr) : bool { - if ($expr instanceof BooleanNot) { - return false; + if ($expr instanceof \PhpParser\Node\Expr\BooleanNot) { + return \false; } - - if ($this->nodeTypeResolver->isStaticType($expr, BooleanType::class)) { - return false; + if ($this->nodeTypeResolver->isStaticType($expr, \PHPStan\Type\BooleanType::class)) { + return \false; } - - return ! $expr instanceof BinaryOp; + return !$expr instanceof \PhpParser\Node\Expr\BinaryOp; } } diff --git a/rules/CodeQuality/Rector/Array_/ArrayThisCallToThisMethodCallRector.php b/rules/CodeQuality/Rector/Array_/ArrayThisCallToThisMethodCallRector.php index 89ee3bb938b..5440330e600 100644 --- a/rules/CodeQuality/Rector/Array_/ArrayThisCallToThisMethodCallRector.php +++ b/rules/CodeQuality/Rector/Array_/ArrayThisCallToThisMethodCallRector.php @@ -1,7 +1,6 @@ arrayCallableMethodReferenceAnalyzer = $arrayCallableMethodReferenceAnalyzer; $this->reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change `[$this, someMethod]` without any args to $this->someMethod()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change `[$this, someMethod]` without any args to $this->someMethod()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -66,8 +55,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -81,109 +69,84 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Array_::class]; + return [\PhpParser\Node\Expr\Array_::class]; } - /** * @param Array_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $arrayCallable = $this->arrayCallableMethodReferenceAnalyzer->match($node); - if (! $arrayCallable instanceof ArrayCallable) { + if (!$arrayCallable instanceof \Rector\NodeCollector\ValueObject\ArrayCallable) { return null; } - if ($this->isAssignedToNetteMagicOnProperty($node)) { return null; } if ($this->isInsideProperty($node)) { return null; } - - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // skip if part of method - if ($parentNode instanceof Arg) { + if ($parentNode instanceof \PhpParser\Node\Arg) { return null; } - - if (! $this->reflectionProvider->hasClass($arrayCallable->getClass())) { + if (!$this->reflectionProvider->hasClass($arrayCallable->getClass())) { return null; } - $classReflection = $this->reflectionProvider->getClass($arrayCallable->getClass()); - if (! $classReflection->hasMethod($arrayCallable->getMethod())) { + if (!$classReflection->hasMethod($arrayCallable->getMethod())) { return null; } - $nativeReflectionClass = $classReflection->getNativeReflection(); - $reflectionMethod = $nativeReflectionClass->getMethod($arrayCallable->getMethod()); $this->privatizeClassMethod($reflectionMethod); - if ($reflectionMethod->getNumberOfParameters() > 0) { - $classMethod = $this->nodeRepository->findClassMethod( - $arrayCallable->getClass(), - $arrayCallable->getMethod() - ); + $classMethod = $this->nodeRepository->findClassMethod($arrayCallable->getClass(), $arrayCallable->getMethod()); if ($classMethod !== null) { return $this->nodeFactory->createClosureFromClassMethod($classMethod); } - return null; } - - return new MethodCall(new Variable('this'), $arrayCallable->getMethod()); + return new \PhpParser\Node\Expr\MethodCall(new \PhpParser\Node\Expr\Variable('this'), $arrayCallable->getMethod()); } - - private function isAssignedToNetteMagicOnProperty(Array_ $array): bool + private function isAssignedToNetteMagicOnProperty(\PhpParser\Node\Expr\Array_ $array) : bool { - $parent = $array->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Assign) { - return false; + $parent = $array->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - if (! $parent->var instanceof ArrayDimFetch) { - return false; + if (!$parent->var instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + return \false; } - - if (! $parent->var->var instanceof PropertyFetch) { - return false; + if (!$parent->var->var instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - /** @var PropertyFetch $propertyFetch */ $propertyFetch = $parent->var->var; return $this->isName($propertyFetch->name, 'on*'); } - - private function isInsideProperty(Array_ $array): bool + private function isInsideProperty(\PhpParser\Node\Expr\Array_ $array) : bool { - $parentProperty = $this->betterNodeFinder->findParentType($array, Property::class); - + $parentProperty = $this->betterNodeFinder->findParentType($array, \PhpParser\Node\Stmt\Property::class); return $parentProperty !== null; } - - private function privatizeClassMethod(ReflectionMethod $reflectionMethod): void + private function privatizeClassMethod(\ReflectionMethod $reflectionMethod) : void { $classMethod = $this->nodeRepository->findClassMethodByMethodReflection($reflectionMethod); - if (! $classMethod instanceof ClassMethod) { + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - if ($classMethod->isPrivate()) { return; } - $this->visibilityManipulator->makePrivate($classMethod); } } diff --git a/rules/CodeQuality/Rector/Array_/CallableThisArrayToAnonymousFunctionRector.php b/rules/CodeQuality/Rector/Array_/CallableThisArrayToAnonymousFunctionRector.php index e5d0a3ecf79..75271f856ba 100644 --- a/rules/CodeQuality/Rector/Array_/CallableThisArrayToAnonymousFunctionRector.php +++ b/rules/CodeQuality/Rector/Array_/CallableThisArrayToAnonymousFunctionRector.php @@ -1,7 +1,6 @@ callableClassMethodMatcher = $callableClassMethodMatcher; $this->anonymousFunctionFactory = $anonymousFunctionFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Convert [$this, "method"] to proper anonymous function', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Convert [$this, "method"] to proper anonymous function', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -70,8 +59,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -90,90 +78,73 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Array_::class]; + return [\PhpParser\Node\Expr\Array_::class]; } - /** * @param Array_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipArray($node)) { return null; } - $firstArrayItem = $node->items[0]; - if (! $firstArrayItem instanceof ArrayItem) { + if (!$firstArrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { return null; } - $objectVariable = $firstArrayItem->value; - if (! $objectVariable instanceof Variable && ! $objectVariable instanceof PropertyFetch) { + if (!$objectVariable instanceof \PhpParser\Node\Expr\Variable && !$objectVariable instanceof \PhpParser\Node\Expr\PropertyFetch) { return null; } - $secondArrayItem = $node->items[1]; - if (! $secondArrayItem instanceof ArrayItem) { + if (!$secondArrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { return null; } - $methodName = $secondArrayItem->value; - if (! $methodName instanceof String_) { + if (!$methodName instanceof \PhpParser\Node\Scalar\String_) { return null; } - $phpMethodReflection = $this->callableClassMethodMatcher->match($objectVariable, $methodName); - if (! $phpMethodReflection instanceof PhpMethodReflection) { + if (!$phpMethodReflection instanceof \PHPStan\Reflection\Php\PhpMethodReflection) { return null; } - return $this->anonymousFunctionFactory->create($phpMethodReflection, $objectVariable); } - - private function shouldSkipArray(Array_ $array): bool + private function shouldSkipArray(\PhpParser\Node\Expr\Array_ $array) : bool { // callback is exactly "[$two, 'items']" - if (count($array->items) !== 2) { - return true; + if (\count($array->items) !== 2) { + return \true; } - // can be totally empty in case of "[, $value]" if ($array->items[0] === null) { - return true; + return \true; } - if ($array->items[1] === null) { - return true; + return \true; } - return $this->isCallbackAtFunctionNames($array, ['register_shutdown_function', 'forward_static_call']); } - /** * @param string[] $functionNames */ - private function isCallbackAtFunctionNames(Array_ $array, array $functionNames): bool + private function isCallbackAtFunctionNames(\PhpParser\Node\Expr\Array_ $array, array $functionNames) : bool { - $parentNode = $array->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Arg) { - return false; + $parentNode = $array->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Arg) { + return \false; } - - $parentParentNode = $parentNode->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentParentNode instanceof FuncCall) { - return false; + $parentParentNode = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentParentNode instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - return $this->isNames($parentParentNode, $functionNames); } } diff --git a/rules/CodeQuality/Rector/Assign/CombinedAssignRector.php b/rules/CodeQuality/Rector/Assign/CombinedAssignRector.php index 52e3a235f46..9963be67b0d 100644 --- a/rules/CodeQuality/Rector/Assign/CombinedAssignRector.php +++ b/rules/CodeQuality/Rector/Assign/CombinedAssignRector.php @@ -1,7 +1,6 @@ assignAndBinaryMap = $assignAndBinaryMap; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Simplify $value = $value + 5; assignments to shorter ones', - [new CodeSample('$value = $value + 5;', '$value += 5;')] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Simplify $value = $value + 5; assignments to shorter ones', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('$value = $value + 5;', '$value += 5;')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof BinaryOp) { + if (!$node->expr instanceof \PhpParser\Node\Expr\BinaryOp) { return null; } - /** @var BinaryOp $binaryNode */ $binaryNode = $node->expr; - - if (! $this->nodeComparator->areNodesEqual($node->var, $binaryNode->left)) { + if (!$this->nodeComparator->areNodesEqual($node->var, $binaryNode->left)) { return null; } - $assignClass = $this->assignAndBinaryMap->getAlternative($binaryNode); if ($assignClass === null) { return null; } - return new $assignClass($node->var, $binaryNode->right); } } diff --git a/rules/CodeQuality/Rector/Assign/SplitListAssignToSeparateLineRector.php b/rules/CodeQuality/Rector/Assign/SplitListAssignToSeparateLineRector.php index 1a7c861daa6..3d99466a415 100644 --- a/rules/CodeQuality/Rector/Assign/SplitListAssignToSeparateLineRector.php +++ b/rules/CodeQuality/Rector/Assign/SplitListAssignToSeparateLineRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var Array_|List_ $leftArray */ $leftArray = $node->var; - /** @var Array_ $rightArray */ $rightArray = $node->expr; - $standaloneAssigns = $this->createStandaloneAssigns($leftArray, $rightArray); $this->addNodesAfterNode($standaloneAssigns, $node); - $this->removeNode($node); - return $node; } - - private function shouldSkip(Assign $assign): bool + private function shouldSkip(\PhpParser\Node\Expr\Assign $assign) : bool { - if (! $assign->var instanceof Array_ && ! $assign->var instanceof List_) { - return true; + if (!$assign->var instanceof \PhpParser\Node\Expr\Array_ && !$assign->var instanceof \PhpParser\Node\Expr\List_) { + return \true; } - $assignExpr = $assign->expr; - if (! $assignExpr instanceof Array_) { - return true; + if (!$assignExpr instanceof \PhpParser\Node\Expr\Array_) { + return \true; } - - if (count($assign->var->items) !== count($assignExpr->items)) { - return true; + if (\count($assign->var->items) !== \count($assignExpr->items)) { + return \true; } - // is value swap return $this->isValueSwap($assign->var, $assignExpr); } - /** * @param Array_|List_ $expr * @return Assign[] */ - private function createStandaloneAssigns(Expr $expr, Array_ $rightArray): array + private function createStandaloneAssigns(\PhpParser\Node\Expr $expr, \PhpParser\Node\Expr\Array_ $rightArray) : array { $standaloneAssigns = []; foreach ($expr->items as $key => $leftArrayItem) { if ($leftArrayItem === null) { continue; } - $rightArrayItem = $rightArray->items[$key]; - - if (! $rightArrayItem instanceof ArrayItem) { + if (!$rightArrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - - $standaloneAssigns[] = new Assign($leftArrayItem->value, $rightArrayItem); + $standaloneAssigns[] = new \PhpParser\Node\Expr\Assign($leftArrayItem->value, $rightArrayItem); } - return $standaloneAssigns; } - /** * @param Array_|List_ $expr */ - private function isValueSwap(Expr $expr, Array_ $secondArray): bool + private function isValueSwap(\PhpParser\Node\Expr $expr, \PhpParser\Node\Expr\Array_ $secondArray) : bool { $firstArrayItemsHash = $this->getArrayItemsHash($expr); $secondArrayItemsHash = $this->getArrayItemsHash($secondArray); - return $firstArrayItemsHash === $secondArrayItemsHash; } - /** * @param Array_|List_ $node */ - private function getArrayItemsHash(Node $node): string + private function getArrayItemsHash(\PhpParser\Node $node) : string { $arrayItemsHashes = []; foreach ($node->items as $arrayItem) { $arrayItemsHashes[] = $this->nodeComparator->printWithoutComments($arrayItem); } - - sort($arrayItemsHashes); - - $arrayItemsHash = implode('', $arrayItemsHashes); - - return sha1($arrayItemsHash); + \sort($arrayItemsHashes); + $arrayItemsHash = \implode('', $arrayItemsHashes); + return \sha1($arrayItemsHash); } } diff --git a/rules/CodeQuality/Rector/BooleanAnd/SimplifyEmptyArrayCheckRector.php b/rules/CodeQuality/Rector/BooleanAnd/SimplifyEmptyArrayCheckRector.php index d6c9fa8b052..f036c1b1407 100644 --- a/rules/CodeQuality/Rector/BooleanAnd/SimplifyEmptyArrayCheckRector.php +++ b/rules/CodeQuality/Rector/BooleanAnd/SimplifyEmptyArrayCheckRector.php @@ -1,7 +1,6 @@ binaryOpManipulator = $binaryOpManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Simplify `is_array` and `empty` functions combination into a simple identical check for an empty array', - [new CodeSample('is_array($values) && empty($values)', '$values === []')] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Simplify `is_array` and `empty` functions combination into a simple identical check for an empty array', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('is_array($values) && empty($values)', '$values === []')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [BooleanAnd::class]; + return [\PhpParser\Node\Expr\BinaryOp\BooleanAnd::class]; } - /** * @param BooleanAnd $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode( $node, // is_array(...) - function (Node $node): bool { - if (! $node instanceof FuncCall) { - return false; + function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } return $this->isName($node, 'is_array'); }, - Empty_::class + \PhpParser\Node\Expr\Empty_::class ); - - if (! $twoNodeMatch instanceof TwoNodeMatch) { + if (!$twoNodeMatch instanceof \Rector\Php71\ValueObject\TwoNodeMatch) { return null; } - /** @var Empty_ $emptyOrNotIdenticalNode */ $emptyOrNotIdenticalNode = $twoNodeMatch->getSecondExpr(); - - return new Identical($emptyOrNotIdenticalNode->expr, new Array_()); + return new \PhpParser\Node\Expr\BinaryOp\Identical($emptyOrNotIdenticalNode->expr, new \PhpParser\Node\Expr\Array_()); } } diff --git a/rules/CodeQuality/Rector/BooleanNot/SimplifyDeMorganBinaryRector.php b/rules/CodeQuality/Rector/BooleanNot/SimplifyDeMorganBinaryRector.php index 543918b8f7c..a306520e3a5 100644 --- a/rules/CodeQuality/Rector/BooleanNot/SimplifyDeMorganBinaryRector.php +++ b/rules/CodeQuality/Rector/BooleanNot/SimplifyDeMorganBinaryRector.php @@ -1,7 +1,6 @@ binaryOpManipulator = $binaryOpManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Simplify negated conditions with de Morgan theorem', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Simplify negated conditions with de Morgan theorem', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $a = 5; $b = 10; $result = !($a > 20 || $b <= 50); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $a = 5; $b = 10; $result = $a <= 20 && $b > 50; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [BooleanNot::class]; + return [\PhpParser\Node\Expr\BooleanNot::class]; } - /** * @param BooleanNot $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof BooleanOr) { + if (!$node->expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return null; } - return $this->binaryOpManipulator->inverseBinaryOp($node->expr); } } diff --git a/rules/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector.php b/rules/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector.php index cf7e252a209..c5e627758b4 100644 --- a/rules/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector.php +++ b/rules/CodeQuality/Rector/Catch_/ThrowWithPreviousExceptionRector.php @@ -1,10 +1,9 @@ reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'When throwing into a catch block, checks that the previous exception is passed to the new throw clause', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('When throwing into a catch block, checks that the previous exception is passed to the new throw clause', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -64,8 +55,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -78,122 +68,97 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Catch_::class]; + return [\PhpParser\Node\Stmt\Catch_::class]; } - /** * @param Catch_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $caughtThrowableVariable = $node->var; - if (! $caughtThrowableVariable instanceof Variable) { + if (!$caughtThrowableVariable instanceof \PhpParser\Node\Expr\Variable) { return null; } - - $this->traverseNodesWithCallable($node->stmts, function (Node $node) use ($caughtThrowableVariable): ?int { - if (! $node instanceof Throw_) { + $this->traverseNodesWithCallable($node->stmts, function (\PhpParser\Node $node) use($caughtThrowableVariable) : ?int { + if (!$node instanceof \PhpParser\Node\Stmt\Throw_) { return null; } - return $this->refactorThrow($node, $caughtThrowableVariable); }); - return $node; } - - private function refactorThrow(Throw_ $throw, Variable $catchedThrowableVariable): ?int + private function refactorThrow(\PhpParser\Node\Stmt\Throw_ $throw, \PhpParser\Node\Expr\Variable $catchedThrowableVariable) : ?int { - if (! $throw->expr instanceof New_) { + if (!$throw->expr instanceof \PhpParser\Node\Expr\New_) { return null; } - $new = $throw->expr; - if (! $new->class instanceof Name) { + if (!$new->class instanceof \PhpParser\Node\Name) { return null; } - $exceptionArgumentPosition = $this->resolveExceptionArgumentPosition($new->class); if ($exceptionArgumentPosition === null) { return null; } - // exception is bundled if (isset($new->args[$exceptionArgumentPosition])) { return null; } - - if (! isset($new->args[0])) { + if (!isset($new->args[0])) { // get previous message - $new->args[0] = new Arg(new MethodCall($catchedThrowableVariable, 'getMessage')); + $new->args[0] = new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\MethodCall($catchedThrowableVariable, 'getMessage')); } - - if (! isset($new->args[1])) { + if (!isset($new->args[1])) { // get previous code - $new->args[1] = new Arg(new MethodCall($catchedThrowableVariable, 'getCode')); + $new->args[1] = new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\MethodCall($catchedThrowableVariable, 'getCode')); } - $arg1 = $new->args[1]; - if ($arg1->name instanceof Identifier && $arg1->name->toString() === 'previous') { - $new->args[1] = new Arg(new MethodCall($catchedThrowableVariable, 'getCode')); + if ($arg1->name instanceof \PhpParser\Node\Identifier && $arg1->name->toString() === 'previous') { + $new->args[1] = new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\MethodCall($catchedThrowableVariable, 'getCode')); $new->args[$exceptionArgumentPosition] = $arg1; } else { - $new->args[$exceptionArgumentPosition] = new Arg($catchedThrowableVariable); + $new->args[$exceptionArgumentPosition] = new \PhpParser\Node\Arg($catchedThrowableVariable); } - // null the node, to fix broken format preserving printers, see https://github.com/rectorphp/rector/issues/5576 - $new->setAttribute(AttributeKey::ORIGINAL_NODE, null); - + $new->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); // nothing more to add - return NodeTraverser::DONT_TRAVERSE_CHILDREN; + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CHILDREN; } - - private function resolveExceptionArgumentPosition(Name $exceptionName): ?int + private function resolveExceptionArgumentPosition(\PhpParser\Node\Name $exceptionName) : ?int { $className = $this->getName($exceptionName); - // is native exception? - if (! Strings::contains($className, '\\')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($className, '\\')) { return self::DEFAULT_EXCEPTION_ARGUMENT_POSITION; } - - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return self::DEFAULT_EXCEPTION_ARGUMENT_POSITION; } - $classReflection = $this->reflectionProvider->getClass($className); - $construct = $classReflection->hasMethod(MethodName::CONSTRUCT); - if (! $construct) { + $construct = $classReflection->hasMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$construct) { return self::DEFAULT_EXCEPTION_ARGUMENT_POSITION; } - $constructorReflectionMethod = $classReflection->getConstructor(); $parametersAcceptor = $constructorReflectionMethod->getVariants()[0]; - foreach ($parametersAcceptor->getParameters() as $position => $parameterReflection) { $parameterType = $parameterReflection->getType(); - if (! $parameterType instanceof TypeWithClassName) { + if (!$parameterType instanceof \PHPStan\Type\TypeWithClassName) { continue; } - - $objectType = new ObjectType('Throwable'); + $objectType = new \PHPStan\Type\ObjectType('Throwable'); if ($objectType->isSuperTypeOf($parameterType)->no()) { continue; } - return $position; } - return null; } } diff --git a/rules/CodeQuality/Rector/ClassMethod/DateTimeToDateTimeInterfaceRector.php b/rules/CodeQuality/Rector/ClassMethod/DateTimeToDateTimeInterfaceRector.php index f1a4033a67e..d2a8d8996db 100644 --- a/rules/CodeQuality/Rector/ClassMethod/DateTimeToDateTimeInterfaceRector.php +++ b/rules/CodeQuality/Rector/ClassMethod/DateTimeToDateTimeInterfaceRector.php @@ -1,7 +1,6 @@ phpDocTypeChanger = $phpDocTypeChanger; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes DateTime type-hint to DateTimeInterface', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes DateTime type-hint to DateTimeInterface', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function methodWithDateTime(\DateTime $dateTime) { @@ -60,8 +51,7 @@ class SomeClass { } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** * @param \DateTime|\DateTimeImmutable $dateTime @@ -72,89 +62,73 @@ class SomeClass { } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::DATE_TIME_INTERFACE)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::DATE_TIME_INTERFACE)) { return null; } - - $isModifiedNode = false; + $isModifiedNode = \false; foreach ($node->getParams() as $param) { - if (! $this->isObjectType($param, new ObjectType('DateTime'))) { + if (!$this->isObjectType($param, new \PHPStan\Type\ObjectType('DateTime'))) { continue; } - $this->refactorParamTypeHint($param); $this->refactorParamDocBlock($param, $node); $this->refactorMethodCalls($param, $node); - $isModifiedNode = true; + $isModifiedNode = \true; } - - if (! $isModifiedNode) { + if (!$isModifiedNode) { return null; } - return $node; } - - private function refactorParamTypeHint(Param $param): void + private function refactorParamTypeHint(\PhpParser\Node\Param $param) : void { - $fullyQualified = new FullyQualified('DateTimeInterface'); - if ($param->type instanceof NullableType) { - $param->type = new NullableType($fullyQualified); + $fullyQualified = new \PhpParser\Node\Name\FullyQualified('DateTimeInterface'); + if ($param->type instanceof \PhpParser\Node\NullableType) { + $param->type = new \PhpParser\Node\NullableType($fullyQualified); return; } - $param->type = $fullyQualified; } - - private function refactorParamDocBlock(Param $param, ClassMethod $classMethod): void + private function refactorParamDocBlock(\PhpParser\Node\Param $param, \PhpParser\Node\Stmt\ClassMethod $classMethod) : void { - $types = [new ObjectType('DateTime'), new ObjectType('DateTimeImmutable')]; - if ($param->type instanceof NullableType) { - $types[] = new NullType(); + $types = [new \PHPStan\Type\ObjectType('DateTime'), new \PHPStan\Type\ObjectType('DateTimeImmutable')]; + if ($param->type instanceof \PhpParser\Node\NullableType) { + $types[] = new \PHPStan\Type\NullType(); } - $paramName = $this->getName($param->var); if ($paramName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); - $this->phpDocTypeChanger->changeParamType($phpDocInfo, new UnionType($types), $param, $paramName); + $this->phpDocTypeChanger->changeParamType($phpDocInfo, new \PHPStan\Type\UnionType($types), $param, $paramName); } - - private function refactorMethodCalls(Param $param, ClassMethod $classMethod): void + private function refactorMethodCalls(\PhpParser\Node\Param $param, \PhpParser\Node\Stmt\ClassMethod $classMethod) : void { if ($classMethod->stmts === null) { return; } - - $this->traverseNodesWithCallable($classMethod->stmts, function (Node $node) use ($param): void { - if (! ($node instanceof MethodCall)) { + $this->traverseNodesWithCallable($classMethod->stmts, function (\PhpParser\Node $node) use($param) : void { + if (!$node instanceof \PhpParser\Node\Expr\MethodCall) { return; } - $this->refactorMethodCall($param, $node); }); } - - private function refactorMethodCall(Param $param, MethodCall $methodCall): void + private function refactorMethodCall(\PhpParser\Node\Param $param, \PhpParser\Node\Expr\MethodCall $methodCall) : void { $paramName = $this->getName($param->var); if ($paramName === null) { @@ -163,38 +137,30 @@ CODE_SAMPLE if ($this->shouldSkipMethodCallRefactor($paramName, $methodCall)) { return; } - - $assign = new Assign(new Variable($paramName), $methodCall); - + $assign = new \PhpParser\Node\Expr\Assign(new \PhpParser\Node\Expr\Variable($paramName), $methodCall); /** @var Node $parent */ - $parent = $methodCall->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Arg) { + $parent = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Arg) { $parent->value = $assign; return; } - - if (! $parent instanceof Expression) { + if (!$parent instanceof \PhpParser\Node\Stmt\Expression) { return; } - $parent->expr = $assign; } - - private function shouldSkipMethodCallRefactor(string $paramName, MethodCall $methodCall): bool + private function shouldSkipMethodCallRefactor(string $paramName, \PhpParser\Node\Expr\MethodCall $methodCall) : bool { - if (! $this->isName($methodCall->var, $paramName)) { - return true; + if (!$this->isName($methodCall->var, $paramName)) { + return \true; } - - if (! $this->isNames($methodCall->name, self::METHODS_RETURNING_CLASS_INSTANCE_MAP)) { - return true; + if (!$this->isNames($methodCall->name, self::METHODS_RETURNING_CLASS_INSTANCE_MAP)) { + return \true; } - - $parentNode = $methodCall->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Node) { - return true; + $parentNode = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node) { + return \true; } - - return $parentNode instanceof Assign; + return $parentNode instanceof \PhpParser\Node\Expr\Assign; } } diff --git a/rules/CodeQuality/Rector/ClassMethod/NarrowUnionTypeDocRector.php b/rules/CodeQuality/Rector/ClassMethod/NarrowUnionTypeDocRector.php index c991d571fda..9de8cbec357 100644 --- a/rules/CodeQuality/Rector/ClassMethod/NarrowUnionTypeDocRector.php +++ b/rules/CodeQuality/Rector/ClassMethod/NarrowUnionTypeDocRector.php @@ -1,7 +1,6 @@ unionTypeAnalyzer = $unionTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes docblock by narrowing type', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes docblock by narrowing type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** * @param object|DateTime $message @@ -45,8 +39,7 @@ class SomeClass { } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** * @param DateTime $message @@ -56,78 +49,62 @@ class SomeClass { } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); $params = $node->getParams(); - foreach ($params as $key => $param) { /** @var string $paramName */ $paramName = $this->getName($param->var); $paramType = $phpDocInfo->getParamType($paramName); - - if (! $paramType instanceof UnionType) { + if (!$paramType instanceof \PHPStan\Type\UnionType) { continue; } - if ($this->unionTypeAnalyzer->isScalar($paramType)) { $this->changeDocObjectScalar($key, $phpDocInfo); continue; } - if ($this->unionTypeAnalyzer->hasObjectWithoutClassType($paramType)) { $this->changeDocObjectWithoutClassType($paramType, $key, $phpDocInfo); } } - if ($phpDocInfo->hasChanged()) { - $node->setAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, true); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, \true); return $node; } - return null; } - - private function changeDocObjectWithoutClassType( - UnionType $unionType, - int $key, - PhpDocInfo $phpDocInfo - ): void { - if (! $this->unionTypeAnalyzer->hasObjectWithoutClassTypeWithOnlyFullyQualifiedObjectType($unionType)) { + private function changeDocObjectWithoutClassType(\PHPStan\Type\UnionType $unionType, int $key, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void + { + if (!$this->unionTypeAnalyzer->hasObjectWithoutClassTypeWithOnlyFullyQualifiedObjectType($unionType)) { return; } - $types = $unionType->getTypes(); $resultType = ''; foreach ($types as $type) { - if ($type instanceof FullyQualifiedObjectType) { + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType) { $resultType .= $type->getClassName() . '|'; } } - - $resultType = rtrim($resultType, '|'); + $resultType = \rtrim($resultType, '|'); $paramTagValueNodes = $phpDocInfo->getParamTagValueNodes(); - $paramTagValueNodes[$key]->type = new IdentifierTypeNode($resultType); + $paramTagValueNodes[$key]->type = new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode($resultType); } - - private function changeDocObjectScalar(int $key, PhpDocInfo $phpDocInfo): void + private function changeDocObjectScalar(int $key, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void { $paramTagValueNodes = $phpDocInfo->getParamTagValueNodes(); - $paramTagValueNodes[$key]->type = new IdentifierTypeNode('scalar'); + $paramTagValueNodes[$key]->type = new \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('scalar'); } } diff --git a/rules/CodeQuality/Rector/Class_/CompleteDynamicPropertiesRector.php b/rules/CodeQuality/Rector/Class_/CompleteDynamicPropertiesRector.php index 53b3fd1ce6b..b3871f55fe4 100644 --- a/rules/CodeQuality/Rector/Class_/CompleteDynamicPropertiesRector.php +++ b/rules/CodeQuality/Rector/Class_/CompleteDynamicPropertiesRector.php @@ -1,7 +1,6 @@ missingPropertiesFactory = $missingPropertiesFactory; $this->localPropertyAnalyzer = $localPropertyAnalyzer; $this->classLikeAnalyzer = $classLikeAnalyzer; $this->reflectionProvider = $reflectionProvider; $this->classAnalyzer = $classAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add missing dynamic properties', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add missing dynamic properties', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function set() @@ -78,8 +63,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -93,116 +77,86 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipClass($node)) { return null; } - $className = $this->getName($node); if ($className === null) { return null; } - - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return null; } - $classReflection = $this->reflectionProvider->getClass($className); - // special case for Laravel Collection macro magic - $fetchedLocalPropertyNameToTypes = $this->localPropertyAnalyzer->resolveFetchedPropertiesToTypesFromClass( - $node - ); - + $fetchedLocalPropertyNameToTypes = $this->localPropertyAnalyzer->resolveFetchedPropertiesToTypesFromClass($node); $propertiesToComplete = $this->resolvePropertiesToComplete($node, $fetchedLocalPropertyNameToTypes); if ($propertiesToComplete === []) { return null; } - $propertiesToComplete = $this->filterOutExistingProperties($classReflection, $propertiesToComplete); - - $newProperties = $this->missingPropertiesFactory->create( - $fetchedLocalPropertyNameToTypes, - $propertiesToComplete - ); - - $node->stmts = array_merge($newProperties, $node->stmts); - + $newProperties = $this->missingPropertiesFactory->create($fetchedLocalPropertyNameToTypes, $propertiesToComplete); + $node->stmts = \array_merge($newProperties, $node->stmts); return $node; } - - private function shouldSkipClass(Class_ $class): bool + private function shouldSkipClass(\PhpParser\Node\Stmt\Class_ $class) : bool { if ($this->classAnalyzer->isAnonymousClass($class)) { - return true; + return \true; } - $className = $this->nodeNameResolver->getName($class); if ($className === null) { - return true; + return \true; } - - if (! $this->reflectionProvider->hasClass($className)) { - return true; + if (!$this->reflectionProvider->hasClass($className)) { + return \true; } - $classReflection = $this->reflectionProvider->getClass($className); - // properties are accessed via magic, nothing we can do if ($classReflection->hasMethod('__set')) { - return true; + return \true; } - return $classReflection->hasMethod('__get'); } - /** * @param array $fetchedLocalPropertyNameToTypes * @return string[] */ - private function resolvePropertiesToComplete(Class_ $class, array $fetchedLocalPropertyNameToTypes): array + private function resolvePropertiesToComplete(\PhpParser\Node\Stmt\Class_ $class, array $fetchedLocalPropertyNameToTypes) : array { $propertyNames = $this->classLikeAnalyzer->resolvePropertyNames($class); - /** @var string[] $fetchedLocalPropertyNames */ - $fetchedLocalPropertyNames = array_keys($fetchedLocalPropertyNameToTypes); - - return array_diff($fetchedLocalPropertyNames, $propertyNames); + $fetchedLocalPropertyNames = \array_keys($fetchedLocalPropertyNameToTypes); + return \array_diff($fetchedLocalPropertyNames, $propertyNames); } - /** * @param string[] $propertiesToComplete * @return string[] */ - private function filterOutExistingProperties(ClassReflection $classReflection, array $propertiesToComplete): array + private function filterOutExistingProperties(\PHPStan\Reflection\ClassReflection $classReflection, array $propertiesToComplete) : array { $missingPropertyNames = []; - // remove other properties that are accessible from this scope foreach ($propertiesToComplete as $propertyToComplete) { if ($classReflection->hasProperty($propertyToComplete)) { continue; } - $missingPropertyNames[] = $propertyToComplete; } - return $missingPropertyNames; } } diff --git a/rules/CodeQuality/Rector/Concat/JoinStringConcatRector.php b/rules/CodeQuality/Rector/Concat/JoinStringConcatRector.php index 3cebd0f2a02..4c23ce1b7e9 100644 --- a/rules/CodeQuality/Rector/Concat/JoinStringConcatRector.php +++ b/rules/CodeQuality/Rector/Concat/JoinStringConcatRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Concat::class]; + return [\PhpParser\Node\Expr\BinaryOp\Concat::class]; } - /** * @param Concat $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $this->nodeReplacementIsRestricted = false; - - if (! $this->isTopMostConcatNode($node)) { + $this->nodeReplacementIsRestricted = \false; + if (!$this->isTopMostConcatNode($node)) { return null; } - $joinedNode = $this->joinConcatIfStrings($node); - if (! $joinedNode instanceof String_) { + if (!$joinedNode instanceof \PhpParser\Node\Scalar\String_) { return null; } - if ($this->nodeReplacementIsRestricted) { return null; } - return $joinedNode; } - - private function isTopMostConcatNode(Concat $concat): bool + private function isTopMostConcatNode(\PhpParser\Node\Expr\BinaryOp\Concat $concat) : bool { - $parent = $concat->getAttribute(AttributeKey::PARENT_NODE); - return ! $parent instanceof Concat; + $parent = $concat->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + return !$parent instanceof \PhpParser\Node\Expr\BinaryOp\Concat; } - /** * @return Concat|String_ */ - private function joinConcatIfStrings(Concat $node): Expr + private function joinConcatIfStrings(\PhpParser\Node\Expr\BinaryOp\Concat $node) : \PhpParser\Node\Expr { $concat = clone $node; - - if ($concat->left instanceof Concat) { + if ($concat->left instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { $concat->left = $this->joinConcatIfStrings($concat->left); } - - if ($concat->right instanceof Concat) { + if ($concat->right instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { $concat->right = $this->joinConcatIfStrings($concat->right); } - - if (! $concat->left instanceof String_) { + if (!$concat->left instanceof \PhpParser\Node\Scalar\String_) { return $node; } - - if (! $concat->right instanceof String_) { + if (!$concat->right instanceof \PhpParser\Node\Scalar\String_) { return $node; } - $leftValue = $concat->left->value; $rightValue = $concat->right->value; - if ($leftValue === "\n") { - $this->nodeReplacementIsRestricted = true; + $this->nodeReplacementIsRestricted = \true; return $node; } - if ($rightValue === "\n") { - $this->nodeReplacementIsRestricted = true; + $this->nodeReplacementIsRestricted = \true; return $node; } - - $resultString = new String_($leftValue . $rightValue); - if (Strings::length($resultString->value) >= self::LINE_BREAK_POINT) { - $this->nodeReplacementIsRestricted = true; + $resultString = new \PhpParser\Node\Scalar\String_($leftValue . $rightValue); + if (\RectorPrefix20210509\Nette\Utils\Strings::length($resultString->value) >= self::LINE_BREAK_POINT) { + $this->nodeReplacementIsRestricted = \true; return $node; } - return $resultString; } } diff --git a/rules/CodeQuality/Rector/Equal/UseIdenticalOverEqualWithSameTypeRector.php b/rules/CodeQuality/Rector/Equal/UseIdenticalOverEqualWithSameTypeRector.php index 3893183a8c3..d3d90c5c132 100644 --- a/rules/CodeQuality/Rector/Equal/UseIdenticalOverEqualWithSameTypeRector.php +++ b/rules/CodeQuality/Rector/Equal/UseIdenticalOverEqualWithSameTypeRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Equal::class, NotEqual::class]; + return [\PhpParser\Node\Expr\BinaryOp\Equal::class, \PhpParser\Node\Expr\BinaryOp\NotEqual::class]; } - /** * @param Equal|NotEqual $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $leftStaticType = $this->getStaticType($node->left); $rightStaticType = $this->getStaticType($node->right); - // objects can be different by content - if ($leftStaticType instanceof ObjectType) { + if ($leftStaticType instanceof \PHPStan\Type\ObjectType) { return null; } - if ($leftStaticType instanceof MixedType) { + if ($leftStaticType instanceof \PHPStan\Type\MixedType) { return null; } - if ($rightStaticType instanceof MixedType) { + if ($rightStaticType instanceof \PHPStan\Type\MixedType) { return null; } - // different types - if (! $leftStaticType->equals($rightStaticType)) { + if (!$leftStaticType->equals($rightStaticType)) { return null; } - - if ($node instanceof Equal) { - return new Identical($node->left, $node->right); + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Equal) { + return new \PhpParser\Node\Expr\BinaryOp\Identical($node->left, $node->right); } - - return new NotIdentical($node->left, $node->right); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($node->left, $node->right); } } diff --git a/rules/CodeQuality/Rector/Expression/InlineIfToExplicitIfRector.php b/rules/CodeQuality/Rector/Expression/InlineIfToExplicitIfRector.php index 0c898368f16..17155041576 100644 --- a/rules/CodeQuality/Rector/Expression/InlineIfToExplicitIfRector.php +++ b/rules/CodeQuality/Rector/Expression/InlineIfToExplicitIfRector.php @@ -1,7 +1,6 @@ binaryOpManipulator = $binaryOpManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change inline if to explicit if', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change inline if to explicit if', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -50,8 +44,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -64,53 +57,43 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Expression::class]; + return [\PhpParser\Node\Stmt\Expression::class]; } - /** * @param Expression $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node->expr instanceof BooleanAnd) { + if ($node->expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { return $this->processExplicitIf($node); } - if ($node->expr instanceof BooleanOr) { + if ($node->expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return $this->processExplicitIf($node); } return null; } - - private function processExplicitIf(Expression $expression): ?Node + private function processExplicitIf(\PhpParser\Node\Stmt\Expression $expression) : ?\PhpParser\Node { /** @var BooleanAnd|BooleanOr $booleanExpr */ $booleanExpr = $expression->expr; - $leftStaticType = $this->getStaticType($booleanExpr->left); - if (! $leftStaticType instanceof BooleanType) { + if (!$leftStaticType instanceof \PHPStan\Type\BooleanType) { return null; } - - if (! $booleanExpr->right instanceof Assign && ! $booleanExpr->right instanceof AssignOp) { + if (!$booleanExpr->right instanceof \PhpParser\Node\Expr\Assign && !$booleanExpr->right instanceof \PhpParser\Node\Expr\AssignOp) { return null; } - /** @var Expr $expr */ - $expr = $booleanExpr instanceof BooleanAnd - ? $booleanExpr->left - : $this->binaryOpManipulator->inverseNode($booleanExpr->left); - $if = new If_($expr); - $if->stmts[] = new Expression($booleanExpr->right); - + $expr = $booleanExpr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd ? $booleanExpr->left : $this->binaryOpManipulator->inverseNode($booleanExpr->left); + $if = new \PhpParser\Node\Stmt\If_($expr); + $if->stmts[] = new \PhpParser\Node\Stmt\Expression($booleanExpr->right); $this->mirrorComments($if, $expression); return $if; } diff --git a/rules/CodeQuality/Rector/For_/ForRepeatedCountToOwnVariableRector.php b/rules/CodeQuality/Rector/For_/ForRepeatedCountToOwnVariableRector.php index 642cf5c6d1d..b10d6ed7575 100644 --- a/rules/CodeQuality/Rector/For_/ForRepeatedCountToOwnVariableRector.php +++ b/rules/CodeQuality/Rector/For_/ForRepeatedCountToOwnVariableRector.php @@ -1,7 +1,6 @@ variableNaming = $variableNaming; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change count() in for function to own variable', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change count() in for function to own variable', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($items) @@ -47,8 +39,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($items) @@ -60,52 +51,33 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [For_::class]; + return [\PhpParser\Node\Stmt\For_::class]; } - /** * @param For_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $countInCond = null; $variableName = null; - - $forScope = $node->getAttribute(AttributeKey::SCOPE); - - $this->traverseNodesWithCallable($node->cond, function (Node $node) use ( - &$countInCond, - &$variableName, - $forScope - ): ?Variable { - if (! $node instanceof FuncCall) { + $forScope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + $this->traverseNodesWithCallable($node->cond, function (\PhpParser\Node $node) use(&$countInCond, &$variableName, $forScope) : ?Variable { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->isName($node, 'count')) { + if (!$this->isName($node, 'count')) { return null; } - $countInCond = $node; - - $variableName = $this->variableNaming->resolveFromFuncCallFirstArgumentWithSuffix( - $node, - 'Count', - 'itemsCount', - $forScope - ); - - return new Variable($variableName); + $variableName = $this->variableNaming->resolveFromFuncCallFirstArgumentWithSuffix($node, 'Count', 'itemsCount', $forScope); + return new \PhpParser\Node\Expr\Variable($variableName); }); if ($countInCond === null) { return null; @@ -113,10 +85,8 @@ CODE_SAMPLE if ($variableName === null) { return null; } - - $countAssign = new Assign(new Variable($variableName), $countInCond); + $countAssign = new \PhpParser\Node\Expr\Assign(new \PhpParser\Node\Expr\Variable($variableName), $countInCond); $this->addNodeBeforeNode($countAssign, $node); - return $node; } } diff --git a/rules/CodeQuality/Rector/For_/ForToForeachRector.php b/rules/CodeQuality/Rector/For_/ForToForeachRector.php index c543cf481ee..c49b460a690 100644 --- a/rules/CodeQuality/Rector/For_/ForToForeachRector.php +++ b/rules/CodeQuality/Rector/For_/ForToForeachRector.php @@ -1,10 +1,9 @@ inflector = $inflector; $this->forAnalyzer = $forAnalyzer; $this->foreachFactory = $foreachFactory; $this->foreachAnalyzer = $foreachAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change for() to foreach() where useful', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change for() to foreach() where useful', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($tokens) @@ -99,8 +81,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($tokens) @@ -113,146 +94,104 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [For_::class]; + return [\PhpParser\Node\Stmt\For_::class]; } - /** * @param For_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $this->reset(); - $this->matchInit($node->init); - - if (! $this->isConditionMatch($node->cond)) { + if (!$this->isConditionMatch($node->cond)) { return null; } - - if (! $this->forAnalyzer->isLoopMatch($node->loop, $this->keyValueName)) { + if (!$this->forAnalyzer->isLoopMatch($node->loop, $this->keyValueName)) { return null; } - if ($this->iteratedExpr === null) { return null; } - if ($this->keyValueName === null) { return null; } - $iteratedVariable = $this->getName($this->iteratedExpr); if ($iteratedVariable === null) { return null; } - $init = $node->init; - if (count($init) > 2) { + if (\count($init) > 2) { return null; } - if ($this->forAnalyzer->isCountValueVariableUsedInsideForStatements($node, $this->countValueVariableExpr)) { return null; } - - if ($this->forAnalyzer->isAssignmentWithArrayDimFetchAsVariableInsideForStatements( - $node, - $this->keyValueName - )) { + if ($this->forAnalyzer->isAssignmentWithArrayDimFetchAsVariableInsideForStatements($node, $this->keyValueName)) { return null; } - if ($this->forAnalyzer->isArrayWithKeyValueNameUnsetted($node)) { return null; } - return $this->processForToForeach($node, $iteratedVariable); } - - private function processForToForeach(For_ $for, string $iteratedVariable): ?Foreach_ + private function processForToForeach(\PhpParser\Node\Stmt\For_ $for, string $iteratedVariable) : ?\PhpParser\Node\Stmt\Foreach_ { $originalVariableSingle = $this->inflector->singularize($iteratedVariable); $iteratedVariableSingle = $originalVariableSingle; if ($iteratedVariableSingle === $iteratedVariable) { - $iteratedVariableSingle = 'single' . ucfirst($iteratedVariableSingle); + $iteratedVariableSingle = 'single' . \ucfirst($iteratedVariableSingle); } - - if (! $this->forAnalyzer->isValueVarUsedNext($for, $iteratedVariableSingle)) { + if (!$this->forAnalyzer->isValueVarUsedNext($for, $iteratedVariableSingle)) { return $this->createForeachFromForWithIteratedVariableSingle($for, $iteratedVariableSingle); } - if ($iteratedVariableSingle === $originalVariableSingle) { return null; } - - if (! $this->forAnalyzer->isValueVarUsedNext($for, $originalVariableSingle)) { + if (!$this->forAnalyzer->isValueVarUsedNext($for, $originalVariableSingle)) { return $this->createForeachFromForWithIteratedVariableSingle($for, $originalVariableSingle); } - return null; } - - private function createForeachFromForWithIteratedVariableSingle(For_ $for, string $iteratedVariableSingle): Foreach_ + private function createForeachFromForWithIteratedVariableSingle(\PhpParser\Node\Stmt\For_ $for, string $iteratedVariableSingle) : \PhpParser\Node\Stmt\Foreach_ { - $foreach = $this->foreachFactory->createFromFor( - $for, - $iteratedVariableSingle, - $this->iteratedExpr, - $this->keyValueName - ); + $foreach = $this->foreachFactory->createFromFor($for, $iteratedVariableSingle, $this->iteratedExpr, $this->keyValueName); $this->mirrorComments($foreach, $for); - if ($this->keyValueName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $this->foreachAnalyzer->useForeachVariableInStmts( - $foreach->expr, - $foreach->valueVar, - $foreach->stmts, - $this->keyValueName - ); - + $this->foreachAnalyzer->useForeachVariableInStmts($foreach->expr, $foreach->valueVar, $foreach->stmts, $this->keyValueName); return $foreach; } - - private function reset(): void + private function reset() : void { $this->keyValueName = null; $this->countValueVariableExpr = null; $this->countValueName = null; $this->iteratedExpr = null; } - /** * @param Expr[] $initExprs */ - private function matchInit(array $initExprs): void + private function matchInit(array $initExprs) : void { foreach ($initExprs as $initExpr) { - if (! $initExpr instanceof Assign) { + if (!$initExpr instanceof \PhpParser\Node\Expr\Assign) { continue; } - if ($this->valueResolver->isValue($initExpr->expr, 0)) { $this->keyValueName = $this->getName($initExpr->var); } - - if (! $initExpr->expr instanceof FuncCall) { + if (!$initExpr->expr instanceof \PhpParser\Node\Expr\FuncCall) { continue; } - $funcCall = $initExpr->expr; - if ($this->nodeNameResolver->isName($funcCall, self::COUNT)) { $this->countValueVariableExpr = $initExpr->var; $this->countValueName = $this->getName($initExpr->var); @@ -260,36 +199,30 @@ CODE_SAMPLE } } } - /** * @param Expr[] $condExprs */ - private function isConditionMatch(array $condExprs): bool + private function isConditionMatch(array $condExprs) : bool { if ($this->forAnalyzer->isCondExprOneOrKeyValueNameNotNull($condExprs, $this->keyValueName)) { - return false; + return \false; } - /** @var string $keyValueName */ $keyValueName = $this->keyValueName; if ($this->countValueName !== null) { return $this->forAnalyzer->isCondExprSmallerOrGreater($condExprs, $keyValueName, $this->countValueName); } - - if (! $condExprs[0] instanceof BinaryOp) { - return false; + if (!$condExprs[0] instanceof \PhpParser\Node\Expr\BinaryOp) { + return \false; } - $funcCall = $condExprs[0]->right; - if (! $funcCall instanceof FuncCall) { - return false; + if (!$funcCall instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - if ($this->nodeNameResolver->isName($funcCall, self::COUNT)) { $this->iteratedExpr = $funcCall->args[0]->value; - return true; + return \true; } - - return false; + return \false; } } diff --git a/rules/CodeQuality/Rector/Foreach_/ForeachItemsAssignToEmptyArrayToAssignRector.php b/rules/CodeQuality/Rector/Foreach_/ForeachItemsAssignToEmptyArrayToAssignRector.php index 8532f589e6b..a2207e979b6 100644 --- a/rules/CodeQuality/Rector/Foreach_/ForeachItemsAssignToEmptyArrayToAssignRector.php +++ b/rules/CodeQuality/Rector/Foreach_/ForeachItemsAssignToEmptyArrayToAssignRector.php @@ -1,7 +1,6 @@ nodeUsageFinder = $nodeUsageFinder; $this->foreachAnalyzer = $foreachAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change foreach() items assign to empty array to direct assign', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change foreach() items assign to empty array to direct assign', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($items) @@ -55,8 +46,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($items) @@ -67,55 +57,45 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Foreach_::class]; + return [\PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $assignVariable = $this->foreachAnalyzer->matchAssignItemsOnlyForeachArrayVariable($node); - if (! $assignVariable instanceof Expr) { + if (!$assignVariable instanceof \PhpParser\Node\Expr) { return null; } - if ($this->shouldSkipAsPartOfNestedForeach($node)) { return null; } - $previousDeclaration = $this->nodeUsageFinder->findPreviousForeachNodeUsage($node, $assignVariable); - if (! $previousDeclaration instanceof Node) { + if (!$previousDeclaration instanceof \PhpParser\Node) { return null; } - - $previousDeclarationParentNode = $previousDeclaration->getAttribute(AttributeKey::PARENT_NODE); - if (! $previousDeclarationParentNode instanceof Assign) { + $previousDeclarationParentNode = $previousDeclaration->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$previousDeclarationParentNode instanceof \PhpParser\Node\Expr\Assign) { return null; } - // must be empty array, otherwise it will false override $defaultValue = $this->valueResolver->getValue($previousDeclarationParentNode->expr); if ($defaultValue !== []) { return null; } - - return new Assign($assignVariable, $node->expr); + return new \PhpParser\Node\Expr\Assign($assignVariable, $node->expr); } - - private function shouldSkipAsPartOfNestedForeach(Foreach_ $foreach): bool + private function shouldSkipAsPartOfNestedForeach(\PhpParser\Node\Stmt\Foreach_ $foreach) : bool { - $foreachParent = $this->betterNodeFinder->findParentType($foreach, Foreach_::class); + $foreachParent = $this->betterNodeFinder->findParentType($foreach, \PhpParser\Node\Stmt\Foreach_::class); return $foreachParent !== null; } } diff --git a/rules/CodeQuality/Rector/Foreach_/ForeachToInArrayRector.php b/rules/CodeQuality/Rector/Foreach_/ForeachToInArrayRector.php index 08ade0e6752..7cf13e6622b 100644 --- a/rules/CodeQuality/Rector/Foreach_/ForeachToInArrayRector.php +++ b/rules/CodeQuality/Rector/Foreach_/ForeachToInArrayRector.php @@ -1,7 +1,6 @@ binaryOpManipulator = $binaryOpManipulator; $this->commentsMerger = $commentsMerger; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Simplify `foreach` loops into `in_array` when possible', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Simplify `foreach` loops into `in_array` when possible', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' foreach ($items as $item) { if ($item === 'something') { return true; @@ -60,174 +51,133 @@ foreach ($items as $item) { return false; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' return in_array('something', $items, true); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Foreach_::class]; + return [\PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipForeach($node)) { return null; } - /** @var If_ $firstNodeInsideForeach */ $firstNodeInsideForeach = $node->stmts[0]; if ($this->shouldSkipIf($firstNodeInsideForeach)) { return null; } - /** @var Identical|Equal $ifCondition */ $ifCondition = $firstNodeInsideForeach->cond; $foreachValueVar = $node->valueVar; - $twoNodeMatch = $this->matchNodes($ifCondition, $foreachValueVar); - if (! $twoNodeMatch instanceof TwoNodeMatch) { + if (!$twoNodeMatch instanceof \Rector\Php71\ValueObject\TwoNodeMatch) { return null; } - $comparedNode = $twoNodeMatch->getSecondExpr(); - if (! $this->isIfBodyABoolReturnNode($firstNodeInsideForeach)) { + if (!$this->isIfBodyABoolReturnNode($firstNodeInsideForeach)) { return null; } - $funcCall = $this->createInArrayFunction($comparedNode, $ifCondition, $node); - /** @var Return_ $returnToRemove */ - $returnToRemove = $node->getAttribute(AttributeKey::NEXT_NODE); - + $returnToRemove = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); /** @var Return_ $return */ $return = $firstNodeInsideForeach->stmts[0]; if ($returnToRemove->expr === null) { return null; } - - if (! $this->valueResolver->isTrueOrFalse($returnToRemove->expr)) { + if (!$this->valueResolver->isTrueOrFalse($returnToRemove->expr)) { return null; } - $returnedExpr = $return->expr; - if (! $returnedExpr instanceof Expr) { + if (!$returnedExpr instanceof \PhpParser\Node\Expr) { return null; } - // cannot be "return true;" + "return true;" if ($this->nodeComparator->areNodesEqual($return, $returnToRemove)) { return null; } - $this->removeNode($returnToRemove); - $return = $this->createReturn($returnedExpr, $funcCall); - $this->commentsMerger->keepChildren($return, $node); - return $return; } - - private function shouldSkipForeach(Foreach_ $foreach): bool + private function shouldSkipForeach(\PhpParser\Node\Stmt\Foreach_ $foreach) : bool { if ($foreach->keyVar !== null) { - return true; + return \true; } - - if (count($foreach->stmts) > 1) { - return true; + if (\count($foreach->stmts) > 1) { + return \true; } - - $nextNode = $foreach->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextNode instanceof Node) { - return true; + $nextNode = $foreach->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextNode instanceof \PhpParser\Node) { + return \true; } - if (! $nextNode instanceof Return_) { - return true; + if (!$nextNode instanceof \PhpParser\Node\Stmt\Return_) { + return \true; } - $returnExpression = $nextNode->expr; - - if (! $returnExpression instanceof Expr) { - return true; + if (!$returnExpression instanceof \PhpParser\Node\Expr) { + return \true; } - - if (! $this->valueResolver->isTrueOrFalse($returnExpression)) { - return true; + if (!$this->valueResolver->isTrueOrFalse($returnExpression)) { + return \true; } - $foreachValueStaticType = $this->getStaticType($foreach->expr); - if ($foreachValueStaticType instanceof ObjectType) { - return true; + if ($foreachValueStaticType instanceof \PHPStan\Type\ObjectType) { + return \true; } - - return ! $foreach->stmts[0] instanceof If_; + return !$foreach->stmts[0] instanceof \PhpParser\Node\Stmt\If_; } - - private function shouldSkipIf(If_ $if): bool + private function shouldSkipIf(\PhpParser\Node\Stmt\If_ $if) : bool { $ifCondition = $if->cond; - if ($ifCondition instanceof Identical) { - return false; + if ($ifCondition instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { + return \false; } - return ! $ifCondition instanceof Equal; + return !$ifCondition instanceof \PhpParser\Node\Expr\BinaryOp\Equal; } - - private function matchNodes(BinaryOp $binaryOp, Expr $expr): ?TwoNodeMatch + private function matchNodes(\PhpParser\Node\Expr\BinaryOp $binaryOp, \PhpParser\Node\Expr $expr) : ?\Rector\Php71\ValueObject\TwoNodeMatch { - return $this->binaryOpManipulator->matchFirstAndSecondConditionNode( - $binaryOp, - Variable::class, - function (Node $node, Node $otherNode) use ($expr): bool { - return $this->nodeComparator->areNodesEqual($otherNode, $expr); - } - ); + return $this->binaryOpManipulator->matchFirstAndSecondConditionNode($binaryOp, \PhpParser\Node\Expr\Variable::class, function (\PhpParser\Node $node, \PhpParser\Node $otherNode) use($expr) : bool { + return $this->nodeComparator->areNodesEqual($otherNode, $expr); + }); } - - private function isIfBodyABoolReturnNode(If_ $if): bool + private function isIfBodyABoolReturnNode(\PhpParser\Node\Stmt\If_ $if) : bool { $ifStatment = $if->stmts[0]; - if (! $ifStatment instanceof Return_) { - return false; + if (!$ifStatment instanceof \PhpParser\Node\Stmt\Return_) { + return \false; } - if ($ifStatment->expr === null) { - return false; + return \false; } - return $this->valueResolver->isTrueOrFalse($ifStatment->expr); } - /** * @param Identical|Equal $binaryOp */ - private function createInArrayFunction(Expr $expr, BinaryOp $binaryOp, Foreach_ $foreach): FuncCall + private function createInArrayFunction(\PhpParser\Node\Expr $expr, \PhpParser\Node\Expr\BinaryOp $binaryOp, \PhpParser\Node\Stmt\Foreach_ $foreach) : \PhpParser\Node\Expr\FuncCall { $arguments = $this->nodeFactory->createArgs([$expr, $foreach->expr]); - - if ($binaryOp instanceof Identical) { + if ($binaryOp instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { $arguments[] = $this->nodeFactory->createArg($this->nodeFactory->createTrue()); } - return $this->nodeFactory->createFuncCall('in_array', $arguments); } - - private function createReturn(Expr $expr, FuncCall $funcCall): Return_ + private function createReturn(\PhpParser\Node\Expr $expr, \PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Stmt\Return_ { - $expr = $this->valueResolver->isFalse($expr) ? new BooleanNot($funcCall) : $funcCall; - - return new Return_($expr); + $expr = $this->valueResolver->isFalse($expr) ? new \PhpParser\Node\Expr\BooleanNot($funcCall) : $funcCall; + return new \PhpParser\Node\Stmt\Return_($expr); } } diff --git a/rules/CodeQuality/Rector/Foreach_/SimplifyForeachToArrayFilterRector.php b/rules/CodeQuality/Rector/Foreach_/SimplifyForeachToArrayFilterRector.php index 79205527ada..8bd6a75fa7e 100644 --- a/rules/CodeQuality/Rector/Foreach_/SimplifyForeachToArrayFilterRector.php +++ b/rules/CodeQuality/Rector/Foreach_/SimplifyForeachToArrayFilterRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Foreach_::class]; + return [\PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var If_ $ifNode */ $ifNode = $node->stmts[0]; - /** @var FuncCall $funcCallNode */ $funcCallNode = $ifNode->cond; - if (count($ifNode->stmts) !== 1) { + if (\count($ifNode->stmts) !== 1) { return null; } - - if (! $this->isSimpleCall($funcCallNode, $node)) { + if (!$this->isSimpleCall($funcCallNode, $node)) { return null; } - - if (! $ifNode->stmts[0] instanceof Expression) { + if (!$ifNode->stmts[0] instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $onlyNodeInIf = $ifNode->stmts[0]->expr; - if (! $onlyNodeInIf instanceof Assign) { + if (!$onlyNodeInIf instanceof \PhpParser\Node\Expr\Assign) { return null; } - $arrayDimFetch = $onlyNodeInIf->var; - if (! $arrayDimFetch instanceof ArrayDimFetch) { + if (!$arrayDimFetch instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return null; } - - if (! $this->nodeComparator->areNodesEqual($onlyNodeInIf->expr, $node->valueVar)) { + if (!$this->nodeComparator->areNodesEqual($onlyNodeInIf->expr, $node->valueVar)) { return null; } - $name = $this->getName($funcCallNode); if ($name === null) { return null; } - - if (! $this->forLoopFillsAnotherArray($node, $arrayDimFetch)) { + if (!$this->forLoopFillsAnotherArray($node, $arrayDimFetch)) { return null; } - return $this->createAssignNode($node, $name, $arrayDimFetch); } - - private function shouldSkip(Foreach_ $foreach): bool + private function shouldSkip(\PhpParser\Node\Stmt\Foreach_ $foreach) : bool { - if (count($foreach->stmts) !== 1) { - return true; + if (\count($foreach->stmts) !== 1) { + return \true; } - - if (! $foreach->stmts[0] instanceof If_) { - return true; + if (!$foreach->stmts[0] instanceof \PhpParser\Node\Stmt\If_) { + return \true; } - /** @var If_ $ifNode */ $ifNode = $foreach->stmts[0]; - if ($ifNode->else !== null) { - return true; + return \true; } - if ($ifNode->elseifs !== []) { - return true; + return \true; } - - return ! $ifNode->cond instanceof FuncCall; + return !$ifNode->cond instanceof \PhpParser\Node\Expr\FuncCall; } - - private function createAssignNode(Foreach_ $foreach, string $name, ArrayDimFetch $arrayDimFetch): Assign + private function createAssignNode(\PhpParser\Node\Stmt\Foreach_ $foreach, string $name, \PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : \PhpParser\Node\Expr\Assign { - $string = new String_($name); - - $args = [new Arg($foreach->expr), new Arg($string)]; - $arrayFilterFuncCall = new FuncCall(new Name('array_filter'), $args); - - return new Assign($arrayDimFetch->var, $arrayFilterFuncCall); + $string = new \PhpParser\Node\Scalar\String_($name); + $args = [new \PhpParser\Node\Arg($foreach->expr), new \PhpParser\Node\Arg($string)]; + $arrayFilterFuncCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('array_filter'), $args); + return new \PhpParser\Node\Expr\Assign($arrayDimFetch->var, $arrayFilterFuncCall); } - - private function forLoopFillsAnotherArray(Foreach_ $foreach, ArrayDimFetch $arrayDimFetch): bool + private function forLoopFillsAnotherArray(\PhpParser\Node\Stmt\Foreach_ $foreach, \PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : bool { $loopVar = $foreach->expr; - if (! $loopVar instanceof Variable) { - return false; + if (!$loopVar instanceof \PhpParser\Node\Expr\Variable) { + return \false; } $varThatIsModified = $arrayDimFetch->var; - if (! $varThatIsModified instanceof Variable) { - return false; + if (!$varThatIsModified instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $loopVar->name !== $varThatIsModified->name; } - - private function isSimpleCall(FuncCall $funcCall, Foreach_ $foreach): bool + private function isSimpleCall(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Stmt\Foreach_ $foreach) : bool { - if (count($funcCall->args) !== 1) { - return false; + if (\count($funcCall->args) !== 1) { + return \false; } - return $this->nodeComparator->areNodesEqual($funcCall->args[0], $foreach->valueVar); } } diff --git a/rules/CodeQuality/Rector/Foreach_/SimplifyForeachToCoalescingRector.php b/rules/CodeQuality/Rector/Foreach_/SimplifyForeachToCoalescingRector.php index e45a7624d07..a3c056371c1 100644 --- a/rules/CodeQuality/Rector/Foreach_/SimplifyForeachToCoalescingRector.php +++ b/rules/CodeQuality/Rector/Foreach_/SimplifyForeachToCoalescingRector.php @@ -1,7 +1,6 @@ foreachManipulator = $foreachManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes foreach that returns set value to ??', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes foreach that returns set value to ??', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' foreach ($this->oldToNewFunctions as $oldFunction => $newFunction) { if ($currentFunction === $oldFunction) { return $newFunction; @@ -57,96 +48,76 @@ foreach ($this->oldToNewFunctions as $oldFunction => $newFunction) { return null; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' return $this->oldToNewFunctions[$currentFunction] ?? null; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Foreach_::class]; + return [\PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::NULL_COALESCE)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::NULL_COALESCE)) { return null; } - $this->return = null; - if ($node->keyVar === null) { return null; } - /** @var Return_|Assign|null $returnOrAssignNode */ $returnOrAssignNode = $this->matchReturnOrAssignNode($node); if ($returnOrAssignNode === null) { return null; } - // return $newValue; // we don't return the node value - if (! $this->nodeComparator->areNodesEqual($node->valueVar, $returnOrAssignNode->expr)) { + if (!$this->nodeComparator->areNodesEqual($node->valueVar, $returnOrAssignNode->expr)) { return null; } - - if ($returnOrAssignNode instanceof Return_) { + if ($returnOrAssignNode instanceof \PhpParser\Node\Stmt\Return_) { return $this->processForeachNodeWithReturnInside($node, $returnOrAssignNode); } - return $this->processForeachNodeWithAssignInside($node, $returnOrAssignNode); } - /** * @return Assign|Return_|null */ - private function matchReturnOrAssignNode(Foreach_ $foreach): ?Node + private function matchReturnOrAssignNode(\PhpParser\Node\Stmt\Foreach_ $foreach) : ?\PhpParser\Node { - return $this->foreachManipulator->matchOnlyStmt($foreach, function (Node $node): ?Node { - if (! $node instanceof If_) { + return $this->foreachManipulator->matchOnlyStmt($foreach, function (\PhpParser\Node $node) : ?Node { + if (!$node instanceof \PhpParser\Node\Stmt\If_) { return null; } - - if (! $node->cond instanceof Identical) { + if (!$node->cond instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { return null; } - - if (count($node->stmts) !== 1) { + if (\count($node->stmts) !== 1) { return null; } - - $innerNode = $node->stmts[0] instanceof Expression ? $node->stmts[0]->expr : $node->stmts[0]; - if ($innerNode instanceof Assign || $innerNode instanceof Return_) { + $innerNode = $node->stmts[0] instanceof \PhpParser\Node\Stmt\Expression ? $node->stmts[0]->expr : $node->stmts[0]; + if ($innerNode instanceof \PhpParser\Node\Expr\Assign || $innerNode instanceof \PhpParser\Node\Stmt\Return_) { return $innerNode; } - return null; }); } - - private function processForeachNodeWithReturnInside(Foreach_ $foreach, Return_ $return): ?Node + private function processForeachNodeWithReturnInside(\PhpParser\Node\Stmt\Foreach_ $foreach, \PhpParser\Node\Stmt\Return_ $return) : ?\PhpParser\Node { - if (! $this->nodeComparator->areNodesEqual($foreach->valueVar, $return->expr)) { + if (!$this->nodeComparator->areNodesEqual($foreach->valueVar, $return->expr)) { return null; } - /** @var If_ $ifNode */ $ifNode = $foreach->stmts[0]; - /** @var Identical $identicalNode */ $identicalNode = $ifNode->cond; - if ($this->nodeComparator->areNodesEqual($identicalNode->left, $foreach->keyVar)) { $checkedNode = $identicalNode->right; } elseif ($this->nodeComparator->areNodesEqual($identicalNode->right, $foreach->keyVar)) { @@ -154,34 +125,24 @@ CODE_SAMPLE } else { return null; } - $nextNode = $foreach->getAttribute(AttributeKey::NEXT_NODE); - + $nextNode = $foreach->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); // is next node Return? - if ($nextNode instanceof Return_) { + if ($nextNode instanceof \PhpParser\Node\Stmt\Return_) { $this->return = $nextNode; $this->removeNode($this->return); } - - $coalesce = new Coalesce(new ArrayDimFetch( - $foreach->expr, - $checkedNode - ), $this->return && $this->return->expr !== null ? $this->return->expr : $checkedNode); - + $coalesce = new \PhpParser\Node\Expr\BinaryOp\Coalesce(new \PhpParser\Node\Expr\ArrayDimFetch($foreach->expr, $checkedNode), $this->return && $this->return->expr !== null ? $this->return->expr : $checkedNode); if ($this->return !== null) { - return new Return_($coalesce); + return new \PhpParser\Node\Stmt\Return_($coalesce); } - return null; } - - private function processForeachNodeWithAssignInside(Foreach_ $foreach, Assign $assign): ?Node + private function processForeachNodeWithAssignInside(\PhpParser\Node\Stmt\Foreach_ $foreach, \PhpParser\Node\Expr\Assign $assign) : ?\PhpParser\Node { /** @var If_ $ifNode */ $ifNode = $foreach->stmts[0]; - /** @var Identical $identicalNode */ $identicalNode = $ifNode->cond; - if ($this->nodeComparator->areNodesEqual($identicalNode->left, $foreach->keyVar)) { $checkedNode = $assign->var; $keyNode = $identicalNode->right; @@ -191,9 +152,7 @@ CODE_SAMPLE } else { return null; } - - $arrayDimFetch = new ArrayDimFetch($foreach->expr, $keyNode); - - return new Assign($checkedNode, new Coalesce($arrayDimFetch, $checkedNode)); + $arrayDimFetch = new \PhpParser\Node\Expr\ArrayDimFetch($foreach->expr, $keyNode); + return new \PhpParser\Node\Expr\Assign($checkedNode, new \PhpParser\Node\Expr\BinaryOp\Coalesce($arrayDimFetch, $checkedNode)); } } diff --git a/rules/CodeQuality/Rector/Foreach_/UnusedForeachValueToArrayKeysRector.php b/rules/CodeQuality/Rector/Foreach_/UnusedForeachValueToArrayKeysRector.php index 22d561cf709..c5e893692aa 100644 --- a/rules/CodeQuality/Rector/Foreach_/UnusedForeachValueToArrayKeysRector.php +++ b/rules/CodeQuality/Rector/Foreach_/UnusedForeachValueToArrayKeysRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Foreach_::class]; + return [\PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->keyVar === null) { return null; } - // special case of nested array items - if ($node->valueVar instanceof Array_) { + if ($node->valueVar instanceof \PhpParser\Node\Expr\Array_) { $node->valueVar = $this->refactorArrayForeachValue($node->valueVar, $node); if ($node->valueVar->items !== []) { return null; } - } elseif ($node->valueVar instanceof Variable) { + } elseif ($node->valueVar instanceof \PhpParser\Node\Expr\Variable) { if ($this->isVariableUsedInForeach($node->valueVar, $node)) { return null; } } else { return null; } - - if (is_a($this->getStaticType($node->expr), ObjectType::class)) { + if (\is_a($this->getStaticType($node->expr), \PHPStan\Type\ObjectType::class)) { return null; } - $this->removeForeachValueAndUseArrayKeys($node); - return $node; } - - private function refactorArrayForeachValue(Array_ $array, Foreach_ $foreach): Array_ + private function refactorArrayForeachValue(\PhpParser\Node\Expr\Array_ $array, \PhpParser\Node\Stmt\Foreach_ $foreach) : \PhpParser\Node\Expr\Array_ { foreach ($array->items as $key => $arrayItem) { - if (! $arrayItem instanceof ArrayItem) { + if (!$arrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - $value = $arrayItem->value; - if (! $value instanceof Variable) { + if (!$value instanceof \PhpParser\Node\Expr\Variable) { return $array; } - if ($this->isVariableUsedInForeach($value, $foreach)) { continue; } - unset($array->items[$key]); } - return $array; } - - private function isVariableUsedInForeach(Variable $variable, Foreach_ $foreach): bool + private function isVariableUsedInForeach(\PhpParser\Node\Expr\Variable $variable, \PhpParser\Node\Stmt\Foreach_ $foreach) : bool { - return (bool) $this->betterNodeFinder->findFirst($foreach->stmts, function (Node $node) use ($variable): bool { + return (bool) $this->betterNodeFinder->findFirst($foreach->stmts, function (\PhpParser\Node $node) use($variable) : bool { return $this->nodeComparator->areNodesEqual($node, $variable); }); } - - private function removeForeachValueAndUseArrayKeys(Foreach_ $foreach): void + private function removeForeachValueAndUseArrayKeys(\PhpParser\Node\Stmt\Foreach_ $foreach) : void { // remove key value $foreach->valueVar = $foreach->keyVar; $foreach->keyVar = null; - $foreach->expr = $this->nodeFactory->createFuncCall('array_keys', [$foreach->expr]); } } diff --git a/rules/CodeQuality/Rector/FuncCall/AddPregQuoteDelimiterRector.php b/rules/CodeQuality/Rector/FuncCall/AddPregQuoteDelimiterRector.php index b02e468d6c6..be33a15e376 100644 --- a/rules/CodeQuality/Rector/FuncCall/AddPregQuoteDelimiterRector.php +++ b/rules/CodeQuality/Rector/FuncCall/AddPregQuoteDelimiterRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'preg_quote')) { + if (!$this->isName($node, 'preg_quote')) { return null; } - // already completed if (isset($node->args[1])) { return null; } - $delimiter = $this->determineDelimiter($node); if ($delimiter === null) { return null; } - - $node->args[1] = new Arg(new String_($delimiter)); - + $node->args[1] = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_($delimiter)); return $node; } - - private function determineDelimiter(FuncCall $funcCall): ?string + private function determineDelimiter(\PhpParser\Node\Expr\FuncCall $funcCall) : ?string { $concat = $this->getUppermostConcat($funcCall); - if (! $concat instanceof Concat) { + if (!$concat instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { return null; } - $leftMostConcatNode = $concat->left; - while ($leftMostConcatNode instanceof Concat) { + while ($leftMostConcatNode instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { $leftMostConcatNode = $leftMostConcatNode->left; } - $rightMostConcatNode = $concat->right; - while ($rightMostConcatNode instanceof Concat) { + while ($rightMostConcatNode instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { $rightMostConcatNode = $rightMostConcatNode->right; } - - if (! $leftMostConcatNode instanceof String_) { + if (!$leftMostConcatNode instanceof \PhpParser\Node\Scalar\String_) { return null; } - - $possibleLeftDelimiter = Strings::substring($leftMostConcatNode->value, 0, 1); - if (! $rightMostConcatNode instanceof String_) { + $possibleLeftDelimiter = \RectorPrefix20210509\Nette\Utils\Strings::substring($leftMostConcatNode->value, 0, 1); + if (!$rightMostConcatNode instanceof \PhpParser\Node\Scalar\String_) { return null; } - - $possibleRightDelimiter = Strings::substring(rtrim($rightMostConcatNode->value, self::ALL_MODIFIERS), -1, 1); + $possibleRightDelimiter = \RectorPrefix20210509\Nette\Utils\Strings::substring(\rtrim($rightMostConcatNode->value, self::ALL_MODIFIERS), -1, 1); if ($possibleLeftDelimiter === $possibleRightDelimiter) { return $possibleLeftDelimiter; } - return null; } - - private function getUppermostConcat(FuncCall $funcCall): ?Concat + private function getUppermostConcat(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr\BinaryOp\Concat { $upperMostConcat = null; - $parent = $funcCall->getAttribute(AttributeKey::PARENT_NODE); - while ($parent instanceof Concat) { + $parent = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + while ($parent instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { $upperMostConcat = $parent; - $parent = $parent->getAttribute(AttributeKey::PARENT_NODE); + $parent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); } return $upperMostConcat; } diff --git a/rules/CodeQuality/Rector/FuncCall/ArrayKeysAndInArrayToArrayKeyExistsRector.php b/rules/CodeQuality/Rector/FuncCall/ArrayKeysAndInArrayToArrayKeyExistsRector.php index b34663d399e..b7072d88a2e 100644 --- a/rules/CodeQuality/Rector/FuncCall/ArrayKeysAndInArrayToArrayKeyExistsRector.php +++ b/rules/CodeQuality/Rector/FuncCall/ArrayKeysAndInArrayToArrayKeyExistsRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->nodeNameResolver->isName($node, 'in_array')) { + if (!$this->nodeNameResolver->isName($node, 'in_array')) { return null; } - $arrayVariable = $node->args[1]->value; - /** @var Assign|Node|null $previousAssignArraysKeysFuncCall */ - $previousAssignArraysKeysFuncCall = $this->betterNodeFinder->findFirstPrevious($node, function (Node $node) use ( - $arrayVariable - ): bool { + $previousAssignArraysKeysFuncCall = $this->betterNodeFinder->findFirstPrevious($node, function (\PhpParser\Node $node) use($arrayVariable) : bool { // breaking out of scope - if ($node instanceof FunctionLike) { - return true; + if ($node instanceof \PhpParser\Node\FunctionLike) { + return \true; } - - if (! $node instanceof Assign) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - if (! $this->nodeComparator->areNodesEqual($arrayVariable, $node->var)) { - return false; + if (!$this->nodeComparator->areNodesEqual($arrayVariable, $node->var)) { + return \false; } - - if (! $node->expr instanceof FuncCall) { - return false; + if (!$node->expr instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - return $this->nodeNameResolver->isName($node->expr, 'array_keys'); }); - - if (! $previousAssignArraysKeysFuncCall instanceof Assign) { + if (!$previousAssignArraysKeysFuncCall instanceof \PhpParser\Node\Expr\Assign) { return null; } - /** @var FuncCall $arrayKeysFuncCall */ $arrayKeysFuncCall = $previousAssignArraysKeysFuncCall->expr; - $this->removeNode($previousAssignArraysKeysFuncCall); - return $this->createArrayKeyExists($node, $arrayKeysFuncCall); } - - private function createArrayKeyExists(FuncCall $inArrayFuncCall, FuncCall $arrayKeysFuncCall): FuncCall + private function createArrayKeyExists(\PhpParser\Node\Expr\FuncCall $inArrayFuncCall, \PhpParser\Node\Expr\FuncCall $arrayKeysFuncCall) : \PhpParser\Node\Expr\FuncCall { $arguments = [$inArrayFuncCall->args[0], $arrayKeysFuncCall->args[0]]; - - return new FuncCall(new Name('array_key_exists'), $arguments); + return new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('array_key_exists'), $arguments); } } diff --git a/rules/CodeQuality/Rector/FuncCall/ArrayMergeOfNonArraysToSimpleArrayRector.php b/rules/CodeQuality/Rector/FuncCall/ArrayMergeOfNonArraysToSimpleArrayRector.php index a3216826052..927c939e1bd 100644 --- a/rules/CodeQuality/Rector/FuncCall/ArrayMergeOfNonArraysToSimpleArrayRector.php +++ b/rules/CodeQuality/Rector/FuncCall/ArrayMergeOfNonArraysToSimpleArrayRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'array_merge')) { + if (!$this->isName($node, 'array_merge')) { return null; } - - $array = new Array_(); + $array = new \PhpParser\Node\Expr\Array_(); foreach ($node->args as $arg) { $nestedArrayItem = $arg->value; - if (! $nestedArrayItem instanceof Array_) { + if (!$nestedArrayItem instanceof \PhpParser\Node\Expr\Array_) { return null; } - foreach ($nestedArrayItem->items as $nestedArrayItemItem) { if ($nestedArrayItemItem === null) { continue; } - - $array->items[] = new ArrayItem($nestedArrayItemItem->value, $nestedArrayItemItem->key); + $array->items[] = new \PhpParser\Node\Expr\ArrayItem($nestedArrayItemItem->value, $nestedArrayItemItem->key); } } - return $array; } } diff --git a/rules/CodeQuality/Rector/FuncCall/CallUserFuncWithArrowFunctionToInlineRector.php b/rules/CodeQuality/Rector/FuncCall/CallUserFuncWithArrowFunctionToInlineRector.php index 163f17eb176..924dbe7a5ec 100644 --- a/rules/CodeQuality/Rector/FuncCall/CallUserFuncWithArrowFunctionToInlineRector.php +++ b/rules/CodeQuality/Rector/FuncCall/CallUserFuncWithArrowFunctionToInlineRector.php @@ -1,7 +1,6 @@ closureArrowFunctionAnalyzer = $closureArrowFunctionAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Refactor call_user_func() with arrow function to direct call', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Refactor call_user_func() with arrow function to direct call', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -43,9 +37,7 @@ final class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -54,41 +46,34 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'call_user_func')) { + if (!$this->isName($node, 'call_user_func')) { return null; } - - if (count($node->args) !== 1) { + if (\count($node->args) !== 1) { return null; } - // change the node $firstArgValue = $node->args[0]->value; - if ($firstArgValue instanceof ArrowFunction) { + if ($firstArgValue instanceof \PhpParser\Node\Expr\ArrowFunction) { return $firstArgValue->expr; } - - if ($firstArgValue instanceof Closure) { + if ($firstArgValue instanceof \PhpParser\Node\Expr\Closure) { return $this->closureArrowFunctionAnalyzer->matchArrowFunctionExpr($firstArgValue); } - return null; } } diff --git a/rules/CodeQuality/Rector/FuncCall/ChangeArrayPushToArrayAssignRector.php b/rules/CodeQuality/Rector/FuncCall/ChangeArrayPushToArrayAssignRector.php index df64730a767..d9bab07540f 100644 --- a/rules/CodeQuality/Rector/FuncCall/ChangeArrayPushToArrayAssignRector.php +++ b/rules/CodeQuality/Rector/FuncCall/ChangeArrayPushToArrayAssignRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'array_push')) { + if (!$this->isName($node, 'array_push')) { return null; } - if ($this->hasArraySpread($node)) { return null; } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Expression) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - $arrayDimFetch = new ArrayDimFetch($node->args[0]->value); - + $arrayDimFetch = new \PhpParser\Node\Expr\ArrayDimFetch($node->args[0]->value); $position = 1; while (isset($node->args[$position])) { - $assign = new Assign($arrayDimFetch, $node->args[$position]->value); - $assignExpression = new Expression($assign); - + $assign = new \PhpParser\Node\Expr\Assign($arrayDimFetch, $node->args[$position]->value); + $assignExpression = new \PhpParser\Node\Stmt\Expression($assign); // keep comments of first line if ($position === 1) { $this->mirrorComments($assignExpression, $node); } - $this->addNodeAfterNode($assignExpression, $node); - ++$position; } - $this->removeNode($node); - return null; } - - private function hasArraySpread(FuncCall $funcCall): bool + private function hasArraySpread(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { foreach ($funcCall->args as $arg) { /** @var Arg $arg */ if ($arg->unpack) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/CodeQuality/Rector/FuncCall/CompactToVariablesRector.php b/rules/CodeQuality/Rector/FuncCall/CompactToVariablesRector.php index fa9551b4d98..5ed3bf3f188 100644 --- a/rules/CodeQuality/Rector/FuncCall/CompactToVariablesRector.php +++ b/rules/CodeQuality/Rector/FuncCall/CompactToVariablesRector.php @@ -1,7 +1,6 @@ compactConverter = $compactConverter; $this->arrayItemsAnalyzer = $arrayItemsAnalyzer; $this->arrayCompacter = $arrayCompacter; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change compact() call to own array', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change compact() call to own array', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -68,8 +57,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -81,95 +69,72 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'compact')) { + if (!$this->isName($node, 'compact')) { return null; } - if ($this->compactConverter->hasAllArgumentsNamed($node)) { return $this->compactConverter->convertToArray($node); } - $firstValue = $node->args[0]->value; $firstValueStaticType = $this->getStaticType($firstValue); - if (! $firstValueStaticType instanceof ConstantArrayType) { + if (!$firstValueStaticType instanceof \PHPStan\Type\Constant\ConstantArrayType) { return null; } - if ($firstValueStaticType->getItemType() instanceof MixedType) { + if ($firstValueStaticType->getItemType() instanceof \PHPStan\Type\MixedType) { return null; } return $this->refactorAssignArray($firstValue, $node); } - - private function refactorAssignedArray(Assign $assign, FuncCall $funcCall, Expr $expr): ?Expr + private function refactorAssignedArray(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr { - if (! $assign->expr instanceof Array_) { + if (!$assign->expr instanceof \PhpParser\Node\Expr\Array_) { return null; } - $array = $assign->expr; - - $assignScope = $assign->getAttribute(AttributeKey::SCOPE); - if (! $assignScope instanceof Scope) { + $assignScope = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$assignScope instanceof \PHPStan\Analyser\Scope) { return null; } - - $isCompactOfUndefinedVariables = $this->arrayItemsAnalyzer->hasArrayExclusiveDefinedVariableNames( - $array, - $assignScope - ); + $isCompactOfUndefinedVariables = $this->arrayItemsAnalyzer->hasArrayExclusiveDefinedVariableNames($array, $assignScope); if ($isCompactOfUndefinedVariables) { - $funcCallScope = $funcCall->getAttribute(AttributeKey::SCOPE); - if (! $funcCallScope instanceof Scope) { + $funcCallScope = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$funcCallScope instanceof \PHPStan\Analyser\Scope) { return null; } - - $isCompactOfDefinedVariables = $this->arrayItemsAnalyzer->hasArrayExclusiveUndefinedVariableNames( - $array, - $funcCallScope - ); + $isCompactOfDefinedVariables = $this->arrayItemsAnalyzer->hasArrayExclusiveUndefinedVariableNames($array, $funcCallScope); if ($isCompactOfDefinedVariables) { $this->arrayCompacter->compactStringToVariableArray($array); return $expr; } } - $this->removeNode($assign); - $this->arrayCompacter->compactStringToVariableArray($array); - $assignVariable = $funcCall->args[0]->value; - $preAssign = new Assign($assignVariable, $array); - - $currentStatement = $funcCall->getAttribute(AttributeKey::CURRENT_STATEMENT); + $preAssign = new \PhpParser\Node\Expr\Assign($assignVariable, $array); + $currentStatement = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); $this->addNodeBeforeNode($preAssign, $currentStatement); - return $expr; } - - private function refactorAssignArray(Expr $expr, FuncCall $funcCall): ?Expr + private function refactorAssignArray(\PhpParser\Node\Expr $expr, \PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr { $previousAssign = $this->betterNodeFinder->findPreviousAssignToExpr($expr); - if (! $previousAssign instanceof Assign) { + if (!$previousAssign instanceof \PhpParser\Node\Expr\Assign) { return null; } - return $this->refactorAssignedArray($previousAssign, $funcCall, $expr); } } diff --git a/rules/CodeQuality/Rector/FuncCall/InArrayAndArrayKeysToArrayKeyExistsRector.php b/rules/CodeQuality/Rector/FuncCall/InArrayAndArrayKeysToArrayKeyExistsRector.php index 4dcf0de5068..350460e6ecb 100644 --- a/rules/CodeQuality/Rector/FuncCall/InArrayAndArrayKeysToArrayKeyExistsRector.php +++ b/rules/CodeQuality/Rector/FuncCall/InArrayAndArrayKeysToArrayKeyExistsRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'in_array')) { + if (!$this->isName($node, 'in_array')) { return null; } - $secondArgument = $node->args[1]->value; - if (! $secondArgument instanceof FuncCall) { + if (!$secondArgument instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->isName($secondArgument, 'array_keys')) { + if (!$this->isName($secondArgument, 'array_keys')) { return null; } - - if (count($secondArgument->args) > 1) { + if (\count($secondArgument->args) > 1) { return null; } - $keyArg = $node->args[0]; $arrayArg = $node->args[1]; - /** @var FuncCall $innerFuncCallNode */ $innerFuncCallNode = $arrayArg->value; $arrayArg = $innerFuncCallNode->args[0]; - - $node->name = new Name('array_key_exists'); + $node->name = new \PhpParser\Node\Name('array_key_exists'); $node->args = [$keyArg, $arrayArg]; - return $node; } } diff --git a/rules/CodeQuality/Rector/FuncCall/IntvalToTypeCastRector.php b/rules/CodeQuality/Rector/FuncCall/IntvalToTypeCastRector.php index 46c692b9a25..5c951dae62a 100644 --- a/rules/CodeQuality/Rector/FuncCall/IntvalToTypeCastRector.php +++ b/rules/CodeQuality/Rector/FuncCall/IntvalToTypeCastRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'intval')) { + if (!$this->isName($node, 'intval')) { return null; } - if (isset($node->args[1])) { $secondArgumentValue = $this->valueResolver->getValue($node->args[1]->value); // default value @@ -72,7 +60,6 @@ CODE_SAMPLE return null; } } - - return new Int_($node->args[0]->value); + return new \PhpParser\Node\Expr\Cast\Int_($node->args[0]->value); } } diff --git a/rules/CodeQuality/Rector/FuncCall/IsAWithStringWithThirdArgumentRector.php b/rules/CodeQuality/Rector/FuncCall/IsAWithStringWithThirdArgumentRector.php index cbb6c2f3c3c..3907ece982b 100644 --- a/rules/CodeQuality/Rector/FuncCall/IsAWithStringWithThirdArgumentRector.php +++ b/rules/CodeQuality/Rector/FuncCall/IsAWithStringWithThirdArgumentRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'is_a')) { + if (!$this->isName($node, 'is_a')) { return null; } - if (isset($node->args[2])) { return null; } - $firstArgumentStaticType = $this->getStaticType($node->args[0]->value); - if (! $firstArgumentStaticType instanceof StringType) { + if (!$firstArgumentStaticType instanceof \PHPStan\Type\StringType) { return null; } - - $node->args[2] = new Arg($this->nodeFactory->createTrue()); - + $node->args[2] = new \PhpParser\Node\Arg($this->nodeFactory->createTrue()); return $node; } } diff --git a/rules/CodeQuality/Rector/FuncCall/RemoveSoleValueSprintfRector.php b/rules/CodeQuality/Rector/FuncCall/RemoveSoleValueSprintfRector.php index 5b77bc3fc2f..edfd7d36dcd 100644 --- a/rules/CodeQuality/Rector/FuncCall/RemoveSoleValueSprintfRector.php +++ b/rules/CodeQuality/Rector/FuncCall/RemoveSoleValueSprintfRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'sprintf')) { + if (!$this->isName($node, 'sprintf')) { return null; } - - if (count($node->args) !== 2) { + if (\count($node->args) !== 2) { return null; } - $maskArgument = $node->args[0]->value; - if (! $maskArgument instanceof String_) { + if (!$maskArgument instanceof \PhpParser\Node\Scalar\String_) { return null; } - if ($maskArgument->value !== '%s') { return null; } - $valueArgument = $node->args[1]->value; - if (! $this->nodeTypeResolver->isStaticType($valueArgument, StringType::class)) { + if (!$this->nodeTypeResolver->isStaticType($valueArgument, \PHPStan\Type\StringType::class)) { return null; } - return $valueArgument; } } diff --git a/rules/CodeQuality/Rector/FuncCall/SetTypeToCastRector.php b/rules/CodeQuality/Rector/FuncCall/SetTypeToCastRector.php index de90f5582b8..b626b576810 100644 --- a/rules/CodeQuality/Rector/FuncCall/SetTypeToCastRector.php +++ b/rules/CodeQuality/Rector/FuncCall/SetTypeToCastRector.php @@ -1,7 +1,6 @@ > */ - private const TYPE_TO_CAST = [ - 'array' => Array_::class, - 'bool' => Bool_::class, - 'boolean' => Bool_::class, - 'double' => Double::class, - 'float' => Double::class, - 'int' => Int_::class, - 'integer' => Int_::class, - 'object' => Object_::class, - 'string' => String_::class, - ]; - - public function getRuleDefinition(): RuleDefinition + private const TYPE_TO_CAST = ['array' => \PhpParser\Node\Expr\Cast\Array_::class, 'bool' => \PhpParser\Node\Expr\Cast\Bool_::class, 'boolean' => \PhpParser\Node\Expr\Cast\Bool_::class, 'double' => \PhpParser\Node\Expr\Cast\Double::class, 'float' => \PhpParser\Node\Expr\Cast\Double::class, 'int' => \PhpParser\Node\Expr\Cast\Int_::class, 'integer' => \PhpParser\Node\Expr\Cast\Int_::class, 'object' => \PhpParser\Node\Expr\Cast\Object_::class, 'string' => \PhpParser\Node\Expr\Cast\String_::class]; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes settype() to (type) where possible', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes settype() to (type) where possible', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($foo) @@ -59,8 +44,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run(array $items) @@ -71,58 +55,46 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'settype')) { + if (!$this->isName($node, 'settype')) { return null; } - $typeNode = $this->valueResolver->getValue($node->args[1]->value); if ($typeNode === null) { return null; } - - $typeNode = strtolower($typeNode); - + $typeNode = \strtolower($typeNode); $varNode = $node->args[0]->value; - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // result of function or probably used - if ($parentNode instanceof Expr || $parentNode instanceof Arg) { + if ($parentNode instanceof \PhpParser\Node\Expr || $parentNode instanceof \PhpParser\Node\Arg) { return null; } - if (isset(self::TYPE_TO_CAST[$typeNode])) { $castClass = self::TYPE_TO_CAST[$typeNode]; $castNode = new $castClass($varNode); - - if ($parentNode instanceof Expression) { + if ($parentNode instanceof \PhpParser\Node\Stmt\Expression) { // bare expression? → assign - return new Assign($varNode, $castNode); + return new \PhpParser\Node\Expr\Assign($varNode, $castNode); } - return $castNode; } - if ($typeNode === 'null') { - return new Assign($varNode, $this->nodeFactory->createNull()); + return new \PhpParser\Node\Expr\Assign($varNode, $this->nodeFactory->createNull()); } - return $node; } } diff --git a/rules/CodeQuality/Rector/FuncCall/SimplifyFuncGetArgsCountRector.php b/rules/CodeQuality/Rector/FuncCall/SimplifyFuncGetArgsCountRector.php index 4ee1d51f5e3..dbc4548f55e 100644 --- a/rules/CodeQuality/Rector/FuncCall/SimplifyFuncGetArgsCountRector.php +++ b/rules/CodeQuality/Rector/FuncCall/SimplifyFuncGetArgsCountRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'count')) { + if (!$this->isName($node, 'count')) { return null; } - - if (! $node->args[0]->value instanceof FuncCall) { + if (!$node->args[0]->value instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - /** @var FuncCall $innerFuncCall */ $innerFuncCall = $node->args[0]->value; - - if (! $this->isName($innerFuncCall, 'func_get_args')) { + if (!$this->isName($innerFuncCall, 'func_get_args')) { return $node; } - return $this->nodeFactory->createFuncCall('func_num_args'); } } diff --git a/rules/CodeQuality/Rector/FuncCall/SimplifyInArrayValuesRector.php b/rules/CodeQuality/Rector/FuncCall/SimplifyInArrayValuesRector.php index 04360fc4530..9729a746dd6 100644 --- a/rules/CodeQuality/Rector/FuncCall/SimplifyInArrayValuesRector.php +++ b/rules/CodeQuality/Rector/FuncCall/SimplifyInArrayValuesRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'in_array')) { + if (!$this->isName($node, 'in_array')) { return null; } - - if (! $node->args[1]->value instanceof FuncCall) { + if (!$node->args[1]->value instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - /** @var FuncCall $innerFunCall */ $innerFunCall = $node->args[1]->value; - if (! $this->isName($innerFunCall, 'array_values')) { + if (!$this->isName($innerFunCall, 'array_values')) { return null; } - $node->args[1] = $innerFunCall->args[0]; - return $node; } } diff --git a/rules/CodeQuality/Rector/FuncCall/SimplifyRegexPatternRector.php b/rules/CodeQuality/Rector/FuncCall/SimplifyRegexPatternRector.php index 1c9abf0e196..ea2d0476776 100644 --- a/rules/CodeQuality/Rector/FuncCall/SimplifyRegexPatternRector.php +++ b/rules/CodeQuality/Rector/FuncCall/SimplifyRegexPatternRector.php @@ -1,10 +1,9 @@ */ - private const COMPLEX_PATTERN_TO_SIMPLE = [ - '[0-9]' => '\d', - '[a-zA-Z0-9_]' => '\w', - '[A-Za-z0-9_]' => '\w', - '[0-9a-zA-Z_]' => '\w', - '[0-9A-Za-z_]' => '\w', - '[\r\n\t\f\v ]' => '\s', - ]; - + private const COMPLEX_PATTERN_TO_SIMPLE = ['[0-9]' => '\\d', '[a-zA-Z0-9_]' => '\\w', '[A-Za-z0-9_]' => '\\w', '[0-9a-zA-Z_]' => '\\w', '[0-9A-Za-z_]' => '\\w', '[\\r\\n\\t\\f\\v ]' => '\\s']; /** * @var RegexPatternArgumentManipulator */ private $regexPatternArgumentManipulator; - - public function __construct(RegexPatternArgumentManipulator $regexPatternArgumentManipulator) + public function __construct(\Rector\Core\Php\Regex\RegexPatternArgumentManipulator $regexPatternArgumentManipulator) { $this->regexPatternArgumentManipulator = $regexPatternArgumentManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Simplify regex pattern to known ranges', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Simplify regex pattern to known ranges', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -55,8 +41,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -65,38 +50,29 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class, StaticCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param FuncCall|StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $patterns = $this->regexPatternArgumentManipulator->matchCallArgumentWithRegexPattern($node); if ($patterns === []) { return null; } - foreach ($patterns as $pattern) { foreach (self::COMPLEX_PATTERN_TO_SIMPLE as $complexPattern => $simple) { - $pattern->value = Strings::replace( - $pattern->value, - '#' . preg_quote($complexPattern, '#') . '#', - $simple - ); + $pattern->value = \RectorPrefix20210509\Nette\Utils\Strings::replace($pattern->value, '#' . \preg_quote($complexPattern, '#') . '#', $simple); } } - return $node; } } diff --git a/rules/CodeQuality/Rector/FuncCall/SimplifyStrposLowerRector.php b/rules/CodeQuality/Rector/FuncCall/SimplifyStrposLowerRector.php index 0c7dad16273..049147b50bd 100644 --- a/rules/CodeQuality/Rector/FuncCall/SimplifyStrposLowerRector.php +++ b/rules/CodeQuality/Rector/FuncCall/SimplifyStrposLowerRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'strpos')) { + if (!$this->isName($node, 'strpos')) { return null; } - - if (! isset($node->args[0])) { + if (!isset($node->args[0])) { return null; } - - if (! $node->args[0]->value instanceof FuncCall) { + if (!$node->args[0]->value instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - /** @var FuncCall $innerFuncCall */ $innerFuncCall = $node->args[0]->value; - if (! $this->isName($innerFuncCall, 'strtolower')) { + if (!$this->isName($innerFuncCall, 'strtolower')) { return null; } - // pop 1 level up $node->args[0] = $innerFuncCall->args[0]; - $node->name = new Name('stripos'); - + $node->name = new \PhpParser\Node\Name('stripos'); return $node; } } diff --git a/rules/CodeQuality/Rector/FuncCall/SingleInArrayToCompareRector.php b/rules/CodeQuality/Rector/FuncCall/SingleInArrayToCompareRector.php index d4f1a682778..4f62e0de277 100644 --- a/rules/CodeQuality/Rector/FuncCall/SingleInArrayToCompareRector.php +++ b/rules/CodeQuality/Rector/FuncCall/SingleInArrayToCompareRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'in_array')) { + if (!$this->isName($node, 'in_array')) { return null; } - - if (! $node->args[1]->value instanceof Array_) { + if (!$node->args[1]->value instanceof \PhpParser\Node\Expr\Array_) { return null; } - /** @var Array_ $arrayNode */ $arrayNode = $node->args[1]->value; - if (count($arrayNode->items) !== 1) { + if (\count($arrayNode->items) !== 1) { return null; } - $firstArrayItem = $arrayNode->items[0]; - if (! $firstArrayItem instanceof ArrayItem) { + if (!$firstArrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { return null; } - $firstArrayItemValue = $firstArrayItem->value; // strict if (isset($node->args[2])) { - return new Identical($node->args[0]->value, $firstArrayItemValue); + return new \PhpParser\Node\Expr\BinaryOp\Identical($node->args[0]->value, $firstArrayItemValue); } - - return new Equal($node->args[0]->value, $firstArrayItemValue); + return new \PhpParser\Node\Expr\BinaryOp\Equal($node->args[0]->value, $firstArrayItemValue); } } diff --git a/rules/CodeQuality/Rector/FuncCall/UnwrapSprintfOneArgumentRector.php b/rules/CodeQuality/Rector/FuncCall/UnwrapSprintfOneArgumentRector.php index 1a71acd4661..7b365b7bebc 100644 --- a/rules/CodeQuality/Rector/FuncCall/UnwrapSprintfOneArgumentRector.php +++ b/rules/CodeQuality/Rector/FuncCall/UnwrapSprintfOneArgumentRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'sprintf')) { + if (!$this->isName($node, 'sprintf')) { return null; } - - if (count($node->args) > 1) { + if (\count($node->args) > 1) { return null; } - if ($node->args[0]->unpack) { return null; } - return $node->args[0]->value; } } diff --git a/rules/CodeQuality/Rector/FunctionLike/RemoveAlwaysTrueConditionSetInConstructorRector.php b/rules/CodeQuality/Rector/FunctionLike/RemoveAlwaysTrueConditionSetInConstructorRector.php index 11ae76a3451..05df893d6b4 100644 --- a/rules/CodeQuality/Rector/FunctionLike/RemoveAlwaysTrueConditionSetInConstructorRector.php +++ b/rules/CodeQuality/Rector/FunctionLike/RemoveAlwaysTrueConditionSetInConstructorRector.php @@ -1,7 +1,6 @@ staticTypeAnalyzer = $staticTypeAnalyzer; $this->typeFactory = $typeFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'If conditions is always true, perform the content right away', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('If conditions is always true, perform the content right away', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { private $value; @@ -73,8 +64,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { private $value; @@ -90,23 +80,19 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Closure::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\Closure::class]; } - /** * @param ClassMethod|Closure $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->stmts === null) { return null; @@ -114,165 +100,128 @@ CODE_SAMPLE if ($node->stmts === []) { return null; } - - $haveNodeChanged = false; + $haveNodeChanged = \false; foreach ($node->stmts as $key => $stmt) { - if ($stmt instanceof Expression) { + if ($stmt instanceof \PhpParser\Node\Stmt\Expression) { $stmt = $stmt->expr; } - - if (! $this->isAlwaysTruableNode($stmt)) { + if (!$this->isAlwaysTruableNode($stmt)) { continue; } - /** @var If_ $stmt */ - if (count($stmt->stmts) === 1) { + if (\count($stmt->stmts) === 1) { $node->stmts[$key] = $stmt->stmts[0]; continue; } - - $haveNodeChanged = true; + $haveNodeChanged = \true; // move all nodes one level up - array_splice($node->stmts, $key, count($stmt->stmts) - 1, $stmt->stmts); + \array_splice($node->stmts, $key, \count($stmt->stmts) - 1, $stmt->stmts); } - if ($haveNodeChanged) { return $node; } - return null; } - - private function isAlwaysTruableNode(Node $node): bool + private function isAlwaysTruableNode(\PhpParser\Node $node) : bool { - if (! $node instanceof If_) { - return false; + if (!$node instanceof \PhpParser\Node\Stmt\If_) { + return \false; } - // just one if - if (count($node->elseifs) !== 0) { - return false; + if (\count($node->elseifs) !== 0) { + return \false; } - // there is some else if ($node->else !== null) { - return false; + return \false; } - // only property fetch, because of constructor set - if (! $node->cond instanceof PropertyFetch) { - return false; + if (!$node->cond instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - $propertyFetchType = $this->resolvePropertyFetchType($node->cond); return $this->staticTypeAnalyzer->isAlwaysTruableType($propertyFetchType); } - - private function resolvePropertyFetchType(PropertyFetch $propertyFetch): Type + private function resolvePropertyFetchType(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : \PHPStan\Type\Type { - $classLike = $propertyFetch->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return new MixedType(); + $classLike = $propertyFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return new \PHPStan\Type\MixedType(); } - $propertyName = $this->getName($propertyFetch); if ($propertyName === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - $property = $classLike->getProperty($propertyName); - if (! $property instanceof Property) { - return new MixedType(); + if (!$property instanceof \PhpParser\Node\Stmt\Property) { + return new \PHPStan\Type\MixedType(); } - // anything but private can be changed from outer scope - if (! $property->isPrivate()) { - return new MixedType(); + if (!$property->isPrivate()) { + return new \PHPStan\Type\MixedType(); } - // set in constructor + changed in class $propertyTypeFromConstructor = $this->resolvePropertyTypeAfterConstructor($classLike, $propertyName); - $resolvedTypes = []; $resolvedTypes[] = $propertyTypeFromConstructor; - $defaultValue = $property->props[0]->default; if ($defaultValue !== null) { $resolvedTypes[] = $this->getStaticType($defaultValue); } - $resolveAssignedType = $this->resolveAssignedTypeInStmtsByPropertyName($classLike->stmts, $propertyName); if ($resolveAssignedType !== null) { $resolvedTypes[] = $resolveAssignedType; } - return $this->typeFactory->createMixedPassedOrUnionTypeAndKeepConstant($resolvedTypes); } - - private function resolvePropertyTypeAfterConstructor(Class_ $class, string $propertyName): Type + private function resolvePropertyTypeAfterConstructor(\PhpParser\Node\Stmt\Class_ $class, string $propertyName) : \PHPStan\Type\Type { $propertyTypeFromConstructor = null; - - $constructClassMethod = $class->getMethod(MethodName::CONSTRUCT); + $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); if ($constructClassMethod !== null) { - $propertyTypeFromConstructor = $this->resolveAssignedTypeInStmtsByPropertyName( - (array) $constructClassMethod->stmts, - $propertyName - ); + $propertyTypeFromConstructor = $this->resolveAssignedTypeInStmtsByPropertyName((array) $constructClassMethod->stmts, $propertyName); } - if ($propertyTypeFromConstructor !== null) { return $propertyTypeFromConstructor; } - // undefined property is null by default - return new NullType(); + return new \PHPStan\Type\NullType(); } - /** * @param Stmt[] $stmts */ - private function resolveAssignedTypeInStmtsByPropertyName(array $stmts, string $propertyName): ?Type + private function resolveAssignedTypeInStmtsByPropertyName(array $stmts, string $propertyName) : ?\PHPStan\Type\Type { $resolvedTypes = []; - - $this->traverseNodesWithCallable($stmts, function (Node $node) use ($propertyName, &$resolvedTypes): ?int { - if ($node instanceof ClassMethod && $this->isName($node, MethodName::CONSTRUCT)) { - return NodeTraverser::DONT_TRAVERSE_CHILDREN; + $this->traverseNodesWithCallable($stmts, function (\PhpParser\Node $node) use($propertyName, &$resolvedTypes) : ?int { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod && $this->isName($node, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CHILDREN; } - - if (! $this->isPropertyFetchAssignOfPropertyName($node, $propertyName)) { + if (!$this->isPropertyFetchAssignOfPropertyName($node, $propertyName)) { return null; } - - if (! $node instanceof Assign) { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - $resolvedTypes[] = $this->getStaticType($node->expr); return null; }); - if ($resolvedTypes === []) { return null; } - return $this->typeFactory->createMixedPassedOrUnionTypeAndKeepConstant($resolvedTypes); } - /** * E.g. $this->{value} = x */ - private function isPropertyFetchAssignOfPropertyName(Node $node, string $propertyName): bool + private function isPropertyFetchAssignOfPropertyName(\PhpParser\Node $node, string $propertyName) : bool { - if (! $node instanceof Assign) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - if (! $node->var instanceof PropertyFetch) { - return false; + if (!$node->var instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - return $this->isName($node->var, $propertyName); } } diff --git a/rules/CodeQuality/Rector/Identical/BooleanNotIdenticalToNotIdenticalRector.php b/rules/CodeQuality/Rector/Identical/BooleanNotIdenticalToNotIdenticalRector.php index ca006e1689d..e9ae02be549 100644 --- a/rules/CodeQuality/Rector/Identical/BooleanNotIdenticalToNotIdenticalRector.php +++ b/rules/CodeQuality/Rector/Identical/BooleanNotIdenticalToNotIdenticalRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identical::class, BooleanNot::class]; + return [\PhpParser\Node\Expr\BinaryOp\Identical::class, \PhpParser\Node\Expr\BooleanNot::class]; } - /** * @param Identical|BooleanNot $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof Identical) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { return $this->processIdentical($node); } - - if ($node->expr instanceof Identical) { + if ($node->expr instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { $identical = $node->expr; - if (! $this->nodeTypeResolver->isStaticType($identical->left, BooleanType::class)) { + if (!$this->nodeTypeResolver->isStaticType($identical->left, \PHPStan\Type\BooleanType::class)) { return null; } - - if (! $this->nodeTypeResolver->isStaticType($identical->right, BooleanType::class)) { + if (!$this->nodeTypeResolver->isStaticType($identical->right, \PHPStan\Type\BooleanType::class)) { return null; } - - return new NotIdentical($identical->left, $identical->right); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($identical->left, $identical->right); } - return null; } - - private function processIdentical(Identical $identical): ?NotIdentical + private function processIdentical(\PhpParser\Node\Expr\BinaryOp\Identical $identical) : ?\PhpParser\Node\Expr\BinaryOp\NotIdentical { - if (! $this->nodeTypeResolver->isStaticType($identical->left, BooleanType::class)) { + if (!$this->nodeTypeResolver->isStaticType($identical->left, \PHPStan\Type\BooleanType::class)) { return null; } - - if (! $this->nodeTypeResolver->isStaticType($identical->right, BooleanType::class)) { + if (!$this->nodeTypeResolver->isStaticType($identical->right, \PHPStan\Type\BooleanType::class)) { return null; } - - if ($identical->left instanceof BooleanNot) { - return new NotIdentical($identical->left->expr, $identical->right); + if ($identical->left instanceof \PhpParser\Node\Expr\BooleanNot) { + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($identical->left->expr, $identical->right); } - return null; } } diff --git a/rules/CodeQuality/Rector/Identical/FlipTypeControlToUseExclusiveTypeRector.php b/rules/CodeQuality/Rector/Identical/FlipTypeControlToUseExclusiveTypeRector.php index 1ff79cfe83c..cf02ead5d5f 100644 --- a/rules/CodeQuality/Rector/Identical/FlipTypeControlToUseExclusiveTypeRector.php +++ b/rules/CodeQuality/Rector/Identical/FlipTypeControlToUseExclusiveTypeRector.php @@ -1,7 +1,6 @@ phpDocTagRemover = $phpDocTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Flip type control to use exclusive type', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Flip type control to use exclusive type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function __construct(array $values) @@ -59,8 +51,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function __construct(array $values) @@ -72,123 +63,96 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identical::class]; + return [\PhpParser\Node\Expr\BinaryOp\Identical::class]; } - /** * @param Identical $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->valueResolver->isNull($node->left) && ! $this->valueResolver->isNull($node->right)) { + if (!$this->valueResolver->isNull($node->left) && !$this->valueResolver->isNull($node->right)) { return null; } - - $variable = $this->valueResolver->isNull($node->left) - ? $node->right - : $node->left; - + $variable = $this->valueResolver->isNull($node->left) ? $node->right : $node->left; $assign = $this->getVariableAssign($node, $variable); - if (! $assign instanceof Assign) { + if (!$assign instanceof \PhpParser\Node\Expr\Assign) { return null; } - - $expression = $assign->getAttribute(AttributeKey::PARENT_NODE); - if (! $expression instanceof Expression) { + $expression = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$expression instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($expression); $type = $phpDocInfo->getVarType(); - - if (! $type instanceof UnionType) { + if (!$type instanceof \PHPStan\Type\UnionType) { $type = $this->getObjectType($assign->expr); } - - if (! $type instanceof UnionType) { + if (!$type instanceof \PHPStan\Type\UnionType) { return null; } - /** @var Type[] $types */ $types = $this->getTypes($type); if ($this->isNotNullOneOf($types)) { return null; } - return $this->processConvertToExclusiveType($types, $variable, $phpDocInfo); } - - private function getVariableAssign(Identical $identical, Expr $expr): ?Node + private function getVariableAssign(\PhpParser\Node\Expr\BinaryOp\Identical $identical, \PhpParser\Node\Expr $expr) : ?\PhpParser\Node { - return $this->betterNodeFinder->findFirstPrevious($identical, function (Node $node) use ($expr): bool { - if (! $node instanceof Assign) { - return false; + return $this->betterNodeFinder->findFirstPrevious($identical, function (\PhpParser\Node $node) use($expr) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - return $this->nodeComparator->areNodesEqual($node->var, $expr); }); } - /** * @return Type[] */ - private function getTypes(UnionType $unionType): array + private function getTypes(\PHPStan\Type\UnionType $unionType) : array { $types = $unionType->getTypes(); - if (count($types) > 2) { + if (\count($types) > 2) { return []; } - return $types; } - /** * @param Type[] $types */ - private function isNotNullOneOf(array $types): bool + private function isNotNullOneOf(array $types) : bool { if ($types === []) { - return true; + return \true; } - if ($types[0] === $types[1]) { - return true; + return \true; } - if ($types[0] instanceof NullType) { - return false; + if ($types[0] instanceof \PHPStan\Type\NullType) { + return \false; } - - return ! $types[1] instanceof NullType; + return !$types[1] instanceof \PHPStan\Type\NullType; } - /** * @param Type[] $types */ - private function processConvertToExclusiveType(array $types, Expr $expr, PhpDocInfo $phpDocInfo): ?BooleanNot + private function processConvertToExclusiveType(array $types, \PhpParser\Node\Expr $expr, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : ?\PhpParser\Node\Expr\BooleanNot { - $type = $types[0] instanceof NullType - ? $types[1] - : $types[0]; - - if (! $type instanceof FullyQualifiedObjectType && ! $type instanceof ObjectType) { + $type = $types[0] instanceof \PHPStan\Type\NullType ? $types[1] : $types[0]; + if (!$type instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType && !$type instanceof \PHPStan\Type\ObjectType) { return null; } - $varTagValueNode = $phpDocInfo->getVarTagValueNode(); - if ($varTagValueNode instanceof VarTagValueNode) { + if ($varTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode) { $this->phpDocTagRemover->removeTagValueFromNode($phpDocInfo, $varTagValueNode); } - - return new BooleanNot(new Instanceof_($expr, new FullyQualified($type->getClassName()))); + return new \PhpParser\Node\Expr\BooleanNot(new \PhpParser\Node\Expr\Instanceof_($expr, new \PhpParser\Node\Name\FullyQualified($type->getClassName()))); } } diff --git a/rules/CodeQuality/Rector/Identical/GetClassToInstanceOfRector.php b/rules/CodeQuality/Rector/Identical/GetClassToInstanceOfRector.php index f88bdceb1d2..7066e6ebdc0 100644 --- a/rules/CodeQuality/Rector/Identical/GetClassToInstanceOfRector.php +++ b/rules/CodeQuality/Rector/Identical/GetClassToInstanceOfRector.php @@ -1,7 +1,6 @@ binaryOpManipulator = $binaryOpManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes comparison with get_class to instanceof', - [ - new CodeSample( - 'if (EventsListener::class === get_class($event->job)) { }', - 'if ($event->job instanceof EventsListener) { }' - ), - ] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes comparison with get_class to instanceof', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('if (EventsListener::class === get_class($event->job)) { }', 'if ($event->job instanceof EventsListener) { }')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identical::class, NotIdentical::class]; + return [\PhpParser\Node\Expr\BinaryOp\Identical::class, \PhpParser\Node\Expr\BinaryOp\NotIdentical::class]; } - /** * @param Identical|NotIdentical $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode( - $node, - function (Node $node): bool { - return $this->isClassReference($node); - }, - function (Node $node): bool { - return $this->isGetClassFuncCallNode($node); - } - ); - - if (! $twoNodeMatch instanceof TwoNodeMatch) { + $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode($node, function (\PhpParser\Node $node) : bool { + return $this->isClassReference($node); + }, function (\PhpParser\Node $node) : bool { + return $this->isGetClassFuncCallNode($node); + }); + if (!$twoNodeMatch instanceof \Rector\Php71\ValueObject\TwoNodeMatch) { return null; } - /** @var ClassConstFetch|String_ $firstExpr */ $firstExpr = $twoNodeMatch->getFirstExpr(); - /** @var FuncCall $funcCall */ $funcCall = $twoNodeMatch->getSecondExpr(); - $varNode = $funcCall->args[0]->value; - - if ($firstExpr instanceof String_) { + if ($firstExpr instanceof \PhpParser\Node\Scalar\String_) { $className = $this->valueResolver->getValue($firstExpr); } else { $className = $this->getName($firstExpr->class); } - if ($className === null) { return null; } - - $class = in_array($className, self::NO_NAMESPACED_CLASSNAMES, true) - ? new Name($className) - : new FullyQualified($className); - $instanceof = new Instanceof_($varNode, $class); - if ($node instanceof NotIdentical) { - return new BooleanNot($instanceof); + $class = \in_array($className, self::NO_NAMESPACED_CLASSNAMES, \true) ? new \PhpParser\Node\Name($className) : new \PhpParser\Node\Name\FullyQualified($className); + $instanceof = new \PhpParser\Node\Expr\Instanceof_($varNode, $class); + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical) { + return new \PhpParser\Node\Expr\BooleanNot($instanceof); } - return $instanceof; } - - private function isClassReference(Node $node): bool + private function isClassReference(\PhpParser\Node $node) : bool { - if (! $node instanceof ClassConstFetch) { + if (!$node instanceof \PhpParser\Node\Expr\ClassConstFetch) { // might be - return $node instanceof String_; + return $node instanceof \PhpParser\Node\Scalar\String_; } - return $this->isName($node->name, 'class'); } - - private function isGetClassFuncCallNode(Node $node): bool + private function isGetClassFuncCallNode(\PhpParser\Node $node) : bool { - if (! $node instanceof FuncCall) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - return $this->isName($node, 'get_class'); } } diff --git a/rules/CodeQuality/Rector/Identical/SimplifyArraySearchRector.php b/rules/CodeQuality/Rector/Identical/SimplifyArraySearchRector.php index bd9eb2b5bad..f94e9a6477c 100644 --- a/rules/CodeQuality/Rector/Identical/SimplifyArraySearchRector.php +++ b/rules/CodeQuality/Rector/Identical/SimplifyArraySearchRector.php @@ -1,7 +1,6 @@ binaryOpManipulator = $binaryOpManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Simplify array_search to in_array', - [ - new CodeSample('array_search("searching", $array) !== false;', 'in_array("searching", $array);'), - new CodeSample( - 'array_search("searching", $array, true) !== false;', - 'in_array("searching", $array, true);' - ), - ] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Simplify array_search to in_array', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('array_search("searching", $array) !== false;', 'in_array("searching", $array);'), new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('array_search("searching", $array, true) !== false;', 'in_array("searching", $array, true);')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identical::class, NotIdentical::class]; + return [\PhpParser\Node\Expr\BinaryOp\Identical::class, \PhpParser\Node\Expr\BinaryOp\NotIdentical::class]; } - /** * @param Identical|NotIdentical $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode( - $node, - function (Node $node): bool { - if (! $node instanceof FuncCall) { - return false; - } - - return $this->nodeNameResolver->isName($node, 'array_search'); - }, - function (Node $node): bool { - return $this->valueResolver->isFalse($node); + $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode($node, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - ); - - if (! $twoNodeMatch instanceof TwoNodeMatch) { + return $this->nodeNameResolver->isName($node, 'array_search'); + }, function (\PhpParser\Node $node) : bool { + return $this->valueResolver->isFalse($node); + }); + if (!$twoNodeMatch instanceof \Rector\Php71\ValueObject\TwoNodeMatch) { return null; } - /** @var FuncCall $arraySearchFuncCall */ $arraySearchFuncCall = $twoNodeMatch->getFirstExpr(); - $inArrayFuncCall = $this->nodeFactory->createFuncCall('in_array', $arraySearchFuncCall->args); - - if ($node instanceof Identical) { - return new BooleanNot($inArrayFuncCall); + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { + return new \PhpParser\Node\Expr\BooleanNot($inArrayFuncCall); } - return $inArrayFuncCall; } } diff --git a/rules/CodeQuality/Rector/Identical/SimplifyBoolIdenticalTrueRector.php b/rules/CodeQuality/Rector/Identical/SimplifyBoolIdenticalTrueRector.php index 9d7c3831877..75d2a410056 100644 --- a/rules/CodeQuality/Rector/Identical/SimplifyBoolIdenticalTrueRector.php +++ b/rules/CodeQuality/Rector/Identical/SimplifyBoolIdenticalTrueRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identical::class, NotIdentical::class]; + return [\PhpParser\Node\Expr\BinaryOp\Identical::class, \PhpParser\Node\Expr\BinaryOp\NotIdentical::class]; } - /** * @param Identical|NotIdentical $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($this->nodeTypeResolver->isStaticType( - $node->left, - BooleanType::class - ) && ! $this->valueResolver->isTrueOrFalse($node->left)) { + if ($this->nodeTypeResolver->isStaticType($node->left, \PHPStan\Type\BooleanType::class) && !$this->valueResolver->isTrueOrFalse($node->left)) { return $this->processBoolTypeToNotBool($node, $node->left, $node->right); } - if (! $this->nodeTypeResolver->isStaticType($node->right, BooleanType::class)) { + if (!$this->nodeTypeResolver->isStaticType($node->right, \PHPStan\Type\BooleanType::class)) { return null; } if ($this->valueResolver->isTrueOrFalse($node->right)) { @@ -78,48 +64,38 @@ CODE_SAMPLE } return $this->processBoolTypeToNotBool($node, $node->right, $node->left); } - - private function processBoolTypeToNotBool(Node $node, Expr $leftExpr, Expr $rightExpr): ?Expr + private function processBoolTypeToNotBool(\PhpParser\Node $node, \PhpParser\Node\Expr $leftExpr, \PhpParser\Node\Expr $rightExpr) : ?\PhpParser\Node\Expr { - if ($node instanceof Identical) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { return $this->refactorIdentical($leftExpr, $rightExpr); } - - if ($node instanceof NotIdentical) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical) { return $this->refactorNotIdentical($leftExpr, $rightExpr); } - return null; } - - private function refactorIdentical(Expr $leftExpr, Expr $rightExpr): ?Expr + private function refactorIdentical(\PhpParser\Node\Expr $leftExpr, \PhpParser\Node\Expr $rightExpr) : ?\PhpParser\Node\Expr { if ($this->valueResolver->isTrue($rightExpr)) { return $leftExpr; } - if ($this->valueResolver->isFalse($rightExpr)) { // prevent !! - if ($leftExpr instanceof BooleanNot) { + if ($leftExpr instanceof \PhpParser\Node\Expr\BooleanNot) { return $leftExpr->expr; } - - return new BooleanNot($leftExpr); + return new \PhpParser\Node\Expr\BooleanNot($leftExpr); } - return null; } - - private function refactorNotIdentical(Expr $leftExpr, Expr $rightExpr): ?Expr + private function refactorNotIdentical(\PhpParser\Node\Expr $leftExpr, \PhpParser\Node\Expr $rightExpr) : ?\PhpParser\Node\Expr { if ($this->valueResolver->isFalse($rightExpr)) { return $leftExpr; } - if ($this->valueResolver->isTrue($rightExpr)) { - return new BooleanNot($leftExpr); + return new \PhpParser\Node\Expr\BooleanNot($leftExpr); } - return null; } } diff --git a/rules/CodeQuality/Rector/Identical/SimplifyConditionsRector.php b/rules/CodeQuality/Rector/Identical/SimplifyConditionsRector.php index fd9b7c6e91e..7040ad1088d 100644 --- a/rules/CodeQuality/Rector/Identical/SimplifyConditionsRector.php +++ b/rules/CodeQuality/Rector/Identical/SimplifyConditionsRector.php @@ -1,7 +1,6 @@ assignAndBinaryMap = $assignAndBinaryMap; $this->binaryOpManipulator = $binaryOpManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Simplify conditions', - [new CodeSample("if (! (\$foo !== 'bar')) {...", "if (\$foo === 'bar') {...")] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Simplify conditions', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample("if (! (\$foo !== 'bar')) {...", "if (\$foo === 'bar') {...")]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [BooleanNot::class, Identical::class]; + return [\PhpParser\Node\Expr\BooleanNot::class, \PhpParser\Node\Expr\BinaryOp\Identical::class]; } - /** * @param BooleanNot|Identical $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof BooleanNot) { + if ($node instanceof \PhpParser\Node\Expr\BooleanNot) { return $this->processBooleanNot($node); } - return $this->processIdenticalAndNotIdentical($node); } - - private function processBooleanNot(BooleanNot $booleanNot): ?Node + private function processBooleanNot(\PhpParser\Node\Expr\BooleanNot $booleanNot) : ?\PhpParser\Node { - if (! $booleanNot->expr instanceof BinaryOp) { + if (!$booleanNot->expr instanceof \PhpParser\Node\Expr\BinaryOp) { return null; } - if ($this->shouldSkip($booleanNot->expr)) { return null; } - return $this->createInversedBooleanOp($booleanNot->expr); } - - private function processIdenticalAndNotIdentical(Identical $identical): ?Node + private function processIdenticalAndNotIdentical(\PhpParser\Node\Expr\BinaryOp\Identical $identical) : ?\PhpParser\Node { - $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode( - $identical, - function (Node $binaryOp): bool { - return $binaryOp instanceof Identical || $binaryOp instanceof NotIdentical; - }, - function (Node $binaryOp): bool { - return $this->valueResolver->isTrueOrFalse($binaryOp); - } - ); - - if (! $twoNodeMatch instanceof TwoNodeMatch) { + $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode($identical, function (\PhpParser\Node $binaryOp) : bool { + return $binaryOp instanceof \PhpParser\Node\Expr\BinaryOp\Identical || $binaryOp instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical; + }, function (\PhpParser\Node $binaryOp) : bool { + return $this->valueResolver->isTrueOrFalse($binaryOp); + }); + if (!$twoNodeMatch instanceof \Rector\Php71\ValueObject\TwoNodeMatch) { return $twoNodeMatch; } - /** @var Identical|NotIdentical $subBinaryOp */ $subBinaryOp = $twoNodeMatch->getFirstExpr(); - $otherNode = $twoNodeMatch->getSecondExpr(); if ($this->valueResolver->isFalse($otherNode)) { return $this->createInversedBooleanOp($subBinaryOp); } - return $subBinaryOp; } - /** * Skip too nested binary || binary > binary combinations */ - private function shouldSkip(BinaryOp $binaryOp): bool + private function shouldSkip(\PhpParser\Node\Expr\BinaryOp $binaryOp) : bool { - if ($binaryOp instanceof BooleanOr) { - return true; + if ($binaryOp instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { + return \true; } - - if ($binaryOp->left instanceof BinaryOp) { - return true; + if ($binaryOp->left instanceof \PhpParser\Node\Expr\BinaryOp) { + return \true; } - return $binaryOp->right instanceof BinaryOp; + return $binaryOp->right instanceof \PhpParser\Node\Expr\BinaryOp; } - - private function createInversedBooleanOp(BinaryOp $binaryOp): ?BinaryOp + private function createInversedBooleanOp(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\PhpParser\Node\Expr\BinaryOp { $inversedBinaryClass = $this->assignAndBinaryMap->getInversed($binaryOp); if ($inversedBinaryClass === null) { return null; } - return new $inversedBinaryClass($binaryOp->left, $binaryOp->right); } } diff --git a/rules/CodeQuality/Rector/Identical/StrlenZeroToIdenticalEmptyStringRector.php b/rules/CodeQuality/Rector/Identical/StrlenZeroToIdenticalEmptyStringRector.php index 44416170b9f..cc9b65228da 100644 --- a/rules/CodeQuality/Rector/Identical/StrlenZeroToIdenticalEmptyStringRector.php +++ b/rules/CodeQuality/Rector/Identical/StrlenZeroToIdenticalEmptyStringRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identical::class]; + return [\PhpParser\Node\Expr\BinaryOp\Identical::class]; } - /** * @param Identical $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $variable = null; - if ($node->left instanceof FuncCall) { - if (! $this->isName($node->left, 'strlen')) { + if ($node->left instanceof \PhpParser\Node\Expr\FuncCall) { + if (!$this->isName($node->left, 'strlen')) { return null; } - - if (! $this->valueResolver->isValue($node->right, 0)) { + if (!$this->valueResolver->isValue($node->right, 0)) { return null; } - $variable = $node->left->args[0]->value; - } elseif ($node->right instanceof FuncCall) { - if (! $this->isName($node->right, 'strlen')) { + } elseif ($node->right instanceof \PhpParser\Node\Expr\FuncCall) { + if (!$this->isName($node->right, 'strlen')) { return null; } - - if (! $this->valueResolver->isValue($node->left, 0)) { + if (!$this->valueResolver->isValue($node->left, 0)) { return null; } - $variable = $node->right->args[0]->value; } else { return null; } - /** @var Expr $variable */ - return new Identical($variable, new String_('')); + return new \PhpParser\Node\Expr\BinaryOp\Identical($variable, new \PhpParser\Node\Scalar\String_('')); } } diff --git a/rules/CodeQuality/Rector/If_/CombineIfRector.php b/rules/CodeQuality/Rector/If_/CombineIfRector.php index a8d29988091..2712af6f1e0 100644 --- a/rules/CodeQuality/Rector/If_/CombineIfRector.php +++ b/rules/CodeQuality/Rector/If_/CombineIfRector.php @@ -1,7 +1,6 @@ commentsMerger = $commentsMerger; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Merges nested if statements', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Merges nested if statements', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -44,8 +38,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -56,59 +49,47 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var If_ $subIf */ $subIf = $node->stmts[0]; - $node->cond = new BooleanAnd($node->cond, $subIf->cond); + $node->cond = new \PhpParser\Node\Expr\BinaryOp\BooleanAnd($node->cond, $subIf->cond); $node->stmts = $subIf->stmts; - $this->commentsMerger->keepComments($node, [$subIf]); - return $node; } - - private function shouldSkip(If_ $if): bool + private function shouldSkip(\PhpParser\Node\Stmt\If_ $if) : bool { if ($if->else !== null) { - return true; + return \true; } - - if (count($if->stmts) !== 1) { - return true; + if (\count($if->stmts) !== 1) { + return \true; } - if ($if->elseifs !== []) { - return true; + return \true; } - - if (! $if->stmts[0] instanceof If_) { - return true; + if (!$if->stmts[0] instanceof \PhpParser\Node\Stmt\If_) { + return \true; } - if ($if->stmts[0]->else !== null) { - return true; + return \true; } - return (bool) $if->stmts[0]->elseifs; } } diff --git a/rules/CodeQuality/Rector/If_/ConsecutiveNullCompareReturnsToNullCoalesceQueueRector.php b/rules/CodeQuality/Rector/If_/ConsecutiveNullCompareReturnsToNullCoalesceQueueRector.php index 2dcd0884ae9..9333f5ceeac 100644 --- a/rules/CodeQuality/Rector/If_/ConsecutiveNullCompareReturnsToNullCoalesceQueueRector.php +++ b/rules/CodeQuality/Rector/If_/ConsecutiveNullCompareReturnsToNullCoalesceQueueRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change multiple null compares to ?? queue', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change multiple null compares to ?? queue', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -62,8 +54,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -72,94 +63,77 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::NULL_COALESCE)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::NULL_COALESCE)) { return null; } - $this->reset(); - $currentNode = $node; while ($currentNode !== null) { - if ($currentNode instanceof If_) { + if ($currentNode instanceof \PhpParser\Node\Stmt\If_) { $comparedNode = $this->ifManipulator->matchIfNotNullReturnValue($currentNode); if ($comparedNode !== null) { $this->coalescingNodes[] = $comparedNode; $this->nodesToRemove[] = $currentNode; - - $currentNode = $currentNode->getAttribute(AttributeKey::NEXT_NODE); + $currentNode = $currentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); continue; } return null; } - if ($this->isReturnNull($currentNode)) { $this->nodesToRemove[] = $currentNode; break; } return null; } - // at least 2 coalescing nodes are needed - if (count($this->coalescingNodes) < 2) { + if (\count($this->coalescingNodes) < 2) { return null; } $this->removeNodes($this->nodesToRemove); - return $this->createReturnCoalesceNode($this->coalescingNodes); } - - private function reset(): void + private function reset() : void { $this->coalescingNodes = []; $this->nodesToRemove = []; } - - private function isReturnNull(Node $node): bool + private function isReturnNull(\PhpParser\Node $node) : bool { - if (! $node instanceof Return_) { - return false; + if (!$node instanceof \PhpParser\Node\Stmt\Return_) { + return \false; } - if ($node->expr === null) { - return false; + return \false; } - return $this->valueResolver->isNull($node->expr); } - /** * @param Expr[] $coalescingNodes */ - private function createReturnCoalesceNode(array $coalescingNodes): Return_ + private function createReturnCoalesceNode(array $coalescingNodes) : \PhpParser\Node\Stmt\Return_ { /** @var Expr $left */ - $left = array_shift($coalescingNodes); - + $left = \array_shift($coalescingNodes); /** @var Expr $right */ - $right = array_shift($coalescingNodes); - - $coalesceNode = new Coalesce($left, $right); + $right = \array_shift($coalescingNodes); + $coalesceNode = new \PhpParser\Node\Expr\BinaryOp\Coalesce($left, $right); foreach ($coalescingNodes as $coalescingNode) { - $coalesceNode = new Coalesce($coalesceNode, $coalescingNode); + $coalesceNode = new \PhpParser\Node\Expr\BinaryOp\Coalesce($coalesceNode, $coalescingNode); } - - return new Return_($coalesceNode); + return new \PhpParser\Node\Stmt\Return_($coalesceNode); } } diff --git a/rules/CodeQuality/Rector/If_/ExplicitBoolCompareRector.php b/rules/CodeQuality/Rector/If_/ExplicitBoolCompareRector.php index bdc8322593d..a00a6e00ec5 100644 --- a/rules/CodeQuality/Rector/If_/ExplicitBoolCompareRector.php +++ b/rules/CodeQuality/Rector/If_/ExplicitBoolCompareRector.php @@ -1,7 +1,6 @@ stringTypeAnalyzer = $stringTypeAnalyzer; $this->arrayTypeAnalyzer = $arrayTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Make if conditions more explicit', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Make if conditions more explicit', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeController { public function run($items) @@ -70,8 +63,7 @@ final class SomeController } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeController { public function run($items) @@ -82,169 +74,134 @@ final class SomeController } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class, ElseIf_::class, Ternary::class]; + return [\PhpParser\Node\Stmt\If_::class, \PhpParser\Node\Stmt\ElseIf_::class, \PhpParser\Node\Expr\Ternary::class]; } - /** * @param If_|ElseIf_|Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { // skip short ternary - if ($node instanceof Ternary && $node->if === null) { + if ($node instanceof \PhpParser\Node\Expr\Ternary && $node->if === null) { return null; } - - if ($node->cond instanceof BooleanNot) { + if ($node->cond instanceof \PhpParser\Node\Expr\BooleanNot) { $conditionNode = $node->cond->expr; - $isNegated = true; + $isNegated = \true; } else { $conditionNode = $node->cond; - $isNegated = false; + $isNegated = \false; } - - if ($conditionNode instanceof Bool_) { + if ($conditionNode instanceof \PhpParser\Node\Expr\Cast\Bool_) { return null; } - $conditionStaticType = $this->getStaticType($conditionNode); - if ($conditionStaticType instanceof BooleanType) { + if ($conditionStaticType instanceof \PHPStan\Type\BooleanType) { return null; } - $newConditionNode = $this->resolveNewConditionNode($conditionNode, $isNegated); - if (! $newConditionNode instanceof BinaryOp) { + if (!$newConditionNode instanceof \PhpParser\Node\Expr\BinaryOp) { return null; } - $node->cond = $newConditionNode; - return $node; } - - private function resolveNewConditionNode(Expr $expr, bool $isNegated): ?BinaryOp + private function resolveNewConditionNode(\PhpParser\Node\Expr $expr, bool $isNegated) : ?\PhpParser\Node\Expr\BinaryOp { - if ($expr instanceof FuncCall && $this->nodeNameResolver->isName($expr, 'count')) { + if ($expr instanceof \PhpParser\Node\Expr\FuncCall && $this->nodeNameResolver->isName($expr, 'count')) { return $this->resolveCount($isNegated, $expr); } - if ($this->arrayTypeAnalyzer->isArrayType($expr)) { return $this->resolveArray($isNegated, $expr); } - if ($this->stringTypeAnalyzer->isStringOrUnionStringOnlyType($expr)) { return $this->resolveString($isNegated, $expr); } - - if ($this->nodeTypeResolver->isStaticType($expr, IntegerType::class)) { + if ($this->nodeTypeResolver->isStaticType($expr, \PHPStan\Type\IntegerType::class)) { return $this->resolveInteger($isNegated, $expr); } - - if ($this->nodeTypeResolver->isStaticType($expr, FloatType::class)) { + if ($this->nodeTypeResolver->isStaticType($expr, \PHPStan\Type\FloatType::class)) { return $this->resolveFloat($isNegated, $expr); } - - if ($this->nodeTypeResolver->isNullableTypeOfSpecificType($expr, ObjectType::class)) { + if ($this->nodeTypeResolver->isNullableTypeOfSpecificType($expr, \PHPStan\Type\ObjectType::class)) { return $this->resolveNullable($isNegated, $expr); } - return null; } - /** * @return Identical|Greater */ - private function resolveCount(bool $isNegated, FuncCall $funcCall): BinaryOp + private function resolveCount(bool $isNegated, \PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\BinaryOp { - $lNumber = new LNumber(0); - + $lNumber = new \PhpParser\Node\Scalar\LNumber(0); // compare === 0, assumption if ($isNegated) { - return new Identical($funcCall, $lNumber); + return new \PhpParser\Node\Expr\BinaryOp\Identical($funcCall, $lNumber); } - - return new Greater($funcCall, $lNumber); + return new \PhpParser\Node\Expr\BinaryOp\Greater($funcCall, $lNumber); } - /** * @return Identical|NotIdentical */ - private function resolveArray(bool $isNegated, Expr $expr): ?BinaryOp + private function resolveArray(bool $isNegated, \PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr\BinaryOp { - if (! $expr instanceof Variable) { + if (!$expr instanceof \PhpParser\Node\Expr\Variable) { return null; } - - $array = new Array_([]); - + $array = new \PhpParser\Node\Expr\Array_([]); // compare === [] if ($isNegated) { - return new Identical($expr, $array); + return new \PhpParser\Node\Expr\BinaryOp\Identical($expr, $array); } - - return new NotIdentical($expr, $array); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, $array); } - /** * @return Identical|NotIdentical */ - private function resolveString(bool $isNegated, Expr $expr): BinaryOp + private function resolveString(bool $isNegated, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\BinaryOp { - $string = new String_(''); - + $string = new \PhpParser\Node\Scalar\String_(''); // compare === '' if ($isNegated) { - return new Identical($expr, $string); + return new \PhpParser\Node\Expr\BinaryOp\Identical($expr, $string); } - - return new NotIdentical($expr, $string); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, $string); } - /** * @return Identical|NotIdentical */ - private function resolveInteger(bool $isNegated, Expr $expr): BinaryOp + private function resolveInteger(bool $isNegated, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\BinaryOp { - $lNumber = new LNumber(0); - + $lNumber = new \PhpParser\Node\Scalar\LNumber(0); if ($isNegated) { - return new Identical($expr, $lNumber); + return new \PhpParser\Node\Expr\BinaryOp\Identical($expr, $lNumber); } - - return new NotIdentical($expr, $lNumber); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, $lNumber); } - - private function resolveFloat(bool $isNegated, Expr $expr): BinaryOp + private function resolveFloat(bool $isNegated, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\BinaryOp { - $dNumber = new DNumber(0.0); - + $dNumber = new \PhpParser\Node\Scalar\DNumber(0.0); if ($isNegated) { - return new Identical($expr, $dNumber); + return new \PhpParser\Node\Expr\BinaryOp\Identical($expr, $dNumber); } - - return new NotIdentical($expr, $dNumber); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, $dNumber); } - /** * @return Identical|NotIdentical */ - private function resolveNullable(bool $isNegated, Expr $expr): BinaryOp + private function resolveNullable(bool $isNegated, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\BinaryOp { $constFetch = $this->nodeFactory->createNull(); - if ($isNegated) { - return new Identical($expr, $constFetch); + return new \PhpParser\Node\Expr\BinaryOp\Identical($expr, $constFetch); } - - return new NotIdentical($expr, $constFetch); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, $constFetch); } } diff --git a/rules/CodeQuality/Rector/If_/ShortenElseIfRector.php b/rules/CodeQuality/Rector/If_/ShortenElseIfRector.php index 20612d26a97..773cde3a849 100644 --- a/rules/CodeQuality/Rector/If_/ShortenElseIfRector.php +++ b/rules/CodeQuality/Rector/If_/ShortenElseIfRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { return $this->shortenElseIf($node); } - - private function shortenElseIf(If_ $node): ?If_ + private function shortenElseIf(\PhpParser\Node\Stmt\If_ $node) : ?\PhpParser\Node\Stmt\If_ { - if (! $node->else instanceof Else_) { + if (!$node->else instanceof \PhpParser\Node\Stmt\Else_) { return null; } - $else = $node->else; - if (count($else->stmts) !== 1) { + if (\count($else->stmts) !== 1) { return null; } - $if = $else->stmts[0]; - if (! $if instanceof If_) { + if (!$if instanceof \PhpParser\Node\Stmt\If_) { return null; } - // Try to shorten the nested if before transforming it to elseif $refactored = $this->shortenElseIf($if); - if ($refactored !== null) { $if = $refactored; } - - $node->elseifs[] = new ElseIf_($if->cond, $if->stmts); - + $node->elseifs[] = new \PhpParser\Node\Stmt\ElseIf_($if->cond, $if->stmts); $node->else = $if->else; - - $node->elseifs = array_merge($node->elseifs, $if->elseifs); - + $node->elseifs = \array_merge($node->elseifs, $if->elseifs); return $node; } } diff --git a/rules/CodeQuality/Rector/If_/SimplifyIfElseToTernaryRector.php b/rules/CodeQuality/Rector/If_/SimplifyIfElseToTernaryRector.php index 97c117b0d37..1116909a5c3 100644 --- a/rules/CodeQuality/Rector/If_/SimplifyIfElseToTernaryRector.php +++ b/rules/CodeQuality/Rector/If_/SimplifyIfElseToTernaryRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->else === null) { return null; } - if ($node->elseifs !== []) { return null; } - $ifAssignVar = $this->resolveOnlyStmtAssignVar($node->stmts); $elseAssignVar = $this->resolveOnlyStmtAssignVar($node->else->stmts); - if (! $ifAssignVar instanceof Expr) { + if (!$ifAssignVar instanceof \PhpParser\Node\Expr) { return null; } - if (! $elseAssignVar instanceof Expr) { + if (!$elseAssignVar instanceof \PhpParser\Node\Expr) { return null; } - - if (! $this->nodeComparator->areNodesEqual($ifAssignVar, $elseAssignVar)) { + if (!$this->nodeComparator->areNodesEqual($ifAssignVar, $elseAssignVar)) { return null; } - $ternaryIf = $this->resolveOnlyStmtAssignExpr($node->stmts); $ternaryElse = $this->resolveOnlyStmtAssignExpr($node->else->stmts); - if (! $ternaryIf instanceof Expr) { + if (!$ternaryIf instanceof \PhpParser\Node\Expr) { return null; } - if (! $ternaryElse instanceof Expr) { + if (!$ternaryElse instanceof \PhpParser\Node\Expr) { return null; } - // has nested ternary → skip, it's super hard to read if ($this->haveNestedTernary([$node->cond, $ternaryIf, $ternaryElse])) { return null; } - - $ternary = new Ternary($node->cond, $ternaryIf, $ternaryElse); - $assign = new Assign($ifAssignVar, $ternary); - + $ternary = new \PhpParser\Node\Expr\Ternary($node->cond, $ternaryIf, $ternaryElse); + $assign = new \PhpParser\Node\Expr\Assign($ifAssignVar, $ternary); // do not create super long lines if ($this->isNodeTooLong($assign)) { return null; } - return $assign; } - /** * @param Stmt[] $stmts */ - private function resolveOnlyStmtAssignVar(array $stmts): ?Expr + private function resolveOnlyStmtAssignVar(array $stmts) : ?\PhpParser\Node\Expr { - if (count($stmts) !== 1) { + if (\count($stmts) !== 1) { return null; } - $onlyStmt = $this->unwrapExpression($stmts[0]); - if (! $onlyStmt instanceof Assign) { + if (!$onlyStmt instanceof \PhpParser\Node\Expr\Assign) { return null; } - return $onlyStmt->var; } - /** * @param Stmt[] $stmts */ - private function resolveOnlyStmtAssignExpr(array $stmts): ?Expr + private function resolveOnlyStmtAssignExpr(array $stmts) : ?\PhpParser\Node\Expr { - if (count($stmts) !== 1) { + if (\count($stmts) !== 1) { return null; } - $onlyStmt = $this->unwrapExpression($stmts[0]); - if (! $onlyStmt instanceof Assign) { + if (!$onlyStmt instanceof \PhpParser\Node\Expr\Assign) { return null; } - return $onlyStmt->expr; } - /** * @param Node[] $nodes */ - private function haveNestedTernary(array $nodes): bool + private function haveNestedTernary(array $nodes) : bool { foreach ($nodes as $node) { - $betterNodeFinderFindInstanceOf = $this->betterNodeFinder->findInstanceOf($node, Ternary::class); + $betterNodeFinderFindInstanceOf = $this->betterNodeFinder->findInstanceOf($node, \PhpParser\Node\Expr\Ternary::class); if ($betterNodeFinderFindInstanceOf !== []) { - return true; + return \true; } } - - return false; + return \false; } - - private function isNodeTooLong(Assign $assign): bool + private function isNodeTooLong(\PhpParser\Node\Expr\Assign $assign) : bool { - return Strings::length($this->print($assign)) > self::LINE_LENGTH_LIMIT; + return \RectorPrefix20210509\Nette\Utils\Strings::length($this->print($assign)) > self::LINE_LENGTH_LIMIT; } } diff --git a/rules/CodeQuality/Rector/If_/SimplifyIfIssetToNullCoalescingRector.php b/rules/CodeQuality/Rector/If_/SimplifyIfIssetToNullCoalescingRector.php index 382b1e2a42a..b2fda083e44 100644 --- a/rules/CodeQuality/Rector/If_/SimplifyIfIssetToNullCoalescingRector.php +++ b/rules/CodeQuality/Rector/If_/SimplifyIfIssetToNullCoalescingRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var Isset_ $issetNode */ $issetNode = $node->cond; - $valueNode = $issetNode->vars[0]; - // various scenarios $ifFirstStmt = $node->stmts[0]; - if (! $ifFirstStmt instanceof Expression) { + if (!$ifFirstStmt instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $else = $node->else; - if (! $else instanceof Else_) { + if (!$else instanceof \PhpParser\Node\Stmt\Else_) { return null; } - $elseFirstStmt = $else->stmts[0]; - if (! $elseFirstStmt instanceof Expression) { + if (!$elseFirstStmt instanceof \PhpParser\Node\Stmt\Expression) { return null; } - /** @var Assign $firstAssign */ $firstAssign = $ifFirstStmt->expr; - /** @var Assign $secondAssign */ $secondAssign = $elseFirstStmt->expr; - // 1. array_merge - if (! $firstAssign->expr instanceof FuncCall) { + if (!$firstAssign->expr instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->isName($firstAssign->expr, 'array_merge')) { + if (!$this->isName($firstAssign->expr, 'array_merge')) { return null; } - - if (! $this->nodeComparator->areNodesEqual($firstAssign->expr->args[0]->value, $valueNode)) { + if (!$this->nodeComparator->areNodesEqual($firstAssign->expr->args[0]->value, $valueNode)) { return null; } - - if (! $this->nodeComparator->areNodesEqual($secondAssign->expr, $firstAssign->expr->args[1]->value)) { + if (!$this->nodeComparator->areNodesEqual($secondAssign->expr, $firstAssign->expr->args[1]->value)) { return null; } - - $args = [new Arg(new Coalesce($valueNode, new Array_([]))), new Arg($secondAssign->expr)]; - $funcCall = new FuncCall(new Name('array_merge'), $args); - - return new Assign($valueNode, $funcCall); + $args = [new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\BinaryOp\Coalesce($valueNode, new \PhpParser\Node\Expr\Array_([]))), new \PhpParser\Node\Arg($secondAssign->expr)]; + $funcCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('array_merge'), $args); + return new \PhpParser\Node\Expr\Assign($valueNode, $funcCall); } - - private function shouldSkip(If_ $if): bool + private function shouldSkip(\PhpParser\Node\Stmt\If_ $if) : bool { if ($if->else === null) { - return true; + return \true; } - - if (count($if->elseifs) > 1) { - return true; + if (\count($if->elseifs) > 1) { + return \true; } - - if (! $if->cond instanceof Isset_) { - return true; + if (!$if->cond instanceof \PhpParser\Node\Expr\Isset_) { + return \true; } - - if (! $this->hasOnlyStatementAssign($if)) { - return true; + if (!$this->hasOnlyStatementAssign($if)) { + return \true; } - - if (! $this->hasOnlyStatementAssign($if->else)) { - return true; + if (!$this->hasOnlyStatementAssign($if->else)) { + return \true; } - $ifStmt = $if->stmts[0]; - if (! $ifStmt instanceof Expression) { - return true; + if (!$ifStmt instanceof \PhpParser\Node\Stmt\Expression) { + return \true; } - - if (! $ifStmt->expr instanceof Assign) { - return true; + if (!$ifStmt->expr instanceof \PhpParser\Node\Expr\Assign) { + return \true; } - - if (! $this->nodeComparator->areNodesEqual($if->cond->vars[0], $ifStmt->expr->var)) { - return true; + if (!$this->nodeComparator->areNodesEqual($if->cond->vars[0], $ifStmt->expr->var)) { + return \true; } - $firstElseStmt = $if->else->stmts[0]; - if (! $firstElseStmt instanceof Expression) { - return false; + if (!$firstElseStmt instanceof \PhpParser\Node\Stmt\Expression) { + return \false; } - - if (! $firstElseStmt->expr instanceof Assign) { - return false; + if (!$firstElseStmt->expr instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - return ! $this->nodeComparator->areNodesEqual($if->cond->vars[0], $firstElseStmt->expr->var); + return !$this->nodeComparator->areNodesEqual($if->cond->vars[0], $firstElseStmt->expr->var); } - /** * @param If_|Else_ $node */ - private function hasOnlyStatementAssign(Node $node): bool + private function hasOnlyStatementAssign(\PhpParser\Node $node) : bool { - if (count($node->stmts) !== 1) { - return false; + if (\count($node->stmts) !== 1) { + return \false; } - - if (! $node->stmts[0] instanceof Expression) { - return false; + if (!$node->stmts[0] instanceof \PhpParser\Node\Stmt\Expression) { + return \false; } - - return $node->stmts[0]->expr instanceof Assign; + return $node->stmts[0]->expr instanceof \PhpParser\Node\Expr\Assign; } } diff --git a/rules/CodeQuality/Rector/If_/SimplifyIfNotNullReturnRector.php b/rules/CodeQuality/Rector/If_/SimplifyIfNotNullReturnRector.php index 09fccca7f89..47d21ce962d 100644 --- a/rules/CodeQuality/Rector/If_/SimplifyIfNotNullReturnRector.php +++ b/rules/CodeQuality/Rector/If_/SimplifyIfNotNullReturnRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes redundant null check to instant return', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes redundant null check to instant return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $newNode = 'something ; if ($newNode !== null) { return $newNode; @@ -42,64 +34,52 @@ if ($newNode !== null) { return null; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $newNode = 'something ; return $newNode; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $comparedNode = $this->ifManipulator->matchIfNotNullReturnValue($node); if ($comparedNode !== null) { $insideIfNode = $node->stmts[0]; - - $nextNode = $node->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextNode instanceof Return_) { + $nextNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextNode instanceof \PhpParser\Node\Stmt\Return_) { return null; } if ($nextNode->expr === null) { return null; } - - if (! $this->valueResolver->isNull($nextNode->expr)) { + if (!$this->valueResolver->isNull($nextNode->expr)) { return null; } - $this->removeNode($nextNode); return $insideIfNode; } - $comparedNode = $this->ifManipulator->matchIfValueReturnValue($node); if ($comparedNode !== null) { - $nextNode = $node->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextNode instanceof Return_) { + $nextNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextNode instanceof \PhpParser\Node\Stmt\Return_) { return null; } - - if (! $this->nodeComparator->areNodesEqual($comparedNode, $nextNode->expr)) { + if (!$this->nodeComparator->areNodesEqual($comparedNode, $nextNode->expr)) { return null; } - $this->removeNode($nextNode); return clone $nextNode; } - return null; } } diff --git a/rules/CodeQuality/Rector/If_/SimplifyIfNullableReturnRector.php b/rules/CodeQuality/Rector/If_/SimplifyIfNullableReturnRector.php index 67a84e655ba..217742dddd8 100644 --- a/rules/CodeQuality/Rector/If_/SimplifyIfNullableReturnRector.php +++ b/rules/CodeQuality/Rector/If_/SimplifyIfNullableReturnRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->assignVariableTypeResolver = $assignVariableTypeResolver; $this->varTagRemover = $varTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Direct return on if nullable check before return', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Direct return on if nullable check before return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -75,8 +64,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -85,186 +73,135 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var BooleanNot|Instanceof_ $cond */ $cond = $node->cond; /** @var Instanceof_ $instanceof */ - $instanceof = $cond instanceof BooleanNot - ? $cond->expr - : $cond; + $instanceof = $cond instanceof \PhpParser\Node\Expr\BooleanNot ? $cond->expr : $cond; $variable = $instanceof->expr; $class = $instanceof->class; - - if (! $class instanceof Name) { + if (!$class instanceof \PhpParser\Node\Name) { return null; } - /** @var Return_ $returnIfStmt */ $returnIfStmt = $node->stmts[0]; - if ($this->isIfStmtReturnIncorrect($cond, $variable, $returnIfStmt)) { return null; } - - $previous = $node->getAttribute(AttributeKey::PREVIOUS_NODE); - if (! $previous instanceof Expression) { + $previous = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if (!$previous instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $previousAssign = $previous->expr; - if (! $previousAssign instanceof Assign) { + if (!$previousAssign instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $this->nodeComparator->areNodesEqual($previousAssign->var, $variable)) { + if (!$this->nodeComparator->areNodesEqual($previousAssign->var, $variable)) { return null; } - /** @var Return_ $next */ - $next = $node->getAttribute(AttributeKey::NEXT_NODE); + $next = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); if ($this->isNextReturnIncorrect($cond, $variable, $next)) { return null; } - $variableType = $this->assignVariableTypeResolver->resolve($previousAssign); - if (! $variableType instanceof UnionType) { + if (!$variableType instanceof \PHPStan\Type\UnionType) { return null; } - $className = $class->toString(); $types = $variableType->getTypes(); - - return $this->processSimplifyNullableReturn( - $variableType, - $types, - $className, - $next, - $previous, - $previousAssign->expr - ); + return $this->processSimplifyNullableReturn($variableType, $types, $className, $next, $previous, $previousAssign->expr); } - - private function isIfStmtReturnIncorrect(Expr $expr, Expr $variable, Return_ $return): bool + private function isIfStmtReturnIncorrect(\PhpParser\Node\Expr $expr, \PhpParser\Node\Expr $variable, \PhpParser\Node\Stmt\Return_ $return) : bool { - if (! $return->expr instanceof Expr) { - return true; + if (!$return->expr instanceof \PhpParser\Node\Expr) { + return \true; } - - if ($expr instanceof BooleanNot && ! $this->valueResolver->isNull($return->expr)) { - return true; + if ($expr instanceof \PhpParser\Node\Expr\BooleanNot && !$this->valueResolver->isNull($return->expr)) { + return \true; } - - return $expr instanceof Instanceof_ && ! $this->nodeComparator->areNodesEqual($variable, $return->expr); + return $expr instanceof \PhpParser\Node\Expr\Instanceof_ && !$this->nodeComparator->areNodesEqual($variable, $return->expr); } - - private function isNextReturnIncorrect(Expr $expr, Expr $variable, Return_ $return): bool + private function isNextReturnIncorrect(\PhpParser\Node\Expr $expr, \PhpParser\Node\Expr $variable, \PhpParser\Node\Stmt\Return_ $return) : bool { - if (! $return->expr instanceof Expr) { - return true; + if (!$return->expr instanceof \PhpParser\Node\Expr) { + return \true; } - - if ($expr instanceof BooleanNot && ! $this->nodeComparator->areNodesEqual($return->expr, $variable)) { - return true; + if ($expr instanceof \PhpParser\Node\Expr\BooleanNot && !$this->nodeComparator->areNodesEqual($return->expr, $variable)) { + return \true; } - - return $expr instanceof Instanceof_ && ! $this->valueResolver->isNull($return->expr); + return $expr instanceof \PhpParser\Node\Expr\Instanceof_ && !$this->valueResolver->isNull($return->expr); } - /** * @param Type[] $types */ - private function processSimplifyNullableReturn( - UnionType $unionType, - array $types, - string $className, - Return_ $return, - Expression $expression, - Expr $expr - ): ?Return_ { - if (count($types) > 2) { + private function processSimplifyNullableReturn(\PHPStan\Type\UnionType $unionType, array $types, string $className, \PhpParser\Node\Stmt\Return_ $return, \PhpParser\Node\Stmt\Expression $expression, \PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Stmt\Return_ + { + if (\count($types) > 2) { return null; } - - if ($types[0] instanceof FullyQualifiedObjectType && $types[1] instanceof NullType && $className === $types[0]->getClassName()) { + if ($types[0] instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType && $types[1] instanceof \PHPStan\Type\NullType && $className === $types[0]->getClassName()) { return $this->removeAndReturn($return, $expression, $expr, $unionType); } - - if ($types[0] instanceof NullType && $types[1] instanceof FullyQualifiedObjectType && $className === $types[1]->getClassName()) { + if ($types[0] instanceof \PHPStan\Type\NullType && $types[1] instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType && $className === $types[1]->getClassName()) { return $this->removeAndReturn($return, $expression, $expr, $unionType); } - if ($this->isNotTypedNullable($types, $className)) { return null; } - return $this->removeAndReturn($return, $expression, $expr, $unionType); } - /** * @param Type[] $types */ - private function isNotTypedNullable(array $types, string $className): bool + private function isNotTypedNullable(array $types, string $className) : bool { - if (! $types[0] instanceof ObjectType) { - return true; + if (!$types[0] instanceof \PHPStan\Type\ObjectType) { + return \true; } - - if (! $types[1] instanceof NullType) { - return true; + if (!$types[1] instanceof \PHPStan\Type\NullType) { + return \true; } - return $className !== $types[0]->getClassName(); } - - private function removeAndReturn(Return_ $return, Expression $expression, Expr $expr, UnionType $unionType): Return_ + private function removeAndReturn(\PhpParser\Node\Stmt\Return_ $return, \PhpParser\Node\Stmt\Expression $expression, \PhpParser\Node\Expr $expr, \PHPStan\Type\UnionType $unionType) : \PhpParser\Node\Stmt\Return_ { $this->removeNode($return); $this->removeNode($expression); - - $return = new Return_($expr); + $return = new \PhpParser\Node\Stmt\Return_($expr); $this->varTagRemover->removeVarPhpTagValueNodeIfNotComment($expression, $unionType); $this->mirrorComments($return, $expression); - return $return; } - - private function shouldSkip(If_ $if): bool + private function shouldSkip(\PhpParser\Node\Stmt\If_ $if) : bool { - if (! $this->ifManipulator->isIfWithOnly($if, Return_::class)) { - return true; + if (!$this->ifManipulator->isIfWithOnly($if, \PhpParser\Node\Stmt\Return_::class)) { + return \true; } - - $next = $if->getAttribute(AttributeKey::NEXT_NODE); - if (! $next instanceof Return_) { - return true; + $next = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$next instanceof \PhpParser\Node\Stmt\Return_) { + return \true; } - $cond = $if->cond; - - if (! $cond instanceof BooleanNot) { - return ! $cond instanceof Instanceof_; + if (!$cond instanceof \PhpParser\Node\Expr\BooleanNot) { + return !$cond instanceof \PhpParser\Node\Expr\Instanceof_; } - - return ! $cond->expr instanceof Instanceof_; + return !$cond->expr instanceof \PhpParser\Node\Expr\Instanceof_; } } diff --git a/rules/CodeQuality/Rector/If_/SimplifyIfReturnBoolRector.php b/rules/CodeQuality/Rector/If_/SimplifyIfReturnBoolRector.php index c6da7325187..4c373a3fa36 100644 --- a/rules/CodeQuality/Rector/If_/SimplifyIfReturnBoolRector.php +++ b/rules/CodeQuality/Rector/If_/SimplifyIfReturnBoolRector.php @@ -1,10 +1,9 @@ commentsMerger = $commentsMerger; $this->exprBoolCaster = $exprBoolCaster; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Shortens if return false/true to direct return', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Shortens if return false/true to direct return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' if (strpos($docToken->getContent(), "\n") === false) { return true; } return false; CODE_SAMPLE - , - 'return strpos($docToken->getContent(), "\n") === false;' - ), - ] - ); +, 'return strpos($docToken->getContent(), "\\n") === false;')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var Return_ $ifInnerNode */ $ifInnerNode = $node->stmts[0]; - /** @var Return_ $nextNode */ - $nextNode = $node->getAttribute(AttributeKey::NEXT_NODE); - + $nextNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); /** @var Node $innerIfInnerNode */ $innerIfInnerNode = $ifInnerNode->expr; - if ($this->valueResolver->isTrue($innerIfInnerNode)) { $newReturnNode = $this->processReturnTrue($node, $nextNode); } elseif ($this->valueResolver->isFalse($innerIfInnerNode)) { @@ -93,125 +74,97 @@ CODE_SAMPLE } else { return null; } - if ($newReturnNode === null) { return null; } - $this->commentsMerger->keepComments($newReturnNode, [$node, $ifInnerNode, $nextNode, $newReturnNode]); $this->removeNode($nextNode); - return $newReturnNode; } - - private function shouldSkip(If_ $if): bool + private function shouldSkip(\PhpParser\Node\Stmt\If_ $if) : bool { if ($if->elseifs !== []) { - return true; + return \true; } - if ($this->isElseSeparatedThenIf($if)) { - return true; + return \true; } - - if (! $this->isIfWithSingleReturnExpr($if)) { - return true; + if (!$this->isIfWithSingleReturnExpr($if)) { + return \true; } - /** @var Return_ $ifInnerNode */ $ifInnerNode = $if->stmts[0]; - /** @var Expr $returnedExpr */ $returnedExpr = $ifInnerNode->expr; - - if (! $this->valueResolver->isTrueOrFalse($returnedExpr)) { - return true; + if (!$this->valueResolver->isTrueOrFalse($returnedExpr)) { + return \true; } - - $nextNode = $if->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextNode instanceof Return_) { - return true; + $nextNode = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextNode instanceof \PhpParser\Node\Stmt\Return_) { + return \true; } if ($nextNode->expr === null) { - return true; + return \true; } // negate + negate → skip for now - if (! $this->valueResolver->isFalse($returnedExpr)) { - return ! $this->valueResolver->isTrueOrFalse($nextNode->expr); + if (!$this->valueResolver->isFalse($returnedExpr)) { + return !$this->valueResolver->isTrueOrFalse($nextNode->expr); } - if (! Strings::contains($this->print($if->cond), '!=')) { - return ! $this->valueResolver->isTrueOrFalse($nextNode->expr); + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($this->print($if->cond), '!=')) { + return !$this->valueResolver->isTrueOrFalse($nextNode->expr); } - return true; + return \true; } - - private function processReturnTrue(If_ $if, Return_ $nextReturnNode): Return_ + private function processReturnTrue(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node\Stmt\Return_ $nextReturnNode) : \PhpParser\Node\Stmt\Return_ { - if ($if->cond instanceof BooleanNot && $nextReturnNode->expr !== null && $this->valueResolver->isTrue( - $nextReturnNode->expr - )) { - return new Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded($if->cond->expr)); + if ($if->cond instanceof \PhpParser\Node\Expr\BooleanNot && $nextReturnNode->expr !== null && $this->valueResolver->isTrue($nextReturnNode->expr)) { + return new \PhpParser\Node\Stmt\Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded($if->cond->expr)); } - - return new Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded($if->cond)); + return new \PhpParser\Node\Stmt\Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded($if->cond)); } - - private function processReturnFalse(If_ $if, Return_ $nextReturnNode): ?Return_ + private function processReturnFalse(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node\Stmt\Return_ $nextReturnNode) : ?\PhpParser\Node\Stmt\Return_ { - if ($if->cond instanceof Identical) { - $notIdentical = new NotIdentical($if->cond->left, $if->cond->right); - - return new Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded($notIdentical)); + if ($if->cond instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { + $notIdentical = new \PhpParser\Node\Expr\BinaryOp\NotIdentical($if->cond->left, $if->cond->right); + return new \PhpParser\Node\Stmt\Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded($notIdentical)); } - if ($nextReturnNode->expr === null) { return null; } - - if (! $this->valueResolver->isTrue($nextReturnNode->expr)) { + if (!$this->valueResolver->isTrue($nextReturnNode->expr)) { return null; } - - if ($if->cond instanceof BooleanNot) { - return new Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded($if->cond->expr)); + if ($if->cond instanceof \PhpParser\Node\Expr\BooleanNot) { + return new \PhpParser\Node\Stmt\Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded($if->cond->expr)); } - - return new Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded(new BooleanNot($if->cond))); + return new \PhpParser\Node\Stmt\Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded(new \PhpParser\Node\Expr\BooleanNot($if->cond))); } - /** * Matches: "else if" */ - private function isElseSeparatedThenIf(If_ $if): bool + private function isElseSeparatedThenIf(\PhpParser\Node\Stmt\If_ $if) : bool { if ($if->else === null) { - return false; + return \false; } - - if (count($if->else->stmts) !== 1) { - return false; + if (\count($if->else->stmts) !== 1) { + return \false; } - $onlyStmt = $if->else->stmts[0]; - - return $onlyStmt instanceof If_; + return $onlyStmt instanceof \PhpParser\Node\Stmt\If_; } - - private function isIfWithSingleReturnExpr(If_ $if): bool + private function isIfWithSingleReturnExpr(\PhpParser\Node\Stmt\If_ $if) : bool { - if (count($if->stmts) !== 1) { - return false; + if (\count($if->stmts) !== 1) { + return \false; } - if ($if->elseifs !== []) { - return false; + return \false; } - $ifInnerNode = $if->stmts[0]; - if (! $ifInnerNode instanceof Return_) { - return false; + if (!$ifInnerNode instanceof \PhpParser\Node\Stmt\Return_) { + return \false; } - // return must have value return $ifInnerNode->expr !== null; } diff --git a/rules/CodeQuality/Rector/Include_/AbsolutizeRequireAndIncludePathRector.php b/rules/CodeQuality/Rector/Include_/AbsolutizeRequireAndIncludePathRector.php index 54a1ae3f1a4..34d99bf76b6 100644 --- a/rules/CodeQuality/Rector/Include_/AbsolutizeRequireAndIncludePathRector.php +++ b/rules/CodeQuality/Rector/Include_/AbsolutizeRequireAndIncludePathRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Include_::class]; + return [\PhpParser\Node\Expr\Include_::class]; } - /** * @param Include_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof String_) { + if (!$node->expr instanceof \PhpParser\Node\Scalar\String_) { return null; } - /** @var string $includeValue */ $includeValue = $this->valueResolver->getValue($node->expr); - // skip phar - if (Strings::startsWith($includeValue, 'phar://')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::startsWith($includeValue, 'phar://')) { return null; } - // skip absolute paths - if (Strings::startsWith($includeValue, '/')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::startsWith($includeValue, '/')) { return null; } - // add preslash to string - if (Strings::startsWith($includeValue, './')) { - $node->expr->value = Strings::substring($includeValue, 1); + if (\RectorPrefix20210509\Nette\Utils\Strings::startsWith($includeValue, './')) { + $node->expr->value = \RectorPrefix20210509\Nette\Utils\Strings::substring($includeValue, 1); } else { $node->expr->value = '/' . $includeValue; } - - $node->expr = new Concat(new Dir(), $node->expr); - + $node->expr = new \PhpParser\Node\Expr\BinaryOp\Concat(new \PhpParser\Node\Scalar\MagicConst\Dir(), $node->expr); return $node; } } diff --git a/rules/CodeQuality/Rector/Isset_/IssetOnPropertyObjectToPropertyExistsRector.php b/rules/CodeQuality/Rector/Isset_/IssetOnPropertyObjectToPropertyExistsRector.php index 006b9ca0bb1..549e2c9f594 100644 --- a/rules/CodeQuality/Rector/Isset_/IssetOnPropertyObjectToPropertyExistsRector.php +++ b/rules/CodeQuality/Rector/Isset_/IssetOnPropertyObjectToPropertyExistsRector.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change isset on property object to property_exists() and not null check', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change isset on property object to property_exists() and not null check', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private $x; @@ -50,8 +44,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { private $x; @@ -62,83 +55,58 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Isset_::class]; + return [\PhpParser\Node\Expr\Isset_::class]; } - /** * @param Isset_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $newNodes = []; - foreach ($node->vars as $issetVar) { - if (! $issetVar instanceof PropertyFetch) { + if (!$issetVar instanceof \PhpParser\Node\Expr\PropertyFetch) { continue; } - $property = $this->nodeRepository->findPropertyByPropertyFetch($issetVar); - if ($property instanceof Property && $property->type) { + if ($property instanceof \PhpParser\Node\Stmt\Property && $property->type) { continue; } - $propertyFetchName = $this->getName($issetVar->name); if ($propertyFetchName === null) { continue; } - $propertyFetchVarType = $this->getObjectType($issetVar->var); - - if ($propertyFetchVarType instanceof TypeWithClassName) { - if (! $this->reflectionProvider->hasClass($propertyFetchVarType->getClassName())) { + if ($propertyFetchVarType instanceof \PHPStan\Type\TypeWithClassName) { + if (!$this->reflectionProvider->hasClass($propertyFetchVarType->getClassName())) { continue; } - $classReflection = $this->reflectionProvider->getClass($propertyFetchVarType->getClassName()); - - if (! $classReflection->hasProperty($propertyFetchName)) { - $newNodes[] = $this->replaceToPropertyExistsWithNullCheck( - $issetVar->var, - $propertyFetchName, - $issetVar - ); + if (!$classReflection->hasProperty($propertyFetchName)) { + $newNodes[] = $this->replaceToPropertyExistsWithNullCheck($issetVar->var, $propertyFetchName, $issetVar); } else { $newNodes[] = $this->createNotIdenticalToNull($issetVar); } } else { - $newNodes[] = $this->replaceToPropertyExistsWithNullCheck( - $issetVar->var, - $propertyFetchName, - $issetVar - ); + $newNodes[] = $this->replaceToPropertyExistsWithNullCheck($issetVar->var, $propertyFetchName, $issetVar); } } - return $this->nodeFactory->createReturnBooleanAnd($newNodes); } - - private function replaceToPropertyExistsWithNullCheck( - Expr $expr, - string $property, - PropertyFetch $propertyFetch - ): BooleanAnd { - $args = [new Arg($expr), new Arg(new String_($property))]; - $propertyExistsFuncCall = $this->nodeFactory->createFuncCall('property_exists', $args); - - return new BooleanAnd($propertyExistsFuncCall, $this->createNotIdenticalToNull($propertyFetch)); - } - - private function createNotIdenticalToNull(Expr $expr): NotIdentical + private function replaceToPropertyExistsWithNullCheck(\PhpParser\Node\Expr $expr, string $property, \PhpParser\Node\Expr\PropertyFetch $propertyFetch) : \PhpParser\Node\Expr\BinaryOp\BooleanAnd { - return new NotIdentical($expr, $this->nodeFactory->createNull()); + $args = [new \PhpParser\Node\Arg($expr), new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_($property))]; + $propertyExistsFuncCall = $this->nodeFactory->createFuncCall('property_exists', $args); + return new \PhpParser\Node\Expr\BinaryOp\BooleanAnd($propertyExistsFuncCall, $this->createNotIdenticalToNull($propertyFetch)); + } + private function createNotIdenticalToNull(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\BinaryOp\NotIdentical + { + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, $this->nodeFactory->createNull()); } } diff --git a/rules/CodeQuality/Rector/LogicalAnd/AndAssignsToSeparateLinesRector.php b/rules/CodeQuality/Rector/LogicalAnd/AndAssignsToSeparateLinesRector.php index 5b277d4d51d..6bf95e235ea 100644 --- a/rules/CodeQuality/Rector/LogicalAnd/AndAssignsToSeparateLinesRector.php +++ b/rules/CodeQuality/Rector/LogicalAnd/AndAssignsToSeparateLinesRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [LogicalAnd::class]; + return [\PhpParser\Node\Expr\BinaryOp\LogicalAnd::class]; } - /** * @param LogicalAnd $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->left instanceof Assign) { + if (!$node->left instanceof \PhpParser\Node\Expr\Assign) { return null; } - if (! $node->right instanceof Assign) { + if (!$node->right instanceof \PhpParser\Node\Expr\Assign) { return null; } - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Expression) { + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $this->addNodeAfterNode($node->right, $node); - return $node->left; } } diff --git a/rules/CodeQuality/Rector/LogicalAnd/LogicalToBooleanRector.php b/rules/CodeQuality/Rector/LogicalAnd/LogicalToBooleanRector.php index f3aff4d44cc..187ffc94e59 100644 --- a/rules/CodeQuality/Rector/LogicalAnd/LogicalToBooleanRector.php +++ b/rules/CodeQuality/Rector/LogicalAnd/LogicalToBooleanRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [LogicalOr::class, LogicalAnd::class]; + return [\PhpParser\Node\Expr\BinaryOp\LogicalOr::class, \PhpParser\Node\Expr\BinaryOp\LogicalAnd::class]; } - /** * @param LogicalOr|LogicalAnd $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof LogicalOr) { - return new BooleanOr($node->left, $node->right); + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\LogicalOr) { + return new \PhpParser\Node\Expr\BinaryOp\BooleanOr($node->left, $node->right); } - - return new BooleanAnd($node->left, $node->right); + return new \PhpParser\Node\Expr\BinaryOp\BooleanAnd($node->left, $node->right); } } diff --git a/rules/CodeQuality/Rector/Name/FixClassCaseSensitivityNameRector.php b/rules/CodeQuality/Rector/Name/FixClassCaseSensitivityNameRector.php index e3c7fe69214..1a9925c59c9 100644 --- a/rules/CodeQuality/Rector/Name/FixClassCaseSensitivityNameRector.php +++ b/rules/CodeQuality/Rector/Name/FixClassCaseSensitivityNameRector.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change miss-typed case sensitivity name to correct one', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change miss-typed case sensitivity name to correct one', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -53,8 +45,7 @@ final class AnotherClass { } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -67,75 +58,60 @@ final class AnotherClass { } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Name::class]; + return [\PhpParser\Node\Name::class]; } - /** * @param Name $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $fullyQualifiedName = $this->resolveFullyQualifiedName($node); - if (! $this->reflectionProvider->hasClass($fullyQualifiedName)) { + if (!$this->reflectionProvider->hasClass($fullyQualifiedName)) { return null; } - $classReflection = $this->reflectionProvider->getClass($fullyQualifiedName); if ($classReflection->isBuiltin()) { // skip built-in classes return null; } - $realClassName = $classReflection->getName(); - if (strtolower($realClassName) !== strtolower($fullyQualifiedName)) { + if (\strtolower($realClassName) !== \strtolower($fullyQualifiedName)) { // skip class alias return null; } - if ($realClassName === $fullyQualifiedName) { return null; } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // do not FQN use imports - if ($parent instanceof UseUse) { - return new Name($realClassName); + if ($parent instanceof \PhpParser\Node\Stmt\UseUse) { + return new \PhpParser\Node\Name($realClassName); } - - return new FullyQualified($realClassName); + return new \PhpParser\Node\Name\FullyQualified($realClassName); } - - private function resolveFullyQualifiedName(Name $name): string + private function resolveFullyQualifiedName(\PhpParser\Node\Name $name) : string { - $parent = $name->getAttribute(AttributeKey::PARENT_NODE); + $parent = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // for some reason, Param gets already corrected name - if (! $parent instanceof Param && ! $parent instanceof ClassConstFetch) { + if (!$parent instanceof \PhpParser\Node\Param && !$parent instanceof \PhpParser\Node\Expr\ClassConstFetch) { return $this->getName($name); } - - $originalName = $name->getAttribute(AttributeKey::ORIGINAL_NAME); - if (! $originalName instanceof Name) { + $originalName = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NAME); + if (!$originalName instanceof \PhpParser\Node\Name) { return $this->getName($name); } - // replace parts from the old one - $originalReversedParts = array_reverse($originalName->parts); - $resolvedReversedParts = array_reverse($name->parts); - + $originalReversedParts = \array_reverse($originalName->parts); + $resolvedReversedParts = \array_reverse($name->parts); $mergedReversedParts = $originalReversedParts + $resolvedReversedParts; - $mergedParts = array_reverse($mergedReversedParts); - - return implode('\\', $mergedParts); + $mergedParts = \array_reverse($mergedReversedParts); + return \implode('\\', $mergedParts); } } diff --git a/rules/CodeQuality/Rector/New_/NewStaticToNewSelfRector.php b/rules/CodeQuality/Rector/New_/NewStaticToNewSelfRector.php index 9e2205d75a2..e47620256e3 100644 --- a/rules/CodeQuality/Rector/New_/NewStaticToNewSelfRector.php +++ b/rules/CodeQuality/Rector/New_/NewStaticToNewSelfRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [New_::class]; + return [\PhpParser\Node\Expr\New_::class]; } - /** * @param New_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $class = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $class instanceof Class_) { + $class = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$class instanceof \PhpParser\Node\Stmt\Class_) { return null; } - - if (! $class->isFinal()) { + if (!$class->isFinal()) { return null; } - - if (! $this->isName($node->class, 'static')) { + if (!$this->isName($node->class, 'static')) { return null; } - - $node->class = new Name('self'); - + $node->class = new \PhpParser\Node\Name('self'); return $node; } } diff --git a/rules/CodeQuality/Rector/NotEqual/CommonNotEqualRector.php b/rules/CodeQuality/Rector/NotEqual/CommonNotEqualRector.php index ff814402255..e551db35e72 100644 --- a/rules/CodeQuality/Rector/NotEqual/CommonNotEqualRector.php +++ b/rules/CodeQuality/Rector/NotEqual/CommonNotEqualRector.php @@ -1,7 +1,6 @@ with same meaning', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Use common != instead of less known <> with same meaning', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run($one, $two) @@ -32,8 +26,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run($one, $two) @@ -42,27 +35,22 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [NotEqual::class]; + return [\PhpParser\Node\Expr\BinaryOp\NotEqual::class]; } - /** * @param NotEqual $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { // invoke override to default "!=" - $node->setAttribute(AttributeKey::ORIGINAL_NODE, null); - + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); return $node; } } diff --git a/rules/CodeQuality/Rector/Return_/SimplifyUselessVariableRector.php b/rules/CodeQuality/Rector/Return_/SimplifyUselessVariableRector.php index 3836b6391eb..5cecbc2c170 100644 --- a/rules/CodeQuality/Rector/Return_/SimplifyUselessVariableRector.php +++ b/rules/CodeQuality/Rector/Return_/SimplifyUselessVariableRector.php @@ -1,7 +1,6 @@ assignAndBinaryMap = $assignAndBinaryMap; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Removes useless variable assigns', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removes useless variable assigns', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' function () { $a = true; return $a; }; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' function () { return true; }; CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Return_::class]; + return [\PhpParser\Node\Stmt\Return_::class]; } - /** * @param Return_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - - $previousNode = $node->getAttribute(AttributeKey::PREVIOUS_NODE); - if (! $previousNode instanceof Expression) { + $previousNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if (!$previousNode instanceof \PhpParser\Node\Stmt\Expression) { return null; } - /** @var AssignOp|Assign $previousNode */ $previousNode = $previousNode->expr; $previousVariableNode = $previousNode->var; - if ($this->hasSomeComment($previousVariableNode)) { return null; } - - if ($previousNode instanceof Assign) { + if ($previousNode instanceof \PhpParser\Node\Expr\Assign) { if ($this->isReturnWithVarAnnotation($node)) { return null; } - $node->expr = $previousNode->expr; } - - if ($previousNode instanceof AssignOp) { + if ($previousNode instanceof \PhpParser\Node\Expr\AssignOp) { $binaryClass = $this->assignAndBinaryMap->getAlternative($previousNode); if ($binaryClass === null) { return null; } - $node->expr = new $binaryClass($previousNode->var, $previousNode->expr); } - $this->removeNode($previousNode); - return $node; } - - private function shouldSkip(Return_ $return): bool + private function shouldSkip(\PhpParser\Node\Stmt\Return_ $return) : bool { - if (! $return->expr instanceof Variable) { - return true; + if (!$return->expr instanceof \PhpParser\Node\Expr\Variable) { + return \true; } - $variableNode = $return->expr; - - $previousExpression = $return->getAttribute(AttributeKey::PREVIOUS_NODE); - if (! $previousExpression instanceof Node) { - return true; + $previousExpression = $return->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if (!$previousExpression instanceof \PhpParser\Node) { + return \true; } - if (! $previousExpression instanceof Expression) { - return true; + if (!$previousExpression instanceof \PhpParser\Node\Stmt\Expression) { + return \true; } - // is variable part of single assign $previousNode = $previousExpression->expr; - if (! $previousNode instanceof AssignOp && ! $previousNode instanceof Assign) { - return true; + if (!$previousNode instanceof \PhpParser\Node\Expr\AssignOp && !$previousNode instanceof \PhpParser\Node\Expr\Assign) { + return \true; } - // is the same variable - if (! $this->nodeComparator->areNodesEqual($previousNode->var, $variableNode)) { - return true; + if (!$this->nodeComparator->areNodesEqual($previousNode->var, $variableNode)) { + return \true; } return $this->isPreviousExpressionVisuallySimilar($previousExpression, $previousNode); } - - private function hasSomeComment(Expr $expr): bool + private function hasSomeComment(\PhpParser\Node\Expr $expr) : bool { if ($expr->getComments() !== []) { - return true; + return \true; } - return $expr->getDocComment() !== null; } - - private function isReturnWithVarAnnotation(Return_ $return): bool + private function isReturnWithVarAnnotation(\PhpParser\Node\Stmt\Return_ $return) : bool { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($return); - return ! $phpDocInfo->getVarType() instanceof MixedType; + return !$phpDocInfo->getVarType() instanceof \PHPStan\Type\MixedType; } - /** * @param AssignOp|Assign $previousNode */ - private function isPreviousExpressionVisuallySimilar(Expression $previousExpression, Node $previousNode): bool + private function isPreviousExpressionVisuallySimilar(\PhpParser\Node\Stmt\Expression $previousExpression, \PhpParser\Node $previousNode) : bool { - $prePreviousExpression = $previousExpression->getAttribute(AttributeKey::PREVIOUS_STATEMENT); - if (! $prePreviousExpression instanceof Expression) { - return false; + $prePreviousExpression = $previousExpression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT); + if (!$prePreviousExpression instanceof \PhpParser\Node\Stmt\Expression) { + return \false; } - if (! $prePreviousExpression->expr instanceof AssignOp) { - return false; + if (!$prePreviousExpression->expr instanceof \PhpParser\Node\Expr\AssignOp) { + return \false; } return $this->nodeComparator->areNodesEqual($prePreviousExpression->expr->var, $previousNode->var); } diff --git a/rules/CodeQuality/Rector/Switch_/SingularSwitchToIfRector.php b/rules/CodeQuality/Rector/Switch_/SingularSwitchToIfRector.php index 530d5ed9ac0..8637ba202ff 100644 --- a/rules/CodeQuality/Rector/Switch_/SingularSwitchToIfRector.php +++ b/rules/CodeQuality/Rector/Switch_/SingularSwitchToIfRector.php @@ -1,7 +1,6 @@ switchManipulator = $switchManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change switch with only 1 check to if', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change switch with only 1 check to if', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeObject { public function run($value) @@ -47,9 +41,7 @@ class SomeObject } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeObject { public function run($value) @@ -63,38 +55,31 @@ class SomeObject } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Switch_::class]; + return [\PhpParser\Node\Stmt\Switch_::class]; } - /** * @param Switch_ $node * @return Node\Stmt[]|If_|null */ - public function refactor(Node $node) + public function refactor(\PhpParser\Node $node) { - if (count($node->cases) !== 1) { + if (\count($node->cases) !== 1) { return null; } - $onlyCase = $node->cases[0]; - // only default → basically unwrap if ($onlyCase->cond === null) { return $onlyCase->stmts; } - - $if = new If_(new Identical($node->cond, $onlyCase->cond)); + $if = new \PhpParser\Node\Stmt\If_(new \PhpParser\Node\Expr\BinaryOp\Identical($node->cond, $onlyCase->cond)); $if->stmts = $this->switchManipulator->removeBreakNodes($onlyCase->stmts); - return $if; } } diff --git a/rules/CodeQuality/Rector/Ternary/ArrayKeyExistsTernaryThenValueToCoalescingRector.php b/rules/CodeQuality/Rector/Ternary/ArrayKeyExistsTernaryThenValueToCoalescingRector.php index 25e6395ed31..efd2f45240b 100644 --- a/rules/CodeQuality/Rector/Ternary/ArrayKeyExistsTernaryThenValueToCoalescingRector.php +++ b/rules/CodeQuality/Rector/Ternary/ArrayKeyExistsTernaryThenValueToCoalescingRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->cond instanceof FuncCall) { + if (!$node->cond instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->isName($node->cond, 'array_key_exists')) { + if (!$this->isName($node->cond, 'array_key_exists')) { return null; } - - if (! $node->if instanceof ArrayDimFetch) { + if (!$node->if instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return null; } - - if (! $this->areArrayKeysExistsArgsMatchingDimFetch($node->cond, $node->if)) { + if (!$this->areArrayKeysExistsArgsMatchingDimFetch($node->cond, $node->if)) { return null; } - - if (! $this->valueResolver->isNull($node->else)) { + if (!$this->valueResolver->isNull($node->else)) { return null; } - - return new Coalesce($node->if, $node->else); + return new \PhpParser\Node\Expr\BinaryOp\Coalesce($node->if, $node->else); } - /** * Equals if: * @@ -93,13 +76,12 @@ CODE_SAMPLE * = * $values[$key] */ - private function areArrayKeysExistsArgsMatchingDimFetch(FuncCall $funcCall, ArrayDimFetch $arrayDimFetch): bool + private function areArrayKeysExistsArgsMatchingDimFetch(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : bool { $keyExpr = $funcCall->args[0]->value; $valuesExpr = $funcCall->args[1]->value; - - if (! $this->nodeComparator->areNodesEqual($arrayDimFetch->var, $valuesExpr)) { - return false; + if (!$this->nodeComparator->areNodesEqual($arrayDimFetch->var, $valuesExpr)) { + return \false; } return $this->nodeComparator->areNodesEqual($arrayDimFetch->dim, $keyExpr); } diff --git a/rules/CodeQuality/Rector/Ternary/SimplifyDuplicatedTernaryRector.php b/rules/CodeQuality/Rector/Ternary/SimplifyDuplicatedTernaryRector.php index da2a574173d..49bf0a5737a 100644 --- a/rules/CodeQuality/Rector/Ternary/SimplifyDuplicatedTernaryRector.php +++ b/rules/CodeQuality/Rector/Ternary/SimplifyDuplicatedTernaryRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->nodeTypeResolver->isStaticType($node->cond, BooleanType::class)) { + if (!$this->nodeTypeResolver->isStaticType($node->cond, \PHPStan\Type\BooleanType::class)) { return null; } - if ($node->if === null) { return null; } - if (! $this->valueResolver->isTrue($node->if)) { + if (!$this->valueResolver->isTrue($node->if)) { return null; } - if (! $this->valueResolver->isFalse($node->else)) { + if (!$this->valueResolver->isFalse($node->else)) { return null; } - return $node->cond; } } diff --git a/rules/CodeQuality/Rector/Ternary/SimplifyTautologyTernaryRector.php b/rules/CodeQuality/Rector/Ternary/SimplifyTautologyTernaryRector.php index 142cce57eeb..2c30e004804 100644 --- a/rules/CodeQuality/Rector/Ternary/SimplifyTautologyTernaryRector.php +++ b/rules/CodeQuality/Rector/Ternary/SimplifyTautologyTernaryRector.php @@ -1,7 +1,6 @@ binaryOpManipulator = $binaryOpManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Simplify tautology ternary to value', [ - new CodeSample( - '$value = ($fullyQualifiedTypeHint !== $typeHint) ? $fullyQualifiedTypeHint : $typeHint;', - '$value = $fullyQualifiedTypeHint;' - ), - ]); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Simplify tautology ternary to value', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('$value = ($fullyQualifiedTypeHint !== $typeHint) ? $fullyQualifiedTypeHint : $typeHint;', '$value = $fullyQualifiedTypeHint;')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->cond instanceof NotIdentical && ! $node->cond instanceof Identical) { + if (!$node->cond instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical && !$node->cond instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { return null; } - - $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode( - $node->cond, - function (Node $leftNode) use ($node): bool { - return $this->nodeComparator->areNodesEqual($leftNode, $node->if); - }, - function (Node $leftNode) use ($node): bool { - return $this->nodeComparator->areNodesEqual($leftNode, $node->else); - } - ); - - if (! $twoNodeMatch instanceof TwoNodeMatch) { + $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode($node->cond, function (\PhpParser\Node $leftNode) use($node) : bool { + return $this->nodeComparator->areNodesEqual($leftNode, $node->if); + }, function (\PhpParser\Node $leftNode) use($node) : bool { + return $this->nodeComparator->areNodesEqual($leftNode, $node->else); + }); + if (!$twoNodeMatch instanceof \Rector\Php71\ValueObject\TwoNodeMatch) { return null; } - return $node->if; } } diff --git a/rules/CodeQuality/Rector/Ternary/SwitchNegatedTernaryRector.php b/rules/CodeQuality/Rector/Ternary/SwitchNegatedTernaryRector.php index 68c7de99ac2..43d2fcfb42c 100644 --- a/rules/CodeQuality/Rector/Ternary/SwitchNegatedTernaryRector.php +++ b/rules/CodeQuality/Rector/Ternary/SwitchNegatedTernaryRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->cond instanceof BooleanNot) { + if (!$node->cond instanceof \PhpParser\Node\Expr\BooleanNot) { return null; } - if ($node->if === null) { return null; } - $node->cond = $node->cond->expr; [$node->if, $node->else] = [$node->else, $node->if]; - return $node; } } diff --git a/rules/CodeQuality/Rector/Ternary/UnnecessaryTernaryExpressionRector.php b/rules/CodeQuality/Rector/Ternary/UnnecessaryTernaryExpressionRector.php index e2e6295cd50..f7d89234c0b 100644 --- a/rules/CodeQuality/Rector/Ternary/UnnecessaryTernaryExpressionRector.php +++ b/rules/CodeQuality/Rector/Ternary/UnnecessaryTernaryExpressionRector.php @@ -1,7 +1,6 @@ assignAndBinaryMap = $assignAndBinaryMap; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove unnecessary ternary expressions.', - [new CodeSample('$foo === $bar ? true : false;', '$foo === $bar;')] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove unnecessary ternary expressions.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('$foo === $bar ? true : false;', '$foo === $bar;')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { /** @var Ternary $ternaryExpression */ $ternaryExpression = $node; - if (! $ternaryExpression->if instanceof Expr) { + if (!$ternaryExpression->if instanceof \PhpParser\Node\Expr) { return null; } - $ifExpression = $ternaryExpression->if; - if (! $this->valueResolver->isTrueOrFalse($ifExpression)) { + if (!$this->valueResolver->isTrueOrFalse($ifExpression)) { return null; } - $elseExpression = $ternaryExpression->else; - if (! $this->valueResolver->isTrueOrFalse($elseExpression)) { + if (!$this->valueResolver->isTrueOrFalse($elseExpression)) { return null; } - $condition = $ternaryExpression->cond; - if (! $condition instanceof BinaryOp) { + if (!$condition instanceof \PhpParser\Node\Expr\BinaryOp) { return $this->processNonBinaryCondition($ifExpression, $elseExpression, $condition); } if ($this->valueResolver->isNull($ifExpression)) { @@ -78,59 +66,48 @@ final class UnnecessaryTernaryExpressionRector extends AbstractRector if ($this->valueResolver->isNull($elseExpression)) { return null; } - /** @var BinaryOp $binaryOperation */ $binaryOperation = $node->cond; - if ($this->valueResolver->isTrue($ifExpression) && $this->valueResolver->isFalse($elseExpression)) { return $binaryOperation; } - $inversedBinaryClass = $this->assignAndBinaryMap->getInversed($binaryOperation); if ($inversedBinaryClass === null) { return null; } - return new $inversedBinaryClass($binaryOperation->left, $binaryOperation->right); } - - private function processNonBinaryCondition(Expr $ifExpression, Expr $elseExpression, Expr $condition): ?Node + private function processNonBinaryCondition(\PhpParser\Node\Expr $ifExpression, \PhpParser\Node\Expr $elseExpression, \PhpParser\Node\Expr $condition) : ?\PhpParser\Node { if ($this->valueResolver->isTrue($ifExpression) && $this->valueResolver->isFalse($elseExpression)) { return $this->processTrueIfExpressionWithFalseElseExpression($condition); } - if (! $this->valueResolver->isFalse($ifExpression)) { + if (!$this->valueResolver->isFalse($ifExpression)) { return null; } - if (! $this->valueResolver->isTrue($elseExpression)) { + if (!$this->valueResolver->isTrue($elseExpression)) { return null; } return $this->processFalseIfExpressionWithTrueElseExpression($condition); } - - private function processTrueIfExpressionWithFalseElseExpression(Expr $expr): Expr + private function processTrueIfExpressionWithFalseElseExpression(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { - if ($this->nodeTypeResolver->isStaticType($expr, BooleanType::class)) { + if ($this->nodeTypeResolver->isStaticType($expr, \PHPStan\Type\BooleanType::class)) { return $expr; } - - return new Bool_($expr); + return new \PhpParser\Node\Expr\Cast\Bool_($expr); } - - private function processFalseIfExpressionWithTrueElseExpression(Expr $expr): Expr + private function processFalseIfExpressionWithTrueElseExpression(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { - if ($expr instanceof BooleanNot) { - if ($this->nodeTypeResolver->isStaticType($expr->expr, BooleanType::class)) { + if ($expr instanceof \PhpParser\Node\Expr\BooleanNot) { + if ($this->nodeTypeResolver->isStaticType($expr->expr, \PHPStan\Type\BooleanType::class)) { return $expr->expr; } - - return new Bool_($expr->expr); + return new \PhpParser\Node\Expr\Cast\Bool_($expr->expr); } - - if ($this->nodeTypeResolver->isStaticType($expr, BooleanType::class)) { - return new BooleanNot($expr); + if ($this->nodeTypeResolver->isStaticType($expr, \PHPStan\Type\BooleanType::class)) { + return new \PhpParser\Node\Expr\BooleanNot($expr); } - - return new BooleanNot(new Bool_($expr)); + return new \PhpParser\Node\Expr\BooleanNot(new \PhpParser\Node\Expr\Cast\Bool_($expr)); } } diff --git a/rules/CodeQuality/TypeResolver/ArrayDimFetchTypeResolver.php b/rules/CodeQuality/TypeResolver/ArrayDimFetchTypeResolver.php index cb43818eddc..ad8d19e6246 100644 --- a/rules/CodeQuality/TypeResolver/ArrayDimFetchTypeResolver.php +++ b/rules/CodeQuality/TypeResolver/ArrayDimFetchTypeResolver.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; } - - public function resolve(ArrayDimFetch $arrayDimFetch): ArrayType + public function resolve(\PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : \PHPStan\Type\ArrayType { $keyStaticType = $this->resolveDimType($arrayDimFetch); $valueStaticType = $this->resolveValueStaticType($arrayDimFetch); - - return new ArrayType($keyStaticType, $valueStaticType); + return new \PHPStan\Type\ArrayType($keyStaticType, $valueStaticType); } - - private function resolveDimType(ArrayDimFetch $arrayDimFetch): Type + private function resolveDimType(\PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : \PHPStan\Type\Type { if ($arrayDimFetch->dim !== null) { return $this->nodeTypeResolver->getStaticType($arrayDimFetch->dim); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - private function resolveValueStaticType(ArrayDimFetch $arrayDimFetch): Type + private function resolveValueStaticType(\PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : \PHPStan\Type\Type { - $parentParent = $arrayDimFetch->getAttribute(AttributeKey::PARENT_NODE); - if ($parentParent instanceof Assign) { + $parentParent = $arrayDimFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentParent instanceof \PhpParser\Node\Expr\Assign) { return $this->nodeTypeResolver->getStaticType($parentParent->expr); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } } diff --git a/rules/CodeQuality/TypeResolver/AssignVariableTypeResolver.php b/rules/CodeQuality/TypeResolver/AssignVariableTypeResolver.php index 4f53d049e85..5cb47dbde36 100644 --- a/rules/CodeQuality/TypeResolver/AssignVariableTypeResolver.php +++ b/rules/CodeQuality/TypeResolver/AssignVariableTypeResolver.php @@ -1,35 +1,29 @@ nodeTypeResolver = $nodeTypeResolver; } - - public function resolve(Assign $assign): Type + public function resolve(\PhpParser\Node\Expr\Assign $assign) : \PHPStan\Type\Type { $variableType = $this->nodeTypeResolver->resolve($assign->var); $exprType = $this->nodeTypeResolver->resolve($assign->expr); - - if ($exprType instanceof UnionType) { + if ($exprType instanceof \PHPStan\Type\UnionType) { $variableType = $exprType; } - return $variableType; } } diff --git a/rules/CodeQualityStrict/NodeFactory/ClassConstFetchFactory.php b/rules/CodeQualityStrict/NodeFactory/ClassConstFetchFactory.php index 6a01dd7ef21..55fabcf91fe 100644 --- a/rules/CodeQualityStrict/NodeFactory/ClassConstFetchFactory.php +++ b/rules/CodeQualityStrict/NodeFactory/ClassConstFetchFactory.php @@ -1,7 +1,6 @@ getFullyQualifiedName()), 'class'); - } elseif ($type instanceof ObjectType) { - $classConstTypes[] = new ClassConstFetch(new FullyQualified($type->getClassName()), 'class'); + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType) { + $classConstTypes[] = new \PhpParser\Node\Expr\ClassConstFetch(new \PhpParser\Node\Name\FullyQualified($type->getFullyQualifiedName()), 'class'); + } elseif ($type instanceof \PHPStan\Type\ObjectType) { + $classConstTypes[] = new \PhpParser\Node\Expr\ClassConstFetch(new \PhpParser\Node\Name\FullyQualified($type->getClassName()), 'class'); } - - if ($type instanceof UnionType) { + if ($type instanceof \PHPStan\Type\UnionType) { foreach ($type->getTypes() as $unionedType) { - if (! $unionedType instanceof TypeWithClassName) { - throw new ShouldNotHappenException(); + if (!$unionedType instanceof \PHPStan\Type\TypeWithClassName) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $classConstTypes[] = new ClassConstFetch(new FullyQualified($unionedType->getClassName()), 'class'); + $classConstTypes[] = new \PhpParser\Node\Expr\ClassConstFetch(new \PhpParser\Node\Name\FullyQualified($unionedType->getClassName()), 'class'); } } - return $classConstTypes; } } diff --git a/rules/CodeQualityStrict/Rector/ClassMethod/ParamTypeToAssertTypeRector.php b/rules/CodeQualityStrict/Rector/ClassMethod/ParamTypeToAssertTypeRector.php index 1fa04384ea1..13518c08f27 100644 --- a/rules/CodeQualityStrict/Rector/ClassMethod/ParamTypeToAssertTypeRector.php +++ b/rules/CodeQualityStrict/Rector/ClassMethod/ParamTypeToAssertTypeRector.php @@ -1,7 +1,6 @@ classConstFetchFactory = $classConstFetchFactory; $this->subTypeAnalyzer = $subTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turn @param type to assert type', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turn @param type to assert type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -55,8 +48,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -68,141 +60,115 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - /** @var Type[] $docParamTypes */ $docParamTypes = $phpDocInfo->getParamTypesByName(); if ($docParamTypes === []) { return null; } - $params = $node->getParams(); if ($params === []) { return null; } - $toBeProcessedTypes = []; foreach ($docParamTypes as $paramName => $docParamType) { - if (! $this->isExclusivelyObjectType($docParamType)) { + if (!$this->isExclusivelyObjectType($docParamType)) { continue; } - /** @var ObjectType|UnionType $docParamType */ $assertionTypes = $this->getToBeProcessedTypes($params, $paramName, $docParamType); if ($assertionTypes === null) { continue; } - - $variableName = ltrim($paramName, '$'); + $variableName = \ltrim($paramName, '$'); $toBeProcessedTypes[$variableName] = $assertionTypes; } - return $this->processAddTypeAssert($node, $toBeProcessedTypes); } - - private function isExclusivelyObjectType(Type $type): bool + private function isExclusivelyObjectType(\PHPStan\Type\Type $type) : bool { - if ($type instanceof ObjectType) { - return true; + if ($type instanceof \PHPStan\Type\ObjectType) { + return \true; } - - if ($type instanceof UnionType) { + if ($type instanceof \PHPStan\Type\UnionType) { foreach ($type->getTypes() as $unionedType) { - if (! $this->isExclusivelyObjectType($unionedType)) { - return false; + if (!$this->isExclusivelyObjectType($unionedType)) { + return \false; } } - - return true; + return \true; } - - return false; + return \false; } - /** * @param Param[] $params * @param ObjectType|UnionType $type * @return ObjectType|UnionType */ - private function getToBeProcessedTypes(array $params, string $key, Type $type): ?Type + private function getToBeProcessedTypes(array $params, string $key, \PHPStan\Type\Type $type) : ?\PHPStan\Type\Type { foreach ($params as $param) { - $paramName = ltrim($key, '$'); - if (! $this->isName($param->var, $paramName)) { + $paramName = \ltrim($key, '$'); + if (!$this->isName($param->var, $paramName)) { continue; } - if ($param->type === null) { continue; } - // skip if doc type is the same as PHP $paramType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); if ($paramType->equals($type)) { continue; } - if ($this->subTypeAnalyzer->isObjectSubType($paramType, $type)) { continue; } - return $type; } - return null; } - /** * @param array $toBeProcessedTypes */ - private function processAddTypeAssert(ClassMethod $classMethod, array $toBeProcessedTypes): ClassMethod + private function processAddTypeAssert(\PhpParser\Node\Stmt\ClassMethod $classMethod, array $toBeProcessedTypes) : \PhpParser\Node\Stmt\ClassMethod { $assertStatements = []; foreach ($toBeProcessedTypes as $variableName => $requiredType) { $classConstFetches = $this->classConstFetchFactory->createFromType($requiredType); - - $arguments = [new Variable($variableName)]; - - if (count($classConstFetches) > 1) { + $arguments = [new \PhpParser\Node\Expr\Variable($variableName)]; + if (\count($classConstFetches) > 1) { $arguments[] = $classConstFetches; $methodName = 'isAnyOf'; } else { $arguments[] = $classConstFetches[0]; $methodName = 'isAOf'; } - $args = $this->nodeFactory->createArgs($arguments); - - $staticCall = $this->nodeFactory->createStaticCall('Webmozart\Assert\Assert', $methodName, $args); - $assertStatements[] = new Expression($staticCall); + $staticCall = $this->nodeFactory->createStaticCall('Webmozart\\Assert\\Assert', $methodName, $args); + $assertStatements[] = new \PhpParser\Node\Stmt\Expression($staticCall); } - return $this->addStatements($classMethod, $assertStatements); } - /** * @param Expression[] $assertStatements */ - private function addStatements(ClassMethod $classMethod, array $assertStatements): ClassMethod + private function addStatements(\PhpParser\Node\Stmt\ClassMethod $classMethod, array $assertStatements) : \PhpParser\Node\Stmt\ClassMethod { - if (! isset($classMethod->stmts[0])) { + if (!isset($classMethod->stmts[0])) { foreach ($assertStatements as $assertStatement) { $classMethod->stmts[] = $assertStatement; } @@ -211,7 +177,6 @@ CODE_SAMPLE $this->addNodeBeforeNode($assertStatement, $classMethod->stmts[0]); } } - return $classMethod; } } diff --git a/rules/CodeQualityStrict/Rector/If_/MoveOutMethodCallInsideIfConditionRector.php b/rules/CodeQualityStrict/Rector/If_/MoveOutMethodCallInsideIfConditionRector.php index ae6cd62880b..d2d15527abe 100644 --- a/rules/CodeQualityStrict/Rector/If_/MoveOutMethodCallInsideIfConditionRector.php +++ b/rules/CodeQualityStrict/Rector/If_/MoveOutMethodCallInsideIfConditionRector.php @@ -1,7 +1,6 @@ methodCallToVariableNameResolver = $methodCallToVariableNameResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Move out method call inside If condition', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Move out method call inside If condition', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' if ($obj->run($arg) === 1) { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $objRun = $obj->run($arg); if ($objRun === 1) { } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { /** @var MethodCall[] $methodCalls */ - $methodCalls = $this->betterNodeFinder->findInstanceOf($node->cond, MethodCall::class); - - $countMethodCalls = count($methodCalls); - + $methodCalls = $this->betterNodeFinder->findInstanceOf($node->cond, \PhpParser\Node\Expr\MethodCall::class); + $countMethodCalls = \count($methodCalls); // No method call or Multiple method calls inside if → skip if ($countMethodCalls !== 1) { return null; } - $methodCall = $methodCalls[0]; - if ($this->shouldSkipMethodCall($methodCall)) { return null; } - return $this->moveOutMethodCall($methodCall, $node); } - - private function shouldSkipMethodCall(MethodCall $methodCall): bool + private function shouldSkipMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { $variableType = $this->getStaticType($methodCall->var); - // From PropertyFetch → skip - if ($variableType instanceof ThisType) { - return true; + if ($variableType instanceof \PHPStan\Type\ThisType) { + return \true; } - $methodCallReturnType = $this->getStaticType($methodCall); - if ($methodCallReturnType instanceof BooleanType) { - return true; + if ($methodCallReturnType instanceof \PHPStan\Type\BooleanType) { + return \true; } - // No Args → skip if ($methodCall->args === []) { - return true; + return \true; } - // Inside Method calls args has Method Call again → skip return $this->isInsideMethodCallHasMethodCall($methodCall); } - - private function moveOutMethodCall(MethodCall $methodCall, If_ $if): ?If_ + private function moveOutMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall, \PhpParser\Node\Stmt\If_ $if) : ?\PhpParser\Node\Stmt\If_ { - $hasParentAssign = (bool) $this->betterNodeFinder->findParentType($methodCall, Assign::class); + $hasParentAssign = (bool) $this->betterNodeFinder->findParentType($methodCall, \PhpParser\Node\Expr\Assign::class); if ($hasParentAssign) { return null; } - $variableName = $this->methodCallToVariableNameResolver->resolveVariableName($methodCall); if ($variableName === null) { return null; } - if ($this->isVariableNameAlreadyDefined($if, $variableName)) { return null; } - - $variable = new Variable($variableName); - $methodCallAssign = new Assign($variable, $methodCall); - + $variable = new \PhpParser\Node\Expr\Variable($variableName); + $methodCallAssign = new \PhpParser\Node\Expr\Assign($variable, $methodCall); $this->addNodebeforeNode($methodCallAssign, $if); - // replace if cond with variable if ($if->cond === $methodCall) { $if->cond = $variable; return $if; } - // replace method call with variable - $this->traverseNodesWithCallable($if->cond, function (Node $node) use ($variable): ?Variable { - if ($node instanceof MethodCall) { + $this->traverseNodesWithCallable($if->cond, function (\PhpParser\Node $node) use($variable) : ?Variable { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { return $variable; } - return null; }); - return $if; } - - private function isInsideMethodCallHasMethodCall(MethodCall $methodCall): bool + private function isInsideMethodCallHasMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { foreach ($methodCall->args as $arg) { - if ($arg->value instanceof MethodCall) { - return true; + if ($arg->value instanceof \PhpParser\Node\Expr\MethodCall) { + return \true; } } - - return false; + return \false; } - - private function isVariableNameAlreadyDefined(If_ $if, string $variableName): bool + private function isVariableNameAlreadyDefined(\PhpParser\Node\Stmt\If_ $if, string $variableName) : bool { - $scope = $if->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - - return $scope->hasVariableType($variableName) - ->yes(); + return $scope->hasVariableType($variableName)->yes(); } } diff --git a/rules/CodeQualityStrict/Rector/Stmt/VarInlineAnnotationToAssertRector.php b/rules/CodeQualityStrict/Rector/Stmt/VarInlineAnnotationToAssertRector.php index c1668d2e16e..87ad30473c3 100644 --- a/rules/CodeQualityStrict/Rector/Stmt/VarInlineAnnotationToAssertRector.php +++ b/rules/CodeQualityStrict/Rector/Stmt/VarInlineAnnotationToAssertRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Stmt::class]; + return [\PhpParser\Node\Stmt::class]; } - /** * @param Stmt $node * @return Node|Node[]|null */ - public function refactor(Node $node) + public function refactor(\PhpParser\Node $node) { // skip properties - if ($node instanceof Property) { + if ($node instanceof \PhpParser\Node\Stmt\Property) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - $docVariableName = $this->getVarDocVariableName($phpDocInfo); if ($docVariableName === null) { return null; } - $variable = $this->findVariableByName($node, $docVariableName); - if (! $variable instanceof Variable) { + if (!$variable instanceof \PhpParser\Node\Expr\Variable) { return null; } - $isVariableJustCreated = $this->isVariableJustCreated($node, $docVariableName); - if (! $isVariableJustCreated) { + if (!$isVariableJustCreated) { return $this->refactorFreshlyCreatedNode($node, $phpDocInfo, $variable); } - return $this->refactorAlreadyCreatedNode($node, $phpDocInfo, $variable); } - - private function getVarDocVariableName(PhpDocInfo $phpDocInfo): ?string + private function getVarDocVariableName(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : ?string { $varTagValueNode = $phpDocInfo->getVarTagValueNode(); - if (! $varTagValueNode instanceof VarTagValueNode) { + if (!$varTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode) { return null; } - $variableName = $varTagValueNode->variableName; // no variable if ($variableName === '') { return null; } - - return ltrim($variableName, '$'); + return \ltrim($variableName, '$'); } - - private function findVariableByName(Stmt $stmt, string $docVariableName): ?Node + private function findVariableByName(\PhpParser\Node\Stmt $stmt, string $docVariableName) : ?\PhpParser\Node { - return $this->betterNodeFinder->findFirst($stmt, function (Node $node) use ($docVariableName): bool { - if (! $node instanceof Variable) { - return false; + return $this->betterNodeFinder->findFirst($stmt, function (\PhpParser\Node $node) use($docVariableName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeNameResolver->isName($node, $docVariableName); }); } - - private function isVariableJustCreated(Stmt $stmt, string $docVariableName): bool + private function isVariableJustCreated(\PhpParser\Node\Stmt $stmt, string $docVariableName) : bool { - if (! $stmt instanceof Expression) { - return false; + if (!$stmt instanceof \PhpParser\Node\Stmt\Expression) { + return \false; } - - if (! $stmt->expr instanceof Assign) { - return false; + if (!$stmt->expr instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - $assign = $stmt->expr; - if (! $assign->var instanceof Variable) { - return false; + if (!$assign->var instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - // the variable is on the left side = just created return $this->nodeNameResolver->isName($assign->var, $docVariableName); } - - private function refactorFreshlyCreatedNode(Stmt $stmt, PhpDocInfo $phpDocInfo, Variable $variable): ?Node + private function refactorFreshlyCreatedNode(\PhpParser\Node\Stmt $stmt, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \PhpParser\Node\Expr\Variable $variable) : ?\PhpParser\Node { - $stmt->setAttribute(AttributeKey::COMMENTS, null); + $stmt->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, null); $type = $phpDocInfo->getVarType(); - $assertFuncCall = $this->createFuncCallBasedOnType($type, $variable); - if (! $assertFuncCall instanceof FuncCall) { + if (!$assertFuncCall instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - $phpDocInfo->removeByType(VarTagValueNode::class); - + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode::class); $this->addNodeBeforeNode($assertFuncCall, $stmt); - return $stmt; } - /** * @return Node[]|null */ - private function refactorAlreadyCreatedNode(Stmt $stmt, PhpDocInfo $phpDocInfo, Variable $variable): ?array + private function refactorAlreadyCreatedNode(\PhpParser\Node\Stmt $stmt, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \PhpParser\Node\Expr\Variable $variable) : ?array { $varTagValue = $phpDocInfo->getVarTagValueNode(); - if (! $varTagValue instanceof VarTagValueNode) { - throw new ShouldNotHappenException(); + if (!$varTagValue instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $phpStanType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType( - $varTagValue->type, - $variable - ); - + $phpStanType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType($varTagValue->type, $variable); $assertFuncCall = $this->createFuncCallBasedOnType($phpStanType, $variable); - if (! $assertFuncCall instanceof FuncCall) { + if (!$assertFuncCall instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - return [$stmt, new Expression($assertFuncCall)]; + return [$stmt, new \PhpParser\Node\Stmt\Expression($assertFuncCall)]; } - - private function createFuncCallBasedOnType(Type $type, Variable $variable): ?FuncCall + private function createFuncCallBasedOnType(\PHPStan\Type\Type $type, \PhpParser\Node\Expr\Variable $variable) : ?\PhpParser\Node\Expr\FuncCall { - if ($type instanceof ObjectType) { - $instanceOf = new Instanceof_($variable, new FullyQualified($type->getClassName())); + if ($type instanceof \PHPStan\Type\ObjectType) { + $instanceOf = new \PhpParser\Node\Expr\Instanceof_($variable, new \PhpParser\Node\Name\FullyQualified($type->getClassName())); return $this->nodeFactory->createFuncCall(self::ASSERT, [$instanceOf]); } - - if ($type instanceof IntegerType) { + if ($type instanceof \PHPStan\Type\IntegerType) { $isInt = $this->nodeFactory->createFuncCall('is_int', [$variable]); return $this->nodeFactory->createFuncCall(self::ASSERT, [$isInt]); } - - if ($type instanceof FloatType) { + if ($type instanceof \PHPStan\Type\FloatType) { $funcCall = $this->nodeFactory->createFuncCall('is_float', [$variable]); return $this->nodeFactory->createFuncCall(self::ASSERT, [$funcCall]); } - - if ($type instanceof StringType) { + if ($type instanceof \PHPStan\Type\StringType) { $isString = $this->nodeFactory->createFuncCall('is_string', [$variable]); return $this->nodeFactory->createFuncCall(self::ASSERT, [$isString]); } - - if ($type instanceof BooleanType) { + if ($type instanceof \PHPStan\Type\BooleanType) { $isInt = $this->nodeFactory->createFuncCall('is_bool', [$variable]); return $this->nodeFactory->createFuncCall(self::ASSERT, [$isInt]); } - return null; } } diff --git a/rules/CodeQualityStrict/Rector/Variable/MoveVariableDeclarationNearReferenceRector.php b/rules/CodeQualityStrict/Rector/Variable/MoveVariableDeclarationNearReferenceRector.php index 138cf6682e8..dd2810f1b2f 100644 --- a/rules/CodeQualityStrict/Rector/Variable/MoveVariableDeclarationNearReferenceRector.php +++ b/rules/CodeQualityStrict/Rector/Variable/MoveVariableDeclarationNearReferenceRector.php @@ -1,7 +1,6 @@ scopeAwareNodeFinder = $scopeAwareNodeFinder; $this->pureFunctionDetector = $pureFunctionDetector; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Move variable declaration near its reference', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Move variable declaration near its reference', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $var = 1; if ($condition === null) { return $var; } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' if ($condition === null) { $var = 1; return $var; } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Variable::class]; + return [\PhpParser\Node\Expr\Variable::class]; } - /** * @param Variable $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! ($parent instanceof Assign && $parent->var === $node)) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!($parent instanceof \PhpParser\Node\Expr\Assign && $parent->var === $node)) { return null; } - - if ($parent->expr instanceof ArrayDimFetch) { + if ($parent->expr instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return null; } - - $expression = $parent->getAttribute(AttributeKey::PARENT_NODE); - if (! $expression instanceof Expression) { + $expression = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$expression instanceof \PhpParser\Node\Stmt\Expression) { return null; } - if ($this->isUsedAsArraykeyOrInsideIfCondition($expression, $node)) { return null; } - if ($this->hasPropertyInExpr($expression, $parent->expr)) { return null; } - if ($this->shouldSkipReAssign($expression, $parent)) { return null; } - $variable = $this->getUsageInNextStmts($expression, $node); - if (! $variable instanceof Variable) { + if (!$variable instanceof \PhpParser\Node\Expr\Variable) { return null; } - /** @var Node $usageStmt */ - $usageStmt = $variable->getAttribute(AttributeKey::CURRENT_STATEMENT); + $usageStmt = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); if ($this->isInsideLoopStmts($usageStmt)) { return null; } - $this->addNodeBeforeNode($expression, $usageStmt); $this->removeNode($expression); - return $node; } - - private function isUsedAsArraykeyOrInsideIfCondition(Expression $expression, Variable $variable): bool + private function isUsedAsArraykeyOrInsideIfCondition(\PhpParser\Node\Stmt\Expression $expression, \PhpParser\Node\Expr\Variable $variable) : bool { - $parentExpression = $expression->getAttribute(AttributeKey::PARENT_NODE); + $parentExpression = $expression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); if ($this->isUsedAsArrayKey($parentExpression, $variable)) { - return true; + return \true; } - return $this->isInsideCondition($expression); } - - private function hasPropertyInExpr(Expression $expression, Expr $expr): bool + private function hasPropertyInExpr(\PhpParser\Node\Stmt\Expression $expression, \PhpParser\Node\Expr $expr) : bool { - return (bool) $this->betterNodeFinder->findFirst($expr, function (Node $node): bool { - return $node instanceof PropertyFetch || $node instanceof StaticPropertyFetch; + return (bool) $this->betterNodeFinder->findFirst($expr, function (\PhpParser\Node $node) : bool { + return $node instanceof \PhpParser\Node\Expr\PropertyFetch || $node instanceof \PhpParser\Node\Expr\StaticPropertyFetch; }); } - - private function shouldSkipReAssign(Expression $expression, Assign $assign): bool + private function shouldSkipReAssign(\PhpParser\Node\Stmt\Expression $expression, \PhpParser\Node\Expr\Assign $assign) : bool { if ($this->hasReAssign($expression, $assign->var)) { - return true; + return \true; } - return $this->hasReAssign($expression, $assign->expr); } - - private function getUsageInNextStmts(Expression $expression, Variable $variable): ?Variable + private function getUsageInNextStmts(\PhpParser\Node\Stmt\Expression $expression, \PhpParser\Node\Expr\Variable $variable) : ?\PhpParser\Node\Expr\Variable { /** @var Node|null $next */ - $next = $expression->getAttribute(AttributeKey::NEXT_NODE); - if (! $next instanceof Node) { + $next = $expression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$next instanceof \PhpParser\Node) { return null; } - if ($this->hasCall($next)) { return null; } - $countFound = $this->getCountFound($next, $variable); if ($countFound === 0) { return null; @@ -179,253 +148,192 @@ CODE_SAMPLE if ($countFound >= 2) { return null; } - $nextVariable = $this->getSameVarName([$next], $variable); - - if ($nextVariable instanceof Variable) { + if ($nextVariable instanceof \PhpParser\Node\Expr\Variable) { return $nextVariable; } - return $this->getSameVarNameInNexts($next, $variable); } - - private function isInsideLoopStmts(Node $node): bool + private function isInsideLoopStmts(\PhpParser\Node $node) : bool { - $loopNode = $this->betterNodeFinder->findParentTypes( - $node, - [For_::class, While_::class, Foreach_::class, Do_::class] - ); + $loopNode = $this->betterNodeFinder->findParentTypes($node, [\PhpParser\Node\Stmt\For_::class, \PhpParser\Node\Stmt\While_::class, \PhpParser\Node\Stmt\Foreach_::class, \PhpParser\Node\Stmt\Do_::class]); return (bool) $loopNode; } - - private function isUsedAsArrayKey(?Node $node, Variable $variable): bool + private function isUsedAsArrayKey(?\PhpParser\Node $node, \PhpParser\Node\Expr\Variable $variable) : bool { - if (! $node instanceof Node) { - return false; + if (!$node instanceof \PhpParser\Node) { + return \false; } - /** @var ArrayDimFetch[] $arrayDimFetches */ - $arrayDimFetches = $this->betterNodeFinder->findInstanceOf($node, ArrayDimFetch::class); - + $arrayDimFetches = $this->betterNodeFinder->findInstanceOf($node, \PhpParser\Node\Expr\ArrayDimFetch::class); foreach ($arrayDimFetches as $arrayDimFetch) { /** @var Node|null $dim */ $dim = $arrayDimFetch->dim; - if (! $dim instanceof Node) { + if (!$dim instanceof \PhpParser\Node) { continue; } - - $isFoundInKey = (bool) $this->betterNodeFinder->findFirst($dim, function (Node $node) use ( - $variable - ): bool { + $isFoundInKey = (bool) $this->betterNodeFinder->findFirst($dim, function (\PhpParser\Node $node) use($variable) : bool { return $this->nodeComparator->areNodesEqual($node, $variable); }); if ($isFoundInKey) { - return true; + return \true; } } - - return false; + return \false; } - - private function isInsideCondition(Expression $expression): bool + private function isInsideCondition(\PhpParser\Node\Stmt\Expression $expression) : bool { - return (bool) $this->scopeAwareNodeFinder->findParentType( - $expression, - [If_::class, Else_::class, ElseIf_::class] - ); + return (bool) $this->scopeAwareNodeFinder->findParentType($expression, [\PhpParser\Node\Stmt\If_::class, \PhpParser\Node\Stmt\Else_::class, \PhpParser\Node\Stmt\ElseIf_::class]); } - - private function hasReAssign(Expression $expression, Expr $expr): bool + private function hasReAssign(\PhpParser\Node\Stmt\Expression $expression, \PhpParser\Node\Expr $expr) : bool { - $next = $expression->getAttribute(AttributeKey::NEXT_NODE); - $exprValues = $this->betterNodeFinder->find($expr, function (Node $node): bool { - return $node instanceof Variable; + $next = $expression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + $exprValues = $this->betterNodeFinder->find($expr, function (\PhpParser\Node $node) : bool { + return $node instanceof \PhpParser\Node\Expr\Variable; }); - if ($exprValues === []) { - return false; + return \false; } - while ($next) { foreach ($exprValues as $exprValue) { - $isReAssign = (bool) $this->betterNodeFinder->findFirst($next, function (Node $node): bool { - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Assign) { - return false; + $isReAssign = (bool) $this->betterNodeFinder->findFirst($next, function (\PhpParser\Node $node) : bool { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Expr\Assign) { + return \false; } $node = $this->mayBeArrayDimFetch($node); return (string) $this->getName($node) === (string) $this->getName($parent->var); }); - - if (! $isReAssign) { + if (!$isReAssign) { continue; } - - return true; + return \true; } - - $next = $next->getAttribute(AttributeKey::NEXT_NODE); + $next = $next->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); } - - return false; + return \false; } - - private function isClassCallerThrowable(StaticCall $staticCall): bool + private function isClassCallerThrowable(\PhpParser\Node\Expr\StaticCall $staticCall) : bool { $class = $staticCall->class; - if (! $class instanceof Name) { - return false; + if (!$class instanceof \PhpParser\Node\Name) { + return \false; } - - $throwableType = new ObjectType('Throwable'); - $type = new ObjectType($class->toString()); - - return $throwableType->isSuperTypeOf($type) - ->yes(); + $throwableType = new \PHPStan\Type\ObjectType('Throwable'); + $type = new \PHPStan\Type\ObjectType($class->toString()); + return $throwableType->isSuperTypeOf($type)->yes(); } - - private function hasCall(Node $node): bool + private function hasCall(\PhpParser\Node $node) : bool { - return (bool) $this->betterNodeFinder->findFirst($node, function (Node $n): bool { - if ($n instanceof StaticCall && ! $this->isClassCallerThrowable($n)) { - return true; + return (bool) $this->betterNodeFinder->findFirst($node, function (\PhpParser\Node $n) : bool { + if ($n instanceof \PhpParser\Node\Expr\StaticCall && !$this->isClassCallerThrowable($n)) { + return \true; } - - if ($n instanceof MethodCall) { - return true; + if ($n instanceof \PhpParser\Node\Expr\MethodCall) { + return \true; } - - if (! $n instanceof FuncCall) { - return false; + if (!$n instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - $funcName = $this->getName($n); if ($funcName === null) { - return false; + return \false; } - - return ! $this->pureFunctionDetector->detect($n); + return !$this->pureFunctionDetector->detect($n); }); } - - private function getCountFound(Node $node, Variable $variable): int + private function getCountFound(\PhpParser\Node $node, \PhpParser\Node\Expr\Variable $variable) : int { $countFound = 0; while ($node) { $isFound = (bool) $this->getSameVarName([$node], $variable); - if ($isFound) { ++$countFound; } - $countFound = $this->countWithElseIf($node, $variable, $countFound); $countFound = $this->countWithTryCatch($node, $variable, $countFound); $countFound = $this->countWithSwitchCase($node, $variable, $countFound); - /** @var Node|null $node */ - $node = $node->getAttribute(AttributeKey::NEXT_NODE); + $node = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); } - return $countFound; } - /** * @param array $multiNodes */ - private function getSameVarName(array $multiNodes, Variable $variable): ?Variable + private function getSameVarName(array $multiNodes, \PhpParser\Node\Expr\Variable $variable) : ?\PhpParser\Node\Expr\Variable { foreach ($multiNodes as $multiNode) { if ($multiNode === null) { continue; } - /** @var Variable|null $found */ - $found = $this->betterNodeFinder->findFirst($multiNode, function (Node $n) use ($variable): bool { + $found = $this->betterNodeFinder->findFirst($multiNode, function (\PhpParser\Node $n) use($variable) : bool { $n = $this->mayBeArrayDimFetch($n); - if (! $n instanceof Variable) { - return false; + if (!$n instanceof \PhpParser\Node\Expr\Variable) { + return \false; } return $this->isName($n, (string) $this->getName($variable)); }); - if ($found !== null) { return $found; } } - return null; } - - private function getSameVarNameInNexts(Node $node, Variable $variable): ?Variable + private function getSameVarNameInNexts(\PhpParser\Node $node, \PhpParser\Node\Expr\Variable $variable) : ?\PhpParser\Node\Expr\Variable { while ($node) { $found = $this->getSameVarName([$node], $variable); - - if ($found instanceof Variable) { + if ($found instanceof \PhpParser\Node\Expr\Variable) { return $found; } - /** @var Node|null $node */ - $node = $node->getAttribute(AttributeKey::NEXT_NODE); + $node = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); } - return null; } - - private function mayBeArrayDimFetch(Node $node): Node + private function mayBeArrayDimFetch(\PhpParser\Node $node) : \PhpParser\Node { - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof ArrayDimFetch) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Expr\ArrayDimFetch) { $node = $parent->var; } - return $node; } - - private function countWithElseIf(Node $node, Variable $variable, int $countFound): int + private function countWithElseIf(\PhpParser\Node $node, \PhpParser\Node\Expr\Variable $variable, int $countFound) : int { - if (! $node instanceof If_) { + if (!$node instanceof \PhpParser\Node\Stmt\If_) { return $countFound; } - $isFoundElseIf = (bool) $this->getSameVarName($node->elseifs, $variable); $isFoundElse = (bool) $this->getSameVarName([$node->else], $variable); - if ($isFoundElseIf || $isFoundElse) { ++$countFound; } - return $countFound; } - - private function countWithTryCatch(Node $node, Variable $variable, int $countFound): int + private function countWithTryCatch(\PhpParser\Node $node, \PhpParser\Node\Expr\Variable $variable, int $countFound) : int { - if (! $node instanceof TryCatch) { + if (!$node instanceof \PhpParser\Node\Stmt\TryCatch) { return $countFound; } - $isFoundInCatch = (bool) $this->getSameVarName($node->catches, $variable); $isFoundInFinally = (bool) $this->getSameVarName([$node->finally], $variable); - if ($isFoundInCatch || $isFoundInFinally) { ++$countFound; } - return $countFound; } - - private function countWithSwitchCase(Node $node, Variable $variable, int $countFound): int + private function countWithSwitchCase(\PhpParser\Node $node, \PhpParser\Node\Expr\Variable $variable, int $countFound) : int { - if (! $node instanceof Switch_) { + if (!$node instanceof \PhpParser\Node\Stmt\Switch_) { return $countFound; } - $isFoundInCases = (bool) $this->getSameVarName($node->cases, $variable); - if ($isFoundInCases) { ++$countFound; } - return $countFound; } } diff --git a/rules/CodeQualityStrict/TypeAnalyzer/SubTypeAnalyzer.php b/rules/CodeQualityStrict/TypeAnalyzer/SubTypeAnalyzer.php index 72e52fc5274..b2dc03207b5 100644 --- a/rules/CodeQualityStrict/TypeAnalyzer/SubTypeAnalyzer.php +++ b/rules/CodeQualityStrict/TypeAnalyzer/SubTypeAnalyzer.php @@ -1,30 +1,24 @@ getClassName() === 'stdClass') { - return true; + return \true; } - - return $mainType->isSuperTypeOf($checkedType) - ->yes(); + return $mainType->isSuperTypeOf($checkedType)->yes(); } } diff --git a/rules/CodingStyle/Application/UseImportsAdder.php b/rules/CodingStyle/Application/UseImportsAdder.php index 80ba20c0e2c..b8649607873 100644 --- a/rules/CodingStyle/Application/UseImportsAdder.php +++ b/rules/CodingStyle/Application/UseImportsAdder.php @@ -1,10 +1,9 @@ usedImportsResolver = $usedImportsResolver; } - /** * @param Stmt[] $stmts * @param FullyQualifiedObjectType[] $useImportTypes * @param FullyQualifiedObjectType[] $functionUseImportTypes * @return Stmt[] */ - public function addImportsToStmts(array $stmts, array $useImportTypes, array $functionUseImportTypes): array + public function addImportsToStmts(array $stmts, array $useImportTypes, array $functionUseImportTypes) : array { $existingUseImportTypes = $this->usedImportsResolver->resolveForStmts($stmts); $existingFunctionUseImports = $this->usedImportsResolver->resolveFunctionImportsForStmts($stmts); - $useImportTypes = $this->diffFullyQualifiedObjectTypes($useImportTypes, $existingUseImportTypes); - $functionUseImportTypes = $this->diffFullyQualifiedObjectTypes( - $functionUseImportTypes, - $existingFunctionUseImports - ); - + $functionUseImportTypes = $this->diffFullyQualifiedObjectTypes($functionUseImportTypes, $existingFunctionUseImports); $newUses = $this->createUses($useImportTypes, $functionUseImportTypes, null); if ($newUses === []) { return $stmts; } - // place after declare strict_types foreach ($stmts as $key => $stmt) { - if ($stmt instanceof Declare_) { - if (isset($stmts[$key + 1]) && $stmts[$key + 1] instanceof Use_) { + if ($stmt instanceof \PhpParser\Node\Stmt\Declare_) { + if (isset($stmts[$key + 1]) && $stmts[$key + 1] instanceof \PhpParser\Node\Stmt\Use_) { $nodesToAdd = $newUses; } else { // add extra space, if there are no new use imports to be added - $nodesToAdd = array_merge([new Nop()], $newUses); + $nodesToAdd = \array_merge([new \PhpParser\Node\Stmt\Nop()], $newUses); } - - array_splice($stmts, $key + 1, 0, $nodesToAdd); - + \array_splice($stmts, $key + 1, 0, $nodesToAdd); return $stmts; } } - // make use stmts first - return array_merge($newUses, $stmts); + return \array_merge($newUses, $stmts); } - /** * @param FullyQualifiedObjectType[] $useImportTypes * @param FullyQualifiedObjectType[] $functionUseImportTypes */ - public function addImportsToNamespace( - Namespace_ $namespace, - array $useImportTypes, - array $functionUseImportTypes - ): void { + public function addImportsToNamespace(\PhpParser\Node\Stmt\Namespace_ $namespace, array $useImportTypes, array $functionUseImportTypes) : void + { $namespaceName = $this->getNamespaceName($namespace); - $existingUseImportTypes = $this->usedImportsResolver->resolveForNode($namespace); $existingFunctionUseImportTypes = $this->usedImportsResolver->resolveFunctionImportsForStmts($namespace->stmts); - $useImportTypes = $this->diffFullyQualifiedObjectTypes($useImportTypes, $existingUseImportTypes); - $functionUseImportTypes = $this->diffFullyQualifiedObjectTypes( - $functionUseImportTypes, - $existingFunctionUseImportTypes - ); - + $functionUseImportTypes = $this->diffFullyQualifiedObjectTypes($functionUseImportTypes, $existingFunctionUseImportTypes); $newUses = $this->createUses($useImportTypes, $functionUseImportTypes, $namespaceName); - $namespace->stmts = array_merge($newUses, $namespace->stmts); + $namespace->stmts = \array_merge($newUses, $namespace->stmts); } - /** * @param FullyQualifiedObjectType[] $mainTypes * @param FullyQualifiedObjectType[] $typesToRemove * @return FullyQualifiedObjectType[] */ - private function diffFullyQualifiedObjectTypes(array $mainTypes, array $typesToRemove): array + private function diffFullyQualifiedObjectTypes(array $mainTypes, array $typesToRemove) : array { foreach ($mainTypes as $key => $mainType) { foreach ($typesToRemove as $typeToRemove) { @@ -107,55 +83,45 @@ final class UseImportsAdder } } } - - return array_values($mainTypes); + return \array_values($mainTypes); } - /** * @param AliasedObjectType[]|FullyQualifiedObjectType[] $useImportTypes * @param FullyQualifiedObjectType[] $functionUseImportTypes * @return Use_[] */ - private function createUses(array $useImportTypes, array $functionUseImportTypes, ?string $namespaceName): array + private function createUses(array $useImportTypes, array $functionUseImportTypes, ?string $namespaceName) : array { $newUses = []; foreach ($useImportTypes as $useImportType) { if ($namespaceName !== null && $this->isCurrentNamespace($namespaceName, $useImportType)) { continue; } - // already imported in previous cycle $newUses[] = $useImportType->getUseNode(); } - foreach ($functionUseImportTypes as $functionUseImportType) { if ($namespaceName !== null && $this->isCurrentNamespace($namespaceName, $functionUseImportType)) { continue; } - // already imported in previous cycle $newUses[] = $functionUseImportType->getFunctionUseNode(); } - return $newUses; } - - private function getNamespaceName(Namespace_ $namespace): ?string + private function getNamespaceName(\PhpParser\Node\Stmt\Namespace_ $namespace) : ?string { if ($namespace->name === null) { return null; } - return $namespace->name->toString(); } - - private function isCurrentNamespace(string $namespaceName, ObjectType $objectType): bool + private function isCurrentNamespace(string $namespaceName, \PHPStan\Type\ObjectType $objectType) : bool { - $afterCurrentNamespace = Strings::after($objectType->getClassName(), $namespaceName . '\\'); - if (! $afterCurrentNamespace) { - return false; + $afterCurrentNamespace = \RectorPrefix20210509\Nette\Utils\Strings::after($objectType->getClassName(), $namespaceName . '\\'); + if (!$afterCurrentNamespace) { + return \false; } - - return ! Strings::contains($afterCurrentNamespace, '\\'); + return !\RectorPrefix20210509\Nette\Utils\Strings::contains($afterCurrentNamespace, '\\'); } } diff --git a/rules/CodingStyle/Application/UseImportsRemover.php b/rules/CodingStyle/Application/UseImportsRemover.php index 7c6eacd14ac..22d129762d0 100644 --- a/rules/CodingStyle/Application/UseImportsRemover.php +++ b/rules/CodingStyle/Application/UseImportsRemover.php @@ -1,13 +1,11 @@ $stmt) { - if (! $stmt instanceof Use_) { + if (!$stmt instanceof \PhpParser\Node\Stmt\Use_) { continue; } - $this->removeUseFromUse($removedShortUses, $stmt); - // nothing left → remove if ($stmt->uses === []) { unset($stmts[$stmtKey]); } } - return $stmts; } - /** * @param string[] $removedShortUses */ - public function removeImportsFromNamespace(Namespace_ $namespace, array $removedShortUses): void + public function removeImportsFromNamespace(\PhpParser\Node\Stmt\Namespace_ $namespace, array $removedShortUses) : void { foreach ($namespace->stmts as $namespaceKey => $stmt) { - if (! $stmt instanceof Use_) { + if (!$stmt instanceof \PhpParser\Node\Stmt\Use_) { continue; } - $this->removeUseFromUse($removedShortUses, $stmt); - // nothing left → remove if ($stmt->uses === []) { unset($namespace->stmts[$namespaceKey]); } } } - /** * @param string[] $removedShortUses */ - private function removeUseFromUse(array $removedShortUses, Use_ $use): void + private function removeUseFromUse(array $removedShortUses, \PhpParser\Node\Stmt\Use_ $use) : void { foreach ($use->uses as $usesKey => $useUse) { foreach ($removedShortUses as $removedShortUse) { if ($useUse->name->getLast() !== $removedShortUse) { continue; } - unset($use->uses[$usesKey]); } } diff --git a/rules/CodingStyle/ClassNameImport/AliasUsesResolver.php b/rules/CodingStyle/ClassNameImport/AliasUsesResolver.php index 8a1e8a9cf3c..f34f228d3b7 100644 --- a/rules/CodingStyle/ClassNameImport/AliasUsesResolver.php +++ b/rules/CodingStyle/ClassNameImport/AliasUsesResolver.php @@ -1,66 +1,52 @@ useImportsTraverser = $useImportsTraverser; $this->betterNodeFinder = $betterNodeFinder; } - /** * @return string[] */ - public function resolveForNode(Node $node): array + public function resolveForNode(\PhpParser\Node $node) : array { - if (! $node instanceof Namespace_) { - $node = $this->betterNodeFinder->findParentType($node, Namespace_::class); + if (!$node instanceof \PhpParser\Node\Stmt\Namespace_) { + $node = $this->betterNodeFinder->findParentType($node, \PhpParser\Node\Stmt\Namespace_::class); } - - if ($node instanceof Namespace_) { + if ($node instanceof \PhpParser\Node\Stmt\Namespace_) { return $this->resolveForNamespace($node); } - return []; } - /** * @return string[] */ - private function resolveForNamespace(Namespace_ $namespace): array + private function resolveForNamespace(\PhpParser\Node\Stmt\Namespace_ $namespace) : array { $aliasedUses = []; - - $this->useImportsTraverser->traverserStmts($namespace->stmts, function ( - UseUse $useUse, - string $name - ) use (&$aliasedUses): void { + $this->useImportsTraverser->traverserStmts($namespace->stmts, function (\PhpParser\Node\Stmt\UseUse $useUse, string $name) use(&$aliasedUses) : void { if ($useUse->alias === null) { return; } - $aliasedUses[] = $name; }); - return $aliasedUses; } } diff --git a/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/AliasClassNameImportSkipVoter.php b/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/AliasClassNameImportSkipVoter.php index 8a48eb3b3fa..7b1d90df0dd 100644 --- a/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/AliasClassNameImportSkipVoter.php +++ b/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/AliasClassNameImportSkipVoter.php @@ -1,15 +1,13 @@ aliasUsesResolver = $aliasUsesResolver; } - - public function shouldSkip(FullyQualifiedObjectType $fullyQualifiedObjectType, Node $node): bool + public function shouldSkip(\Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType, \PhpParser\Node $node) : bool { $aliasedUses = $this->aliasUsesResolver->resolveForNode($node); - foreach ($aliasedUses as $aliasedUse) { - $aliasedUseLowered = strtolower($aliasedUse); - + $aliasedUseLowered = \strtolower($aliasedUse); // its aliased, we cannot just rename it - if (Strings::endsWith($aliasedUseLowered, '\\' . $fullyQualifiedObjectType->getShortNameLowered())) { - return true; + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($aliasedUseLowered, '\\' . $fullyQualifiedObjectType->getShortNameLowered())) { + return \true; } } - - return false; + return \false; } } diff --git a/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/ClassLikeNameClassNameImportSkipVoter.php b/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/ClassLikeNameClassNameImportSkipVoter.php index 4d6e2ce3969..4f3edf126e0 100644 --- a/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/ClassLikeNameClassNameImportSkipVoter.php +++ b/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/ClassLikeNameClassNameImportSkipVoter.php @@ -1,14 +1,12 @@ shortNameResolver = $shortNameResolver; } - - public function shouldSkip(FullyQualifiedObjectType $fullyQualifiedObjectType, Node $node): bool + public function shouldSkip(\Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType, \PhpParser\Node $node) : bool { $classLikeNames = $this->shortNameResolver->resolveShortClassLikeNamesForNode($node); - foreach ($classLikeNames as $classLikeName) { - if (strtolower($classLikeName) === $fullyQualifiedObjectType->getShortNameLowered()) { - return true; + if (\strtolower($classLikeName) === $fullyQualifiedObjectType->getShortNameLowered()) { + return \true; } } - - return false; + return \false; } } diff --git a/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/FullyQualifiedNameClassNameImportSkipVoter.php b/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/FullyQualifiedNameClassNameImportSkipVoter.php index ae1729bcd27..bf7172e74e8 100644 --- a/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/FullyQualifiedNameClassNameImportSkipVoter.php +++ b/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/FullyQualifiedNameClassNameImportSkipVoter.php @@ -1,7 +1,6 @@ shortNameResolver = $shortNameResolver; $this->currentFileProvider = $currentFileProvider; } - - public function shouldSkip(FullyQualifiedObjectType $fullyQualifiedObjectType, Node $node): bool + public function shouldSkip(\Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType, \PhpParser\Node $node) : bool { // "new X" or "X::static()" $file = $this->currentFileProvider->getFile(); $shortNamesToFullyQualifiedNames = $this->shortNameResolver->resolveForNode($file); - foreach ($shortNamesToFullyQualifiedNames as $shortName => $fullyQualifiedName) { - $shortNameLowered = strtolower($shortName); + $shortNameLowered = \strtolower($shortName); if ($fullyQualifiedObjectType->getShortNameLowered() !== $shortNameLowered) { continue; } - - return $fullyQualifiedObjectType->getClassNameLowered() !== strtolower($fullyQualifiedName); + return $fullyQualifiedObjectType->getClassNameLowered() !== \strtolower($fullyQualifiedName); } - - return false; + return \false; } } diff --git a/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/UsesClassNameImportSkipVoter.php b/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/UsesClassNameImportSkipVoter.php index 7e839a879fa..de8c5af7d42 100644 --- a/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/UsesClassNameImportSkipVoter.php +++ b/rules/CodingStyle/ClassNameImport/ClassNameImportSkipVoter/UsesClassNameImportSkipVoter.php @@ -1,14 +1,12 @@ useNodesToAddCollector = $useNodesToAddCollector; } - - public function shouldSkip(FullyQualifiedObjectType $fullyQualifiedObjectType, Node $node): bool + public function shouldSkip(\Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType, \PhpParser\Node $node) : bool { $useImportTypes = $this->useNodesToAddCollector->getUseImportTypesByNode($node); - foreach ($useImportTypes as $useImportType) { - if (! $useImportType->equals($fullyQualifiedObjectType) && $useImportType->areShortNamesEqual( - $fullyQualifiedObjectType - ) - ) { - return true; + if (!$useImportType->equals($fullyQualifiedObjectType) && $useImportType->areShortNamesEqual($fullyQualifiedObjectType)) { + return \true; } - if ($useImportType->equals($fullyQualifiedObjectType)) { - return false; + return \false; } } - - return false; + return \false; } } diff --git a/rules/CodingStyle/ClassNameImport/ClassNameImportSkipper.php b/rules/CodingStyle/ClassNameImport/ClassNameImportSkipper.php index 80115067d23..7878b4e2598 100644 --- a/rules/CodingStyle/ClassNameImport/ClassNameImportSkipper.php +++ b/rules/CodingStyle/ClassNameImport/ClassNameImportSkipper.php @@ -1,24 +1,21 @@ classNameImportSkipVoters = $classNameImportSkipVoters; } - - public function shouldSkipNameForFullyQualifiedObjectType( - Node $node, - FullyQualifiedObjectType $fullyQualifiedObjectType - ): bool { + public function shouldSkipNameForFullyQualifiedObjectType(\PhpParser\Node $node, \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType) : bool + { foreach ($this->classNameImportSkipVoters as $classNameImportSkipVoter) { if ($classNameImportSkipVoter->shouldSkip($fullyQualifiedObjectType, $node)) { - return true; + return \true; } } - - return false; + return \false; } - - public function isShortNameInUseStatement(Name $name): bool + public function isShortNameInUseStatement(\PhpParser\Node\Name $name) : bool { $longName = $name->toString(); - if (Strings::contains($longName, '\\')) { - return false; + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($longName, '\\')) { + return \false; } - return $this->isFoundInUse($name); } - - public function isFoundInUse(Name $name): bool + public function isFoundInUse(\PhpParser\Node\Name $name) : bool { /** @var Use_[] $uses */ - $uses = (array) $name->getAttribute(AttributeKey::USE_NODES); - + $uses = (array) $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::USE_NODES); foreach ($uses as $use) { foreach ($use->uses as $useUse) { if ($useUse->name->getLast() !== $name->getLast()) { continue; } - - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/CodingStyle/ClassNameImport/ShortNameResolver.php b/rules/CodingStyle/ClassNameImport/ShortNameResolver.php index ff3b727a053..83604467c08 100644 --- a/rules/CodingStyle/ClassNameImport/ShortNameResolver.php +++ b/rules/CodingStyle/ClassNameImport/ShortNameResolver.php @@ -1,11 +1,10 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeNameResolver = $nodeNameResolver; $this->nodeFinder = $nodeFinder; $this->reflectionProvider = $reflectionProvider; $this->betterNodeFinder = $betterNodeFinder; } - /** * Avoids circular reference * @required */ - public function autowireShortNameResolver(PhpDocInfoFactory $phpDocInfoFactory): void + public function autowireShortNameResolver(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory $phpDocInfoFactory) : void { $this->phpDocInfoFactory = $phpDocInfoFactory; } - /** * @return array */ - public function resolveForNode(File $file): array + public function resolveForNode(\Rector\Core\ValueObject\Application\File $file) : array { $smartFileInfo = $file->getSmartFileInfo(); $nodeRealPath = $smartFileInfo->getRealPath(); - if (isset($this->shortNamesByFilePath[$nodeRealPath])) { return $this->shortNamesByFilePath[$nodeRealPath]; } - $shortNamesToFullyQualifiedNames = $this->resolveForStmts($file->getNewStmts()); $this->shortNamesByFilePath[$nodeRealPath] = $shortNamesToFullyQualifiedNames; - return $shortNamesToFullyQualifiedNames; } - /** * Collects all "class ", "trait " and "interface " * @return string[] */ - public function resolveShortClassLikeNamesForNode(Node $node): array + public function resolveShortClassLikeNamesForNode(\PhpParser\Node $node) : array { - $namespace = $this->betterNodeFinder->findParentType($node, Namespace_::class); - if (! $namespace instanceof Namespace_) { + $namespace = $this->betterNodeFinder->findParentType($node, \PhpParser\Node\Stmt\Namespace_::class); + if (!$namespace instanceof \PhpParser\Node\Stmt\Namespace_) { // only handle namespace nodes return []; } - /** @var ClassLike[] $classLikes */ - $classLikes = $this->nodeFinder->findInstanceOf($namespace, ClassLike::class); - + $classLikes = $this->nodeFinder->findInstanceOf($namespace, \PhpParser\Node\Stmt\ClassLike::class); $shortClassLikeNames = []; foreach ($classLikes as $classLike) { $shortClassLikeNames[] = $this->nodeNameResolver->getShortName($classLike); } - - return array_unique($shortClassLikeNames); + return \array_unique($shortClassLikeNames); } - /** * @param Node[] $stmts * @return array */ - private function resolveForStmts(array $stmts): array + private function resolveForStmts(array $stmts) : array { $shortNamesToFullyQualifiedNames = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmts, function (Node $node) use ( - &$shortNamesToFullyQualifiedNames - ): void { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmts, function (\PhpParser\Node $node) use(&$shortNamesToFullyQualifiedNames) : void { // class name is used! - if ($node instanceof ClassLike && $node->name instanceof Identifier) { + if ($node instanceof \PhpParser\Node\Stmt\ClassLike && $node->name instanceof \PhpParser\Node\Identifier) { $fullyQualifiedName = $this->nodeNameResolver->getName($node); if ($fullyQualifiedName === null) { return; } - $shortNamesToFullyQualifiedNames[$node->name->toString()] = $fullyQualifiedName; return; } - - if (! $node instanceof Name) { + if (!$node instanceof \PhpParser\Node\Name) { return; } - - $originalName = $node->getAttribute(AttributeKey::ORIGINAL_NAME); - if (! $originalName instanceof Name) { + $originalName = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NAME); + if (!$originalName instanceof \PhpParser\Node\Name) { return; } - // already short - if (Strings::contains($originalName->toString(), '\\')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($originalName->toString(), '\\')) { return; } - $fullyQualifiedName = $this->nodeNameResolver->getName($node); $shortNamesToFullyQualifiedNames[$originalName->toString()] = $fullyQualifiedName; }); - $docBlockShortNamesToFullyQualifiedNames = $this->resolveFromDocBlocks($stmts); - return array_merge($shortNamesToFullyQualifiedNames, $docBlockShortNamesToFullyQualifiedNames); + return \array_merge($shortNamesToFullyQualifiedNames, $docBlockShortNamesToFullyQualifiedNames); } - /** * @param Node[] $stmts * @return array */ - private function resolveFromDocBlocks(array $stmts): array + private function resolveFromDocBlocks(array $stmts) : array { $reflectionClass = $this->resolveNativeClassReflection($stmts); - $shortNamesToFullyQualifiedNames = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmts, function (Node $node) use ( - &$shortNamesToFullyQualifiedNames, - $reflectionClass - ): void { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmts, function (\PhpParser\Node $node) use(&$shortNamesToFullyQualifiedNames, $reflectionClass) : void { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - foreach ($phpDocInfo->getPhpDocNode()->children as $phpDocChildNode) { /** @var PhpDocChildNode $phpDocChildNode */ $shortTagName = $this->resolveShortTagNameFromPhpDocChildNode($phpDocChildNode); if ($shortTagName === null) { continue; } - if ($reflectionClass !== null) { - $fullyQualifiedTagName = Reflection::expandClassName($shortTagName, $reflectionClass); + $fullyQualifiedTagName = \RectorPrefix20210509\Nette\Utils\Reflection::expandClassName($shortTagName, $reflectionClass); } else { $fullyQualifiedTagName = $shortTagName; } - $shortNamesToFullyQualifiedNames[$shortTagName] = $fullyQualifiedTagName; } }); - return $shortNamesToFullyQualifiedNames; } - - private function resolveShortTagNameFromPhpDocChildNode(PhpDocChildNode $phpDocChildNode): ?string + private function resolveShortTagNameFromPhpDocChildNode(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode $phpDocChildNode) : ?string { - if (! $phpDocChildNode instanceof PhpDocTagNode) { + if (!$phpDocChildNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { return null; } - - $tagName = ltrim($phpDocChildNode->name, '@'); - + $tagName = \ltrim($phpDocChildNode->name, '@'); // is annotation class - big letter? - if (Strings::match($tagName, self::BIG_LETTER_START_REGEX)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($tagName, self::BIG_LETTER_START_REGEX)) { return $tagName; } - - if (! $this->isValueNodeWithType($phpDocChildNode->value)) { + if (!$this->isValueNodeWithType($phpDocChildNode->value)) { return null; } - $typeNode = $phpDocChildNode->value->type; - if (! $typeNode instanceof IdentifierTypeNode) { + if (!$typeNode instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode) { return null; } - - if (Strings::contains($typeNode->name, '\\')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($typeNode->name, '\\')) { return null; } - return $typeNode->name; } - - private function isValueNodeWithType(PhpDocTagValueNode $phpDocTagValueNode): bool + private function isValueNodeWithType(\PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode $phpDocTagValueNode) : bool { - return $phpDocTagValueNode instanceof PropertyTagValueNode || - $phpDocTagValueNode instanceof ReturnTagValueNode || - $phpDocTagValueNode instanceof ParamTagValueNode || - $phpDocTagValueNode instanceof VarTagValueNode || - $phpDocTagValueNode instanceof ThrowsTagValueNode; + return $phpDocTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PropertyTagValueNode || $phpDocTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode || $phpDocTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode || $phpDocTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode || $phpDocTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ThrowsTagValueNode; } - /** * @param Node[] $stmts */ - private function resolveNativeClassReflection(array $stmts): ?ReflectionClass + private function resolveNativeClassReflection(array $stmts) : ?\ReflectionClass { - $firstClassLike = $this->nodeFinder->findFirstInstanceOf($stmts, ClassLike::class); - if (! $firstClassLike instanceof ClassLike) { + $firstClassLike = $this->nodeFinder->findFirstInstanceOf($stmts, \PhpParser\Node\Stmt\ClassLike::class); + if (!$firstClassLike instanceof \PhpParser\Node\Stmt\ClassLike) { return null; } - $className = $this->nodeNameResolver->getName($firstClassLike); - if (! $className) { + if (!$className) { return null; } - - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return null; } - $classReflection = $this->reflectionProvider->getClass($className); return $classReflection->getNativeReflection(); } diff --git a/rules/CodingStyle/ClassNameImport/UseImportsTraverser.php b/rules/CodingStyle/ClassNameImport/UseImportsTraverser.php index 25da48cdb58..5ca06e658f8 100644 --- a/rules/CodingStyle/ClassNameImport/UseImportsTraverser.php +++ b/rules/CodingStyle/ClassNameImport/UseImportsTraverser.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - /** * @param Stmt[] $stmts */ - public function traverserStmtsForFunctions(array $stmts, callable $callable): void + public function traverserStmtsForFunctions(array $stmts, callable $callable) : void { - $this->traverseForType($stmts, $callable, Use_::TYPE_FUNCTION); + $this->traverseForType($stmts, $callable, \PhpParser\Node\Stmt\Use_::TYPE_FUNCTION); } - /** * @param Stmt[] $stmts */ - public function traverserStmts(array $stmts, callable $callable): void + public function traverserStmts(array $stmts, callable $callable) : void { - $this->traverseForType($stmts, $callable, Use_::TYPE_NORMAL); + $this->traverseForType($stmts, $callable, \PhpParser\Node\Stmt\Use_::TYPE_NORMAL); } - /** * @param Stmt[] $stmts */ - private function traverseForType(array $stmts, callable $callable, int $desiredType): void + private function traverseForType(array $stmts, callable $callable, int $desiredType) : void { - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmts, function (Node $node) use ( - $callable, - $desiredType - ) { - if ($node instanceof Use_) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmts, function (\PhpParser\Node $node) use($callable, $desiredType) { + if ($node instanceof \PhpParser\Node\Stmt\Use_) { // only import uses if ($node->type !== $desiredType) { return null; } - foreach ($node->uses as $useUse) { $name = $this->nodeNameResolver->getName($useUse); $callable($useUse, $name); } } - - if ($node instanceof GroupUse) { + if ($node instanceof \PhpParser\Node\Stmt\GroupUse) { $this->processGroupUse($node, $desiredType, $callable); } - return null; }); } - - private function processGroupUse(GroupUse $groupUse, int $desiredType, callable $callable): void + private function processGroupUse(\PhpParser\Node\Stmt\GroupUse $groupUse, int $desiredType, callable $callable) : void { - if ($groupUse->type !== Use_::TYPE_UNKNOWN) { + if ($groupUse->type !== \PhpParser\Node\Stmt\Use_::TYPE_UNKNOWN) { return; } - $prefixName = $groupUse->prefix->toString(); - foreach ($groupUse->uses as $useUse) { if ($useUse->type !== $desiredType) { continue; } - $name = $prefixName . '\\' . $this->nodeNameResolver->getName($useUse); $callable($useUse, $name); } diff --git a/rules/CodingStyle/ClassNameImport/UsedImportsResolver.php b/rules/CodingStyle/ClassNameImport/UsedImportsResolver.php index 15dc66e0c52..599b180862f 100644 --- a/rules/CodingStyle/ClassNameImport/UsedImportsResolver.php +++ b/rules/CodingStyle/ClassNameImport/UsedImportsResolver.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; $this->useImportsTraverser = $useImportsTraverser; } - /** * @return FullyQualifiedObjectType[] */ - public function resolveForNode(Node $node): array + public function resolveForNode(\PhpParser\Node $node) : array { - if ($node instanceof Namespace_) { + if ($node instanceof \PhpParser\Node\Stmt\Namespace_) { $namespace = $node; } else { - $namespace = $this->betterNodeFinder->findParentType($node, Namespace_::class); + $namespace = $this->betterNodeFinder->findParentType($node, \PhpParser\Node\Stmt\Namespace_::class); } - - if ($namespace instanceof Namespace_) { + if ($namespace instanceof \PhpParser\Node\Stmt\Namespace_) { return $this->resolveForNamespace($namespace); } - return []; } - /** * @param Stmt[] $stmts * @return FullyQualifiedObjectType[] */ - public function resolveForStmts(array $stmts): array + public function resolveForStmts(array $stmts) : array { $usedImports = []; - /** @var Class_|null $class */ - $class = $this->betterNodeFinder->findFirstInstanceOf($stmts, Class_::class); - + $class = $this->betterNodeFinder->findFirstInstanceOf($stmts, \PhpParser\Node\Stmt\Class_::class); // add class itself if ($class !== null) { $className = $this->nodeNameResolver->getName($class); if ($className !== null) { - $usedImports[] = new FullyQualifiedObjectType($className); + $usedImports[] = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($className); } } - - $this->useImportsTraverser->traverserStmts($stmts, function ( - UseUse $useUse, - string $name - ) use (&$usedImports): void { - $usedImports[] = new FullyQualifiedObjectType($name); + $this->useImportsTraverser->traverserStmts($stmts, function (\PhpParser\Node\Stmt\UseUse $useUse, string $name) use(&$usedImports) : void { + $usedImports[] = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($name); }); - return $usedImports; } - /** * @param Stmt[] $stmts * @return FullyQualifiedObjectType[] */ - public function resolveFunctionImportsForStmts(array $stmts): array + public function resolveFunctionImportsForStmts(array $stmts) : array { $usedFunctionImports = []; - - $this->useImportsTraverser->traverserStmtsForFunctions($stmts, function ( - UseUse $useUse, - string $name - ) use (&$usedFunctionImports): void { - $usedFunctionImports[] = new FullyQualifiedObjectType($name); + $this->useImportsTraverser->traverserStmtsForFunctions($stmts, function (\PhpParser\Node\Stmt\UseUse $useUse, string $name) use(&$usedFunctionImports) : void { + $usedFunctionImports[] = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($name); }); - return $usedFunctionImports; } - /** * @return FullyQualifiedObjectType[] */ - private function resolveForNamespace(Namespace_ $namespace): array + private function resolveForNamespace(\PhpParser\Node\Stmt\Namespace_ $namespace) : array { return $this->resolveForStmts($namespace->stmts); } diff --git a/rules/CodingStyle/Contract/ClassNameImport/ClassNameImportSkipVoterInterface.php b/rules/CodingStyle/Contract/ClassNameImport/ClassNameImportSkipVoterInterface.php index 6637d3f25b3..e8c1ceb3888 100644 --- a/rules/CodingStyle/Contract/ClassNameImport/ClassNameImportSkipVoterInterface.php +++ b/rules/CodingStyle/Contract/ClassNameImport/ClassNameImportSkipVoterInterface.php @@ -1,13 +1,11 @@ getShortName($name); - return lcfirst($shortName); + return \lcfirst($shortName); } - /** * @param string|Name|Identifier|ClassLike $name */ - public function getShortName($name): string + public function getShortName($name) : string { - if ($name instanceof ClassLike) { + if ($name instanceof \PhpParser\Node\Stmt\ClassLike) { if ($name->name === null) { return ''; } - return $this->getShortName($name->name); } - - if ($name instanceof Name || $name instanceof Identifier) { + if ($name instanceof \PhpParser\Node\Name || $name instanceof \PhpParser\Node\Identifier) { $name = $name->toString(); } - - $name = trim($name, '\\'); - - return Strings::after($name, '\\', -1) ?: $name; + $name = \trim($name, '\\'); + return \RectorPrefix20210509\Nette\Utils\Strings::after($name, '\\', -1) ?: $name; } - - public function getNamespace(string $fullyQualifiedName): ?string + public function getNamespace(string $fullyQualifiedName) : ?string { - $fullyQualifiedName = trim($fullyQualifiedName, '\\'); - - return Strings::before($fullyQualifiedName, '\\', -1) ?: null; + $fullyQualifiedName = \trim($fullyQualifiedName, '\\'); + return \RectorPrefix20210509\Nette\Utils\Strings::before($fullyQualifiedName, '\\', -1) ?: null; } - - public function getNameFromFileInfo(SmartFileInfo $smartFileInfo): string + public function getNameFromFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : string { $basenameWithoutSuffix = $smartFileInfo->getBasenameWithoutSuffix(); - // remove PHPUnit fixture file prefix - if (StaticPHPUnitEnvironment::isPHPUnitRun()) { - $basenameWithoutSuffix = Strings::replace($basenameWithoutSuffix, self::INPUT_HASH_NAMING_REGEX, ''); + if (\Rector\Testing\PHPUnit\StaticPHPUnitEnvironment::isPHPUnitRun()) { + $basenameWithoutSuffix = \RectorPrefix20210509\Nette\Utils\Strings::replace($basenameWithoutSuffix, self::INPUT_HASH_NAMING_REGEX, ''); } - - $stringy = new Stringy($basenameWithoutSuffix); + $stringy = new \RectorPrefix20210509\Stringy\Stringy($basenameWithoutSuffix); return (string) $stringy->upperCamelize(); } - /** * "some_function" → "someFunction" */ - public function createMethodNameFromFunction(Function_ $function): string + public function createMethodNameFromFunction(\PhpParser\Node\Stmt\Function_ $function) : string { $functionName = (string) $function->name; - - $stringy = new Stringy($functionName); + $stringy = new \RectorPrefix20210509\Stringy\Stringy($functionName); return (string) $stringy->camelize(); } - - public function replaceSuffix(string $content, string $oldSuffix, string $newSuffix): string + public function replaceSuffix(string $content, string $oldSuffix, string $newSuffix) : string { - if (! Strings::endsWith($content, $oldSuffix)) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::endsWith($content, $oldSuffix)) { return $content . $newSuffix; } - - $contentWithoutOldSuffix = Strings::substring($content, 0, -Strings::length($oldSuffix)); + $contentWithoutOldSuffix = \RectorPrefix20210509\Nette\Utils\Strings::substring($content, 0, -\RectorPrefix20210509\Nette\Utils\Strings::length($oldSuffix)); return $contentWithoutOldSuffix . $newSuffix; } } diff --git a/rules/CodingStyle/Naming/NameRenamer.php b/rules/CodingStyle/Naming/NameRenamer.php index 43e63540aec..1d839c4e247 100644 --- a/rules/CodingStyle/Naming/NameRenamer.php +++ b/rules/CodingStyle/Naming/NameRenamer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; } - /** * @param NameAndParent[] $usedNameNodes */ - public function renameNameNode(array $usedNameNodes, string $lastName): void + public function renameNameNode(array $usedNameNodes, string $lastName) : void { foreach ($usedNameNodes as $usedNameNode) { $parentNode = $usedNameNode->getParentNode(); $usedName = $usedNameNode->getNameNode(); - - if ($parentNode instanceof TraitUse) { + if ($parentNode instanceof \PhpParser\Node\Stmt\TraitUse) { $this->renameTraitUse($lastName, $parentNode, $usedName); } - - if ($parentNode instanceof Class_) { + if ($parentNode instanceof \PhpParser\Node\Stmt\Class_) { $this->renameClass($lastName, $parentNode, $usedName); } - - if ($parentNode instanceof Param) { + if ($parentNode instanceof \PhpParser\Node\Param) { $this->renameParam($lastName, $parentNode, $usedName); } - - if ($parentNode instanceof New_) { + if ($parentNode instanceof \PhpParser\Node\Expr\New_) { $this->renameNew($lastName, $parentNode, $usedName); } - - if ($parentNode instanceof ClassMethod) { + if ($parentNode instanceof \PhpParser\Node\Stmt\ClassMethod) { $this->renameClassMethod($lastName, $parentNode, $usedName); } - - if ($parentNode instanceof Interface_) { + if ($parentNode instanceof \PhpParser\Node\Stmt\Interface_) { $this->renameInterface($lastName, $parentNode, $usedName); } - - if ($parentNode instanceof StaticCall) { + if ($parentNode instanceof \PhpParser\Node\Expr\StaticCall) { $this->renameStaticCall($lastName, $parentNode); } } } - /** * @param Name|Identifier $usedNameNode */ - private function renameTraitUse(string $lastName, TraitUse $traitUse, Node $usedNameNode): void + private function renameTraitUse(string $lastName, \PhpParser\Node\Stmt\TraitUse $traitUse, \PhpParser\Node $usedNameNode) : void { foreach ($traitUse->traits as $key => $traitName) { - if (! $this->nodeNameResolver->areNamesEqual($traitName, $usedNameNode)) { + if (!$this->nodeNameResolver->areNamesEqual($traitName, $usedNameNode)) { continue; } - - $traitUse->traits[$key] = new Name($lastName); + $traitUse->traits[$key] = new \PhpParser\Node\Name($lastName); } } - /** * @param Name|Identifier $usedNameNode */ - private function renameClass(string $lastName, Class_ $class, Node $usedNameNode): void + private function renameClass(string $lastName, \PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node $usedNameNode) : void { if ($class->name !== null && $this->nodeNameResolver->areNamesEqual($class->name, $usedNameNode)) { - $class->name = new Identifier($lastName); + $class->name = new \PhpParser\Node\Identifier($lastName); } - if ($class->extends !== null && $this->nodeNameResolver->areNamesEqual($class->extends, $usedNameNode)) { - $class->extends = new Name($lastName); + $class->extends = new \PhpParser\Node\Name($lastName); } - foreach ($class->implements as $key => $implementNode) { if ($this->nodeNameResolver->areNamesEqual($implementNode, $usedNameNode)) { - $class->implements[$key] = new Name($lastName); + $class->implements[$key] = new \PhpParser\Node\Name($lastName); } } } - /** * @param Name|Identifier $usedNameNode */ - private function renameParam(string $lastName, Param $param, Node $usedNameNode): void + private function renameParam(string $lastName, \PhpParser\Node\Param $param, \PhpParser\Node $usedNameNode) : void { if ($param->type === null) { return; } - if (! $this->nodeNameResolver->areNamesEqual($param->type, $usedNameNode)) { + if (!$this->nodeNameResolver->areNamesEqual($param->type, $usedNameNode)) { return; } - $param->type = new Name($lastName); + $param->type = new \PhpParser\Node\Name($lastName); } - /** * @param Name|Identifier $usedNameNode */ - private function renameNew(string $lastName, New_ $new, Node $usedNameNode): void + private function renameNew(string $lastName, \PhpParser\Node\Expr\New_ $new, \PhpParser\Node $usedNameNode) : void { if ($this->nodeNameResolver->areNamesEqual($new->class, $usedNameNode)) { - $new->class = new Name($lastName); + $new->class = new \PhpParser\Node\Name($lastName); } } - /** * @param Name|Identifier $usedNameNode */ - private function renameClassMethod(string $lastName, ClassMethod $classMethod, Node $usedNameNode): void + private function renameClassMethod(string $lastName, \PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node $usedNameNode) : void { if ($classMethod->returnType === null) { return; } - - if (! $this->nodeNameResolver->areNamesEqual($classMethod->returnType, $usedNameNode)) { + if (!$this->nodeNameResolver->areNamesEqual($classMethod->returnType, $usedNameNode)) { return; } - - $classMethod->returnType = new Name($lastName); + $classMethod->returnType = new \PhpParser\Node\Name($lastName); } - /** * @param Name|Identifier $usedNameNode */ - private function renameInterface(string $lastName, Interface_ $interface, Node $usedNameNode): void + private function renameInterface(string $lastName, \PhpParser\Node\Stmt\Interface_ $interface, \PhpParser\Node $usedNameNode) : void { foreach ($interface->extends as $key => $extendInterfaceName) { - if (! $this->nodeNameResolver->areNamesEqual($extendInterfaceName, $usedNameNode)) { + if (!$this->nodeNameResolver->areNamesEqual($extendInterfaceName, $usedNameNode)) { continue; } - - $interface->extends[$key] = new Name($lastName); + $interface->extends[$key] = new \PhpParser\Node\Name($lastName); } } - - private function renameStaticCall(string $lastName, StaticCall $staticCall): void + private function renameStaticCall(string $lastName, \PhpParser\Node\Expr\StaticCall $staticCall) : void { - $staticCall->class = new Name($lastName); + $staticCall->class = new \PhpParser\Node\Name($lastName); } } diff --git a/rules/CodingStyle/Node/ConcatJoiner.php b/rules/CodingStyle/Node/ConcatJoiner.php index 08becacd472..feadf55f0cd 100644 --- a/rules/CodingStyle/Node/ConcatJoiner.php +++ b/rules/CodingStyle/Node/ConcatJoiner.php @@ -1,7 +1,6 @@ getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Concat) { + $parentNode = $concat->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { $this->reset(); } - $this->processConcatSide($concat->left); $this->processConcatSide($concat->right); - - return new ConcatStringAndPlaceholders($this->content, $this->placeholderNodes); + return new \Rector\CodingStyle\ValueObject\ConcatStringAndPlaceholders($this->content, $this->placeholderNodes); } - - private function reset(): void + private function reset() : void { $this->content = ''; $this->placeholderNodes = []; } - - private function processConcatSide(Expr $expr): void + private function processConcatSide(\PhpParser\Node\Expr $expr) : void { - if ($expr instanceof String_) { + if ($expr instanceof \PhpParser\Node\Scalar\String_) { $this->content .= $expr->value; - } elseif ($expr instanceof Concat) { + } elseif ($expr instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { $this->joinToStringAndPlaceholderNodes($expr); } else { - $objectHash = '____' . spl_object_hash($expr) . '____'; + $objectHash = '____' . \spl_object_hash($expr) . '____'; $this->placeholderNodes[$objectHash] = $expr; - $this->content .= $objectHash; } } diff --git a/rules/CodingStyle/Node/ConcatManipulator.php b/rules/CodingStyle/Node/ConcatManipulator.php index 128e43dad39..5e7d472cdbd 100644 --- a/rules/CodingStyle/Node/ConcatManipulator.php +++ b/rules/CodingStyle/Node/ConcatManipulator.php @@ -1,69 +1,53 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeComparator = $nodeComparator; } - - public function getFirstConcatItem(Concat $concat): Expr + public function getFirstConcatItem(\PhpParser\Node\Expr\BinaryOp\Concat $concat) : \PhpParser\Node\Expr { // go to the deep, until there is no concat - while ($concat->left instanceof Concat) { + while ($concat->left instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { $concat = $concat->left; } - return $concat->left; } - - public function removeFirstItemFromConcat(Concat $concat): Expr + public function removeFirstItemFromConcat(\PhpParser\Node\Expr\BinaryOp\Concat $concat) : \PhpParser\Node\Expr { // just 2 items, return right one - if (! $concat->left instanceof Concat) { + if (!$concat->left instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { return $concat->right; } - $newConcat = clone $concat; $firstConcatItem = $this->getFirstConcatItem($concat); - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($newConcat, function (Node $node) use ( - $firstConcatItem - ): ?Expr { - if (! $node instanceof Concat) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($newConcat, function (\PhpParser\Node $node) use($firstConcatItem) : ?Expr { + if (!$node instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { return null; } - - if (! $this->nodeComparator->areNodesEqual($node->left, $firstConcatItem)) { + if (!$this->nodeComparator->areNodesEqual($node->left, $firstConcatItem)) { return null; } - return $node->right; }); - return $newConcat; } } diff --git a/rules/CodingStyle/Node/DocAliasResolver.php b/rules/CodingStyle/Node/DocAliasResolver.php index 6a7ba10de18..e71bc3da1d0 100644 --- a/rules/CodingStyle/Node/DocAliasResolver.php +++ b/rules/CodingStyle/Node/DocAliasResolver.php @@ -1,10 +1,9 @@ \w+)(\\\\)?#s'; - + private const DOC_ALIAS_REGEX = '#\\@(?\\w+)(\\\\)?#s'; /** * @var SimpleCallableNodeTraverser */ private $simpleCallableNodeTraverser; - /** * @var PhpDocInfoFactory */ private $phpDocInfoFactory; - - public function __construct( - SimpleCallableNodeTraverser $simpleCallableNodeTraverser, - PhpDocInfoFactory $phpDocInfoFactory - ) { + public function __construct(\RectorPrefix20210509\Symplify\Astral\NodeTraverser\SimpleCallableNodeTraverser $simpleCallableNodeTraverser, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory $phpDocInfoFactory) + { $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->phpDocInfoFactory = $phpDocInfoFactory; } - /** * @return string[] */ - public function resolve(Node $node): array + public function resolve(\PhpParser\Node $node) : array { $possibleDocAliases = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($node, function (Node $node) use ( - &$possibleDocAliases - ): void { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($node, function (\PhpParser\Node $node) use(&$possibleDocAliases) : void { $docComment = $node->getDocComment(); - if (! $docComment instanceof Doc) { + if (!$docComment instanceof \PhpParser\Comment\Doc) { return; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); $possibleDocAliases = $this->collectVarType($phpDocInfo, $possibleDocAliases); - // e.g. "use Dotrine\ORM\Mapping as ORM" etc. - $matches = Strings::matchAll($docComment->getText(), self::DOC_ALIAS_REGEX); + $matches = \RectorPrefix20210509\Nette\Utils\Strings::matchAll($docComment->getText(), self::DOC_ALIAS_REGEX); foreach ($matches as $match) { $possibleDocAliases[] = $match['possible_alias']; } }); - - return array_unique($possibleDocAliases); + return \array_unique($possibleDocAliases); } - /** * @param string[] $possibleDocAliases * @return string[] */ - private function collectVarType(PhpDocInfo $phpDocInfo, array $possibleDocAliases): array + private function collectVarType(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, array $possibleDocAliases) : array { $possibleDocAliases = $this->appendPossibleAliases($phpDocInfo->getVarType(), $possibleDocAliases); $possibleDocAliases = $this->appendPossibleAliases($phpDocInfo->getReturnType(), $possibleDocAliases); - foreach ($phpDocInfo->getParamTypesByName() as $paramType) { $possibleDocAliases = $this->appendPossibleAliases($paramType, $possibleDocAliases); } - return $possibleDocAliases; } - /** * @param string[] $possibleDocAliases * @return string[] */ - private function appendPossibleAliases(Type $varType, array $possibleDocAliases): array + private function appendPossibleAliases(\PHPStan\Type\Type $varType, array $possibleDocAliases) : array { - if ($varType instanceof AliasedObjectType) { + if ($varType instanceof \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType) { $possibleDocAliases[] = $varType->getClassName(); } - - if ($varType instanceof UnionType) { + if ($varType instanceof \PHPStan\Type\UnionType) { foreach ($varType->getTypes() as $type) { $possibleDocAliases = $this->appendPossibleAliases($type, $possibleDocAliases); } } - return $possibleDocAliases; } } diff --git a/rules/CodingStyle/Node/NameImporter.php b/rules/CodingStyle/Node/NameImporter.php index f5d73d1bf32..cbb3171d46f 100644 --- a/rules/CodingStyle/Node/NameImporter.php +++ b/rules/CodingStyle/Node/NameImporter.php @@ -1,10 +1,9 @@ staticTypeMapper = $staticTypeMapper; $this->aliasUsesResolver = $aliasUsesResolver; $this->classNameImportSkipper = $classNameImportSkipper; @@ -81,141 +64,106 @@ final class NameImporter $this->useNodesToAddCollector = $useNodesToAddCollector; $this->reflectionProvider = $reflectionProvider; } - - public function importName(Name $name): ?Name + public function importName(\PhpParser\Node\Name $name) : ?\PhpParser\Node\Name { if ($this->shouldSkipName($name)) { return null; } - if ($this->classNameImportSkipper->isShortNameInUseStatement($name)) { return null; } - $staticType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($name); - if (! $staticType instanceof FullyQualifiedObjectType) { + if (!$staticType instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType) { return null; } - $this->aliasedUses = $this->aliasUsesResolver->resolveForNode($name); - return $this->importNameAndCollectNewUseStatement($name, $staticType); } - - private function shouldSkipName(Name $name): bool + private function shouldSkipName(\PhpParser\Node\Name $name) : bool { - $virtualNode = $name->getAttribute(AttributeKey::VIRTUAL_NODE); + $virtualNode = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::VIRTUAL_NODE); if ($virtualNode) { - return true; + return \true; } - // is scalar name? - if (in_array($name->toLowerString(), ['true', 'false', 'bool'], true)) { - return true; + if (\in_array($name->toLowerString(), ['true', 'false', 'bool'], \true)) { + return \true; } - // namespace // use ; if ($this->isNamespaceOrUseImportName($name)) { - return true; + return \true; } - if ($this->isFunctionOrConstantImportWithSingleName($name)) { - return true; + return \true; } - // Importing root namespace classes (like \DateTime) is optional - $importShortClasses = $this->parameterProvider->provideParameter(Option::IMPORT_SHORT_CLASSES); - if (! $importShortClasses) { + $importShortClasses = $this->parameterProvider->provideParameter(\Rector\Core\Configuration\Option::IMPORT_SHORT_CLASSES); + if (!$importShortClasses) { $name = $this->nodeNameResolver->getName($name); - if ($name !== null && substr_count($name, '\\') === 0) { - return true; + if ($name !== null && \substr_count($name, '\\') === 0) { + return \true; } } - - return false; + return \false; } - - private function importNameAndCollectNewUseStatement( - Name $name, - FullyQualifiedObjectType $fullyQualifiedObjectType - ): ?Name { + private function importNameAndCollectNewUseStatement(\PhpParser\Node\Name $name, \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType) : ?\PhpParser\Node\Name + { // the same end is already imported → skip - if ($this->classNameImportSkipper->shouldSkipNameForFullyQualifiedObjectType( - $name, - $fullyQualifiedObjectType - )) { + if ($this->classNameImportSkipper->shouldSkipNameForFullyQualifiedObjectType($name, $fullyQualifiedObjectType)) { return null; } - if ($this->useNodesToAddCollector->isShortImported($name, $fullyQualifiedObjectType)) { if ($this->useNodesToAddCollector->isImportShortable($name, $fullyQualifiedObjectType)) { return $fullyQualifiedObjectType->getShortNameNode(); } - return null; } - $this->addUseImport($name, $fullyQualifiedObjectType); - // possibly aliased foreach ($this->aliasedUses as $aliasedUse) { if ($fullyQualifiedObjectType->getClassName() === $aliasedUse) { return null; } } - return $fullyQualifiedObjectType->getShortNameNode(); } - /** * Skip: * - namespace name * - use import name */ - private function isNamespaceOrUseImportName(Name $name): bool + private function isNamespaceOrUseImportName(\PhpParser\Node\Name $name) : bool { - $parentNode = $name->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Namespace_) { - return true; + $parentNode = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Stmt\Namespace_) { + return \true; } - - return $parentNode instanceof UseUse; + return $parentNode instanceof \PhpParser\Node\Stmt\UseUse; } - - private function isFunctionOrConstantImportWithSingleName(Name $name): bool + private function isFunctionOrConstantImportWithSingleName(\PhpParser\Node\Name $name) : bool { - $parentNode = $name->getAttribute(AttributeKey::PARENT_NODE); - + $parentNode = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); $fullName = $name->toString(); - - $autoImportNames = $this->parameterProvider->provideParameter(Option::AUTO_IMPORT_NAMES); - if ($autoImportNames && ! $parentNode instanceof Node && ! Strings::contains( - $fullName, - '\\' - ) && $this->reflectionProvider->hasFunction(new Name($fullName), null)) { - return true; + $autoImportNames = $this->parameterProvider->provideParameter(\Rector\Core\Configuration\Option::AUTO_IMPORT_NAMES); + if ($autoImportNames && !$parentNode instanceof \PhpParser\Node && !\RectorPrefix20210509\Nette\Utils\Strings::contains($fullName, '\\') && $this->reflectionProvider->hasFunction(new \PhpParser\Node\Name($fullName), null)) { + return \true; } - - if ($parentNode instanceof ConstFetch) { - return count($name->parts) === 1; + if ($parentNode instanceof \PhpParser\Node\Expr\ConstFetch) { + return \count($name->parts) === 1; } - - if ($parentNode instanceof FuncCall) { - return count($name->parts) === 1; + if ($parentNode instanceof \PhpParser\Node\Expr\FuncCall) { + return \count($name->parts) === 1; } - - return false; + return \false; } - - private function addUseImport(Name $name, FullyQualifiedObjectType $fullyQualifiedObjectType): void + private function addUseImport(\PhpParser\Node\Name $name, \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType $fullyQualifiedObjectType) : void { if ($this->useNodesToAddCollector->hasImport($name, $fullyQualifiedObjectType)) { return; } - - $parentNode = $name->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof FuncCall) { + $parentNode = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\FuncCall) { $this->useNodesToAddCollector->addFunctionUseImport($name, $fullyQualifiedObjectType); } else { $this->useNodesToAddCollector->addUseImport($name, $fullyQualifiedObjectType); diff --git a/rules/CodingStyle/Node/UseManipulator.php b/rules/CodingStyle/Node/UseManipulator.php index 2a1a686272c..fa19d54e561 100644 --- a/rules/CodingStyle/Node/UseManipulator.php +++ b/rules/CodingStyle/Node/UseManipulator.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; } - /** * @return NameAndParent[][] */ - public function resolveUsedNameNodes(Node $node): array + public function resolveUsedNameNodes(\PhpParser\Node $node) : array { $this->resolvedNodeNames = []; - $this->resolveUsedNames($node); $this->resolveUsedClassNames($node); $this->resolveTraitUseNames($node); - return $this->resolvedNodeNames; } - - private function resolveUsedNames(Node $node): void + private function resolveUsedNames(\PhpParser\Node $node) : void { /** @var Name[] $namedNodes */ - $namedNodes = $this->betterNodeFinder->findInstanceOf($node, Name::class); - + $namedNodes = $this->betterNodeFinder->findInstanceOf($node, \PhpParser\Node\Name::class); foreach ($namedNodes as $namedNode) { /** node name before becoming FQN - attribute from @see NameResolver */ - $originalName = $namedNode->getAttribute(AttributeKey::ORIGINAL_NAME); - if (! $originalName instanceof Name) { + $originalName = $namedNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NAME); + if (!$originalName instanceof \PhpParser\Node\Name) { continue; } - - $parentNode = $namedNode->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Node) { - throw new ShouldNotHappenException(); + $parentNode = $namedNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $this->resolvedNodeNames[$originalName->toString()][] = new NameAndParent($namedNode, $parentNode); + $this->resolvedNodeNames[$originalName->toString()][] = new \Rector\CodingStyle\ValueObject\NameAndParent($namedNode, $parentNode); } } - - private function resolveUsedClassNames(Node $searchNode): void + private function resolveUsedClassNames(\PhpParser\Node $searchNode) : void { /** @var ClassLike[] $classLikes */ $classLikes = $this->betterNodeFinder->findClassLikes([$searchNode]); - foreach ($classLikes as $classLike) { $classLikeName = $classLike->name; - if (! $classLikeName instanceof Identifier) { + if (!$classLikeName instanceof \PhpParser\Node\Identifier) { continue; } - $name = $this->nodeNameResolver->getName($classLikeName); if ($name === null) { continue; } - - $this->resolvedNodeNames[$name][] = new NameAndParent($classLikeName, $classLike); + $this->resolvedNodeNames[$name][] = new \Rector\CodingStyle\ValueObject\NameAndParent($classLikeName, $classLike); } } - - private function resolveTraitUseNames(Node $searchNode): void + private function resolveTraitUseNames(\PhpParser\Node $searchNode) : void { /** @var Identifier[] $identifiers */ - $identifiers = $this->betterNodeFinder->findInstanceOf($searchNode, Identifier::class); - + $identifiers = $this->betterNodeFinder->findInstanceOf($searchNode, \PhpParser\Node\Identifier::class); foreach ($identifiers as $identifier) { - $parentNode = $identifier->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof UseUse) { + $parentNode = $identifier->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Stmt\UseUse) { continue; } - - $this->resolvedNodeNames[$identifier->name][] = new NameAndParent($identifier, $parentNode); + $this->resolvedNodeNames[$identifier->name][] = new \Rector\CodingStyle\ValueObject\NameAndParent($identifier, $parentNode); } } } diff --git a/rules/CodingStyle/Node/UseNameAliasToNameResolver.php b/rules/CodingStyle/Node/UseNameAliasToNameResolver.php index b6b4a0056c8..88075be3964 100644 --- a/rules/CodingStyle/Node/UseNameAliasToNameResolver.php +++ b/rules/CodingStyle/Node/UseNameAliasToNameResolver.php @@ -1,53 +1,44 @@ shortNameResolver = $shortNameResolver; $this->classNaming = $classNaming; } - /** * @return array */ - public function resolve(File $file, Use_ $use): array + public function resolve(\Rector\Core\ValueObject\Application\File $file, \PhpParser\Node\Stmt\Use_ $use) : array { $useNamesAliasToName = []; - $shortNames = $this->shortNameResolver->resolveForNode($file); foreach ($shortNames as $alias => $useImport) { - if (! is_string($alias)) { + if (!\is_string($alias)) { continue; } - $shortName = $this->classNaming->getShortName($useImport); if ($shortName === $alias) { continue; } - $useNamesAliasToName[$shortName][] = $alias; } - return $useNamesAliasToName; } } diff --git a/rules/CodingStyle/NodeAnalyzer/ImplodeAnalyzer.php b/rules/CodingStyle/NodeAnalyzer/ImplodeAnalyzer.php index 82d764a065e..35af8a059f6 100644 --- a/rules/CodingStyle/NodeAnalyzer/ImplodeAnalyzer.php +++ b/rules/CodingStyle/NodeAnalyzer/ImplodeAnalyzer.php @@ -1,46 +1,39 @@ nodeNameResolver = $nodeNameResolver; } - /** * Matches: "implode('","', $items)" */ - public function isImplodeToJson(Expr $expr): bool + public function isImplodeToJson(\PhpParser\Node\Expr $expr) : bool { - if (! $expr instanceof FuncCall) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - - if (! $this->nodeNameResolver->isName($expr, 'implode')) { - return false; + if (!$this->nodeNameResolver->isName($expr, 'implode')) { + return \false; } - - if (! isset($expr->args[1])) { - return false; + if (!isset($expr->args[1])) { + return \false; } - $firstArgumentValue = $expr->args[0]->value; - if (! $firstArgumentValue instanceof String_) { - return true; + if (!$firstArgumentValue instanceof \PhpParser\Node\Scalar\String_) { + return \true; } return $firstArgumentValue->value === '","'; } diff --git a/rules/CodingStyle/NodeAnalyzer/SpreadVariablesCollector.php b/rules/CodingStyle/NodeAnalyzer/SpreadVariablesCollector.php index b950919f45e..25c882a83da 100644 --- a/rules/CodingStyle/NodeAnalyzer/SpreadVariablesCollector.php +++ b/rules/CodingStyle/NodeAnalyzer/SpreadVariablesCollector.php @@ -1,36 +1,30 @@ */ - public function resolveFromClassMethod(ClassMethod $classMethod): array + public function resolveFromClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $spreadParams = []; - foreach ($classMethod->params as $key => $param) { // prevent race-condition removal on class method - $originalParam = $param->getAttribute(AttributeKey::ORIGINAL_NODE); - if (! $originalParam instanceof Param) { + $originalParam = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE); + if (!$originalParam instanceof \PhpParser\Node\Param) { continue; } - - if (! $originalParam->variadic) { + if (!$originalParam->variadic) { continue; } - $spreadParams[$key] = $param; } - return $spreadParams; } } diff --git a/rules/CodingStyle/NodeFactory/ArrayCallableToMethodCallFactory.php b/rules/CodingStyle/NodeFactory/ArrayCallableToMethodCallFactory.php index b9e5e201b4a..62a9b6012f2 100644 --- a/rules/CodingStyle/NodeFactory/ArrayCallableToMethodCallFactory.php +++ b/rules/CodingStyle/NodeFactory/ArrayCallableToMethodCallFactory.php @@ -1,7 +1,6 @@ items) !== 2) { + if (\count($array->items) !== 2) { return null; } - $firstItem = $array->items[0]; $secondItem = $array->items[1]; - - if (! $firstItem instanceof ArrayItem) { + if (!$firstItem instanceof \PhpParser\Node\Expr\ArrayItem) { return null; } - - if (! $secondItem instanceof ArrayItem) { + if (!$secondItem instanceof \PhpParser\Node\Expr\ArrayItem) { return null; } - - if (! $secondItem->value instanceof String_) { + if (!$secondItem->value instanceof \PhpParser\Node\Scalar\String_) { return null; } - - if (! $firstItem->value instanceof PropertyFetch && ! $firstItem->value instanceof Variable) { + if (!$firstItem->value instanceof \PhpParser\Node\Expr\PropertyFetch && !$firstItem->value instanceof \PhpParser\Node\Expr\Variable) { return null; } - $string = $secondItem->value; $methodName = $string->value; - - return new MethodCall($firstItem->value, $methodName); + return new \PhpParser\Node\Expr\MethodCall($firstItem->value, $methodName); } } diff --git a/rules/CodingStyle/NodeFactory/JsonArrayFactory.php b/rules/CodingStyle/NodeFactory/JsonArrayFactory.php index 3728caf070f..c7e0165b707 100644 --- a/rules/CodingStyle/NodeFactory/JsonArrayFactory.php +++ b/rules/CodingStyle/NodeFactory/JsonArrayFactory.php @@ -1,10 +1,9 @@ nodeFactory = $nodeFactory; $this->implodeAnalyzer = $implodeAnalyzer; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - - public function createFromJsonString(string $stringValue): Array_ + public function createFromJsonString(string $stringValue) : \PhpParser\Node\Expr\Array_ { - $array = Json::decode($stringValue, Json::FORCE_ARRAY); + $array = \RectorPrefix20210509\Nette\Utils\Json::decode($stringValue, \RectorPrefix20210509\Nette\Utils\Json::FORCE_ARRAY); return $this->nodeFactory->createArray($array); } - /** * @param Expr[] $placeholderNodes */ - public function createFromJsonStringAndPlaceholders(string $jsonString, array $placeholderNodes): Array_ + public function createFromJsonStringAndPlaceholders(string $jsonString, array $placeholderNodes) : \PhpParser\Node\Expr\Array_ { $jsonArray = $this->createFromJsonString($jsonString); $this->replaceNodeObjectHashPlaceholdersWithNodes($jsonArray, $placeholderNodes); - return $jsonArray; } - /** * @param Expr[] $placeholderNodes */ - private function replaceNodeObjectHashPlaceholdersWithNodes(Array_ $array, array $placeholderNodes): void + private function replaceNodeObjectHashPlaceholdersWithNodes(\PhpParser\Node\Expr\Array_ $array, array $placeholderNodes) : void { // traverse and replace placeholder by original nodes - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($array, function (Node $node) use ( - $placeholderNodes - ): ?Expr { - if ($node instanceof Array_ && count($node->items) === 1) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($array, function (\PhpParser\Node $node) use($placeholderNodes) : ?Expr { + if ($node instanceof \PhpParser\Node\Expr\Array_ && \count($node->items) === 1) { $onlyItem = $node->items[0]; - if (! $onlyItem instanceof ArrayItem) { - throw new ShouldNotHappenException(); + if (!$onlyItem instanceof \PhpParser\Node\Expr\ArrayItem) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $placeholderNode = $this->matchPlaceholderNode($onlyItem->value, $placeholderNodes); - if ($placeholderNode && $this->implodeAnalyzer->isImplodeToJson($placeholderNode)) { /** @var FuncCall $placeholderNode */ return $placeholderNode->args[1]->value; } } - return $this->matchPlaceholderNode($node, $placeholderNodes); }); } - /** * @param Expr[] $placeholderNodes */ - private function matchPlaceholderNode(Node $node, array $placeholderNodes): ?Expr + private function matchPlaceholderNode(\PhpParser\Node $node, array $placeholderNodes) : ?\PhpParser\Node\Expr { - if (! $node instanceof String_) { + if (!$node instanceof \PhpParser\Node\Scalar\String_) { return null; } - return $placeholderNodes[$node->value] ?? null; } } diff --git a/rules/CodingStyle/NodeFactory/JsonEncodeStaticCallFactory.php b/rules/CodingStyle/NodeFactory/JsonEncodeStaticCallFactory.php index 93d17ddb231..e05ea3130e6 100644 --- a/rules/CodingStyle/NodeFactory/JsonEncodeStaticCallFactory.php +++ b/rules/CodingStyle/NodeFactory/JsonEncodeStaticCallFactory.php @@ -1,7 +1,6 @@ nodeFactory = $nodeFactory; } - /** * Creates + adds * * $jsonData = ['...']; * $json = Nette\Utils\Json::encode($jsonData); */ - public function createFromArray(Expr $assignExpr, Array_ $jsonArray): Assign + public function createFromArray(\PhpParser\Node\Expr $assignExpr, \PhpParser\Node\Expr\Array_ $jsonArray) : \PhpParser\Node\Expr\Assign { - $jsonDataAssign = new Assign($assignExpr, $jsonArray); - - $jsonDataVariable = new Variable('jsonData'); - $jsonDataAssign->expr = $this->nodeFactory->createStaticCall('Nette\Utils\Json', 'encode', [$jsonDataVariable]); - + $jsonDataAssign = new \PhpParser\Node\Expr\Assign($assignExpr, $jsonArray); + $jsonDataVariable = new \PhpParser\Node\Expr\Variable('jsonData'); + $jsonDataAssign->expr = $this->nodeFactory->createStaticCall('Nette\\Utils\\Json', 'encode', [$jsonDataVariable]); return $jsonDataAssign; } } diff --git a/rules/CodingStyle/Rector/Assign/ManualJsonStringToJsonEncodeArrayRector.php b/rules/CodingStyle/Rector/Assign/ManualJsonStringToJsonEncodeArrayRector.php index 3fbb766d0f0..e908d5fbcfa 100644 --- a/rules/CodingStyle/Rector/Assign/ManualJsonStringToJsonEncodeArrayRector.php +++ b/rules/CodingStyle/Rector/Assign/ManualJsonStringToJsonEncodeArrayRector.php @@ -1,12 +1,11 @@ [^\"])(?____\w+____)#'; - + private const UNQUOTED_OBJECT_HASH_REGEX = '#(?[^\\"])(?____\\w+____)#'; /** * @var string * @see https://regex101.com/r/jdJ6n9/1 */ - private const JSON_STRING_REGEX = '#{(.*?\:.*?)}#s'; - + private const JSON_STRING_REGEX = '#{(.*?\\:.*?)}#s'; /** * @var ConcatJoiner */ private $concatJoiner; - /** * @var ConcatManipulator */ private $concatManipulator; - /** * @var JsonEncodeStaticCallFactory */ private $jsonEncodeStaticCallFactory; - /** * @var JsonArrayFactory */ private $jsonArrayFactory; - - public function __construct( - ConcatJoiner $concatJoiner, - ConcatManipulator $concatManipulator, - JsonEncodeStaticCallFactory $jsonEncodeStaticCallFactory, - JsonArrayFactory $jsonArrayFactory - ) { + public function __construct(\Rector\CodingStyle\Node\ConcatJoiner $concatJoiner, \Rector\CodingStyle\Node\ConcatManipulator $concatManipulator, \Rector\CodingStyle\NodeFactory\JsonEncodeStaticCallFactory $jsonEncodeStaticCallFactory, \Rector\CodingStyle\NodeFactory\JsonArrayFactory $jsonArrayFactory) + { $this->concatJoiner = $concatJoiner; $this->concatManipulator = $concatManipulator; $this->jsonEncodeStaticCallFactory = $jsonEncodeStaticCallFactory; $this->jsonArrayFactory = $jsonArrayFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add extra space before new assign set', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add extra space before new assign set', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -88,8 +73,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use Nette\Utils\Json; final class SomeClass @@ -104,219 +88,154 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node->expr instanceof String_) { + if ($node->expr instanceof \PhpParser\Node\Scalar\String_) { $stringValue = $node->expr->value; - // A. full json string $isJsonString = $this->isJsonString($stringValue); if ($isJsonString) { $jsonArray = $this->jsonArrayFactory->createFromJsonString($stringValue); $jsonEncodeAssign = $this->jsonEncodeStaticCallFactory->createFromArray($node->var, $jsonArray); - - $jsonDataVariable = new Variable('jsonData'); - $jsonDataAssign = new Assign($jsonDataVariable, $jsonArray); - + $jsonDataVariable = new \PhpParser\Node\Expr\Variable('jsonData'); + $jsonDataAssign = new \PhpParser\Node\Expr\Assign($jsonDataVariable, $jsonArray); $this->addNodeBeforeNode($jsonDataAssign, $node); - return $jsonEncodeAssign; } - // B. just start of a json? join with all the strings that concat so same variable $concatExpressionJoinData = $this->collectContentAndPlaceholderNodesFromNextExpressions($node); - $stringValue .= $concatExpressionJoinData->getString(); - - return $this->removeNodesAndCreateJsonEncodeFromStringValue( - $concatExpressionJoinData->getNodesToRemove(), - $stringValue, - $concatExpressionJoinData->getPlaceholdersToNodes(), - $node - ); + return $this->removeNodesAndCreateJsonEncodeFromStringValue($concatExpressionJoinData->getNodesToRemove(), $stringValue, $concatExpressionJoinData->getPlaceholdersToNodes(), $node); } - - if ($node->expr instanceof Concat) { + if ($node->expr instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { // process only first concat - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Concat) { + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { return null; } - $concatStringAndPlaceholders = $this->concatJoiner->joinToStringAndPlaceholderNodes($node->expr); - // B. just start of a json? join with all the strings that concat so same variable $concatExpressionJoinData = $this->collectContentAndPlaceholderNodesFromNextExpressions($node); - - $placeholderNodes = array_merge( - $concatStringAndPlaceholders->getPlaceholderNodes(), - $concatExpressionJoinData->getPlaceholdersToNodes() - ); - + $placeholderNodes = \array_merge($concatStringAndPlaceholders->getPlaceholderNodes(), $concatExpressionJoinData->getPlaceholdersToNodes()); $stringValue = $concatStringAndPlaceholders->getContent(); $stringValue .= $concatExpressionJoinData->getString(); - - return $this->removeNodesAndCreateJsonEncodeFromStringValue( - $concatExpressionJoinData->getNodesToRemove(), - $stringValue, - $placeholderNodes, - $node - ); + return $this->removeNodesAndCreateJsonEncodeFromStringValue($concatExpressionJoinData->getNodesToRemove(), $stringValue, $placeholderNodes, $node); } - return null; } - - private function isJsonString(string $stringValue): bool + private function isJsonString(string $stringValue) : bool { - if (! (bool) Strings::match($stringValue, self::JSON_STRING_REGEX)) { - return false; + if (!(bool) \RectorPrefix20210509\Nette\Utils\Strings::match($stringValue, self::JSON_STRING_REGEX)) { + return \false; } - try { - return (bool) Json::decode($stringValue, Json::FORCE_ARRAY); - } catch (JsonException $jsonException) { - return false; + return (bool) \RectorPrefix20210509\Nette\Utils\Json::decode($stringValue, \RectorPrefix20210509\Nette\Utils\Json::FORCE_ARRAY); + } catch (\RectorPrefix20210509\Nette\Utils\JsonException $jsonException) { + return \false; } } - - private function collectContentAndPlaceholderNodesFromNextExpressions(Assign $assign): ConcatExpressionJoinData + private function collectContentAndPlaceholderNodesFromNextExpressions(\PhpParser\Node\Expr\Assign $assign) : \Rector\CodingStyle\ValueObject\ConcatExpressionJoinData { - $concatExpressionJoinData = new ConcatExpressionJoinData(); - + $concatExpressionJoinData = new \Rector\CodingStyle\ValueObject\ConcatExpressionJoinData(); $currentNode = $assign; - while ($nextExprAndConcatItem = $this->matchNextExprAssignConcatToSameVariable($assign->var, $currentNode)) { $concatItemNode = $nextExprAndConcatItem->getConcatItemNode(); - - if ($concatItemNode instanceof String_) { + if ($concatItemNode instanceof \PhpParser\Node\Scalar\String_) { $concatExpressionJoinData->addString($concatItemNode->value); - } elseif ($concatItemNode instanceof Concat) { - $joinToStringAndPlaceholderNodes = $this->concatJoiner->joinToStringAndPlaceholderNodes( - $concatItemNode - ); - + } elseif ($concatItemNode instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { + $joinToStringAndPlaceholderNodes = $this->concatJoiner->joinToStringAndPlaceholderNodes($concatItemNode); $content = $joinToStringAndPlaceholderNodes->getContent(); $concatExpressionJoinData->addString($content); - foreach ($joinToStringAndPlaceholderNodes->getPlaceholderNodes() as $placeholder => $expr) { /** @var string $placeholder */ $concatExpressionJoinData->addPlaceholderToNode($placeholder, $expr); } - } elseif ($concatItemNode instanceof Expr) { - $objectHash = '____' . spl_object_hash($concatItemNode) . '____'; - + } elseif ($concatItemNode instanceof \PhpParser\Node\Expr) { + $objectHash = '____' . \spl_object_hash($concatItemNode) . '____'; $concatExpressionJoinData->addString($objectHash); $concatExpressionJoinData->addPlaceholderToNode($objectHash, $concatItemNode); } - $concatExpressionJoinData->addNodeToRemove($nextExprAndConcatItem->getRemovedExpr()); - // jump to next one $currentNode = $this->getNextExpression($currentNode); - if (! $currentNode instanceof Node) { + if (!$currentNode instanceof \PhpParser\Node) { return $concatExpressionJoinData; } } - return $concatExpressionJoinData; } - /** * @param Node[] $nodesToRemove * @param Expr[] $placeholderNodes */ - private function removeNodesAndCreateJsonEncodeFromStringValue( - array $nodesToRemove, - string $stringValue, - array $placeholderNodes, - Assign $assign - ): ?Assign { - $stringValue = Strings::replace($stringValue, self::UNQUOTED_OBJECT_HASH_REGEX, '$1"$2"'); - if (! $this->isJsonString($stringValue)) { + private function removeNodesAndCreateJsonEncodeFromStringValue(array $nodesToRemove, string $stringValue, array $placeholderNodes, \PhpParser\Node\Expr\Assign $assign) : ?\PhpParser\Node\Expr\Assign + { + $stringValue = \RectorPrefix20210509\Nette\Utils\Strings::replace($stringValue, self::UNQUOTED_OBJECT_HASH_REGEX, '$1"$2"'); + if (!$this->isJsonString($stringValue)) { return null; } - $this->removeNodes($nodesToRemove); - $jsonArray = $this->jsonArrayFactory->createFromJsonStringAndPlaceholders($stringValue, $placeholderNodes); - $jsonDataVariable = new Variable('jsonData'); - $jsonDataAssign = new Assign($jsonDataVariable, $jsonArray); - + $jsonDataVariable = new \PhpParser\Node\Expr\Variable('jsonData'); + $jsonDataAssign = new \PhpParser\Node\Expr\Assign($jsonDataVariable, $jsonArray); $this->addNodeBeforeNode($jsonDataAssign, $assign); - return $this->jsonEncodeStaticCallFactory->createFromArray($assign->var, $jsonArray); } - /** * @param Assign|ConcatAssign $currentNode */ - private function matchNextExprAssignConcatToSameVariable(Expr $expr, Node $currentNode): ?NodeToRemoveAndConcatItem + private function matchNextExprAssignConcatToSameVariable(\PhpParser\Node\Expr $expr, \PhpParser\Node $currentNode) : ?\Rector\CodingStyle\ValueObject\NodeToRemoveAndConcatItem { $nextExpression = $this->getNextExpression($currentNode); - if (! $nextExpression instanceof Expression) { + if (!$nextExpression instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $nextExpressionNode = $nextExpression->expr; - if ($nextExpressionNode instanceof ConcatAssign) { + if ($nextExpressionNode instanceof \PhpParser\Node\Expr\AssignOp\Concat) { // is assign to same variable? - if (! $this->nodeComparator->areNodesEqual($expr, $nextExpressionNode->var)) { + if (!$this->nodeComparator->areNodesEqual($expr, $nextExpressionNode->var)) { return null; } - - return new NodeToRemoveAndConcatItem($nextExpressionNode, $nextExpressionNode->expr); + return new \Rector\CodingStyle\ValueObject\NodeToRemoveAndConcatItem($nextExpressionNode, $nextExpressionNode->expr); } - // $value = $value . '...'; - if ($nextExpressionNode instanceof Assign) { - if (! $nextExpressionNode->expr instanceof Concat) { + if ($nextExpressionNode instanceof \PhpParser\Node\Expr\Assign) { + if (!$nextExpressionNode->expr instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { return null; } - // is assign to same variable? - if (! $this->nodeComparator->areNodesEqual($expr, $nextExpressionNode->var)) { + if (!$this->nodeComparator->areNodesEqual($expr, $nextExpressionNode->var)) { return null; } - $firstConcatItem = $this->concatManipulator->getFirstConcatItem($nextExpressionNode->expr); - // is the first concat the same variable - if (! $this->nodeComparator->areNodesEqual($expr, $firstConcatItem)) { + if (!$this->nodeComparator->areNodesEqual($expr, $firstConcatItem)) { return null; } - // return all but first node $allButFirstConcatItem = $this->concatManipulator->removeFirstItemFromConcat($nextExpressionNode->expr); - - return new NodeToRemoveAndConcatItem($nextExpressionNode, $allButFirstConcatItem); + return new \Rector\CodingStyle\ValueObject\NodeToRemoveAndConcatItem($nextExpressionNode, $allButFirstConcatItem); } - return null; } - - private function getNextExpression(Node $node): ?Node + private function getNextExpression(\PhpParser\Node $node) : ?\PhpParser\Node { - $currentExpression = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); - if (! $currentExpression instanceof Expression) { + $currentExpression = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); + if (!$currentExpression instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - return $currentExpression->getAttribute(AttributeKey::NEXT_NODE); + return $currentExpression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); } } diff --git a/rules/CodingStyle/Rector/Assign/PHPStormVarAnnotationRector.php b/rules/CodingStyle/Rector/Assign/PHPStormVarAnnotationRector.php index 4106bf338a7..839dda55c91 100644 --- a/rules/CodingStyle/Rector/Assign/PHPStormVarAnnotationRector.php +++ b/rules/CodingStyle/Rector/Assign/PHPStormVarAnnotationRector.php @@ -1,10 +1,9 @@ \$\w+)(?\s+)(?[\\\\\w]+)#'; - - public function getRuleDefinition(): RuleDefinition + private const VARIABLE_NAME_AND_TYPE_MATCH_REGEX = '#(?\\$\\w+)(?\\s+)(?[\\\\\\w]+)#'; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change various @var annotation formats to one PHPStorm understands', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change various @var annotation formats to one PHPStorm understands', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $config = 5; /** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */ CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' /** @var \Shopsys\FrameworkBundle\Model\Product\Filter\ProductFilterConfig $config */ $config = 5; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $expression = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); - + $expression = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); // unable to analyze - if (! $expression instanceof Expression) { + if (!$expression instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - $nextNode = $expression->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextNode instanceof Node) { + $nextNode = $expression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextNode instanceof \PhpParser\Node) { return null; } - $docContent = $this->getDocContent($nextNode); if ($docContent === '') { return null; } - - if (! Strings::contains($docContent, '@var')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($docContent, '@var')) { return null; } - - if (! $node->var instanceof Variable) { + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - $varName = '$' . $this->getName($node->var); - $varPattern = '# ' . preg_quote($varName, '#') . ' #'; - if (! Strings::match($docContent, $varPattern)) { + $varPattern = '# ' . \preg_quote($varName, '#') . ' #'; + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($docContent, $varPattern)) { return null; } - // switch docs $expression->setDocComment($this->createDocComment($nextNode)); - $expressionPhpDocInfo = $this->phpDocInfoFactory->createFromNode($expression); - $expression->setAttribute(AttributeKey::PHP_DOC_INFO, $expressionPhpDocInfo); - + $expression->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, $expressionPhpDocInfo); // invoke override - $expression->setAttribute(AttributeKey::ORIGINAL_NODE, null); - + $expression->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); // remove otherwise empty node - if ($nextNode instanceof Nop) { + if ($nextNode instanceof \PhpParser\Node\Stmt\Nop) { $this->removeNode($nextNode); return null; } - // remove commnets - $nextNode->setAttribute(AttributeKey::PHP_DOC_INFO, null); - $nextNode->setAttribute(AttributeKey::COMMENTS, null); - + $nextNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, null); + $nextNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, null); return $node; } - - private function getDocContent(Node $node): string + private function getDocContent(\PhpParser\Node $node) : string { $docComment = $node->getDocComment(); if ($docComment !== null) { return $docComment->getText(); } - if ($node->getComments() !== []) { $docContent = ''; foreach ($node->getComments() as $comment) { $docContent .= $comment->getText(); } - return $docContent; } - return ''; } - - private function createDocComment(Node $node): Doc + private function createDocComment(\PhpParser\Node $node) : \PhpParser\Comment\Doc { if ($node->getDocComment() !== null) { return $node->getDocComment(); } - $docContent = $this->getDocContent($node); - // normalize content - // starts with "/*", instead of "/**" - if (Strings::startsWith($docContent, '/* ')) { - $docContent = Strings::replace($docContent, self::SINGLE_ASTERISK_COMMENT_START_REGEX, '/** '); + if (\RectorPrefix20210509\Nette\Utils\Strings::startsWith($docContent, '/* ')) { + $docContent = \RectorPrefix20210509\Nette\Utils\Strings::replace($docContent, self::SINGLE_ASTERISK_COMMENT_START_REGEX, '/** '); } - // $value is first, instead of type is first - if (Strings::match($docContent, self::VAR_ANNOTATION_REGEX)) { - $docContent = Strings::replace($docContent, self::VARIABLE_NAME_AND_TYPE_MATCH_REGEX, '$3$2$1'); + if (\RectorPrefix20210509\Nette\Utils\Strings::match($docContent, self::VAR_ANNOTATION_REGEX)) { + $docContent = \RectorPrefix20210509\Nette\Utils\Strings::replace($docContent, self::VARIABLE_NAME_AND_TYPE_MATCH_REGEX, '$3$2$1'); } - - return new Doc($docContent); + return new \PhpParser\Comment\Doc($docContent); } } diff --git a/rules/CodingStyle/Rector/Assign/SplitDoubleAssignRector.php b/rules/CodingStyle/Rector/Assign/SplitDoubleAssignRector.php index 6e3406fdce5..1da9651130f 100644 --- a/rules/CodingStyle/Rector/Assign/SplitDoubleAssignRector.php +++ b/rules/CodingStyle/Rector/Assign/SplitDoubleAssignRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Expression) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - if (! $node->expr instanceof Assign) { + if (!$node->expr instanceof \PhpParser\Node\Expr\Assign) { return null; } - - $newAssign = new Assign($node->var, $node->expr->expr); - - if (! $this->isExprCallOrNew($node->expr->expr)) { + $newAssign = new \PhpParser\Node\Expr\Assign($node->var, $node->expr->expr); + if (!$this->isExprCallOrNew($node->expr->expr)) { $this->addNodeAfterNode($node->expr, $node); return $newAssign; } - - $varAssign = new Assign($node->expr->var, $node->var); - $this->addNodeBeforeNode(new Expression($newAssign), $node); - + $varAssign = new \PhpParser\Node\Expr\Assign($node->expr->var, $node->var); + $this->addNodeBeforeNode(new \PhpParser\Node\Stmt\Expression($newAssign), $node); return $varAssign; } - - private function isExprCallOrNew(Expr $expr): bool + private function isExprCallOrNew(\PhpParser\Node\Expr $expr) : bool { - if ($expr instanceof MethodCall) { - return true; + if ($expr instanceof \PhpParser\Node\Expr\MethodCall) { + return \true; } - - if ($expr instanceof StaticCall) { - return true; + if ($expr instanceof \PhpParser\Node\Expr\StaticCall) { + return \true; } - - if ($expr instanceof FuncCall) { - return true; + if ($expr instanceof \PhpParser\Node\Expr\FuncCall) { + return \true; } - - return $expr instanceof New_; + return $expr instanceof \PhpParser\Node\Expr\New_; } } diff --git a/rules/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector.php b/rules/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector.php index cde38b8c34f..1f63ca79b86 100644 --- a/rules/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector.php +++ b/rules/CodingStyle/Rector/Catch_/CatchExceptionNameMatchingTypeRector.php @@ -1,35 +1,28 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Catch_::class]; + return [\PhpParser\Node\Stmt\Catch_::class]; } - /** * @param Catch_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (count($node->types) !== 1) { + if (\count($node->types) !== 1) { return null; } - if ($node->var === null) { return null; } - $oldVariableName = $this->getName($node->var); - if (! $oldVariableName) { + if (!$oldVariableName) { return null; } - $type = $node->types[0]; $typeShortName = $this->nodeNameResolver->getShortName($type); - - $newVariableName = Strings::replace( - lcfirst($typeShortName), - self::STARTS_WITH_ABBREVIATION_REGEX, - function (array $matches): string { - $output = ''; - - $output .= isset($matches[1]) ? strtolower($matches[1]) : ''; - $output .= $matches[2] ?? ''; - $output .= $matches[3] ?? ''; - - return $output; - } - ); - + $newVariableName = \RectorPrefix20210509\Nette\Utils\Strings::replace(\lcfirst($typeShortName), self::STARTS_WITH_ABBREVIATION_REGEX, function (array $matches) : string { + $output = ''; + $output .= isset($matches[1]) ? \strtolower($matches[1]) : ''; + $output .= $matches[2] ?? ''; + $output .= $matches[3] ?? ''; + return $output; + }); if ($oldVariableName === $newVariableName) { return null; } - - $newVariable = new Variable($newVariableName); - $isFoundInPrevious = (bool) $this->betterNodeFinder->findFirstPrevious($node, function (Node $n) use ( - $newVariable - ): bool { + $newVariable = new \PhpParser\Node\Expr\Variable($newVariableName); + $isFoundInPrevious = (bool) $this->betterNodeFinder->findFirstPrevious($node, function (\PhpParser\Node $n) use($newVariable) : bool { return $this->nodeComparator->areNodesEqual($n, $newVariable); }); - if ($isFoundInPrevious) { return null; } - $node->var->name = $newVariableName; $this->renameVariableInStmts($node, $oldVariableName, $newVariableName); - return $node; } - - private function renameVariableInStmts(Catch_ $catch, string $oldVariableName, string $newVariableName): void + private function renameVariableInStmts(\PhpParser\Node\Stmt\Catch_ $catch, string $oldVariableName, string $newVariableName) : void { - $this->traverseNodesWithCallable($catch->stmts, function (Node $node) use ( - $oldVariableName, - $newVariableName - ): void { - if (! $node instanceof Variable) { + $this->traverseNodesWithCallable($catch->stmts, function (\PhpParser\Node $node) use($oldVariableName, $newVariableName) : void { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { return; } - - if (! $this->nodeNameResolver->isName($node, $oldVariableName)) { + if (!$this->nodeNameResolver->isName($node, $oldVariableName)) { return; } - $node->name = $newVariableName; }); } diff --git a/rules/CodingStyle/Rector/ClassConst/SplitGroupedConstantsAndPropertiesRector.php b/rules/CodingStyle/Rector/ClassConst/SplitGroupedConstantsAndPropertiesRector.php index 5a2183ae535..f3c26785da6 100644 --- a/rules/CodingStyle/Rector/ClassConst/SplitGroupedConstantsAndPropertiesRector.php +++ b/rules/CodingStyle/Rector/ClassConst/SplitGroupedConstantsAndPropertiesRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassConst::class, Property::class]; + return [\PhpParser\Node\Stmt\ClassConst::class, \PhpParser\Node\Stmt\Property::class]; } - /** * @param ClassConst|Property $node * @return Node|Node[]|null */ - public function refactor(Node $node) + public function refactor(\PhpParser\Node $node) { - if ($node instanceof ClassConst) { - if (count($node->consts) < 2) { + if ($node instanceof \PhpParser\Node\Stmt\ClassConst) { + if (\count($node->consts) < 2) { return null; } - /** @var Const_[] $allConsts */ $allConsts = $node->consts; - /** @var Const_ $firstConst */ - $firstConst = array_shift($allConsts); + $firstConst = \array_shift($allConsts); $node->consts = [$firstConst]; - $nextClassConsts = $this->createNextClassConsts($allConsts, $node); - - return array_merge([$node], $nextClassConsts); + return \array_merge([$node], $nextClassConsts); } - - if (count($node->props) < 2) { + if (\count($node->props) < 2) { return null; } - $allProperties = $node->props; /** @var PropertyProperty $firstPropertyProperty */ - $firstPropertyProperty = array_shift($allProperties); + $firstPropertyProperty = \array_shift($allProperties); $node->props = [$firstPropertyProperty]; - $nextProperties = []; foreach ($allProperties as $allProperty) { - $nextProperties[] = new Property($node->flags, [$allProperty], $node->getAttributes()); + $nextProperties[] = new \PhpParser\Node\Stmt\Property($node->flags, [$allProperty], $node->getAttributes()); } - - return array_merge([$node], $nextProperties); + return \array_merge([$node], $nextProperties); } - /** * @param Const_[] $consts * @return ClassConst[] */ - private function createNextClassConsts(array $consts, ClassConst $classConst): array + private function createNextClassConsts(array $consts, \PhpParser\Node\Stmt\ClassConst $classConst) : array { $decoratedConsts = []; - foreach ($consts as $const) { - $decoratedConsts[] = new ClassConst([$const], $classConst->flags, $classConst->getAttributes()); + $decoratedConsts[] = new \PhpParser\Node\Stmt\ClassConst([$const], $classConst->flags, $classConst->getAttributes()); } - return $decoratedConsts; } } diff --git a/rules/CodingStyle/Rector/ClassConst/VarConstantCommentRector.php b/rules/CodingStyle/Rector/ClassConst/VarConstantCommentRector.php index ee2bf421653..b6de9feb0fd 100644 --- a/rules/CodingStyle/Rector/ClassConst/VarConstantCommentRector.php +++ b/rules/CodingStyle/Rector/ClassConst/VarConstantCommentRector.php @@ -1,7 +1,6 @@ typeComparator = $typeComparator; $this->phpDocTypeChanger = $phpDocTypeChanger; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Constant should have a @var comment with type', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Constant should have a @var comment with type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { const HI = 'hi'; } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -63,102 +53,81 @@ class SomeClass const HI = 'hi'; } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassConst::class]; + return [\PhpParser\Node\Stmt\ClassConst::class]; } - /** * @param ClassConst $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (count($node->consts) > 1) { + if (\count($node->consts) > 1) { return null; } - $constType = $this->getStaticType($node->consts[0]->value); - if ($constType instanceof MixedType) { + if ($constType instanceof \PHPStan\Type\MixedType) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - if ($this->shouldSkipConstantArrayType($constType, $phpDocInfo)) { return null; } - if ($this->typeComparator->isSubtype($constType, $phpDocInfo->getVarType())) { return null; } - $this->phpDocTypeChanger->changeVarType($phpDocInfo, $constType); - return $node; } - - private function hasTwoAndMoreGenericClassStringTypes(ConstantArrayType $constantArrayType): bool + private function hasTwoAndMoreGenericClassStringTypes(\PHPStan\Type\Constant\ConstantArrayType $constantArrayType) : bool { $typeNode = $this->staticTypeMapper->mapPHPStanTypeToPHPStanPhpDocTypeNode($constantArrayType); - if (! $typeNode instanceof ArrayTypeNode) { - return false; + if (!$typeNode instanceof \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode) { + return \false; } - - if (! $typeNode->type instanceof UnionTypeNode) { - return false; + if (!$typeNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\UnionTypeNode) { + return \false; } - $genericTypeNodeCount = 0; foreach ($typeNode->type->types as $unionedTypeNode) { - if ($unionedTypeNode instanceof GenericTypeNode) { + if ($unionedTypeNode instanceof \PHPStan\PhpDocParser\Ast\Type\GenericTypeNode) { ++$genericTypeNodeCount; } } - return $genericTypeNodeCount > 1; } - /** * Skip big arrays and mixed[] constants */ - private function shouldSkipConstantArrayType(Type $constType, PhpDocInfo $phpDocInfo): bool + private function shouldSkipConstantArrayType(\PHPStan\Type\Type $constType, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : bool { - if (! $constType instanceof ConstantArrayType) { - return false; + if (!$constType instanceof \PHPStan\Type\Constant\ConstantArrayType) { + return \false; } - $currentVarType = $phpDocInfo->getVarType(); - if ($currentVarType instanceof ArrayType && $currentVarType->getItemType() instanceof MixedType) { - return true; + if ($currentVarType instanceof \PHPStan\Type\ArrayType && $currentVarType->getItemType() instanceof \PHPStan\Type\MixedType) { + return \true; } - if ($this->hasTwoAndMoreGenericClassStringTypes($constType)) { - return true; + return \true; } - return $this->isHugeNestedConstantArrayTyp($constType); } - - private function isHugeNestedConstantArrayTyp(ConstantArrayType $constantArrayType): bool + private function isHugeNestedConstantArrayTyp(\PHPStan\Type\Constant\ConstantArrayType $constantArrayType) : bool { - if (count($constantArrayType->getValueTypes()) <= 3) { - return false; + if (\count($constantArrayType->getValueTypes()) <= 3) { + return \false; } - foreach ($constantArrayType->getValueTypes() as $constValueType) { - if ($constValueType instanceof ConstantArrayType) { - return true; + if ($constValueType instanceof \PHPStan\Type\Constant\ConstantArrayType) { + return \true; } } - - return false; + return \false; } } diff --git a/rules/CodingStyle/Rector/ClassMethod/FuncGetArgsToVariadicParamRector.php b/rules/CodingStyle/Rector/ClassMethod/FuncGetArgsToVariadicParamRector.php index 73f3bedd62d..fdfac86fb78 100644 --- a/rules/CodingStyle/Rector/ClassMethod/FuncGetArgsToVariadicParamRector.php +++ b/rules/CodingStyle/Rector/ClassMethod/FuncGetArgsToVariadicParamRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Function_::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class]; } - /** * @param ClassMethod|Function_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::VARIADIC_PARAM)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::VARIADIC_PARAM)) { return null; } - if ($node->params !== []) { return null; } - $assign = $this->matchFuncGetArgsVariableAssign($node); - if (! $assign instanceof Assign) { + if (!$assign instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if ($assign->var instanceof Variable) { + if ($assign->var instanceof \PhpParser\Node\Expr\Variable) { $variableName = $this->getName($assign->var); if ($variableName === null) { return null; } - $this->removeNode($assign); } else { $variableName = 'args'; - $assign->expr = new Variable('args'); + $assign->expr = new \PhpParser\Node\Expr\Variable('args'); } - $node->params[] = $this->createVariadicParam($variableName); - return $node; } - /** * @param ClassMethod|Function_ $functionLike */ - private function matchFuncGetArgsVariableAssign(FunctionLike $functionLike): ?Assign + private function matchFuncGetArgsVariableAssign(\PhpParser\Node\FunctionLike $functionLike) : ?\PhpParser\Node\Expr\Assign { /** @var Assign[] $assigns */ - $assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, Assign::class); - + $assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, \PhpParser\Node\Expr\Assign::class); foreach ($assigns as $assign) { - if (! $assign->expr instanceof FuncCall) { + if (!$assign->expr instanceof \PhpParser\Node\Expr\FuncCall) { continue; } - - if (! $this->isName($assign->expr, 'func_get_args')) { + if (!$this->isName($assign->expr, 'func_get_args')) { continue; } - return $assign; } - return null; } - - private function createVariadicParam(string $variableName): Param + private function createVariadicParam(string $variableName) : \PhpParser\Node\Param { - $variable = new Variable($variableName); - return new Param($variable, null, null, false, true); + $variable = new \PhpParser\Node\Expr\Variable($variableName); + return new \PhpParser\Node\Param($variable, null, null, \false, \true); } } diff --git a/rules/CodingStyle/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector.php b/rules/CodingStyle/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector.php index 3b02d1236f8..1b82adac377 100644 --- a/rules/CodingStyle/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector.php +++ b/rules/CodingStyle/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { // possibly trait return null; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - /** @var string $methodName */ $methodName = $this->getName($node->name); - foreach ($classReflection->getParents() as $parentClassReflection) { - if (! $parentClassReflection->hasMethod($methodName)) { + if (!$parentClassReflection->hasMethod($methodName)) { continue; } - $nativeClassReflection = $parentClassReflection->getNativeReflection(); - $parentReflectionMethod = $nativeClassReflection->getMethod($methodName); if ($this->isClassMethodCompatibleWithParentReflectionMethod($node, $parentReflectionMethod)) { return null; } - if ($this->isConstructorWithStaticFactory($node, $methodName)) { return null; } - $this->changeClassMethodVisibilityBasedOnReflectionMethod($node, $parentReflectionMethod); - return $node; } - return null; } - - private function isClassMethodCompatibleWithParentReflectionMethod( - ClassMethod $classMethod, - ReflectionMethod $reflectionMethod - ): bool { + private function isClassMethodCompatibleWithParentReflectionMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \ReflectionMethod $reflectionMethod) : bool + { if ($reflectionMethod->isPublic() && $classMethod->isPublic()) { - return true; + return \true; } - if ($reflectionMethod->isProtected() && $classMethod->isProtected()) { - return true; + return \true; } - if (! $reflectionMethod->isPrivate()) { - return false; + if (!$reflectionMethod->isPrivate()) { + return \false; } return $classMethod->isPrivate(); } - /** * Parent constructor visibility override is allowed only since PHP 7.2+ * @see https://3v4l.org/RFYmn */ - private function isConstructorWithStaticFactory(ClassMethod $classMethod, string $methodName): bool + private function isConstructorWithStaticFactory(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $methodName) : bool { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::PARENT_VISIBILITY_OVERRIDE)) { - return false; + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::PARENT_VISIBILITY_OVERRIDE)) { + return \false; } - - if ($methodName !== MethodName::CONSTRUCT) { - return false; + if ($methodName !== \Rector\Core\ValueObject\MethodName::CONSTRUCT) { + return \false; } - - $classLike = $classMethod->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return false; + $classLike = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } - foreach ($classLike->getMethods() as $iteratedClassMethod) { - if (! $iteratedClassMethod->isPublic()) { + if (!$iteratedClassMethod->isPublic()) { continue; } - - if (! $iteratedClassMethod->isStatic()) { + if (!$iteratedClassMethod->isStatic()) { continue; } - $isStaticSelfFactory = $this->isStaticNamedConstructor($iteratedClassMethod); - - if (! $isStaticSelfFactory) { + if (!$isStaticSelfFactory) { continue; } - - return true; + return \true; } - - return false; + return \false; } - - private function changeClassMethodVisibilityBasedOnReflectionMethod( - ClassMethod $classMethod, - ReflectionMethod $reflectionMethod - ): void { + private function changeClassMethodVisibilityBasedOnReflectionMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \ReflectionMethod $reflectionMethod) : void + { if ($reflectionMethod->isPublic()) { $this->visibilityManipulator->makePublic($classMethod); return; } - if ($reflectionMethod->isProtected()) { $this->visibilityManipulator->makeProtected($classMethod); return; } - if ($reflectionMethod->isPrivate()) { $this->visibilityManipulator->makePrivate($classMethod); return; } } - /** * Looks for: * public static someMethod() { return new self(); } * or * public static someMethod() { return new static(); } */ - private function isStaticNamedConstructor(ClassMethod $classMethod): bool + private function isStaticNamedConstructor(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - if (! $classMethod->isPublic()) { - return false; + if (!$classMethod->isPublic()) { + return \false; } - - if (! $classMethod->isStatic()) { - return false; + if (!$classMethod->isStatic()) { + return \false; } - - return (bool) $this->betterNodeFinder->findFirst($classMethod, function (Node $node): bool { - if (! $node instanceof Return_) { - return false; + return (bool) $this->betterNodeFinder->findFirst($classMethod, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Stmt\Return_) { + return \false; } - - if (! $node->expr instanceof New_) { - return false; + if (!$node->expr instanceof \PhpParser\Node\Expr\New_) { + return \false; } - return $this->isNames($node->expr->class, ['self', 'static']); }); } diff --git a/rules/CodingStyle/Rector/ClassMethod/NewlineBeforeNewAssignSetRector.php b/rules/CodingStyle/Rector/ClassMethod/NewlineBeforeNewAssignSetRector.php index 6e6257bd908..ca622fc06d4 100644 --- a/rules/CodingStyle/Rector/ClassMethod/NewlineBeforeNewAssignSetRector.php +++ b/rules/CodingStyle/Rector/ClassMethod/NewlineBeforeNewAssignSetRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Function_::class, Closure::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Expr\Closure::class]; } - /** * @param ClassMethod|Function_|Closure $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $this->reset(); - - $hasChanged = false; - + $hasChanged = \false; foreach ((array) $node->stmts as $key => $stmt) { $currentStmtVariableName = $this->resolveCurrentStmtVariableName($stmt); - if ($this->shouldAddEmptyLine($currentStmtVariableName, $node, $key)) { - $hasChanged = true; + $hasChanged = \true; // insert newline before $stmts = (array) $node->stmts; - array_splice($stmts, $key, 0, [new Nop()]); + \array_splice($stmts, $key, 0, [new \PhpParser\Node\Stmt\Nop()]); $node->stmts = $stmts; } - $this->previousPreviousStmtVariableName = $this->previousStmtVariableName; $this->previousStmtVariableName = $currentStmtVariableName; } - return $hasChanged ? $node : null; } - - private function reset(): void + private function reset() : void { $this->previousStmtVariableName = null; $this->previousPreviousStmtVariableName = null; } - - private function resolveCurrentStmtVariableName(Stmt $stmt): ?string + private function resolveCurrentStmtVariableName(\PhpParser\Node\Stmt $stmt) : ?string { $stmt = $this->unwrapExpression($stmt); - - if ($stmt instanceof Assign || $stmt instanceof MethodCall) { + if ($stmt instanceof \PhpParser\Node\Expr\Assign || $stmt instanceof \PhpParser\Node\Expr\MethodCall) { if ($this->shouldSkipLeftVariable($stmt)) { return null; } - - if (! $stmt->var instanceof MethodCall && ! $stmt->var instanceof StaticCall) { + if (!$stmt->var instanceof \PhpParser\Node\Expr\MethodCall && !$stmt->var instanceof \PhpParser\Node\Expr\StaticCall) { return $this->getName($stmt->var); } } - return null; } - /** * @param ClassMethod|Function_|Closure $node */ - private function shouldAddEmptyLine(?string $currentStmtVariableName, Node $node, int $key): bool + private function shouldAddEmptyLine(?string $currentStmtVariableName, \PhpParser\Node $node, int $key) : bool { - if (! $this->isNewVariableThanBefore($currentStmtVariableName)) { - return false; + if (!$this->isNewVariableThanBefore($currentStmtVariableName)) { + return \false; } - // this is already empty line before - return ! $this->isPreceededByEmptyLine($node, $key); + return !$this->isPreceededByEmptyLine($node, $key); } - /** * @param Assign|MethodCall $node */ - private function shouldSkipLeftVariable(Node $node): bool + private function shouldSkipLeftVariable(\PhpParser\Node $node) : bool { - if (! $node->var instanceof Variable) { - return false; + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - // local method call return $this->nodeNameResolver->isName($node->var, 'this'); } - - private function isNewVariableThanBefore(?string $currentStmtVariableName): bool + private function isNewVariableThanBefore(?string $currentStmtVariableName) : bool { if ($this->previousPreviousStmtVariableName === null) { - return false; + return \false; } - if ($this->previousStmtVariableName === null) { - return false; + return \false; } - if ($currentStmtVariableName === null) { - return false; + return \false; } - if ($this->previousStmtVariableName !== $this->previousPreviousStmtVariableName) { - return false; + return \false; } - return $this->previousStmtVariableName !== $currentStmtVariableName; } - /** * @param ClassMethod|Function_|Closure $node */ - private function isPreceededByEmptyLine(Node $node, int $key): bool + private function isPreceededByEmptyLine(\PhpParser\Node $node, int $key) : bool { if ($node->stmts === null) { - return false; + return \false; } - $previousNode = $node->stmts[$key - 1]; $currentNode = $node->stmts[$key]; - - return abs($currentNode->getLine() - $previousNode->getLine()) >= 2; + return \abs($currentNode->getLine() - $previousNode->getLine()) >= 2; } } diff --git a/rules/CodingStyle/Rector/ClassMethod/RemoveDoubleUnderscoreInMethodNameRector.php b/rules/CodingStyle/Rector/ClassMethod/RemoveDoubleUnderscoreInMethodNameRector.php index f81058a04eb..ca8555f3f34 100644 --- a/rules/CodingStyle/Rector/ClassMethod/RemoveDoubleUnderscoreInMethodNameRector.php +++ b/rules/CodingStyle/Rector/ClassMethod/RemoveDoubleUnderscoreInMethodNameRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, MethodCall::class, StaticCall::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param ClassMethod|MethodCall|StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $methodName = $this->getName($node->name); if ($methodName === null) { return null; } - - if (in_array($methodName, ObjectMagicMethods::METHOD_NAMES, true)) { + if (\in_array($methodName, \Rector\CodingStyle\ValueObject\ObjectMagicMethods::METHOD_NAMES, \true)) { return null; } - - if (! Strings::match($methodName, self::DOUBLE_UNDERSCORE_START_REGEX)) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($methodName, self::DOUBLE_UNDERSCORE_START_REGEX)) { return null; } - - $newName = Strings::substring($methodName, 2); - - if (is_numeric($newName[0])) { + $newName = \RectorPrefix20210509\Nette\Utils\Strings::substring($methodName, 2); + if (\is_numeric($newName[0])) { return null; } - - $node->name = new Identifier($newName); - + $node->name = new \PhpParser\Node\Identifier($newName); return $node; } } diff --git a/rules/CodingStyle/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector.php b/rules/CodingStyle/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector.php index 5b26494945a..79e282645f2 100644 --- a/rules/CodingStyle/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector.php +++ b/rules/CodingStyle/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector.php @@ -1,7 +1,6 @@ nodeTransformer = $nodeTransformer; $this->commentsMerger = $commentsMerger; - // default values - $this->methodsToYields = [ - new ReturnArrayClassMethodToYield('PHPUnit\Framework\TestCase', 'provideData'), - new ReturnArrayClassMethodToYield('PHPUnit\Framework\TestCase', 'provideData*'), - new ReturnArrayClassMethodToYield('PHPUnit\Framework\TestCase', 'dataProvider'), - new ReturnArrayClassMethodToYield('PHPUnit\Framework\TestCase', 'dataProvider*'), - ]; + $this->methodsToYields = [new \Rector\CodingStyle\ValueObject\ReturnArrayClassMethodToYield('PHPUnit\\Framework\\TestCase', 'provideData'), new \Rector\CodingStyle\ValueObject\ReturnArrayClassMethodToYield('PHPUnit\\Framework\\TestCase', 'provideData*'), new \Rector\CodingStyle\ValueObject\ReturnArrayClassMethodToYield('PHPUnit\\Framework\\TestCase', 'dataProvider'), new \Rector\CodingStyle\ValueObject\ReturnArrayClassMethodToYield('PHPUnit\\Framework\\TestCase', 'dataProvider*')]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turns array return to yield return in specific type and method', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns array return to yield return in specific type and method', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() @@ -76,8 +61,7 @@ class SomeEventSubscriber implements EventSubscriberInterface } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() @@ -86,116 +70,88 @@ class SomeEventSubscriber implements EventSubscriberInterface } } CODE_SAMPLE - , - [ - self::METHODS_TO_YIELDS => [ - new ReturnArrayClassMethodToYield('EventSubscriberInterface', 'getSubscribedEvents'), - ], - ] - ), - ]); +, [self::METHODS_TO_YIELDS => [new \Rector\CodingStyle\ValueObject\ReturnArrayClassMethodToYield('EventSubscriberInterface', 'getSubscribedEvents')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $hasChanged = false; + $hasChanged = \false; foreach ($this->methodsToYields as $methodToYield) { - if (! $this->isObjectType($node, $methodToYield->getObjectType())) { + if (!$this->isObjectType($node, $methodToYield->getObjectType())) { continue; } - - if (! $this->isName($node, $methodToYield->getMethod())) { + if (!$this->isName($node, $methodToYield->getMethod())) { continue; } - $arrayNode = $this->collectReturnArrayNodesFromClassMethod($node); - if (! $arrayNode instanceof Array_) { + if (!$arrayNode instanceof \PhpParser\Node\Expr\Array_) { continue; } - $this->transformArrayToYieldsOnMethodNode($node, $arrayNode); - $this->commentsMerger->keepParent($node, $arrayNode); - $hasChanged = true; + $hasChanged = \true; } - - if (! $hasChanged) { + if (!$hasChanged) { return null; } - return $node; } - /** * @param mixed[] $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $methodsToYields = $configuration[self::METHODS_TO_YIELDS] ?? []; - Assert::allIsInstanceOf($methodsToYields, ReturnArrayClassMethodToYield::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($methodsToYields, \Rector\CodingStyle\ValueObject\ReturnArrayClassMethodToYield::class); $this->methodsToYields = $methodsToYields; } - - private function collectReturnArrayNodesFromClassMethod(ClassMethod $classMethod): ?Array_ + private function collectReturnArrayNodesFromClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PhpParser\Node\Expr\Array_ { if ($classMethod->stmts === null) { return null; } - foreach ($classMethod->stmts as $statement) { - if ($statement instanceof Return_) { + if ($statement instanceof \PhpParser\Node\Stmt\Return_) { $returnedExpr = $statement->expr; - if (! $returnedExpr instanceof Array_) { + if (!$returnedExpr instanceof \PhpParser\Node\Expr\Array_) { continue; } - return $returnedExpr; } } - return null; } - - private function transformArrayToYieldsOnMethodNode(ClassMethod $classMethod, Array_ $array): void + private function transformArrayToYieldsOnMethodNode(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Expr\Array_ $array) : void { $yieldNodes = $this->nodeTransformer->transformArrayToYields($array); - // remove whole return node - $parentNode = $array->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Node) { - throw new ShouldNotHappenException(); + $parentNode = $array->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $this->removeReturnTag($classMethod); - // change return typehint - $classMethod->returnType = new FullyQualified('Iterator'); - + $classMethod->returnType = new \PhpParser\Node\Name\FullyQualified('Iterator'); foreach ((array) $classMethod->stmts as $key => $classMethodStmt) { - if (! $classMethodStmt instanceof Return_) { + if (!$classMethodStmt instanceof \PhpParser\Node\Stmt\Return_) { continue; } - unset($classMethod->stmts[$key]); } - - $classMethod->stmts = array_merge((array) $classMethod->stmts, $yieldNodes); + $classMethod->stmts = \array_merge((array) $classMethod->stmts, $yieldNodes); } - - private function removeReturnTag(ClassMethod $classMethod): void + private function removeReturnTag(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); - $phpDocInfo->removeByType(ReturnTagValueNode::class); + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode::class); } } diff --git a/rules/CodingStyle/Rector/ClassMethod/UnSpreadOperatorRector.php b/rules/CodingStyle/Rector/ClassMethod/UnSpreadOperatorRector.php index 7eaf8761c29..8c1002cf4e2 100644 --- a/rules/CodingStyle/Rector/ClassMethod/UnSpreadOperatorRector.php +++ b/rules/CodingStyle/Rector/ClassMethod/UnSpreadOperatorRector.php @@ -1,7 +1,6 @@ spreadVariablesCollector = $spreadVariablesCollector; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove spread operator', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove spread operator', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run(...$array) @@ -46,8 +40,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run(array $array) @@ -60,95 +53,77 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, MethodCall::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\MethodCall::class]; } - /** * @param ClassMethod|MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { return $this->processUnspreadOperatorClassMethodParams($node); } - return $this->processUnspreadOperatorMethodCallArgs($node); } - - private function processUnspreadOperatorClassMethodParams(ClassMethod $classMethod): ?ClassMethod + private function processUnspreadOperatorClassMethodParams(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PhpParser\Node\Stmt\ClassMethod { $spreadParams = $this->spreadVariablesCollector->resolveFromClassMethod($classMethod); if ($spreadParams === []) { return null; } - foreach ($spreadParams as $spreadParam) { - $spreadParam->variadic = false; - $spreadParam->type = new Identifier('array'); + $spreadParam->variadic = \false; + $spreadParam->type = new \PhpParser\Node\Identifier('array'); } - return $classMethod; } - - private function processUnspreadOperatorMethodCallArgs(MethodCall $methodCall): ?MethodCall + private function processUnspreadOperatorMethodCallArgs(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node\Expr\MethodCall { $classMethod = $this->nodeRepository->findClassMethodByMethodCall($methodCall); - if (! $classMethod instanceof ClassMethod) { + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - $spreadParams = $this->spreadVariablesCollector->resolveFromClassMethod($classMethod); if ($spreadParams === []) { return null; } - - $firstSpreadParamPosition = array_key_first($spreadParams); + \reset($spreadParams); + $firstSpreadParamPosition = \key($spreadParams); $variadicArgs = $this->resolveVariadicArgsByVariadicParams($methodCall, $firstSpreadParamPosition); - - $hasUnpacked = false; - + $hasUnpacked = \false; foreach ($variadicArgs as $position => $variadicArg) { if ($variadicArg->unpack) { - $variadicArg->unpack = false; - $hasUnpacked = true; + $variadicArg->unpack = \false; + $hasUnpacked = \true; $methodCall->args[$position] = $variadicArg; } } - if ($hasUnpacked) { return $methodCall; } - - $methodCall->args[$firstSpreadParamPosition] = new Arg($this->nodeFactory->createArray($variadicArgs)); + $methodCall->args[$firstSpreadParamPosition] = new \PhpParser\Node\Arg($this->nodeFactory->createArray($variadicArgs)); return $methodCall; } - /** * @return Arg[] */ - private function resolveVariadicArgsByVariadicParams(MethodCall $methodCall, int $firstSpreadParamPosition): array + private function resolveVariadicArgsByVariadicParams(\PhpParser\Node\Expr\MethodCall $methodCall, int $firstSpreadParamPosition) : array { $variadicArgs = []; - foreach ($methodCall->args as $position => $arg) { if ($position < $firstSpreadParamPosition) { continue; } - $variadicArgs[] = $arg; - $this->nodeRemover->removeArg($methodCall, $position); } - return $variadicArgs; } } diff --git a/rules/CodingStyle/Rector/ClassMethod/YieldClassMethodToArrayClassMethodRector.php b/rules/CodingStyle/Rector/ClassMethod/YieldClassMethodToArrayClassMethodRector.php index 5b5f91bc8e7..50e898ea25f 100644 --- a/rules/CodingStyle/Rector/ClassMethod/YieldClassMethodToArrayClassMethodRector.php +++ b/rules/CodingStyle/Rector/ClassMethod/YieldClassMethodToArrayClassMethodRector.php @@ -1,7 +1,6 @@ */ private $methodsByType = []; - /** * @var NodeTransformer */ private $nodeTransformer; - /** * @param array $methodsByType */ - public function __construct(NodeTransformer $nodeTransformer, array $methodsByType = []) + public function __construct(\Rector\Core\PhpParser\NodeTransformer $nodeTransformer, array $methodsByType = []) { $this->methodsByType = $methodsByType; $this->nodeTransformer = $nodeTransformer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turns yield return to array return in specific type and method', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns yield return to array return in specific type and method', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() @@ -62,8 +54,7 @@ class SomeEventSubscriber implements EventSubscriberInterface } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() @@ -72,83 +63,62 @@ class SomeEventSubscriber implements EventSubscriberInterface } } CODE_SAMPLE - , - [ - self::METHODS_BY_TYPE => [ - 'EventSubscriberInterface' => ['getSubscribedEvents'], - ], - ] - ), - ]); +, [self::METHODS_BY_TYPE => ['EventSubscriberInterface' => ['getSubscribedEvents']]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->methodsByType as $type => $methods) { - if (! $this->isObjectType($node, new ObjectType($type))) { + if (!$this->isObjectType($node, new \PHPStan\Type\ObjectType($type))) { continue; } - foreach ($methods as $method) { - if (! $this->isName($node, $method)) { + if (!$this->isName($node, $method)) { continue; } - $yieldNodes = $this->collectYieldNodesFromClassMethod($node); if ($yieldNodes === []) { continue; } - $arrayNode = $this->nodeTransformer->transformYieldsToArray($yieldNodes); $this->removeNodes($yieldNodes); - - $node->returnType = new Identifier('array'); - - $returnExpression = new Return_($arrayNode); - $node->stmts = array_merge((array) $node->stmts, [$returnExpression]); + $node->returnType = new \PhpParser\Node\Identifier('array'); + $returnExpression = new \PhpParser\Node\Stmt\Return_($arrayNode); + $node->stmts = \array_merge((array) $node->stmts, [$returnExpression]); } } - return $node; } - - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->methodsByType = $configuration[self::METHODS_BY_TYPE] ?? []; } - /** * @return Yield_[] */ - private function collectYieldNodesFromClassMethod(ClassMethod $classMethod): array + private function collectYieldNodesFromClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $yieldNodes = []; - if ($classMethod->stmts === null) { return []; } - foreach ($classMethod->stmts as $statement) { - if (! $statement instanceof Expression) { + if (!$statement instanceof \PhpParser\Node\Stmt\Expression) { continue; } - - if ($statement->expr instanceof Yield_) { + if ($statement->expr instanceof \PhpParser\Node\Expr\Yield_) { $yieldNodes[] = $statement->expr; } } - return $yieldNodes; } } diff --git a/rules/CodingStyle/Rector/Class_/AddArrayDefaultToArrayPropertyRector.php b/rules/CodingStyle/Rector/Class_/AddArrayDefaultToArrayPropertyRector.php index c6bab94a2f5..83ce1b582a5 100644 --- a/rules/CodingStyle/Rector/Class_/AddArrayDefaultToArrayPropertyRector.php +++ b/rules/CodingStyle/Rector/Class_/AddArrayDefaultToArrayPropertyRector.php @@ -1,7 +1,6 @@ propertyFetchAnalyzer = $propertyFetchAnalyzer; $this->iterableTypeAnalyzer = $iterableTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Adds array default value to property to prevent foreach over null error', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Adds array default value to property to prevent foreach over null error', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -67,8 +56,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -82,192 +70,143 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $changedProperties = $this->collectPropertyNamesWithMissingDefaultArray($node); if ($changedProperties === []) { return null; } - $this->completeDefaultArrayToPropertyNames($node, $changedProperties); - // $this->variable !== null && count($this->variable) > 0 → count($this->variable) > 0 $this->clearNotNullBeforeCount($node, $changedProperties); - // $this->variable === null → $this->variable === [] $this->replaceNullComparisonOfArrayPropertiesWithArrayComparison($node, $changedProperties); - return $node; } - /** * @return string[] */ - private function collectPropertyNamesWithMissingDefaultArray(Class_ $class): array + private function collectPropertyNamesWithMissingDefaultArray(\PhpParser\Node\Stmt\Class_ $class) : array { $propertyNames = []; - $this->traverseNodesWithCallable($class, function (Node $node) use (&$propertyNames) { - if (! $node instanceof PropertyProperty) { + $this->traverseNodesWithCallable($class, function (\PhpParser\Node $node) use(&$propertyNames) { + if (!$node instanceof \PhpParser\Node\Stmt\PropertyProperty) { return null; } - if ($node->default !== null) { return null; } - $varType = $this->resolveVarType($node); - if (! $this->iterableTypeAnalyzer->detect($varType)) { + if (!$this->iterableTypeAnalyzer->detect($varType)) { return null; } - $propertyNames[] = $this->getName($node); - return null; }); - return $propertyNames; } - /** * @param string[] $propertyNames */ - private function completeDefaultArrayToPropertyNames(Class_ $class, array $propertyNames): void + private function completeDefaultArrayToPropertyNames(\PhpParser\Node\Stmt\Class_ $class, array $propertyNames) : void { - $this->traverseNodesWithCallable($class, function (Node $class) use ($propertyNames): ?PropertyProperty { - if (! $class instanceof PropertyProperty) { + $this->traverseNodesWithCallable($class, function (\PhpParser\Node $class) use($propertyNames) : ?PropertyProperty { + if (!$class instanceof \PhpParser\Node\Stmt\PropertyProperty) { return null; } - - if (! $this->isNames($class, $propertyNames)) { + if (!$this->isNames($class, $propertyNames)) { return null; } - - $class->default = new Array_(); - + $class->default = new \PhpParser\Node\Expr\Array_(); return $class; }); } - /** * @param string[] $propertyNames */ - private function clearNotNullBeforeCount(Class_ $class, array $propertyNames): void + private function clearNotNullBeforeCount(\PhpParser\Node\Stmt\Class_ $class, array $propertyNames) : void { - $this->traverseNodesWithCallable($class, function (Node $node) use ($propertyNames): ?Expr { - if (! $node instanceof BooleanAnd) { + $this->traverseNodesWithCallable($class, function (\PhpParser\Node $node) use($propertyNames) : ?Expr { + if (!$node instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { return null; } - if (! $this->isLocalPropertyOfNamesNotIdenticalToNull($node->left, $propertyNames)) { + if (!$this->isLocalPropertyOfNamesNotIdenticalToNull($node->left, $propertyNames)) { return null; } - - $isNextNodeCountingProperty = (bool) $this->betterNodeFinder->findFirst($node->right, function (Node $node) use ( - $propertyNames - ): ?bool { - if (! $node instanceof FuncCall) { + $isNextNodeCountingProperty = (bool) $this->betterNodeFinder->findFirst($node->right, function (\PhpParser\Node $node) use($propertyNames) : ?bool { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->isName($node, 'count')) { + if (!$this->isName($node, 'count')) { return null; } - - if (! isset($node->args[0])) { + if (!isset($node->args[0])) { return null; } - $countedArgument = $node->args[0]->value; - if (! $countedArgument instanceof PropertyFetch) { + if (!$countedArgument instanceof \PhpParser\Node\Expr\PropertyFetch) { return null; } - return $this->isNames($countedArgument, $propertyNames); }); - - if (! $isNextNodeCountingProperty) { + if (!$isNextNodeCountingProperty) { return null; } - return $node->right; }); } - /** * @param string[] $propertyNames */ - private function replaceNullComparisonOfArrayPropertiesWithArrayComparison( - Class_ $class, - array $propertyNames - ): void { + private function replaceNullComparisonOfArrayPropertiesWithArrayComparison(\PhpParser\Node\Stmt\Class_ $class, array $propertyNames) : void + { // replace comparison to "null" with "[]" - $this->traverseNodesWithCallable($class, function (Node $node) use ($propertyNames): ?BinaryOp { - if (! $node instanceof BinaryOp) { + $this->traverseNodesWithCallable($class, function (\PhpParser\Node $node) use($propertyNames) : ?BinaryOp { + if (!$node instanceof \PhpParser\Node\Expr\BinaryOp) { return null; } - - if ($this->propertyFetchAnalyzer->isLocalPropertyOfNames( - $node->left, - $propertyNames - ) && $this->valueResolver->isNull($node->right)) { - $node->right = new Array_(); + if ($this->propertyFetchAnalyzer->isLocalPropertyOfNames($node->left, $propertyNames) && $this->valueResolver->isNull($node->right)) { + $node->right = new \PhpParser\Node\Expr\Array_(); } - - if ($this->propertyFetchAnalyzer->isLocalPropertyOfNames( - $node->right, - $propertyNames - ) && $this->valueResolver->isNull($node->left)) { - $node->left = new Array_(); + if ($this->propertyFetchAnalyzer->isLocalPropertyOfNames($node->right, $propertyNames) && $this->valueResolver->isNull($node->left)) { + $node->left = new \PhpParser\Node\Expr\Array_(); } - return $node; }); } - - private function resolveVarType(PropertyProperty $propertyProperty): Type + private function resolveVarType(\PhpParser\Node\Stmt\PropertyProperty $propertyProperty) : \PHPStan\Type\Type { /** @var Property $property */ - $property = $propertyProperty->getAttribute(AttributeKey::PARENT_NODE); - + $property = $propertyProperty->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); return $phpDocInfo->getVarType(); } - /** * @param string[] $propertyNames */ - private function isLocalPropertyOfNamesNotIdenticalToNull(Expr $expr, array $propertyNames): bool + private function isLocalPropertyOfNamesNotIdenticalToNull(\PhpParser\Node\Expr $expr, array $propertyNames) : bool { - if (! $expr instanceof NotIdentical) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical) { + return \false; } - - if ($this->propertyFetchAnalyzer->isLocalPropertyOfNames( - $expr->left, - $propertyNames - ) && $this->valueResolver->isNull($expr->right)) { - return true; + if ($this->propertyFetchAnalyzer->isLocalPropertyOfNames($expr->left, $propertyNames) && $this->valueResolver->isNull($expr->right)) { + return \true; } - - if (! $this->propertyFetchAnalyzer->isLocalPropertyOfNames($expr->right, $propertyNames)) { - return false; + if (!$this->propertyFetchAnalyzer->isLocalPropertyOfNames($expr->right, $propertyNames)) { + return \false; } - return $this->valueResolver->isNull($expr->left); } } diff --git a/rules/CodingStyle/Rector/Encapsed/EncapsedStringsToSprintfRector.php b/rules/CodingStyle/Rector/Encapsed/EncapsedStringsToSprintfRector.php index 3792bacb2f5..73fd97f5275 100644 --- a/rules/CodingStyle/Rector/Encapsed/EncapsedStringsToSprintfRector.php +++ b/rules/CodingStyle/Rector/Encapsed/EncapsedStringsToSprintfRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Encapsed::class]; + return [\PhpParser\Node\Scalar\Encapsed::class]; } - /** * @param Encapsed $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $this->sprintfFormat = ''; $this->argumentVariables = []; - foreach ($node->parts as $part) { - if ($part instanceof EncapsedStringPart) { + if ($part instanceof \PhpParser\Node\Scalar\EncapsedStringPart) { $this->collectEncapsedStringPart($part); - } elseif ($part instanceof Expr) { + } elseif ($part instanceof \PhpParser\Node\Expr) { $this->collectExpr($part); } } - return $this->createSprintfFuncCallOrConcat($this->sprintfFormat, $this->argumentVariables); } - - private function collectEncapsedStringPart(EncapsedStringPart $encapsedStringPart): void + private function collectEncapsedStringPart(\PhpParser\Node\Scalar\EncapsedStringPart $encapsedStringPart) : void { $stringValue = $encapsedStringPart->value; if ($stringValue === "\n") { - $this->argumentVariables[] = new ConstFetch(new Name('PHP_EOL')); + $this->argumentVariables[] = new \PhpParser\Node\Expr\ConstFetch(new \PhpParser\Node\Name('PHP_EOL')); $this->sprintfFormat .= '%s'; return; } - $this->sprintfFormat .= $stringValue; } - - private function collectExpr(Expr $expr): void + private function collectExpr(\PhpParser\Node\Expr $expr) : void { $this->sprintfFormat .= '%s'; - // remove: ${wrap} → $wrap - if ($expr instanceof Variable) { - $expr->setAttribute(AttributeKey::ORIGINAL_NODE, null); + if ($expr instanceof \PhpParser\Node\Expr\Variable) { + $expr->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); } - $this->argumentVariables[] = $expr; } - /** * @param Expr[] $argumentVariables * @return Concat|FuncCall|null */ - private function createSprintfFuncCallOrConcat(string $string, array $argumentVariables): ?Node + private function createSprintfFuncCallOrConcat(string $string, array $argumentVariables) : ?\PhpParser\Node { // special case for variable with PHP_EOL - if ($string === '%s%s' && count($argumentVariables) === 2 && $this->hasEndOfLine($argumentVariables)) { - return new Concat($argumentVariables[0], $argumentVariables[1]); + if ($string === '%s%s' && \count($argumentVariables) === 2 && $this->hasEndOfLine($argumentVariables)) { + return new \PhpParser\Node\Expr\BinaryOp\Concat($argumentVariables[0], $argumentVariables[1]); } - - if (Strings::contains($string, PHP_EOL)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($string, \PHP_EOL)) { return null; } - - $arguments = [new Arg(new String_($string))]; + $arguments = [new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_($string))]; foreach ($argumentVariables as $argumentVariable) { - $arguments[] = new Arg($argumentVariable); + $arguments[] = new \PhpParser\Node\Arg($argumentVariable); } - - return new FuncCall(new Name('sprintf'), $arguments); + return new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('sprintf'), $arguments); } - /** * @param Expr[] $argumentVariables */ - private function hasEndOfLine(array $argumentVariables): bool + private function hasEndOfLine(array $argumentVariables) : bool { foreach ($argumentVariables as $argumentVariable) { - if (! $argumentVariable instanceof ConstFetch) { + if (!$argumentVariable instanceof \PhpParser\Node\Expr\ConstFetch) { continue; } - if ($this->isName($argumentVariable, 'PHP_EOL')) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/CodingStyle/Rector/Encapsed/WrapEncapsedVariableInCurlyBracesRector.php b/rules/CodingStyle/Rector/Encapsed/WrapEncapsedVariableInCurlyBracesRector.php index 3fa1c29c9a6..0adb02ad2e8 100644 --- a/rules/CodingStyle/Rector/Encapsed/WrapEncapsedVariableInCurlyBracesRector.php +++ b/rules/CodingStyle/Rector/Encapsed/WrapEncapsedVariableInCurlyBracesRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Encapsed::class]; + return [\PhpParser\Node\Scalar\Encapsed::class]; } - /** * @param Encapsed $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $startTokenPos = $node->getStartTokenPos(); - $hasVariableBeenWrapped = false; - + $hasVariableBeenWrapped = \false; foreach ($node->parts as $index => $nodePart) { - if ($nodePart instanceof Variable) { - $previousNode = $nodePart->getAttribute(AttributeKey::PREVIOUS_NODE); - $previousNodeEndTokenPosition = $previousNode instanceof Node ? $previousNode->getEndTokenPos() : $startTokenPos; - + if ($nodePart instanceof \PhpParser\Node\Expr\Variable) { + $previousNode = $nodePart->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + $previousNodeEndTokenPosition = $previousNode instanceof \PhpParser\Node ? $previousNode->getEndTokenPos() : $startTokenPos; if ($previousNodeEndTokenPosition + 1 === $nodePart->getStartTokenPos()) { - $hasVariableBeenWrapped = true; - $node->parts[$index] = new Variable($nodePart->name); + $hasVariableBeenWrapped = \true; + $node->parts[$index] = new \PhpParser\Node\Expr\Variable($nodePart->name); } } } - - if (! $hasVariableBeenWrapped) { + if (!$hasVariableBeenWrapped) { return null; } - return $node; } } diff --git a/rules/CodingStyle/Rector/FuncCall/CallUserFuncArrayToVariadicRector.php b/rules/CodingStyle/Rector/FuncCall/CallUserFuncArrayToVariadicRector.php index 3cd7d4c66d0..ddb4c18446b 100644 --- a/rules/CodingStyle/Rector/FuncCall/CallUserFuncArrayToVariadicRector.php +++ b/rules/CodingStyle/Rector/FuncCall/CallUserFuncArrayToVariadicRector.php @@ -1,7 +1,6 @@ arrayCallableToMethodCallFactory = $arrayCallableToMethodCallFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replace call_user_func_array() with variadic', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replace call_user_func_array() with variadic', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -48,8 +42,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -58,68 +51,55 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::ARRAY_SPREAD)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::ARRAY_SPREAD)) { return null; } - - if (! $this->isName($node, 'call_user_func_array')) { + if (!$this->isName($node, 'call_user_func_array')) { return null; } - $firstArgValue = $node->args[0]->value; $secondArgValue = $node->args[1]->value; - - if ($firstArgValue instanceof String_) { + if ($firstArgValue instanceof \PhpParser\Node\Scalar\String_) { $functionName = $this->valueResolver->getValue($firstArgValue); return $this->createFuncCall($secondArgValue, $functionName); } - // method call - if ($firstArgValue instanceof Array_) { + if ($firstArgValue instanceof \PhpParser\Node\Expr\Array_) { return $this->createMethodCall($firstArgValue, $secondArgValue); } - return null; } - - private function createFuncCall(Expr $expr, string $functionName): FuncCall + private function createFuncCall(\PhpParser\Node\Expr $expr, string $functionName) : \PhpParser\Node\Expr\FuncCall { $args = []; $args[] = $this->createUnpackedArg($expr); - return $this->nodeFactory->createFuncCall($functionName, $args); } - - private function createMethodCall(Array_ $array, Expr $secondExpr): ?MethodCall + private function createMethodCall(\PhpParser\Node\Expr\Array_ $array, \PhpParser\Node\Expr $secondExpr) : ?\PhpParser\Node\Expr\MethodCall { $methodCall = $this->arrayCallableToMethodCallFactory->create($array); - if (! $methodCall instanceof MethodCall) { + if (!$methodCall instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - $methodCall->args[] = $this->createUnpackedArg($secondExpr); return $methodCall; } - - private function createUnpackedArg(Expr $expr): Arg + private function createUnpackedArg(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Arg { - return new Arg($expr, false, true); + return new \PhpParser\Node\Arg($expr, \false, \true); } } diff --git a/rules/CodingStyle/Rector/FuncCall/CallUserFuncToMethodCallRector.php b/rules/CodingStyle/Rector/FuncCall/CallUserFuncToMethodCallRector.php index 4f80c29694b..2495aae5623 100644 --- a/rules/CodingStyle/Rector/FuncCall/CallUserFuncToMethodCallRector.php +++ b/rules/CodingStyle/Rector/FuncCall/CallUserFuncToMethodCallRector.php @@ -1,7 +1,6 @@ arrayCallableToMethodCallFactory = $arrayCallableToMethodCallFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Refactor call_user_func() on known class method to a method call', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Refactor call_user_func() on known class method to a method call', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -43,9 +37,7 @@ final class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -54,40 +46,33 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'call_user_func')) { + if (!$this->isName($node, 'call_user_func')) { return null; } - $firstArgValue = $node->args[0]->value; - if (! $firstArgValue instanceof Array_) { + if (!$firstArgValue instanceof \PhpParser\Node\Expr\Array_) { return null; } - $methodCall = $this->arrayCallableToMethodCallFactory->create($firstArgValue); - if (! $methodCall instanceof MethodCall) { + if (!$methodCall instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - $originalArgs = $node->args; unset($originalArgs[0]); - $methodCall->args = $originalArgs; return $methodCall; } diff --git a/rules/CodingStyle/Rector/FuncCall/ConsistentImplodeRector.php b/rules/CodingStyle/Rector/FuncCall/ConsistentImplodeRector.php index c782a3924c6..189de15d5aa 100644 --- a/rules/CodingStyle/Rector/FuncCall/ConsistentImplodeRector.php +++ b/rules/CodingStyle/Rector/FuncCall/ConsistentImplodeRector.php @@ -1,7 +1,6 @@ stringTypeAnalyzer = $stringTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes various implode forms to consistent one', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes various implode forms to consistent one', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run(array $items) @@ -48,8 +40,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run(array $items) @@ -61,47 +52,36 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'implode')) { + if (!$this->isName($node, 'implode')) { return null; } - - if (count($node->args) === 1) { + if (\count($node->args) === 1) { // complete default value '' $node->args[1] = $node->args[0]; - $node->args[0] = new Arg(new String_('')); - + $node->args[0] = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_('')); return $node; } - $firstArgumentValue = $node->args[0]->value; - if ($firstArgumentValue instanceof String_) { + if ($firstArgumentValue instanceof \PhpParser\Node\Scalar\String_) { return null; } - - if (count($node->args) === 2 && $this->stringTypeAnalyzer->isStringOrUnionStringOnlyType( - $node->args[1]->value - )) { - $node->args = array_reverse($node->args); + if (\count($node->args) === 2 && $this->stringTypeAnalyzer->isStringOrUnionStringOnlyType($node->args[1]->value)) { + $node->args = \array_reverse($node->args); } - return $node; } } diff --git a/rules/CodingStyle/Rector/FuncCall/ConsistentPregDelimiterRector.php b/rules/CodingStyle/Rector/FuncCall/ConsistentPregDelimiterRector.php index 8f5d745204c..675ddc47120 100644 --- a/rules/CodingStyle/Rector/FuncCall/ConsistentPregDelimiterRector.php +++ b/rules/CodingStyle/Rector/FuncCall/ConsistentPregDelimiterRector.php @@ -1,10 +1,9 @@ .*?)(?[imsxeADSUXJu]*)$#s'; - /** * All with pattern as 1st argument * @var array */ - private const FUNCTIONS_WITH_REGEX_PATTERN = [ - 'preg_match' => 0, - 'preg_replace_callback_array' => 0, - 'preg_replace_callback' => 0, - 'preg_replace' => 0, - 'preg_match_all' => 0, - 'preg_split' => 0, - 'preg_grep' => 0, - ]; - + private const FUNCTIONS_WITH_REGEX_PATTERN = ['preg_match' => 0, 'preg_replace_callback_array' => 0, 'preg_replace_callback' => 0, 'preg_replace' => 0, 'preg_match_all' => 0, 'preg_split' => 0, 'preg_grep' => 0]; /** * All with pattern as 2st argument * @var array> */ - private const STATIC_METHODS_WITH_REGEX_PATTERN = [ - 'Nette\Utils\Strings' => [ - 'match' => 1, - 'matchAll' => 1, - 'replace' => 1, - 'split' => 1, - ], - ]; - + private const STATIC_METHODS_WITH_REGEX_PATTERN = ['Nette\\Utils\\Strings' => ['match' => 1, 'matchAll' => 1, 'replace' => 1, 'split' => 1]]; /** * @var string */ private $delimiter = '#'; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replace PREG delimiter with configured one', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replace PREG delimiter with configured one', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -81,8 +57,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -92,94 +67,71 @@ class SomeClass } } CODE_SAMPLE -, - [ - self::DELIMITER => '#', - ] - ), - ]); +, [self::DELIMITER => '#'])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class, StaticCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param FuncCall|StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof FuncCall) { + if ($node instanceof \PhpParser\Node\Expr\FuncCall) { return $this->refactorFuncCall($node); } - foreach (self::STATIC_METHODS_WITH_REGEX_PATTERN as $type => $methodsToPositions) { - if (! $this->isObjectType($node->class, new ObjectType($type))) { + if (!$this->isObjectType($node->class, new \PHPStan\Type\ObjectType($type))) { continue; } - foreach ($methodsToPositions as $method => $position) { - if (! $this->isName($node->name, $method)) { + if (!$this->isName($node->name, $method)) { continue; } - $this->refactorArgument($node->args[$position]); - return $node; } } - return null; } - - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->delimiter = $configuration[self::DELIMITER] ?? '#'; } - - private function refactorFuncCall(FuncCall $funcCall): ?FuncCall + private function refactorFuncCall(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr\FuncCall { foreach (self::FUNCTIONS_WITH_REGEX_PATTERN as $function => $position) { - if (! $this->isName($funcCall, $function)) { + if (!$this->isName($funcCall, $function)) { continue; } - $this->refactorArgument($funcCall->args[$position]); - return $funcCall; } - return null; } - - private function refactorArgument(Arg $arg): void + private function refactorArgument(\PhpParser\Node\Arg $arg) : void { - if (! $arg->value instanceof String_) { + if (!$arg->value instanceof \PhpParser\Node\Scalar\String_) { return; } - /** @var String_ $string */ $string = $arg->value; $value = $string->value; - - $string->value = Strings::replace($value, self::INNER_REGEX, function (array $match): string { + $string->value = \RectorPrefix20210509\Nette\Utils\Strings::replace($value, self::INNER_REGEX, function (array $match) : string { $innerPattern = $match['content']; - $positionDelimiter = strpos($innerPattern, $this->delimiter); - + $positionDelimiter = \strpos($innerPattern, $this->delimiter); if ($positionDelimiter > 0) { - $innerPattern = str_replace($this->delimiter, '\\' . $this->delimiter, $innerPattern); + $innerPattern = \str_replace($this->delimiter, '\\' . $this->delimiter, $innerPattern); } - // change delimiter - if (strlen($innerPattern) > 2 && $innerPattern[0] === $innerPattern[strlen($innerPattern) - 1]) { + if (\strlen($innerPattern) > 2 && $innerPattern[0] === $innerPattern[\strlen($innerPattern) - 1]) { $innerPattern[0] = $this->delimiter; - $innerPattern[strlen($innerPattern) - 1] = $this->delimiter; + $innerPattern[\strlen($innerPattern) - 1] = $this->delimiter; } - return $innerPattern . $match['close']; }); } diff --git a/rules/CodingStyle/Rector/FuncCall/CountArrayToEmptyArrayComparisonRector.php b/rules/CodingStyle/Rector/FuncCall/CountArrayToEmptyArrayComparisonRector.php index adfd3521ca4..277e34b330f 100644 --- a/rules/CodingStyle/Rector/FuncCall/CountArrayToEmptyArrayComparisonRector.php +++ b/rules/CodingStyle/Rector/FuncCall/CountArrayToEmptyArrayComparisonRector.php @@ -1,7 +1,6 @@ 0; ! count($array); CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $array === []; $array !== []; $array === []; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class, BooleanNot::class]; + return [\PhpParser\Node\Expr\FuncCall::class, \PhpParser\Node\Expr\BooleanNot::class]; } - /** * @param FuncCall|BooleanNot $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof BooleanNot) { + if ($node instanceof \PhpParser\Node\Expr\BooleanNot) { return $this->processMarkTruthyNegation($node); } - - if (! $this->isName($node, 'count')) { + if (!$this->isName($node, 'count')) { return null; } - /** @var Expr $expr */ $expr = $node->args[0]->value; - // not pass array type, skip - if (! $this->isArray($expr)) { + if (!$this->isArray($expr)) { return null; } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - - if (! $parent instanceof Node) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node) { return null; } - $processIdentical = $this->processIdentical($parent, $node, $expr); if ($processIdentical !== null) { return $processIdentical; } - $processGreaterOrSmaller = $this->processGreaterOrSmaller($parent, $node, $expr); if ($processGreaterOrSmaller !== null) { return $processGreaterOrSmaller; } - return $this->processMarkTruthy($parent, $node, $expr); } - - private function processMarkTruthyNegation(BooleanNot $booleanNot): ?Identical + private function processMarkTruthyNegation(\PhpParser\Node\Expr\BooleanNot $booleanNot) : ?\PhpParser\Node\Expr\BinaryOp\Identical { - if (! $booleanNot->expr instanceof FuncCall) { + if (!$booleanNot->expr instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->isName($booleanNot->expr, 'count')) { + if (!$this->isName($booleanNot->expr, 'count')) { return null; } - /** @var Expr $expr */ $expr = $booleanNot->expr->args[0]->value; - // not pass array type, skip - if (! $this->isArray($expr)) { + if (!$this->isArray($expr)) { return null; } - - return new Identical($expr, new Array_([])); + return new \PhpParser\Node\Expr\BinaryOp\Identical($expr, new \PhpParser\Node\Expr\Array_([])); } - - private function isArray(Expr $expr): bool + private function isArray(\PhpParser\Node\Expr $expr) : bool { /** @var Scope|null $scope */ - $scope = $expr->getAttribute(AttributeKey::SCOPE); - - if (! $scope instanceof Scope) { - return false; + $scope = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - - return $scope->getType($expr) instanceof ArrayType; + return $scope->getType($expr) instanceof \PHPStan\Type\ArrayType; } - - private function processIdentical(Node $node, FuncCall $funcCall, Expr $expr): ?Expr + private function processIdentical(\PhpParser\Node $node, \PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr { - if ($node instanceof Identical && $node->right instanceof LNumber && $node->right->value === 0) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Identical && $node->right instanceof \PhpParser\Node\Scalar\LNumber && $node->right->value === 0) { $this->removeNode($funcCall); - $node->right = new Array_([]); - + $node->right = new \PhpParser\Node\Expr\Array_([]); return $expr; } - - if ($node instanceof Identical && $node->left instanceof LNumber && $node->left->value === 0) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Identical && $node->left instanceof \PhpParser\Node\Scalar\LNumber && $node->left->value === 0) { $this->removeNode($funcCall); - $node->left = new Array_([]); - + $node->left = new \PhpParser\Node\Expr\Array_([]); return $expr; } - return null; } - - private function processGreaterOrSmaller(Node $node, FuncCall $funcCall, Expr $expr): ?NotIdentical + private function processGreaterOrSmaller(\PhpParser\Node $node, \PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr\BinaryOp\NotIdentical { - if ($node instanceof Greater && $node->right instanceof LNumber && $node->right->value === 0) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Greater && $node->right instanceof \PhpParser\Node\Scalar\LNumber && $node->right->value === 0) { $this->removeNode($funcCall); $this->removeNode($node->right); - - return new NotIdentical($expr, new Array_([])); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, new \PhpParser\Node\Expr\Array_([])); } - - if ($node instanceof Smaller && $node->left instanceof LNumber && $node->left->value === 0) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Smaller && $node->left instanceof \PhpParser\Node\Scalar\LNumber && $node->left->value === 0) { $this->removeNode($funcCall); $this->removeNode($node->left); - - return new NotIdentical(new Array_([]), $expr); + return new \PhpParser\Node\Expr\BinaryOp\NotIdentical(new \PhpParser\Node\Expr\Array_([]), $expr); } - return null; } - - private function processMarkTruthy(Node $node, FuncCall $funcCall, Expr $expr): ?Expr + private function processMarkTruthy(\PhpParser\Node $node, \PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr { - if (! $node instanceof If_ && ! $node instanceof ElseIf_) { + if (!$node instanceof \PhpParser\Node\Stmt\If_ && !$node instanceof \PhpParser\Node\Stmt\ElseIf_) { return null; } - if ($node->cond === $funcCall) { - $node->cond = new NotIdentical($expr, new Array_([])); + $node->cond = new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, new \PhpParser\Node\Expr\Array_([])); return $node->cond; } - return null; } } diff --git a/rules/CodingStyle/Rector/FuncCall/PreslashSimpleFunctionRector.php b/rules/CodingStyle/Rector/FuncCall/PreslashSimpleFunctionRector.php index 3c07de8c990..a503bcd6fbf 100644 --- a/rules/CodingStyle/Rector/FuncCall/PreslashSimpleFunctionRector.php +++ b/rules/CodingStyle/Rector/FuncCall/PreslashSimpleFunctionRector.php @@ -1,31 +1,25 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node->name instanceof FullyQualified) { + if ($node->name instanceof \PhpParser\Node\Name\FullyQualified) { return null; } - $functionName = $this->getName($node); if ($functionName === null) { return null; } - - if (Strings::contains($functionName, '\\')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($functionName, '\\')) { return null; } - - $node->name = new FullyQualified($functionName); - + $node->name = new \PhpParser\Node\Name\FullyQualified($functionName); return $node; } } diff --git a/rules/CodingStyle/Rector/FuncCall/StrictArraySearchRector.php b/rules/CodingStyle/Rector/FuncCall/StrictArraySearchRector.php index 8209ed40766..ca2dbb3be07 100644 --- a/rules/CodingStyle/Rector/FuncCall/StrictArraySearchRector.php +++ b/rules/CodingStyle/Rector/FuncCall/StrictArraySearchRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'array_search')) { + if (!$this->isName($node, 'array_search')) { return null; } - - if (count($node->args) === 2) { + if (\count($node->args) === 2) { $node->args[2] = $this->nodeFactory->createArg($this->nodeFactory->createTrue()); } - return $node; } } diff --git a/rules/CodingStyle/Rector/FuncCall/VersionCompareFuncCallToConstantRector.php b/rules/CodingStyle/Rector/FuncCall/VersionCompareFuncCallToConstantRector.php index b924eb6337e..6d0f49d314d 100644 --- a/rules/CodingStyle/Rector/FuncCall/VersionCompareFuncCallToConstantRector.php +++ b/rules/CodingStyle/Rector/FuncCall/VersionCompareFuncCallToConstantRector.php @@ -1,10 +1,9 @@ > */ - private const OPERATOR_TO_COMPARISON = [ - '=' => Identical::class, - '==' => Identical::class, - 'eq' => Identical::class, - '!=' => NotIdentical::class, - '<>' => NotIdentical::class, - 'ne' => NotIdentical::class, - '>' => Greater::class, - 'gt' => Greater::class, - '<' => Smaller::class, - 'lt' => Smaller::class, - '>=' => GreaterOrEqual::class, - 'ge' => GreaterOrEqual::class, - '<=' => SmallerOrEqual::class, - 'le' => SmallerOrEqual::class, - ]; - + private const OPERATOR_TO_COMPARISON = ['=' => \PhpParser\Node\Expr\BinaryOp\Identical::class, '==' => \PhpParser\Node\Expr\BinaryOp\Identical::class, 'eq' => \PhpParser\Node\Expr\BinaryOp\Identical::class, '!=' => \PhpParser\Node\Expr\BinaryOp\NotIdentical::class, '<>' => \PhpParser\Node\Expr\BinaryOp\NotIdentical::class, 'ne' => \PhpParser\Node\Expr\BinaryOp\NotIdentical::class, '>' => \PhpParser\Node\Expr\BinaryOp\Greater::class, 'gt' => \PhpParser\Node\Expr\BinaryOp\Greater::class, '<' => \PhpParser\Node\Expr\BinaryOp\Smaller::class, 'lt' => \PhpParser\Node\Expr\BinaryOp\Smaller::class, '>=' => \PhpParser\Node\Expr\BinaryOp\GreaterOrEqual::class, 'ge' => \PhpParser\Node\Expr\BinaryOp\GreaterOrEqual::class, '<=' => \PhpParser\Node\Expr\BinaryOp\SmallerOrEqual::class, 'le' => \PhpParser\Node\Expr\BinaryOp\SmallerOrEqual::class]; /** * @var string * @see https://regex101.com/r/yl9g25/1 */ - private const SEMANTIC_VERSION_REGEX = '#^\d+\.\d+\.\d+$#'; - - public function getRuleDefinition(): RuleDefinition + private const SEMANTIC_VERSION_REGEX = '#^\\d+\\.\\d+\\.\\d+$#'; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes use of call to version compare function to use of PHP version constant', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes use of call to version compare function to use of PHP version constant', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -70,8 +47,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -80,77 +56,59 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'version_compare')) { + if (!$this->isName($node, 'version_compare')) { return null; } - - if (count($node->args) !== 3) { + if (\count($node->args) !== 3) { return null; } - - if (! $this->isPhpVersionConstant($node->args[0]->value) && ! $this->isPhpVersionConstant( - $node->args[1]->value - )) { + if (!$this->isPhpVersionConstant($node->args[0]->value) && !$this->isPhpVersionConstant($node->args[1]->value)) { return null; } - $left = $this->getNewNodeForArg($node->args[0]->value); $right = $this->getNewNodeForArg($node->args[1]->value); - /** @var String_ $operator */ $operator = $node->args[2]->value; $comparisonClass = self::OPERATOR_TO_COMPARISON[$operator->value]; - return new $comparisonClass($left, $right); } - - private function isPhpVersionConstant(Expr $expr): bool + private function isPhpVersionConstant(\PhpParser\Node\Expr $expr) : bool { - if (! $expr instanceof ConstFetch) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\ConstFetch) { + return \false; } return $expr->name->toString() === 'PHP_VERSION'; } - - private function getNewNodeForArg(Expr $expr): Expr + private function getNewNodeForArg(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { if ($this->isPhpVersionConstant($expr)) { - return new ConstFetch(new Name('PHP_VERSION_ID')); + return new \PhpParser\Node\Expr\ConstFetch(new \PhpParser\Node\Name('PHP_VERSION_ID')); } - return $this->getVersionNumberFormVersionString($expr); } - - private function getVersionNumberFormVersionString(Expr $expr): LNumber + private function getVersionNumberFormVersionString(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Scalar\LNumber { - if (! $expr instanceof String_) { - throw new ShouldNotHappenException(); + if (!$expr instanceof \PhpParser\Node\Scalar\String_) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - if (! Strings::match($expr->value, self::SEMANTIC_VERSION_REGEX)) { - throw new ShouldNotHappenException(); + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($expr->value, self::SEMANTIC_VERSION_REGEX)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $versionParts = explode('.', $expr->value); - - return new LNumber((int) $versionParts[0] * 10000 + (int) $versionParts[1] * 100 + (int) $versionParts[2]); + $versionParts = \explode('.', $expr->value); + return new \PhpParser\Node\Scalar\LNumber((int) $versionParts[0] * 10000 + (int) $versionParts[1] * 100 + (int) $versionParts[2]); } } diff --git a/rules/CodingStyle/Rector/If_/NullableCompareToNullRector.php b/rules/CodingStyle/Rector/If_/NullableCompareToNullRector.php index 58f858ba204..411393facb9 100644 --- a/rules/CodingStyle/Rector/If_/NullableCompareToNullRector.php +++ b/rules/CodingStyle/Rector/If_/NullableCompareToNullRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node->cond instanceof BooleanNot && $this->isNullableNonScalarType($node->cond->expr)) { - $node->cond = new Identical($node->cond->expr, $this->nodeFactory->createNull()); - + if ($node->cond instanceof \PhpParser\Node\Expr\BooleanNot && $this->isNullableNonScalarType($node->cond->expr)) { + $node->cond = new \PhpParser\Node\Expr\BinaryOp\Identical($node->cond->expr, $this->nodeFactory->createNull()); return $node; } - if ($this->isNullableNonScalarType($node->cond)) { - $node->cond = new NotIdentical($node->cond, $this->nodeFactory->createNull()); - + $node->cond = new \PhpParser\Node\Expr\BinaryOp\NotIdentical($node->cond, $this->nodeFactory->createNull()); return $node; } - return null; } - - private function isNullableNonScalarType(Node $node): bool + private function isNullableNonScalarType(\PhpParser\Node $node) : bool { $staticType = $this->getStaticType($node); - if ($staticType instanceof MixedType) { - return false; + if ($staticType instanceof \PHPStan\Type\MixedType) { + return \false; } - - if (! $staticType instanceof UnionType) { - return false; + if (!$staticType instanceof \PHPStan\Type\UnionType) { + return \false; } - // is non-nullable? - if ($staticType->isSuperTypeOf(new NullType())->no()) { - return false; + if ($staticType->isSuperTypeOf(new \PHPStan\Type\NullType())->no()) { + return \false; } - // is array? foreach ($staticType->getTypes() as $subType) { - if ($subType instanceof ArrayType) { - return false; + if ($subType instanceof \PHPStan\Type\ArrayType) { + return \false; } } - // is string? - if ($staticType->isSuperTypeOf(new StringType())->yes()) { - return false; + if ($staticType->isSuperTypeOf(new \PHPStan\Type\StringType())->yes()) { + return \false; } - // is number? - if ($staticType->isSuperTypeOf(new IntegerType())->yes()) { - return false; + if ($staticType->isSuperTypeOf(new \PHPStan\Type\IntegerType())->yes()) { + return \false; } - // is bool? - if ($staticType->isSuperTypeOf(new BooleanType())->yes()) { - return false; + if ($staticType->isSuperTypeOf(new \PHPStan\Type\BooleanType())->yes()) { + return \false; } - - return ! $staticType->isSuperTypeOf(new FloatType()) - ->yes(); + return !$staticType->isSuperTypeOf(new \PHPStan\Type\FloatType())->yes(); } } diff --git a/rules/CodingStyle/Rector/Include_/FollowRequireByDirRector.php b/rules/CodingStyle/Rector/Include_/FollowRequireByDirRector.php index 9909214479c..ddcd9883368 100644 --- a/rules/CodingStyle/Rector/Include_/FollowRequireByDirRector.php +++ b/rules/CodingStyle/Rector/Include_/FollowRequireByDirRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Include_::class]; + return [\PhpParser\Node\Expr\Include_::class]; } - /** * @param Include_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node->expr instanceof Concat && $node->expr->left instanceof String_ && $this->isRefactorableStringPath( - $node->expr->left - )) { + if ($node->expr instanceof \PhpParser\Node\Expr\BinaryOp\Concat && $node->expr->left instanceof \PhpParser\Node\Scalar\String_ && $this->isRefactorableStringPath($node->expr->left)) { $node->expr->left = $this->prefixWithDir($node->expr->left); - return $node; } - - if ($node->expr instanceof String_ && $this->isRefactorableStringPath($node->expr)) { + if ($node->expr instanceof \PhpParser\Node\Scalar\String_ && $this->isRefactorableStringPath($node->expr)) { $node->expr = $this->prefixWithDir($node->expr); - return $node; } // nothing we can do return null; } - - private function isRefactorableStringPath(String_ $string): bool + private function isRefactorableStringPath(\PhpParser\Node\Scalar\String_ $string) : bool { - return ! Strings::startsWith($string->value, 'phar://'); + return !\RectorPrefix20210509\Nette\Utils\Strings::startsWith($string->value, 'phar://'); } - - private function prefixWithDir(String_ $string): Concat + private function prefixWithDir(\PhpParser\Node\Scalar\String_ $string) : \PhpParser\Node\Expr\BinaryOp\Concat { $this->removeExtraDotSlash($string); $this->prependSlashIfMissing($string); - - return new Concat(new Dir(), $string); + return new \PhpParser\Node\Expr\BinaryOp\Concat(new \PhpParser\Node\Scalar\MagicConst\Dir(), $string); } - /** * Remove "./" which would break the path */ - private function removeExtraDotSlash(String_ $string): void + private function removeExtraDotSlash(\PhpParser\Node\Scalar\String_ $string) : void { - if (! Strings::startsWith($string->value, './')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::startsWith($string->value, './')) { return; } - - $string->value = Strings::replace($string->value, '#^\.\/#', '/'); + $string->value = \RectorPrefix20210509\Nette\Utils\Strings::replace($string->value, '#^\\.\\/#', '/'); } - - private function prependSlashIfMissing(String_ $string): void + private function prependSlashIfMissing(\PhpParser\Node\Scalar\String_ $string) : void { - if (Strings::startsWith($string->value, '/')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::startsWith($string->value, '/')) { return; } - $string->value = '/' . $string->value; } } diff --git a/rules/CodingStyle/Rector/MethodCall/PreferThisOrSelfMethodCallRector.php b/rules/CodingStyle/Rector/MethodCall/PreferThisOrSelfMethodCallRector.php index 0d537461869..eeb7d98c747 100644 --- a/rules/CodingStyle/Rector/MethodCall/PreferThisOrSelfMethodCallRector.php +++ b/rules/CodingStyle/Rector/MethodCall/PreferThisOrSelfMethodCallRector.php @@ -1,7 +1,6 @@ */ private $typeToPreference = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes $this->... and static:: to self:: or vise versa for given types', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes $this->... and static:: to self:: or vise versa for given types', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass extends \PHPUnit\Framework\TestCase { public function run() @@ -50,8 +43,7 @@ class SomeClass extends \PHPUnit\Framework\TestCase } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass extends \PHPUnit\Framework\TestCase { public function run() @@ -60,112 +52,82 @@ class SomeClass extends \PHPUnit\Framework\TestCase } } CODE_SAMPLE - , - [ - self::TYPE_TO_PREFERENCE => [ - 'PHPUnit\Framework\TestCase' => PreferenceSelfThis::PREFER_SELF, - ], - ] - ), - ]); +, [self::TYPE_TO_PREFERENCE => ['PHPUnit\\Framework\\TestCase' => \Rector\CodingStyle\ValueObject\PreferenceSelfThis::PREFER_SELF]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class, StaticCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param MethodCall|StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->typeToPreference as $type => $preference) { - if (! $this->nodeTypeResolver->isMethodStaticCallOrClassMethodObjectType($node, new ObjectType($type))) { + if (!$this->nodeTypeResolver->isMethodStaticCallOrClassMethodObjectType($node, new \PHPStan\Type\ObjectType($type))) { continue; } - - if ($preference === PreferenceSelfThis::PREFER_SELF) { + if ($preference === \Rector\CodingStyle\ValueObject\PreferenceSelfThis::PREFER_SELF) { return $this->processToSelf($node); } - return $this->processToThis($node); } - return null; } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $typeToPreference = $configuration[self::TYPE_TO_PREFERENCE] ?? []; - Assert::allString($typeToPreference); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allString($typeToPreference); foreach ($typeToPreference as $singleTypeToPreference) { $this->ensurePreferenceIsValid($singleTypeToPreference); } - $this->typeToPreference = $typeToPreference; } - /** * @param MethodCall|StaticCall $node */ - private function processToSelf(Node $node): ?StaticCall + private function processToSelf(\PhpParser\Node $node) : ?\PhpParser\Node\Expr\StaticCall { - if ($node instanceof StaticCall && ! $this->isNames($node->class, [self::SELF, 'static'])) { + if ($node instanceof \PhpParser\Node\Expr\StaticCall && !$this->isNames($node->class, [self::SELF, 'static'])) { return null; } - - if ($node instanceof MethodCall && ! $this->isName($node->var, 'this')) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall && !$this->isName($node->var, 'this')) { return null; } - $name = $this->getName($node->name); if ($name === null) { return null; } - return $this->nodeFactory->createStaticCall(self::SELF, $name, $node->args); } - /** * @param MethodCall|StaticCall $node */ - private function processToThis(Node $node): ?MethodCall + private function processToThis(\PhpParser\Node $node) : ?\PhpParser\Node\Expr\MethodCall { - if ($node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - - if (! $this->isNames($node->class, [self::SELF, 'static'])) { + if (!$this->isNames($node->class, [self::SELF, 'static'])) { return null; } - $name = $this->getName($node->name); if ($name === null) { return null; } - return $this->nodeFactory->createMethodCall('this', $name, $node->args); } - - private function ensurePreferenceIsValid(string $preference): void + private function ensurePreferenceIsValid(string $preference) : void { - if (in_array($preference, PreferenceSelfThis::ALLOWED_VALUES, true)) { + if (\in_array($preference, \Rector\CodingStyle\ValueObject\PreferenceSelfThis::ALLOWED_VALUES, \true)) { return; } - - throw new InvalidConfigurationException(sprintf( - 'Preference configuration "%s" for "%s" is not valid. Use one of "%s"', - $preference, - self::class, - implode('", "', PreferenceSelfThis::ALLOWED_VALUES) - )); + throw new \Rector\Core\Exception\Configuration\InvalidConfigurationException(\sprintf('Preference configuration "%s" for "%s" is not valid. Use one of "%s"', $preference, self::class, \implode('", "', \Rector\CodingStyle\ValueObject\PreferenceSelfThis::ALLOWED_VALUES))); } } diff --git a/rules/CodingStyle/Rector/MethodCall/UseMessageVariableForSprintfInSymfonyStyleRector.php b/rules/CodingStyle/Rector/MethodCall/UseMessageVariableForSprintfInSymfonyStyleRector.php index 8ca3ca43fd3..cbd870b5cf2 100644 --- a/rules/CodingStyle/Rector/MethodCall/UseMessageVariableForSprintfInSymfonyStyleRector.php +++ b/rules/CodingStyle/Rector/MethodCall/UseMessageVariableForSprintfInSymfonyStyleRector.php @@ -1,7 +1,6 @@ symfonyStyle->method()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Decouple $message property from sprintf() calls in $this->symfonyStyle->method()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' use Symfony\Component\Console\Style\SymfonyStyle; final class SomeClass @@ -36,8 +30,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use Symfony\Component\Console\Style\SymfonyStyle; final class SomeClass @@ -49,47 +42,37 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isObjectType($node->var, new ObjectType('Symfony\Component\Console\Style\SymfonyStyle'))) { + if (!$this->isObjectType($node->var, new \PHPStan\Type\ObjectType('Symfony\\Component\\Console\\Style\\SymfonyStyle'))) { return null; } - - if (! isset($node->args[0])) { + if (!isset($node->args[0])) { return null; } - $argValue = $node->args[0]->value; - if (! $argValue instanceof FuncCall) { + if (!$argValue instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->nodeNameResolver->isName($argValue, 'sprintf')) { + if (!$this->nodeNameResolver->isName($argValue, 'sprintf')) { return null; } - - $messageVariable = new Variable('message'); - $assign = new Assign($messageVariable, $argValue); + $messageVariable = new \PhpParser\Node\Expr\Variable('message'); + $assign = new \PhpParser\Node\Expr\Assign($messageVariable, $argValue); $this->addNodeBeforeNode($assign, $node); - $node->args[0]->value = $messageVariable; - return $node; } } diff --git a/rules/CodingStyle/Rector/Plus/UseIncrementAssignRector.php b/rules/CodingStyle/Rector/Plus/UseIncrementAssignRector.php index e854e606ba5..3dd3a46ed41 100644 --- a/rules/CodingStyle/Rector/Plus/UseIncrementAssignRector.php +++ b/rules/CodingStyle/Rector/Plus/UseIncrementAssignRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Plus::class, Minus::class]; + return [\PhpParser\Node\Expr\AssignOp\Plus::class, \PhpParser\Node\Expr\AssignOp\Minus::class]; } - /** * @param Plus|Minus $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof LNumber) { + if (!$node->expr instanceof \PhpParser\Node\Scalar\LNumber) { return null; } - if ($node->expr->value !== 1) { return null; } - - if ($node instanceof Plus) { - return new PreInc($node->var); + if ($node instanceof \PhpParser\Node\Expr\AssignOp\Plus) { + return new \PhpParser\Node\Expr\PreInc($node->var); } - - return new PreDec($node->var); + return new \PhpParser\Node\Expr\PreDec($node->var); } } diff --git a/rules/CodingStyle/Rector/PostInc/PostIncDecToPreIncDecRector.php b/rules/CodingStyle/Rector/PostInc/PostIncDecToPreIncDecRector.php index e621d5cd222..cae6c9989fc 100644 --- a/rules/CodingStyle/Rector/PostInc/PostIncDecToPreIncDecRector.php +++ b/rules/CodingStyle/Rector/PostInc/PostIncDecToPreIncDecRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [PostInc::class, PostDec::class]; + return [\PhpParser\Node\Expr\PostInc::class, \PhpParser\Node\Expr\PostDec::class]; } - /** * @param PostInc|PostDec $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); if ($this->isAnExpression($parentNode)) { return $this->processPrePost($node); } - - if ($parentNode instanceof ArrayDimFetch && $this->nodeComparator->areNodesEqual($parentNode->dim, $node)) { + if ($parentNode instanceof \PhpParser\Node\Expr\ArrayDimFetch && $this->nodeComparator->areNodesEqual($parentNode->dim, $node)) { return $this->processPreArray($node, $parentNode); } - if (! $parentNode instanceof For_) { + if (!$parentNode instanceof \PhpParser\Node\Stmt\For_) { return null; } - if (count($parentNode->loop) !== 1) { + if (\count($parentNode->loop) !== 1) { return null; } - if (! $this->nodeComparator->areNodesEqual($parentNode->loop[0], $node)) { + if (!$this->nodeComparator->areNodesEqual($parentNode->loop[0], $node)) { return null; } return $this->processPreFor($node, $parentNode); } - - private function isAnExpression(?Node $node = null): bool + private function isAnExpression(?\PhpParser\Node $node = null) : bool { - if (! $node instanceof Node) { - return false; + if (!$node instanceof \PhpParser\Node) { + return \false; } - return $node instanceof Expression; + return $node instanceof \PhpParser\Node\Stmt\Expression; } - /** * @param PostInc|PostDec $node */ - private function processPrePost(Node $node): Expr + private function processPrePost(\PhpParser\Node $node) : \PhpParser\Node\Expr { - if ($node instanceof PostInc) { - return new PreInc($node->var); + if ($node instanceof \PhpParser\Node\Expr\PostInc) { + return new \PhpParser\Node\Expr\PreInc($node->var); } - - return new PreDec($node->var); + return new \PhpParser\Node\Expr\PreDec($node->var); } - /** * @param PostInc|PostDec $node */ - private function processPreArray(Node $node, ArrayDimFetch $arrayDimFetch): ?Expr + private function processPreArray(\PhpParser\Node $node, \PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : ?\PhpParser\Node\Expr { - $parentOfArrayDimFetch = $arrayDimFetch->getAttribute(AttributeKey::PARENT_NODE); - if (! $this->isAnExpression($parentOfArrayDimFetch)) { + $parentOfArrayDimFetch = $arrayDimFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$this->isAnExpression($parentOfArrayDimFetch)) { return null; } - $arrayDimFetch->dim = $node->var; $this->addNodeAfterNode($this->processPrePost($node), $arrayDimFetch); - return $arrayDimFetch->dim; } - /** * @param PostInc|PostDec $node */ - private function processPreFor(Node $node, For_ $for): Expr + private function processPreFor(\PhpParser\Node $node, \PhpParser\Node\Stmt\For_ $for) : \PhpParser\Node\Expr { $for->loop = [$this->processPrePost($node)]; return $for->loop[0]; diff --git a/rules/CodingStyle/Rector/Property/AddFalseDefaultToBoolPropertyRector.php b/rules/CodingStyle/Rector/Property/AddFalseDefaultToBoolPropertyRector.php index 6be58af64db..5fe3f1bcb53 100644 --- a/rules/CodingStyle/Rector/Property/AddFalseDefaultToBoolPropertyRector.php +++ b/rules/CodingStyle/Rector/Property/AddFalseDefaultToBoolPropertyRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (count($node->props) !== 1) { + if (\count($node->props) !== 1) { return null; } - $onlyProperty = $node->props[0]; if ($onlyProperty->default !== null) { return null; } - - if (! $this->isBoolDocType($node)) { + if (!$this->isBoolDocType($node)) { return null; } - $onlyProperty->default = $this->nodeFactory->createFalse(); - return $node; } - - private function isBoolDocType(Property $property): bool + private function isBoolDocType(\PhpParser\Node\Stmt\Property $property) : bool { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); - return $phpDocInfo->getVarType() instanceof BooleanType; + return $phpDocInfo->getVarType() instanceof \PHPStan\Type\BooleanType; } } diff --git a/rules/CodingStyle/Rector/String_/SplitStringClassConstantToClassConstFetchRector.php b/rules/CodingStyle/Rector/String_/SplitStringClassConstantToClassConstFetchRector.php index c5c3bb8e8ab..468ac50cb3b 100644 --- a/rules/CodingStyle/Rector/String_/SplitStringClassConstantToClassConstFetchRector.php +++ b/rules/CodingStyle/Rector/String_/SplitStringClassConstantToClassConstFetchRector.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Separate class constant in a string to class constant fetch and string', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Separate class constant in a string to class constant fetch and string', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { const HI = true; @@ -49,8 +41,7 @@ class AnotherClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { const HI = true; @@ -64,37 +55,29 @@ class AnotherClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [String_::class]; + return [\PhpParser\Node\Scalar\String_::class]; } - /** * @param String_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (substr_count($node->value, '::') !== 1) { + if (\substr_count($node->value, '::') !== 1) { return null; } - // a possible constant reference - [$possibleClass, $secondPart] = explode('::', $node->value); - - if (! $this->reflectionProvider->hasClass($possibleClass)) { + [$possibleClass, $secondPart] = \explode('::', $node->value); + if (!$this->reflectionProvider->hasClass($possibleClass)) { return null; } - - $classConstFetch = new ClassConstFetch(new FullyQualified(ltrim($possibleClass, '\\')), 'class'); - - return new Concat($classConstFetch, new String_('::' . $secondPart)); + $classConstFetch = new \PhpParser\Node\Expr\ClassConstFetch(new \PhpParser\Node\Name\FullyQualified(\ltrim($possibleClass, '\\')), 'class'); + return new \PhpParser\Node\Expr\BinaryOp\Concat($classConstFetch, new \PhpParser\Node\Scalar\String_('::' . $secondPart)); } } diff --git a/rules/CodingStyle/Rector/String_/SymplifyQuoteEscapeRector.php b/rules/CodingStyle/Rector/String_/SymplifyQuoteEscapeRector.php index b6092649925..a63596c7afd 100644 --- a/rules/CodingStyle/Rector/String_/SymplifyQuoteEscapeRector.php +++ b/rules/CodingStyle/Rector/String_/SymplifyQuoteEscapeRector.php @@ -1,35 +1,28 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [String_::class]; + return [\PhpParser\Node\Scalar\String_::class]; } - /** * @param String_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $doubleQuoteCount = substr_count($node->value, '"'); - $singleQuoteCount = substr_count($node->value, "'"); - $kind = $node->getAttribute(AttributeKey::KIND); - - if ($kind === String_::KIND_SINGLE_QUOTED) { + $doubleQuoteCount = \substr_count($node->value, '"'); + $singleQuoteCount = \substr_count($node->value, "'"); + $kind = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND); + if ($kind === \PhpParser\Node\Scalar\String_::KIND_SINGLE_QUOTED) { $this->processSingleQuoted($node, $doubleQuoteCount, $singleQuoteCount); } - - $quoteKind = $node->getAttribute(AttributeKey::KIND); - if ($quoteKind === String_::KIND_DOUBLE_QUOTED) { + $quoteKind = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND); + if ($quoteKind === \PhpParser\Node\Scalar\String_::KIND_DOUBLE_QUOTED) { $this->processDoubleQuoted($node, $singleQuoteCount, $doubleQuoteCount); } - return $node; } - - private function processSingleQuoted(String_ $string, int $doubleQuoteCount, int $singleQuoteCount): void + private function processSingleQuoted(\PhpParser\Node\Scalar\String_ $string, int $doubleQuoteCount, int $singleQuoteCount) : void { if ($doubleQuoteCount === 0 && $singleQuoteCount > 0) { // contains chars that will be newly escaped if ($this->isMatchEscapedChars($string->value)) { return; } - - $string->setAttribute(AttributeKey::KIND, String_::KIND_DOUBLE_QUOTED); + $string->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND, \PhpParser\Node\Scalar\String_::KIND_DOUBLE_QUOTED); // invoke override - $string->setAttribute(AttributeKey::ORIGINAL_NODE, null); + $string->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); } } - - private function processDoubleQuoted(String_ $string, int $singleQuoteCount, int $doubleQuoteCount): void + private function processDoubleQuoted(\PhpParser\Node\Scalar\String_ $string, int $singleQuoteCount, int $doubleQuoteCount) : void { if ($singleQuoteCount === 0 && $doubleQuoteCount > 0) { // contains chars that will be newly escaped if ($this->isMatchEscapedChars($string->value)) { return; } - - $string->setAttribute(AttributeKey::KIND, String_::KIND_SINGLE_QUOTED); + $string->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND, \PhpParser\Node\Scalar\String_::KIND_SINGLE_QUOTED); // invoke override - $string->setAttribute(AttributeKey::ORIGINAL_NODE, null); + $string->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); } } - - private function isMatchEscapedChars(string $string): bool + private function isMatchEscapedChars(string $string) : bool { - return (bool) Strings::match($string, self::ESCAPED_CHAR_REGEX); + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($string, self::ESCAPED_CHAR_REGEX); } } diff --git a/rules/CodingStyle/Rector/String_/UseClassKeywordForClassNameResolutionRector.php b/rules/CodingStyle/Rector/String_/UseClassKeywordForClassNameResolutionRector.php index c53319583ab..bef7cafc8b4 100644 --- a/rules/CodingStyle/Rector/String_/UseClassKeywordForClassNameResolutionRector.php +++ b/rules/CodingStyle/Rector/String_/UseClassKeywordForClassNameResolutionRector.php @@ -1,10 +1,9 @@ [\\\\a-zA-Z0-9_\\x80-\\xff]*)::#'; - /** * @var ReflectionProvider */ private $reflectionProvider; - - public function __construct(ReflectionProvider $reflectionProvider) + public function __construct(\PHPStan\Reflection\ReflectionProvider $reflectionProvider) { $this->reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Use `class` keyword for class name resolution in string instead of hardcoded string reference', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Use `class` keyword for class name resolution in string instead of hardcoded string reference', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $value = 'App\SomeClass::someMethod()'; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $value = \App\SomeClass . '::someMethod()'; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [String_::class]; + return [\PhpParser\Node\Scalar\String_::class]; } - /** * @param String_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $classNames = $this->getExistingClasses($node); if ($classNames === []) { return $node; } - $parts = $this->getParts($node, $classNames); if ($parts === []) { return null; } - $exprsToConcat = $this->createExpressionsToConcat($parts); return $this->nodeFactory->createConcat($exprsToConcat); } - /** * @return string[] */ - public function getExistingClasses(String_ $string): array + public function getExistingClasses(\PhpParser\Node\Scalar\String_ $string) : array { /** @var mixed[] $matches */ - $matches = Strings::matchAll($string->value, self::CLASS_BEFORE_STATIC_ACCESS_REGEX, PREG_PATTERN_ORDER); - if (! isset($matches['class_name'])) { + $matches = \RectorPrefix20210509\Nette\Utils\Strings::matchAll($string->value, self::CLASS_BEFORE_STATIC_ACCESS_REGEX, \PREG_PATTERN_ORDER); + if (!isset($matches['class_name'])) { return []; } - $classNames = []; - foreach ($matches['class_name'] as $matchedClassName) { - if (! $this->reflectionProvider->hasClass($matchedClassName)) { + if (!$this->reflectionProvider->hasClass($matchedClassName)) { continue; } - $classNames[] = $matchedClassName; } - return $classNames; } - /** * @param string[] $classNames * @return mixed[] */ - public function getParts(String_ $string, array $classNames): array + public function getParts(\PhpParser\Node\Scalar\String_ $string, array $classNames) : array { - $quotedClassNames = array_map('preg_quote', $classNames); - + $quotedClassNames = \array_map('preg_quote', $classNames); // @see https://regex101.com/r/8nGS0F/1 - $parts = Strings::split($string->value, '#(' . implode('|', $quotedClassNames) . ')#'); - - return array_filter($parts, function (string $className): bool { + $parts = \RectorPrefix20210509\Nette\Utils\Strings::split($string->value, '#(' . \implode('|', $quotedClassNames) . ')#'); + return \array_filter($parts, function (string $className) : bool { return $className !== ''; }); } - /** * @param string[] $parts * @return ClassConstFetch[]|String_[] */ - private function createExpressionsToConcat(array $parts): array + private function createExpressionsToConcat(array $parts) : array { $exprsToConcat = []; foreach ($parts as $part) { if ($this->reflectionProvider->hasClass($part)) { - $exprsToConcat[] = new ClassConstFetch(new FullyQualified(ltrim($part, '\\')), 'class'); + $exprsToConcat[] = new \PhpParser\Node\Expr\ClassConstFetch(new \PhpParser\Node\Name\FullyQualified(\ltrim($part, '\\')), 'class'); } else { - $exprsToConcat[] = new String_($part); + $exprsToConcat[] = new \PhpParser\Node\Scalar\String_($part); } } return $exprsToConcat; diff --git a/rules/CodingStyle/Rector/Switch_/BinarySwitchToIfElseRector.php b/rules/CodingStyle/Rector/Switch_/BinarySwitchToIfElseRector.php index 5a17ac8bc08..c31bbe490b6 100644 --- a/rules/CodingStyle/Rector/Switch_/BinarySwitchToIfElseRector.php +++ b/rules/CodingStyle/Rector/Switch_/BinarySwitchToIfElseRector.php @@ -1,7 +1,6 @@ switchManipulator = $switchManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes switch with 2 options to if-else', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes switch with 2 options to if-else', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' switch ($foo) { case 'my string': $result = 'ok'; @@ -46,71 +40,58 @@ switch ($foo) { $result = 'not ok'; } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' if ($foo == 'my string') { $result = 'ok; } else { $result = 'not ok'; } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Switch_::class]; + return [\PhpParser\Node\Stmt\Switch_::class]; } - /** * @param Switch_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (count($node->cases) > 2) { + if (\count($node->cases) > 2) { return null; } - /** @var Case_ $firstCase */ - $firstCase = array_shift($node->cases); + $firstCase = \array_shift($node->cases); if ($firstCase->cond === null) { return null; } - - $secondCase = array_shift($node->cases); - + $secondCase = \array_shift($node->cases); // special case with empty first case → || $isFirstCaseEmpty = $firstCase->stmts === []; if ($isFirstCaseEmpty && $secondCase !== null && $secondCase->cond !== null) { - $else = new BooleanOr(new Equal($node->cond, $firstCase->cond), new Equal($node->cond, $secondCase->cond)); - - $ifNode = new If_($else); + $else = new \PhpParser\Node\Expr\BinaryOp\BooleanOr(new \PhpParser\Node\Expr\BinaryOp\Equal($node->cond, $firstCase->cond), new \PhpParser\Node\Expr\BinaryOp\Equal($node->cond, $secondCase->cond)); + $ifNode = new \PhpParser\Node\Stmt\If_($else); $ifNode->stmts = $this->switchManipulator->removeBreakNodes($secondCase->stmts); - return $ifNode; } - - $ifNode = new If_(new Equal($node->cond, $firstCase->cond)); + $ifNode = new \PhpParser\Node\Stmt\If_(new \PhpParser\Node\Expr\BinaryOp\Equal($node->cond, $firstCase->cond)); $ifNode->stmts = $this->switchManipulator->removeBreakNodes($firstCase->stmts); - // just one condition - if (! $secondCase instanceof Case_) { + if (!$secondCase instanceof \PhpParser\Node\Stmt\Case_) { return $ifNode; } - if ($secondCase->cond !== null) { // has condition - $equal = new Equal($node->cond, $secondCase->cond); - $ifNode->elseifs[] = new ElseIf_($equal, $this->switchManipulator->removeBreakNodes($secondCase->stmts)); + $equal = new \PhpParser\Node\Expr\BinaryOp\Equal($node->cond, $secondCase->cond); + $ifNode->elseifs[] = new \PhpParser\Node\Stmt\ElseIf_($equal, $this->switchManipulator->removeBreakNodes($secondCase->stmts)); } else { // defaults - $ifNode->else = new Else_($this->switchManipulator->removeBreakNodes($secondCase->stmts)); + $ifNode->else = new \PhpParser\Node\Stmt\Else_($this->switchManipulator->removeBreakNodes($secondCase->stmts)); } - return $ifNode; } } diff --git a/rules/CodingStyle/Rector/Ternary/TernaryConditionVariableAssignmentRector.php b/rules/CodingStyle/Rector/Ternary/TernaryConditionVariableAssignmentRector.php index 553f955fbb8..2f9763dad0e 100644 --- a/rules/CodingStyle/Rector/Ternary/TernaryConditionVariableAssignmentRector.php +++ b/rules/CodingStyle/Rector/Ternary/TernaryConditionVariableAssignmentRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $nodeIf = $node->if; $nodeElse = $node->else; - if (! $nodeIf instanceof Assign) { + if (!$nodeIf instanceof \PhpParser\Node\Expr\Assign) { return null; } - if (! $nodeElse instanceof Assign) { + if (!$nodeElse instanceof \PhpParser\Node\Expr\Assign) { return null; } - $nodeIfVar = $nodeIf->var; $nodeElseVar = $nodeElse->var; - if (! $nodeIfVar instanceof Variable) { + if (!$nodeIfVar instanceof \PhpParser\Node\Expr\Variable) { return null; } - if (! $nodeElseVar instanceof Variable) { + if (!$nodeElseVar instanceof \PhpParser\Node\Expr\Variable) { return null; } - if ($nodeIfVar->name !== $nodeElseVar->name) { return null; } - - $previousNode = $node->getAttribute(AttributeKey::PREVIOUS_NODE); + $previousNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); if ($previousNode !== null) { return null; } - $node->if = $nodeIf->expr; $node->else = $nodeElse->expr; - - $variable = new Variable($nodeIfVar->name); - - return new Assign($variable, $node); + $variable = new \PhpParser\Node\Expr\Variable($nodeIfVar->name); + return new \PhpParser\Node\Expr\Assign($variable, $node); } } diff --git a/rules/CodingStyle/Rector/Use_/RemoveUnusedAliasRector.php b/rules/CodingStyle/Rector/Use_/RemoveUnusedAliasRector.php index cbcb7b86e29..14d8a36fbc7 100644 --- a/rules/CodingStyle/Rector/Use_/RemoveUnusedAliasRector.php +++ b/rules/CodingStyle/Rector/Use_/RemoveUnusedAliasRector.php @@ -1,7 +1,6 @@ */ private $useNamesAliasToName = []; - /** * @var string[] */ private $resolvedDocPossibleAliases = []; - /** * @var DocAliasResolver */ private $docAliasResolver; - /** * @var UseNameAliasToNameResolver */ private $useNameAliasToNameResolver; - /** * @var UseManipulator */ private $useManipulator; - /** * @var NameRenamer */ private $nameRenamer; - - public function __construct( - DocAliasResolver $docAliasResolver, - UseManipulator $useManipulator, - UseNameAliasToNameResolver $useNameAliasToNameResolver, - NameRenamer $nameRenamer - ) { + public function __construct(\Rector\CodingStyle\Node\DocAliasResolver $docAliasResolver, \Rector\CodingStyle\Node\UseManipulator $useManipulator, \Rector\CodingStyle\Node\UseNameAliasToNameResolver $useNameAliasToNameResolver, \Rector\CodingStyle\Naming\NameRenamer $nameRenamer) + { $this->docAliasResolver = $docAliasResolver; $this->useNameAliasToNameResolver = $useNameAliasToNameResolver; $this->useManipulator = $useManipulator; $this->nameRenamer = $nameRenamer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Removes unused use aliases. Keep annotation aliases like "Doctrine\ORM\Mapping as ORM" to keep convention format', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removes unused use aliases. Keep annotation aliases like "Doctrine\\ORM\\Mapping as ORM" to keep convention format', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' use Symfony\Kernel as BaseKernel; class SomeClass extends BaseKernel { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use Symfony\Kernel; class SomeClass extends Kernel { } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Use_::class]; + return [\PhpParser\Node\Stmt\Use_::class]; } - /** * @param Use_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipUse($node)) { return null; } - $searchNode = $this->resolveSearchNode($node); - if (! $searchNode instanceof Node) { + if (!$searchNode instanceof \PhpParser\Node) { return null; } - $this->resolvedNodeNames = $this->useManipulator->resolveUsedNameNodes($searchNode); $this->resolvedDocPossibleAliases = $this->docAliasResolver->resolve($searchNode); - $this->useNamesAliasToName = $this->useNameAliasToNameResolver->resolve($this->file, $node); - // lowercase $this->resolvedDocPossibleAliases = $this->lowercaseArray($this->resolvedDocPossibleAliases); - - $this->resolvedNodeNames = array_change_key_case($this->resolvedNodeNames, CASE_LOWER); - $this->useNamesAliasToName = array_change_key_case($this->useNamesAliasToName, CASE_LOWER); - + $this->resolvedNodeNames = \array_change_key_case($this->resolvedNodeNames, \CASE_LOWER); + $this->useNamesAliasToName = \array_change_key_case($this->useNamesAliasToName, \CASE_LOWER); foreach ($node->uses as $use) { if ($use->alias === null) { continue; } - $lastName = $use->name->getLast(); - $lowercasedLastName = strtolower($lastName); - + $lowercasedLastName = \strtolower($lastName); /** @var string $aliasName */ $aliasName = $this->getName($use->alias); if ($this->shouldSkip($node, $use->name, $lastName, $aliasName)) { continue; } - // only last name is used → no need for alias if (isset($this->resolvedNodeNames[$lowercasedLastName])) { $use->alias = null; continue; } - $this->refactorAliasName($aliasName, $lastName, $use); } - return $node; } - - private function shouldSkipUse(Use_ $use): bool + private function shouldSkipUse(\PhpParser\Node\Stmt\Use_ $use) : bool { // skip cases without namespace, problematic to analyse - $namespace = $this->betterNodeFinder->findParentType($use, Namespace_::class); - if (! $namespace instanceof Node) { - return true; + $namespace = $this->betterNodeFinder->findParentType($use, \PhpParser\Node\Stmt\Namespace_::class); + if (!$namespace instanceof \PhpParser\Node) { + return \true; } - - return ! $this->hasUseAlias($use); + return !$this->hasUseAlias($use); } - - private function resolveSearchNode(Use_ $use): ?Node + private function resolveSearchNode(\PhpParser\Node\Stmt\Use_ $use) : ?\PhpParser\Node { - $searchNode = $use->getAttribute(AttributeKey::PARENT_NODE); + $searchNode = $use->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); if ($searchNode !== null) { return $searchNode; } - - return $use->getAttribute(AttributeKey::NEXT_NODE); + return $use->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); } - /** * @param string[] $values * @return string[] */ - private function lowercaseArray(array $values): array + private function lowercaseArray(array $values) : array { - return array_map('strtolower', $values); + return \array_map('strtolower', $values); } - - private function shouldSkip(Use_ $use, Name $name, string $lastName, string $aliasName): bool + private function shouldSkip(\PhpParser\Node\Stmt\Use_ $use, \PhpParser\Node\Name $name, string $lastName, string $aliasName) : bool { // PHP is case insensitive - $loweredLastName = strtolower($lastName); - $loweredAliasName = strtolower($aliasName); - + $loweredLastName = \strtolower($lastName); + $loweredAliasName = \strtolower($aliasName); // both are used → nothing to remove if (isset($this->resolvedNodeNames[$loweredLastName], $this->resolvedNodeNames[$loweredAliasName])) { - return true; + return \true; } - // part of some @Doc annotation - if (in_array($loweredAliasName, $this->resolvedDocPossibleAliases, true)) { - return true; + if (\in_array($loweredAliasName, $this->resolvedDocPossibleAliases, \true)) { + return \true; } - - return (bool) $this->betterNodeFinder->findFirstNext($use, function (Node $node) use ($name): bool { - if (! $node instanceof ClassConstFetch) { - return false; + return (bool) $this->betterNodeFinder->findFirstNext($use, function (\PhpParser\Node $node) use($name) : bool { + if (!$node instanceof \PhpParser\Node\Expr\ClassConstFetch) { + return \false; } - - if (! $node->class instanceof Name) { - return false; + if (!$node->class instanceof \PhpParser\Node\Name) { + return \false; } - return $node->class->toString() === $name->toString(); }); } - - private function refactorAliasName(string $aliasName, string $lastName, UseUse $useUse): void + private function refactorAliasName(string $aliasName, string $lastName, \PhpParser\Node\Stmt\UseUse $useUse) : void { // only alias name is used → use last name directly - - $lowerAliasName = strtolower($aliasName); - if (! isset($this->resolvedNodeNames[$lowerAliasName])) { + $lowerAliasName = \strtolower($aliasName); + if (!isset($this->resolvedNodeNames[$lowerAliasName])) { return; } - // keep to differentiate 2 aliases classes - $lowerLastName = strtolower($lastName); - if (count($this->useNamesAliasToName[$lowerLastName] ?? []) > 1) { + $lowerLastName = \strtolower($lastName); + if (\count($this->useNamesAliasToName[$lowerLastName] ?? []) > 1) { return; } - $this->nameRenamer->renameNameNode($this->resolvedNodeNames[$lowerAliasName], $lastName); $useUse->alias = null; } - - private function hasUseAlias(Use_ $use): bool + private function hasUseAlias(\PhpParser\Node\Stmt\Use_ $use) : bool { foreach ($use->uses as $useUse) { if ($useUse->alias !== null) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/CodingStyle/Rector/Use_/SeparateMultiUseImportsRector.php b/rules/CodingStyle/Rector/Use_/SeparateMultiUseImportsRector.php index 8c7e8048aef..89aa4cf0c63 100644 --- a/rules/CodingStyle/Rector/Use_/SeparateMultiUseImportsRector.php +++ b/rules/CodingStyle/Rector/Use_/SeparateMultiUseImportsRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Use_::class, TraitUse::class]; + return [\PhpParser\Node\Stmt\Use_::class, \PhpParser\Node\Stmt\TraitUse::class]; } - /** * @param Use_|TraitUse $node * @return Use_[]|TraitUse[]|null */ - public function refactor(Node $node): ?array + public function refactor(\PhpParser\Node $node) : ?array { - if ($node instanceof Use_) { + if ($node instanceof \PhpParser\Node\Stmt\Use_) { return $this->refactorUseImport($node); } - return $this->refactorTraitUse($node); } - /** * @return Use_[]|null $use */ - private function refactorUseImport(Use_ $use): ?array + private function refactorUseImport(\PhpParser\Node\Stmt\Use_ $use) : ?array { - if (count($use->uses) < 2) { + if (\count($use->uses) < 2) { return null; } - $uses = []; foreach ($use->uses as $singleUse) { - $uses[] = new Use_([$singleUse]); + $uses[] = new \PhpParser\Node\Stmt\Use_([$singleUse]); } - return $uses; } - /** * @return TraitUse[]|null */ - private function refactorTraitUse(TraitUse $traitUse): ?array + private function refactorTraitUse(\PhpParser\Node\Stmt\TraitUse $traitUse) : ?array { - if (count($traitUse->traits) < 2) { + if (\count($traitUse->traits) < 2) { return null; } - $traitUses = []; foreach ($traitUse->traits as $singleTraitUse) { - $traitUses[] = new TraitUse([$singleTraitUse]); + $traitUses[] = new \PhpParser\Node\Stmt\TraitUse([$singleTraitUse]); } - return $traitUses; } } diff --git a/rules/CodingStyle/TypeAnalyzer/IterableTypeAnalyzer.php b/rules/CodingStyle/TypeAnalyzer/IterableTypeAnalyzer.php index b1540565249..cf431d135df 100644 --- a/rules/CodingStyle/TypeAnalyzer/IterableTypeAnalyzer.php +++ b/rules/CodingStyle/TypeAnalyzer/IterableTypeAnalyzer.php @@ -1,36 +1,30 @@ getTypes() as $unionedType) { - if (! $this->detect($unionedType)) { - return false; + if (!$this->detect($unionedType)) { + return \false; } } - - return true; + return \true; } - - return false; + return \false; } } diff --git a/rules/CodingStyle/ValueObject/ConcatExpressionJoinData.php b/rules/CodingStyle/ValueObject/ConcatExpressionJoinData.php index ad0b693f30d..a58d34a8aae 100644 --- a/rules/CodingStyle/ValueObject/ConcatExpressionJoinData.php +++ b/rules/CodingStyle/ValueObject/ConcatExpressionJoinData.php @@ -1,61 +1,51 @@ values[] = $value; } - - public function addNodeToRemove(Node $node): void + public function addNodeToRemove(\PhpParser\Node $node) : void { $this->nodesToRemove[] = $node; } - - public function getString(): string + public function getString() : string { - return implode('', $this->values); + return \implode('', $this->values); } - /** * @return Node[] */ - public function getNodesToRemove(): array + public function getNodesToRemove() : array { return $this->nodesToRemove; } - - public function addPlaceholderToNode(string $objectHash, Expr $expr): void + public function addPlaceholderToNode(string $objectHash, \PhpParser\Node\Expr $expr) : void { $this->placeholdersToNodes[$objectHash] = $expr; } - /** * @return Expr[] */ - public function getPlaceholdersToNodes(): array + public function getPlaceholdersToNodes() : array { return $this->placeholdersToNodes; } diff --git a/rules/CodingStyle/ValueObject/ConcatStringAndPlaceholders.php b/rules/CodingStyle/ValueObject/ConcatStringAndPlaceholders.php index 96c1b9b41f0..3e35bd5b79b 100644 --- a/rules/CodingStyle/ValueObject/ConcatStringAndPlaceholders.php +++ b/rules/CodingStyle/ValueObject/ConcatStringAndPlaceholders.php @@ -1,23 +1,19 @@ content = $content; $this->placeholderNodes = $placeholderNodes; } - - public function getContent(): string + public function getContent() : string { return $this->content; } - /** * @return Expr[] */ - public function getPlaceholderNodes(): array + public function getPlaceholderNodes() : array { return $this->placeholderNodes; } diff --git a/rules/CodingStyle/ValueObject/NameAndParent.php b/rules/CodingStyle/ValueObject/NameAndParent.php index 6838789390f..428469428f4 100644 --- a/rules/CodingStyle/ValueObject/NameAndParent.php +++ b/rules/CodingStyle/ValueObject/NameAndParent.php @@ -1,43 +1,37 @@ nameNode = $nameNode; $this->parentNode = $parentNode; } - /** * @return Name|Identifier */ - public function getNameNode(): Node + public function getNameNode() : \PhpParser\Node { return $this->nameNode; } - - public function getParentNode(): Node + public function getParentNode() : \PhpParser\Node { return $this->parentNode; } diff --git a/rules/CodingStyle/ValueObject/NodeToRemoveAndConcatItem.php b/rules/CodingStyle/ValueObject/NodeToRemoveAndConcatItem.php index 194edc5d419..7bb372e34b3 100644 --- a/rules/CodingStyle/ValueObject/NodeToRemoveAndConcatItem.php +++ b/rules/CodingStyle/ValueObject/NodeToRemoveAndConcatItem.php @@ -1,36 +1,30 @@ removedExpr = $removedExpr; $this->concatItemNode = $concatItemNode; } - - public function getRemovedExpr(): Expr + public function getRemovedExpr() : \PhpParser\Node\Expr { return $this->removedExpr; } - - public function getConcatItemNode(): Node + public function getConcatItemNode() : \PhpParser\Node { return $this->concatItemNode; } diff --git a/rules/CodingStyle/ValueObject/ObjectMagicMethods.php b/rules/CodingStyle/ValueObject/ObjectMagicMethods.php index a84b6613f23..e4278eec98f 100644 --- a/rules/CodingStyle/ValueObject/ObjectMagicMethods.php +++ b/rules/CodingStyle/ValueObject/ObjectMagicMethods.php @@ -1,33 +1,13 @@ type = $type; $this->method = $method; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->type); + return new \PHPStan\Type\ObjectType($this->type); } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } diff --git a/rules/Composer/Application/FileProcessor/ComposerFileProcessor.php b/rules/Composer/Application/FileProcessor/ComposerFileProcessor.php index 6cdc77f5bcd..cf19c8a13b3 100644 --- a/rules/Composer/Application/FileProcessor/ComposerFileProcessor.php +++ b/rules/Composer/Application/FileProcessor/ComposerFileProcessor.php @@ -1,107 +1,86 @@ composerJsonFactory = $composerJsonFactory; $this->composerJsonPrinter = $composerJsonPrinter; $this->composerRectors = $composerRectors; } - /** * @param File[] $files */ - public function process(array $files): void + public function process(array $files) : void { if ($this->composerRectors === []) { return; } - foreach ($files as $file) { $this->processFile($file); } } - - public function supports(File $file): bool + public function supports(\Rector\Core\ValueObject\Application\File $file) : bool { $smartFileInfo = $file->getSmartFileInfo(); - if ($this->isJsonInTests($smartFileInfo)) { - return true; + return \true; } - return $smartFileInfo->getBasename() === 'composer.json'; } - /** * @return string[] */ - public function getSupportedFileExtensions(): array + public function getSupportedFileExtensions() : array { return ['json']; } - - private function processFile(File $file): void + private function processFile(\Rector\Core\ValueObject\Application\File $file) : void { // to avoid modification of file - $smartFileInfo = $file->getSmartFileInfo(); $composerJson = $this->composerJsonFactory->createFromFileInfo($smartFileInfo); - $oldComposerJson = clone $composerJson; foreach ($this->composerRectors as $composerRector) { $composerRector->refactor($composerJson); } - // nothing has changed if ($oldComposerJson->getJsonArray() === $composerJson->getJsonArray()) { return; } - $changeFileContent = $this->composerJsonPrinter->printToString($composerJson); $file->changeFileContent($changeFileContent); } - - private function isJsonInTests(SmartFileInfo $fileInfo): bool + private function isJsonInTests(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo) : bool { - if (! StaticPHPUnitEnvironment::isPHPUnitRun()) { - return false; + if (!\Rector\Testing\PHPUnit\StaticPHPUnitEnvironment::isPHPUnitRun()) { + return \false; } - return $fileInfo->hasSuffixes(['json']); } } diff --git a/rules/Composer/Contract/Rector/ComposerRectorInterface.php b/rules/Composer/Contract/Rector/ComposerRectorInterface.php index bf559b713c8..b0db90d948b 100644 --- a/rules/Composer/Contract/Rector/ComposerRectorInterface.php +++ b/rules/Composer/Contract/Rector/ComposerRectorInterface.php @@ -1,14 +1,12 @@ versionParser = $versionParser; } - /** * @param VersionAwareInterface[] $versionAwares */ - public function validate(array $versionAwares): void + public function validate(array $versionAwares) : void { foreach ($versionAwares as $versionAware) { $this->versionParser->parseConstraints($versionAware->getVersion()); diff --git a/rules/Composer/Rector/AddPackageToRequireComposerRector.php b/rules/Composer/Rector/AddPackageToRequireComposerRector.php index a17b1129ef9..6c4486f21da 100644 --- a/rules/Composer/Rector/AddPackageToRequireComposerRector.php +++ b/rules/Composer/Rector/AddPackageToRequireComposerRector.php @@ -1,75 +1,60 @@ versionGuard = $versionGuard; } - - public function refactor(ComposerJson $composerJson): void + public function refactor(\RectorPrefix20210509\Symplify\ComposerJsonManipulator\ValueObject\ComposerJson $composerJson) : void { foreach ($this->packagesAndVersions as $packageAndVersion) { $composerJson->addRequiredPackage($packageAndVersion->getPackageName(), $packageAndVersion->getVersion()); } } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add package to "require" in `composer.json`', [new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add package to "require" in `composer.json`', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' { "require": { "symfony/console": "^3.4" } } CODE_SAMPLE - , - [ - self::PACKAGES_AND_VERSIONS => [new PackageAndVersion('symfony/console', '^3.4')], - ] - ), - ]); +, [self::PACKAGES_AND_VERSIONS => [new \Rector\Composer\ValueObject\PackageAndVersion('symfony/console', '^3.4')]])]); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $packagesAndVersions = $configuration[self::PACKAGES_AND_VERSIONS] ?? []; $this->versionGuard->validate($packagesAndVersions); diff --git a/rules/Composer/Rector/AddPackageToRequireDevComposerRector.php b/rules/Composer/Rector/AddPackageToRequireDevComposerRector.php index 8816fba2877..a4b96261dc1 100644 --- a/rules/Composer/Rector/AddPackageToRequireDevComposerRector.php +++ b/rules/Composer/Rector/AddPackageToRequireDevComposerRector.php @@ -1,78 +1,60 @@ versionGuard = $versionGuard; } - - public function refactor(ComposerJson $composerJson): void + public function refactor(\RectorPrefix20210509\Symplify\ComposerJsonManipulator\ValueObject\ComposerJson $composerJson) : void { foreach ($this->packageAndVersions as $packageAndVersion) { - $composerJson->addRequiredDevPackage( - $packageAndVersion->getPackageName(), - $packageAndVersion->getVersion() - ); + $composerJson->addRequiredDevPackage($packageAndVersion->getPackageName(), $packageAndVersion->getVersion()); } } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add package to "require-dev" in `composer.json`', [new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add package to "require-dev" in `composer.json`', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' { "require-dev": { "symfony/console": "^3.4" } } CODE_SAMPLE - , - [ - self::PACKAGES_AND_VERSIONS => [new PackageAndVersion('symfony/console', '^3.4')], - ] - ), - ]); +, [self::PACKAGES_AND_VERSIONS => [new \Rector\Composer\ValueObject\PackageAndVersion('symfony/console', '^3.4')]])]); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $packagesAndVersions = $configuration[self::PACKAGES_AND_VERSIONS] ?? []; $this->versionGuard->validate($packagesAndVersions); diff --git a/rules/Composer/Rector/ChangePackageVersionComposerRector.php b/rules/Composer/Rector/ChangePackageVersionComposerRector.php index 5d39ec02eb6..d5ef7fdcc1e 100644 --- a/rules/Composer/Rector/ChangePackageVersionComposerRector.php +++ b/rules/Composer/Rector/ChangePackageVersionComposerRector.php @@ -1,81 +1,63 @@ versionGuard = $versionGuard; } - - public function refactor(ComposerJson $composerJson): void + public function refactor(\RectorPrefix20210509\Symplify\ComposerJsonManipulator\ValueObject\ComposerJson $composerJson) : void { foreach ($this->packagesAndVersions as $packageAndVersion) { - $composerJson->changePackageVersion( - $packageAndVersion->getPackageName(), - $packageAndVersion->getVersion() - ); + $composerJson->changePackageVersion($packageAndVersion->getPackageName(), $packageAndVersion->getVersion()); } } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change package version `composer.json`', [new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change package version `composer.json`', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' { "require-dev": { "symfony/console": "^3.4" } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' { "require": { "symfony/console": "^4.4" } } CODE_SAMPLE - , - [ - self::PACKAGES_AND_VERSIONS => [new PackageAndVersion('symfony/console', '^4.4')], - ] - ), - ]); +, [self::PACKAGES_AND_VERSIONS => [new \Rector\Composer\ValueObject\PackageAndVersion('symfony/console', '^4.4')]])]); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $packagesAndVersions = $configuration[self::PACKAGES_AND_VERSIONS] ?? []; $this->versionGuard->validate($packagesAndVersions); diff --git a/rules/Composer/Rector/RemovePackageComposerRector.php b/rules/Composer/Rector/RemovePackageComposerRector.php index 3cd0d639217..4ba8204dd65 100644 --- a/rules/Composer/Rector/RemovePackageComposerRector.php +++ b/rules/Composer/Rector/RemovePackageComposerRector.php @@ -1,63 +1,50 @@ packageNames as $packageName) { $composerJson->removePackage($packageName); } } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove package from "require" and "require-dev" in `composer.json`', [new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove package from "require" and "require-dev" in `composer.json`', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' { "require": { "symfony/console": "^3.4" } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' { } CODE_SAMPLE - , - [ - self::PACKAGE_NAMES => ['symfony/console'], - ] - ), - ]); +, [self::PACKAGE_NAMES => ['symfony/console']])]); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->packageNames = $configuration[self::PACKAGE_NAMES] ?? []; } diff --git a/rules/Composer/Rector/ReplacePackageAndVersionComposerRector.php b/rules/Composer/Rector/ReplacePackageAndVersionComposerRector.php index 8cbe4b479f1..b141a341982 100644 --- a/rules/Composer/Rector/ReplacePackageAndVersionComposerRector.php +++ b/rules/Composer/Rector/ReplacePackageAndVersionComposerRector.php @@ -1,86 +1,63 @@ versionGuard = $versionGuard; } - - public function refactor(ComposerJson $composerJson): void + public function refactor(\RectorPrefix20210509\Symplify\ComposerJsonManipulator\ValueObject\ComposerJson $composerJson) : void { foreach ($this->replacePackagesAndVersions as $replacePackageAndVersion) { - $composerJson->replacePackage( - $replacePackageAndVersion->getOldPackageName(), - $replacePackageAndVersion->getNewPackageName(), - $replacePackageAndVersion->getVersion() - ); + $composerJson->replacePackage($replacePackageAndVersion->getOldPackageName(), $replacePackageAndVersion->getNewPackageName(), $replacePackageAndVersion->getVersion()); } } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change package name and version `composer.json`', [new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change package name and version `composer.json`', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' { "require-dev": { "symfony/console": "^3.4" } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' { "require-dev": { "symfony/http-kernel": "^4.4" } } CODE_SAMPLE - , - [ - self::REPLACE_PACKAGES_AND_VERSIONS => [new ReplacePackageAndVersion( - 'symfony/console', - 'symfony/http-kernel', - '^4.4' - )], - ] - ), - ]); +, [self::REPLACE_PACKAGES_AND_VERSIONS => [new \Rector\Composer\ValueObject\ReplacePackageAndVersion('symfony/console', 'symfony/http-kernel', '^4.4')]])]); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $replacePackagesAndVersions = $configuration[self::REPLACE_PACKAGES_AND_VERSIONS] ?? []; $this->versionGuard->validate($replacePackagesAndVersions); diff --git a/rules/Composer/ValueObject/PackageAndVersion.php b/rules/Composer/ValueObject/PackageAndVersion.php index 72e41884c16..ffc92de347e 100644 --- a/rules/Composer/ValueObject/PackageAndVersion.php +++ b/rules/Composer/ValueObject/PackageAndVersion.php @@ -1,35 +1,29 @@ packageName = $packageName; $this->version = $version; } - - public function getPackageName(): string + public function getPackageName() : string { return $this->packageName; } - - public function getVersion(): string + public function getVersion() : string { return $this->version; } diff --git a/rules/Composer/ValueObject/ReplacePackageAndVersion.php b/rules/Composer/ValueObject/ReplacePackageAndVersion.php index a7951cd6f35..6fd12023b16 100644 --- a/rules/Composer/ValueObject/ReplacePackageAndVersion.php +++ b/rules/Composer/ValueObject/ReplacePackageAndVersion.php @@ -1,54 +1,41 @@ oldPackageName = $oldPackageName; $this->newPackageName = $newPackageName; $this->version = $version; } - - public function getOldPackageName(): string + public function getOldPackageName() : string { return $this->oldPackageName; } - - public function getNewPackageName(): string + public function getNewPackageName() : string { return $this->newPackageName; } - - public function getVersion(): string + public function getVersion() : string { return $this->version; } diff --git a/rules/DeadCode/Comparator/CurrentAndParentClassMethodComparator.php b/rules/DeadCode/Comparator/CurrentAndParentClassMethodComparator.php index f6268bb32c0..b48e85830b3 100644 --- a/rules/DeadCode/Comparator/CurrentAndParentClassMethodComparator.php +++ b/rules/DeadCode/Comparator/CurrentAndParentClassMethodComparator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->methodReflectionProvider = $methodReflectionProvider; $this->parameterDefaultsComparator = $parameterDefaultsComparator; $this->parameterTypeComparator = $parameterTypeComparator; $this->nodeComparator = $nodeComparator; } - - public function isParentCallMatching(ClassMethod $classMethod, StaticCall $staticCall): bool + public function isParentCallMatching(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Expr\StaticCall $staticCall) : bool { - if (! $this->isSameMethodParentCall($classMethod, $staticCall)) { - return false; + if (!$this->isSameMethodParentCall($classMethod, $staticCall)) { + return \false; } - - if (! $this->areArgsAndParamsEqual($staticCall->args, $classMethod->params)) { - return false; + if (!$this->areArgsAndParamsEqual($staticCall->args, $classMethod->params)) { + return \false; } - - if (! $this->parameterTypeComparator->compareCurrentClassMethodAndParentStaticCall($classMethod, $staticCall)) { - return false; + if (!$this->parameterTypeComparator->compareCurrentClassMethodAndParentStaticCall($classMethod, $staticCall)) { + return \false; } - - return ! $this->isParentClassMethodVisibilityOrDefaultOverride($classMethod, $staticCall); + return !$this->isParentClassMethodVisibilityOrDefaultOverride($classMethod, $staticCall); } - - private function isSameMethodParentCall(ClassMethod $classMethod, StaticCall $staticCall): bool + private function isSameMethodParentCall(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Expr\StaticCall $staticCall) : bool { - if (! $this->nodeNameResolver->areNamesEqual($staticCall->name, $classMethod->name)) { - return false; + if (!$this->nodeNameResolver->areNamesEqual($staticCall->name, $classMethod->name)) { + return \false; } - return $this->nodeNameResolver->isName($staticCall->class, 'parent'); } - /** * @param Arg[] $parentStaticCallArgs * @param Param[] $currentClassMethodParams */ - private function areArgsAndParamsEqual(array $parentStaticCallArgs, array $currentClassMethodParams): bool + private function areArgsAndParamsEqual(array $parentStaticCallArgs, array $currentClassMethodParams) : bool { - if (count($parentStaticCallArgs) !== count($currentClassMethodParams)) { - return false; + if (\count($parentStaticCallArgs) !== \count($currentClassMethodParams)) { + return \false; } - if ($parentStaticCallArgs === []) { - return true; + return \true; } - foreach ($parentStaticCallArgs as $key => $arg) { - if (! isset($currentClassMethodParams[$key])) { - return false; + if (!isset($currentClassMethodParams[$key])) { + return \false; } - // this only compares variable name, but those can be differnt, so its kinda useless $param = $currentClassMethodParams[$key]; - if (! $this->nodeComparator->areNodesEqual($param->var, $arg->value)) { - return false; + if (!$this->nodeComparator->areNodesEqual($param->var, $arg->value)) { + return \false; } } - - return true; + return \true; } - - private function isParentClassMethodVisibilityOrDefaultOverride( - ClassMethod $classMethod, - StaticCall $staticCall - ): bool { - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + private function isParentClassMethodVisibilityOrDefaultOverride(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Expr\StaticCall $staticCall) : bool + { + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - $methodName = $this->nodeNameResolver->getName($staticCall->name); if ($methodName === null) { - return false; + return \false; } - foreach ($classReflection->getParents() as $parentClassReflection) { - if (! $parentClassReflection->hasMethod($methodName)) { + if (!$parentClassReflection->hasMethod($methodName)) { continue; } - $nativeParentClassReflection = $parentClassReflection->getNativeReflection(); $nativeParentClassMethodReflection = $nativeParentClassReflection->getMethod($methodName); - - if (! $nativeParentClassMethodReflection->isProtected()) { + if (!$nativeParentClassMethodReflection->isProtected()) { return $this->checkOverrideUsingReflection($classMethod, $parentClassReflection, $methodName); } - - if (! $nativeParentClassMethodReflection->isPublic()) { + if (!$nativeParentClassMethodReflection->isPublic()) { return $this->checkOverrideUsingReflection($classMethod, $parentClassReflection, $methodName); } - - return true; + return \true; } - - return false; + return \false; } - - private function checkOverrideUsingReflection( - ClassMethod $classMethod, - ClassReflection $classReflection, - string $methodName - ): bool { - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - throw new ShouldNotHappenException(); + private function checkOverrideUsingReflection(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Reflection\ClassReflection $classReflection, string $methodName) : bool + { + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $parentMethodReflection = $classReflection->getMethod($methodName, $scope); - // 3rd party code if ($parentMethodReflection !== null) { - if (! $parentMethodReflection->isPrivate() && ! $parentMethodReflection->isPublic() && $classMethod->isPublic()) { - return true; + if (!$parentMethodReflection->isPrivate() && !$parentMethodReflection->isPublic() && $classMethod->isPublic()) { + return \true; } - if ($parentMethodReflection->isInternal()->yes()) { // we can't know for certain so we assume its a override with purpose - return true; + return \true; } - if ($this->areParameterDefaultsDifferent($classMethod, $parentMethodReflection)) { - return true; + return \true; } } - - return false; + return \false; } - - private function areParameterDefaultsDifferent( - ClassMethod $classMethod, - MethodReflection $methodReflection - ): bool { - $parameterReflections = $this->methodReflectionProvider->getParameterReflectionsFromMethodReflection( - $methodReflection - ); - + private function areParameterDefaultsDifferent(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Reflection\MethodReflection $methodReflection) : bool + { + $parameterReflections = $this->methodReflectionProvider->getParameterReflectionsFromMethodReflection($methodReflection); foreach ($parameterReflections as $key => $parameterReflection) { - if (! isset($classMethod->params[$key])) { + if (!isset($classMethod->params[$key])) { if ($parameterReflection->getDefaultValue() !== null) { continue; } - - return true; + return \true; } - $methodParam = $classMethod->params[$key]; - - if ($this->parameterDefaultsComparator->areDefaultValuesDifferent( - $parameterReflection, - $methodParam - )) { - return true; + if ($this->parameterDefaultsComparator->areDefaultValuesDifferent($parameterReflection, $methodParam)) { + return \true; } } - - return false; + return \false; } } diff --git a/rules/DeadCode/Comparator/Parameter/ParameterDefaultsComparator.php b/rules/DeadCode/Comparator/Parameter/ParameterDefaultsComparator.php index 54fe5a4137a..6ddcc0747f5 100644 --- a/rules/DeadCode/Comparator/Parameter/ParameterDefaultsComparator.php +++ b/rules/DeadCode/Comparator/Parameter/ParameterDefaultsComparator.php @@ -1,7 +1,6 @@ valueResolver = $valueResolver; } - - public function areDefaultValuesDifferent(ParameterReflection $parameterReflection, Param $param): bool + public function areDefaultValuesDifferent(\PHPStan\Reflection\ParameterReflection $parameterReflection, \PhpParser\Node\Param $param) : bool { if ($parameterReflection->getDefaultValue() === null && $param->default === null) { - return false; + return \false; } - if ($this->isMutuallyExclusiveNull($parameterReflection, $param)) { - return true; + return \true; } - /** @var Expr $paramDefault */ $paramDefault = $param->default; - $firstParameterValue = $this->resolveParameterReflectionDefaultValue($parameterReflection); $secondParameterValue = $this->valueResolver->getValue($paramDefault); - return $firstParameterValue !== $secondParameterValue; } - - private function isMutuallyExclusiveNull(ParameterReflection $parameterReflection, Param $param): bool + private function isMutuallyExclusiveNull(\PHPStan\Reflection\ParameterReflection $parameterReflection, \PhpParser\Node\Param $param) : bool { if ($parameterReflection->getDefaultValue() === null && $param->default !== null) { - return true; + return \true; } if ($parameterReflection->getDefaultValue() === null) { - return false; + return \false; } return $param->default === null; } - /** * @return bool|float|int|string|mixed[]|null */ - private function resolveParameterReflectionDefaultValue(ParameterReflection $parameterReflection) + private function resolveParameterReflectionDefaultValue(\PHPStan\Reflection\ParameterReflection $parameterReflection) { $defaultValue = $parameterReflection->getDefaultValue(); - if (! $defaultValue instanceof ConstantType) { - throw new ShouldNotHappenException(); + if (!$defaultValue instanceof \PHPStan\Type\ConstantType) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - if ($defaultValue instanceof ConstantArrayType) { + if ($defaultValue instanceof \PHPStan\Type\Constant\ConstantArrayType) { return $defaultValue->getAllArrays(); } - /** @var ConstantStringType|ConstantIntegerType|ConstantFloatType|ConstantBooleanType|NullType $defaultValue */ return $defaultValue->getValue(); } diff --git a/rules/DeadCode/Comparator/Parameter/ParameterTypeComparator.php b/rules/DeadCode/Comparator/Parameter/ParameterTypeComparator.php index 860369673e2..bc703b0471f 100644 --- a/rules/DeadCode/Comparator/Parameter/ParameterTypeComparator.php +++ b/rules/DeadCode/Comparator/Parameter/ParameterTypeComparator.php @@ -1,43 +1,34 @@ methodReflectionProvider = $methodReflectionProvider; } - - public function compareCurrentClassMethodAndParentStaticCall( - ClassMethod $classMethod, - StaticCall $staticCall - ): bool { + public function compareCurrentClassMethodAndParentStaticCall(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Expr\StaticCall $staticCall) : bool + { $currentParameterTypes = $this->methodReflectionProvider->provideParameterTypesByClassMethod($classMethod); $parentParameterTypes = $this->methodReflectionProvider->provideParameterTypesByStaticCall($staticCall); - foreach ($currentParameterTypes as $key => $currentParameterType) { - if (! isset($parentParameterTypes[$key])) { + if (!isset($parentParameterTypes[$key])) { continue; } - $parentParameterType = $parentParameterTypes[$key]; - if (! $currentParameterType->equals($parentParameterType)) { - return false; + if (!$currentParameterType->equals($parentParameterType)) { + return \false; } } - - return true; + return \true; } } diff --git a/rules/DeadCode/ConditionEvaluator.php b/rules/DeadCode/ConditionEvaluator.php index 3355fd06763..f0b0687ef75 100644 --- a/rules/DeadCode/ConditionEvaluator.php +++ b/rules/DeadCode/ConditionEvaluator.php @@ -1,7 +1,6 @@ evaluateVersionCompareCondition($condition); } - - if ($condition instanceof BinaryToVersionCompareCondition) { + if ($condition instanceof \Rector\DeadCode\ValueObject\BinaryToVersionCompareCondition) { return $this->evaluateBinaryToVersionCompareCondition($condition); } - return null; } - /** * @return bool|int */ - private function evaluateVersionCompareCondition(VersionCompareCondition $versionCompareCondition) + private function evaluateVersionCompareCondition(\Rector\DeadCode\ValueObject\VersionCompareCondition $versionCompareCondition) { $compareSign = $versionCompareCondition->getCompareSign(); if ($compareSign !== null) { - return version_compare( - (string) $versionCompareCondition->getFirstVersion(), - (string) $versionCompareCondition->getSecondVersion(), - $compareSign - ); + return \version_compare((string) $versionCompareCondition->getFirstVersion(), (string) $versionCompareCondition->getSecondVersion(), $compareSign); } - - return version_compare( - (string) $versionCompareCondition->getFirstVersion(), - (string) $versionCompareCondition->getSecondVersion() - ); + return \version_compare((string) $versionCompareCondition->getFirstVersion(), (string) $versionCompareCondition->getSecondVersion()); } - - private function evaluateBinaryToVersionCompareCondition( - BinaryToVersionCompareCondition $binaryToVersionCompareCondition - ): bool { - $versionCompareResult = $this->evaluateVersionCompareCondition( - $binaryToVersionCompareCondition->getVersionCompareCondition() - ); - - if ($binaryToVersionCompareCondition->getBinaryClass() === Identical::class) { + private function evaluateBinaryToVersionCompareCondition(\Rector\DeadCode\ValueObject\BinaryToVersionCompareCondition $binaryToVersionCompareCondition) : bool + { + $versionCompareResult = $this->evaluateVersionCompareCondition($binaryToVersionCompareCondition->getVersionCompareCondition()); + if ($binaryToVersionCompareCondition->getBinaryClass() === \PhpParser\Node\Expr\BinaryOp\Identical::class) { return $binaryToVersionCompareCondition->getExpectedValue() === $versionCompareResult; } - - if ($binaryToVersionCompareCondition->getBinaryClass() === NotIdentical::class) { + if ($binaryToVersionCompareCondition->getBinaryClass() === \PhpParser\Node\Expr\BinaryOp\NotIdentical::class) { return $binaryToVersionCompareCondition->getExpectedValue() !== $versionCompareResult; } - - if ($binaryToVersionCompareCondition->getBinaryClass() === Equal::class) { + if ($binaryToVersionCompareCondition->getBinaryClass() === \PhpParser\Node\Expr\BinaryOp\Equal::class) { // weak comparison on purpose return $binaryToVersionCompareCondition->getExpectedValue() === $versionCompareResult; } - - if ($binaryToVersionCompareCondition->getBinaryClass() === NotEqual::class) { + if ($binaryToVersionCompareCondition->getBinaryClass() === \PhpParser\Node\Expr\BinaryOp\NotEqual::class) { // weak comparison on purpose return $binaryToVersionCompareCondition->getExpectedValue() !== $versionCompareResult; } - - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } } diff --git a/rules/DeadCode/ConditionResolver.php b/rules/DeadCode/ConditionResolver.php index b2f369a53f1..6a7c23fcacc 100644 --- a/rules/DeadCode/ConditionResolver.php +++ b/rules/DeadCode/ConditionResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->valueResolver = $valueResolver; $this->phpVersionProvider = $phpVersionProvider; $this->phpVersionFactory = $phpVersionFactory; } - - public function resolveFromExpr(Expr $expr): ?ConditionInterface + public function resolveFromExpr(\PhpParser\Node\Expr $expr) : ?\Rector\DeadCode\Contract\ConditionInterface { if ($this->isVersionCompareFuncCall($expr)) { /** @var FuncCall $expr */ return $this->resolveVersionCompareConditionForFuncCall($expr); } - - if (! $expr instanceof Identical && ! $expr instanceof Equal && ! $expr instanceof NotIdentical && ! $expr instanceof NotEqual) { + if (!$expr instanceof \PhpParser\Node\Expr\BinaryOp\Identical && !$expr instanceof \PhpParser\Node\Expr\BinaryOp\Equal && !$expr instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical && !$expr instanceof \PhpParser\Node\Expr\BinaryOp\NotEqual) { return null; } - - $binaryClass = get_class($expr); - + $binaryClass = \get_class($expr); if ($this->isVersionCompareFuncCall($expr->left)) { /** @var FuncCall $funcCall */ $funcCall = $expr->left; return $this->resolveFuncCall($funcCall, $expr->right, $binaryClass); } - if ($this->isVersionCompareFuncCall($expr->right)) { /** @var FuncCall $funcCall */ $funcCall = $expr->right; - $versionCompareCondition = $this->resolveVersionCompareConditionForFuncCall($funcCall); - if (! $versionCompareCondition instanceof VersionCompareCondition) { + if (!$versionCompareCondition instanceof \Rector\DeadCode\ValueObject\VersionCompareCondition) { return null; } - $expectedValue = $this->valueResolver->getValue($expr->left); - - return new BinaryToVersionCompareCondition($versionCompareCondition, $binaryClass, $expectedValue); + return new \Rector\DeadCode\ValueObject\BinaryToVersionCompareCondition($versionCompareCondition, $binaryClass, $expectedValue); } - return null; } - - private function isVersionCompareFuncCall(Node $node): bool + private function isVersionCompareFuncCall(\PhpParser\Node $node) : bool { - if (! $node instanceof FuncCall) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - return $this->nodeNameResolver->isName($node, 'version_compare'); } - - private function resolveVersionCompareConditionForFuncCall(FuncCall $funcCall): ?VersionCompareCondition + private function resolveVersionCompareConditionForFuncCall(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\Rector\DeadCode\ValueObject\VersionCompareCondition { $firstVersion = $this->resolveArgumentValue($funcCall, 0); if ($firstVersion === null) { return null; } - $secondVersion = $this->resolveArgumentValue($funcCall, 1); if ($secondVersion === null) { return null; } - // includes compare sign as 3rd argument $versionCompareSign = null; if (isset($funcCall->args[2])) { $versionCompareSign = $this->valueResolver->getValue($funcCall->args[2]->value); } - - return new VersionCompareCondition($firstVersion, $secondVersion, $versionCompareSign); + return new \Rector\DeadCode\ValueObject\VersionCompareCondition($firstVersion, $secondVersion, $versionCompareSign); } - - private function resolveFuncCall( - FuncCall $funcCall, - Expr $expr, - string $binaryClass - ): ?BinaryToVersionCompareCondition { + private function resolveFuncCall(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr $expr, string $binaryClass) : ?\Rector\DeadCode\ValueObject\BinaryToVersionCompareCondition + { $versionCompareCondition = $this->resolveVersionCompareConditionForFuncCall($funcCall); - if (! $versionCompareCondition instanceof VersionCompareCondition) { + if (!$versionCompareCondition instanceof \Rector\DeadCode\ValueObject\VersionCompareCondition) { return null; } - $expectedValue = $this->valueResolver->getValue($expr); - - return new BinaryToVersionCompareCondition($versionCompareCondition, $binaryClass, $expectedValue); + return new \Rector\DeadCode\ValueObject\BinaryToVersionCompareCondition($versionCompareCondition, $binaryClass, $expectedValue); } - - private function resolveArgumentValue(FuncCall $funcCall, int $argumentPosition): ?int + private function resolveArgumentValue(\PhpParser\Node\Expr\FuncCall $funcCall, int $argumentPosition) : ?int { $firstArgValue = $funcCall->args[$argumentPosition]->value; - /** @var mixed|null $version */ $version = $this->valueResolver->getValue($firstArgValue); - if (in_array($version, ['PHP_VERSION', 'PHP_VERSION_ID'], true)) { + if (\in_array($version, ['PHP_VERSION', 'PHP_VERSION_ID'], \true)) { return $this->phpVersionProvider->provide(); } - - if (is_string($version)) { + if (\is_string($version)) { return $this->phpVersionFactory->createIntVersion($version); } - return $version; } } diff --git a/rules/DeadCode/Contract/ConditionInterface.php b/rules/DeadCode/Contract/ConditionInterface.php index 8d3747bae1d..789722a0667 100644 --- a/rules/DeadCode/Contract/ConditionInterface.php +++ b/rules/DeadCode/Contract/ConditionInterface.php @@ -1,7 +1,6 @@ */ - private const FUNCTIONS_BY_VERSION = [ - PhpVersion::PHP_56 => ['session_abort', 'hash_equals', 'ldap_escape'], - PhpVersion::PHP_70 => [ - 'random_int', - 'random_bytes', - 'intdiv', - 'preg_replace_callback_array', - 'error_clear_last', - ], - PhpVersion::PHP_71 => ['is_iterable'], - PhpVersion::PHP_72 => ['spl_object_id', 'stream_isatty'], - PhpVersion::PHP_73 => ['array_key_first', 'array_key_last', 'hrtime', 'is_countable'], - PhpVersion::PHP_74 => ['get_mangled_object_vars', 'mb_str_split', 'password_algos'], - ]; - + private const FUNCTIONS_BY_VERSION = [\Rector\Core\ValueObject\PhpVersion::PHP_56 => ['session_abort', 'hash_equals', 'ldap_escape'], \Rector\Core\ValueObject\PhpVersion::PHP_70 => ['random_int', 'random_bytes', 'intdiv', 'preg_replace_callback_array', 'error_clear_last'], \Rector\Core\ValueObject\PhpVersion::PHP_71 => ['is_iterable'], \Rector\Core\ValueObject\PhpVersion::PHP_72 => ['spl_object_id', 'stream_isatty'], \Rector\Core\ValueObject\PhpVersion::PHP_73 => ['array_key_first', 'array_key_last', 'hrtime', 'is_countable'], \Rector\Core\ValueObject\PhpVersion::PHP_74 => ['get_mangled_object_vars', 'mb_str_split', 'password_algos']]; /** * @var PhpVersionProvider */ private $phpVersionProvider; - - public function __construct(PhpVersionProvider $phpVersionProvider) + public function __construct(\Rector\Core\Php\PhpVersionProvider $phpVersionProvider) { $this->phpVersionProvider = $phpVersionProvider; } - - public function isFunctionSupported(string $desiredFunction): bool + public function isFunctionSupported(string $desiredFunction) : bool { foreach (self::FUNCTIONS_BY_VERSION as $version => $functions) { - if (! in_array($desiredFunction, $functions, true)) { + if (!\in_array($desiredFunction, $functions, \true)) { continue; } - - if (! $this->phpVersionProvider->isAtLeastPhpVersion($version)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion($version)) { continue; } - - return true; + return \true; } - - return false; + return \false; } } diff --git a/rules/DeadCode/NodeAnalyzer/InstanceOfUniqueKeyResolver.php b/rules/DeadCode/NodeAnalyzer/InstanceOfUniqueKeyResolver.php index 5835068fcba..28c563a8120 100644 --- a/rules/DeadCode/NodeAnalyzer/InstanceOfUniqueKeyResolver.php +++ b/rules/DeadCode/NodeAnalyzer/InstanceOfUniqueKeyResolver.php @@ -1,40 +1,34 @@ nodeNameResolver = $nodeNameResolver; } - - public function resolve(Instanceof_ $instanceof): ?string + public function resolve(\PhpParser\Node\Expr\Instanceof_ $instanceof) : ?string { - if (! $instanceof->expr instanceof Variable) { + if (!$instanceof->expr instanceof \PhpParser\Node\Expr\Variable) { return null; } $variableName = $this->nodeNameResolver->getName($instanceof->expr); if ($variableName === null) { return null; } - $className = $this->nodeNameResolver->getName($instanceof->class); if ($className === null) { return null; } - return $variableName . '_' . $className; } } diff --git a/rules/DeadCode/NodeAnalyzer/UsedVariableNameAnalyzer.php b/rules/DeadCode/NodeAnalyzer/UsedVariableNameAnalyzer.php index d823e08db31..91327a772c2 100644 --- a/rules/DeadCode/NodeAnalyzer/UsedVariableNameAnalyzer.php +++ b/rules/DeadCode/NodeAnalyzer/UsedVariableNameAnalyzer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; } - - public function isVariableNamed(Node $node, Variable $variable): bool + public function isVariableNamed(\PhpParser\Node $node, \PhpParser\Node\Expr\Variable $variable) : bool { - if (($node instanceof MethodCall || $node instanceof PropertyFetch) && ($node->name instanceof Variable && is_string( - $node->name->name - ))) { + if (($node instanceof \PhpParser\Node\Expr\MethodCall || $node instanceof \PhpParser\Node\Expr\PropertyFetch) && ($node->name instanceof \PhpParser\Node\Expr\Variable && \is_string($node->name->name))) { return $this->nodeNameResolver->isName($variable, $node->name->name); } - - if (! $node instanceof Variable) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeNameResolver->areNamesEqual($variable, $node); } } diff --git a/rules/DeadCode/NodeCollector/ModifiedVariableNamesCollector.php b/rules/DeadCode/NodeCollector/ModifiedVariableNamesCollector.php index d2ced33ed89..ba57dbba851 100644 --- a/rules/DeadCode/NodeCollector/ModifiedVariableNamesCollector.php +++ b/rules/DeadCode/NodeCollector/ModifiedVariableNamesCollector.php @@ -1,7 +1,6 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeNameResolver = $nodeNameResolver; } - /** * @return string[] */ - public function collectModifiedVariableNames(Stmt $stmt): array + public function collectModifiedVariableNames(\PhpParser\Node\Stmt $stmt) : array { $argNames = $this->collectFromArgs($stmt); $assignNames = $this->collectFromAssigns($stmt); - - return array_merge($argNames, $assignNames); + return \array_merge($argNames, $assignNames); } - /** * @return string[] */ - private function collectFromArgs(Stmt $stmt): array + private function collectFromArgs(\PhpParser\Node\Stmt $stmt) : array { $variableNames = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmt, function (Node $node) use ( - &$variableNames - ) { - if (! $node instanceof Arg) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmt, function (\PhpParser\Node $node) use(&$variableNames) { + if (!$node instanceof \PhpParser\Node\Arg) { return null; } - - if (! $this->isVariableChangedInReference($node)) { + if (!$this->isVariableChangedInReference($node)) { return null; } - $variableName = $this->nodeNameResolver->getName($node->value); if ($variableName === null) { return null; } - $variableNames[] = $variableName; }); - return $variableNames; } - /** * @return string[] */ - private function collectFromAssigns(Stmt $stmt): array + private function collectFromAssigns(\PhpParser\Node\Stmt $stmt) : array { $modifiedVariableNames = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmt, function (Node $node) use ( - &$modifiedVariableNames - ) { - if (! $node instanceof Assign) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmt, function (\PhpParser\Node $node) use(&$modifiedVariableNames) { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $node->var instanceof Variable) { + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - $variableName = $this->nodeNameResolver->getName($node->var); if ($variableName === null) { return null; } - $modifiedVariableNames[] = $variableName; }); - return $modifiedVariableNames; } - - private function isVariableChangedInReference(Arg $arg): bool + private function isVariableChangedInReference(\PhpParser\Node\Arg $arg) : bool { - $parentNode = $arg->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof FuncCall) { - return false; + $parentNode = $arg->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - return $this->nodeNameResolver->isNames($parentNode, ['array_shift', 'array_pop']); } } diff --git a/rules/DeadCode/NodeCollector/NodeByTypeAndPositionCollector.php b/rules/DeadCode/NodeCollector/NodeByTypeAndPositionCollector.php index e42b320feab..ca77aa842d0 100644 --- a/rules/DeadCode/NodeCollector/NodeByTypeAndPositionCollector.php +++ b/rules/DeadCode/NodeCollector/NodeByTypeAndPositionCollector.php @@ -1,7 +1,6 @@ flowOfControlLocator = $flowOfControlLocator; $this->nodeNameResolver = $nodeNameResolver; } - /** * @param Variable[] $assignedVariables * @param Variable[] $assignedVariablesUse * @return VariableNodeUse[] */ - public function collectNodesByTypeAndPosition( - array $assignedVariables, - array $assignedVariablesUse, - FunctionLike $functionLike - ): array { + public function collectNodesByTypeAndPosition(array $assignedVariables, array $assignedVariablesUse, \PhpParser\Node\FunctionLike $functionLike) : array + { $nodesByTypeAndPosition = []; - foreach ($assignedVariables as $assignedVariable) { /** @var int $startTokenPos */ - $startTokenPos = $assignedVariable->getAttribute(AttributeKey::START_TOKEN_POSITION); - + $startTokenPos = $assignedVariable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::START_TOKEN_POSITION); // not in different scope, than previous one - e.g. if/while/else... // get nesting level to $classMethodNode /** @var Assign $assign */ - $assign = $assignedVariable->getAttribute(AttributeKey::PARENT_NODE); + $assign = $assignedVariable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); $nestingHash = $this->flowOfControlLocator->resolveNestingHashFromFunctionLike($functionLike, $assign); - /** @var string $variableName */ $variableName = $this->nodeNameResolver->getName($assignedVariable); - - $nodesByTypeAndPosition[] = new VariableNodeUse( - $startTokenPos, - $variableName, - VariableNodeUse::TYPE_ASSIGN, - $assignedVariable, - $nestingHash - ); + $nodesByTypeAndPosition[] = new \Rector\DeadCode\ValueObject\VariableNodeUse($startTokenPos, $variableName, \Rector\DeadCode\ValueObject\VariableNodeUse::TYPE_ASSIGN, $assignedVariable, $nestingHash); } - foreach ($assignedVariablesUse as $assignedVariableUse) { /** @var int $startTokenPos */ - $startTokenPos = $assignedVariableUse->getAttribute(AttributeKey::START_TOKEN_POSITION); - + $startTokenPos = $assignedVariableUse->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::START_TOKEN_POSITION); /** @var string $variableName */ $variableName = $this->nodeNameResolver->getName($assignedVariableUse); - - $nodesByTypeAndPosition[] = new VariableNodeUse( - $startTokenPos, - $variableName, - VariableNodeUse::TYPE_USE, - $assignedVariableUse - ); + $nodesByTypeAndPosition[] = new \Rector\DeadCode\ValueObject\VariableNodeUse($startTokenPos, $variableName, \Rector\DeadCode\ValueObject\VariableNodeUse::TYPE_USE, $assignedVariableUse); } - return $this->sortByStart($nodesByTypeAndPosition); } - /** * @param VariableNodeUse[] $nodesByTypeAndPosition * @return VariableNodeUse[] */ - private function sortByStart(array $nodesByTypeAndPosition): array + private function sortByStart(array $nodesByTypeAndPosition) : array { - usort( - $nodesByTypeAndPosition, - function (VariableNodeUse $firstVariableNodeUse, VariableNodeUse $secondVariableNodeUse): int { - return $firstVariableNodeUse->getStartTokenPosition() <=> $secondVariableNodeUse->getStartTokenPosition(); - } - ); + \usort($nodesByTypeAndPosition, function (\Rector\DeadCode\ValueObject\VariableNodeUse $firstVariableNodeUse, \Rector\DeadCode\ValueObject\VariableNodeUse $secondVariableNodeUse) : int { + return $firstVariableNodeUse->getStartTokenPosition() <=> $secondVariableNodeUse->getStartTokenPosition(); + }); return $nodesByTypeAndPosition; } } diff --git a/rules/DeadCode/NodeCollector/UnusedParameterResolver.php b/rules/DeadCode/NodeCollector/UnusedParameterResolver.php index 977cb79eb0d..530458aa34b 100644 --- a/rules/DeadCode/NodeCollector/UnusedParameterResolver.php +++ b/rules/DeadCode/NodeCollector/UnusedParameterResolver.php @@ -1,7 +1,6 @@ classMethodManipulator = $classMethodManipulator; $this->nodeNameResolver = $nodeNameResolver; } - /** * @return Param[] */ - public function resolve(ClassMethod $classMethod): array + public function resolve(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $unusedParameters = []; - foreach ($classMethod->params as $i => $param) { // skip property promotion /** @var Param $param */ if ($param->flags !== 0) { continue; } - if ($this->classMethodManipulator->isParameterUsedInClassMethod($param, $classMethod)) { // reset to keep order of removed arguments, if not construtctor - probably autowired - if (! $this->nodeNameResolver->isName($classMethod, MethodName::CONSTRUCT)) { + if (!$this->nodeNameResolver->isName($classMethod, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { $unusedParameters = []; } - continue; } - $unusedParameters[$i] = $param; } - return $unusedParameters; } } diff --git a/rules/DeadCode/NodeFinder/NextVariableUsageNodeFinder.php b/rules/DeadCode/NodeFinder/NextVariableUsageNodeFinder.php index fc679b4fac6..cce5458941e 100644 --- a/rules/DeadCode/NodeFinder/NextVariableUsageNodeFinder.php +++ b/rules/DeadCode/NodeFinder/NextVariableUsageNodeFinder.php @@ -1,7 +1,6 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->parentScopeFinder = $parentScopeFinder; $this->betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; $this->nodeComparator = $nodeComparator; } - - public function find(Assign $assign): ?Node + public function find(\PhpParser\Node\Expr\Assign $assign) : ?\PhpParser\Node { $scopeNode = $this->parentScopeFinder->find($assign); if ($scopeNode === null) { return null; } - /** @var Variable $expr */ $expr = $assign->var; - $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $scopeNode->stmts, function ( - Node $currentNode - ) use ($expr, &$nextUsageOfVariable): ?int { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $scopeNode->stmts, function (\PhpParser\Node $currentNode) use($expr, &$nextUsageOfVariable) : ?int { // used above the assign if ($currentNode->getStartTokenPos() < $expr->getStartTokenPos()) { return null; } - // skip self if ($this->nodeComparator->areSameNode($currentNode, $expr)) { return null; } - - if (! $this->nodeComparator->areNodesEqual($currentNode, $expr)) { + if (!$this->nodeComparator->areNodesEqual($currentNode, $expr)) { return null; } - - $currentNodeParent = $currentNode->getAttribute(AttributeKey::PARENT_NODE); - - if ($currentNodeParent instanceof Assign && ! $this->hasInParentExpression($currentNodeParent, $expr)) { - return NodeTraverser::STOP_TRAVERSAL; + $currentNodeParent = $currentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($currentNodeParent instanceof \PhpParser\Node\Expr\Assign && !$this->hasInParentExpression($currentNodeParent, $expr)) { + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; } - $nextUsageOfVariable = $currentNode; - - return NodeTraverser::STOP_TRAVERSAL; + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; }); - return $nextUsageOfVariable; } - - private function hasInParentExpression(Assign $assign, Variable $variable): bool + private function hasInParentExpression(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Expr\Variable $variable) : bool { $name = $this->nodeNameResolver->getName($variable); if ($name === null) { - return false; + return \false; } - return $this->betterNodeFinder->hasVariableOfName($assign->expr, $name); } } diff --git a/rules/DeadCode/NodeFinder/PreviousVariableAssignNodeFinder.php b/rules/DeadCode/NodeFinder/PreviousVariableAssignNodeFinder.php index bd3b445dfcb..c9a3e13c734 100644 --- a/rules/DeadCode/NodeFinder/PreviousVariableAssignNodeFinder.php +++ b/rules/DeadCode/NodeFinder/PreviousVariableAssignNodeFinder.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; $this->nodeComparator = $nodeComparator; } - - public function find(Assign $assign): ?Node + public function find(\PhpParser\Node\Expr\Assign $assign) : ?\PhpParser\Node { $currentAssign = $assign; - $variableName = $this->nodeNameResolver->getName($assign->var); if ($variableName === null) { return null; } - - return $this->betterNodeFinder->findFirstPrevious($assign, function (Node $node) use ( - $variableName, - $currentAssign - ): bool { - if (! $node instanceof Assign) { - return false; + return $this->betterNodeFinder->findFirstPrevious($assign, function (\PhpParser\Node $node) use($variableName, $currentAssign) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - // skip self if ($this->nodeComparator->areSameNode($node, $currentAssign)) { - return false; + return \false; } - return $this->nodeNameResolver->isName($node->var, $variableName); }); } diff --git a/rules/DeadCode/NodeFinder/VariableUseFinder.php b/rules/DeadCode/NodeFinder/VariableUseFinder.php index 0f91ca1d256..276a0cce235 100644 --- a/rules/DeadCode/NodeFinder/VariableUseFinder.php +++ b/rules/DeadCode/NodeFinder/VariableUseFinder.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; $this->nodeComparator = $nodeComparator; } - /** * @param Variable[] $assignedVariables * @return Variable[] */ - public function resolveUsedVariables(Node $node, array $assignedVariables): array + public function resolveUsedVariables(\PhpParser\Node $node, array $assignedVariables) : array { - return $this->betterNodeFinder->find($node, function (Node $node) use ($assignedVariables): bool { - if (! $node instanceof Variable) { - return false; + return $this->betterNodeFinder->find($node, function (\PhpParser\Node $node) use($assignedVariables) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // is the left assign - not use of one - if ($parentNode instanceof Assign && ($parentNode->var instanceof Variable && $parentNode->var === $node)) { - return false; + if ($parentNode instanceof \PhpParser\Node\Expr\Assign && ($parentNode->var instanceof \PhpParser\Node\Expr\Variable && $parentNode->var === $node)) { + return \false; } $nodeNameResolverGetName = $this->nodeNameResolver->getName($node); - // simple variable only if ($nodeNameResolverGetName === null) { - return false; + return \false; } - return $this->nodeComparator->isNodeEqual($node, $assignedVariables); }); } diff --git a/rules/DeadCode/NodeManipulator/ControllerClassMethodManipulator.php b/rules/DeadCode/NodeManipulator/ControllerClassMethodManipulator.php index 962af312630..8eda84ecddf 100644 --- a/rules/DeadCode/NodeManipulator/ControllerClassMethodManipulator.php +++ b/rules/DeadCode/NodeManipulator/ControllerClassMethodManipulator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->phpDocInfoFactory = $phpDocInfoFactory; } - - public function isControllerClassMethodWithBehaviorAnnotation(ClassMethod $classMethod): bool + public function isControllerClassMethodWithBehaviorAnnotation(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - if (! $this->isControllerClassMethod($classMethod)) { - return false; + if (!$this->isControllerClassMethod($classMethod)) { + return \false; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); - return $phpDocInfo->hasByType(GenericTagValueNode::class); + return $phpDocInfo->hasByType(\PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode::class); } - - private function isControllerClassMethod(ClassMethod $classMethod): bool + private function isControllerClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - if (! $classMethod->isPublic()) { - return false; + if (!$classMethod->isPublic()) { + return \false; } - - $classLike = $classMethod->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return false; + $classLike = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } - return $this->hasParentClassController($classLike); } - - private function hasParentClassController(Class_ $class): bool + private function hasParentClassController(\PhpParser\Node\Stmt\Class_ $class) : bool { if ($class->extends === null) { - return false; + return \false; } - return $this->nodeNameResolver->isName($class->extends, '#(Controller|Presenter)$#'); } } diff --git a/rules/DeadCode/NodeManipulator/CountManipulator.php b/rules/DeadCode/NodeManipulator/CountManipulator.php index 62f00c5031a..62966cea018 100644 --- a/rules/DeadCode/NodeManipulator/CountManipulator.php +++ b/rules/DeadCode/NodeManipulator/CountManipulator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->nodeComparator = $nodeComparator; } - - public function isCounterHigherThanOne(Node $node, Expr $expr): bool + public function isCounterHigherThanOne(\PhpParser\Node $node, \PhpParser\Node\Expr $expr) : bool { // e.g. count($values) > 0 - if ($node instanceof Greater) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Greater) { return $this->processGreater($node, $expr); } - // e.g. count($values) >= 1 - if ($node instanceof GreaterOrEqual) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\GreaterOrEqual) { return $this->processGreaterOrEqual($node, $expr); } - // e.g. 0 < count($values) - if ($node instanceof Smaller) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Smaller) { return $this->processSmaller($node, $expr); } - // e.g. 1 <= count($values) - if ($node instanceof SmallerOrEqual) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\SmallerOrEqual) { return $this->processSmallerOrEqual($node, $expr); } - - return false; + return \false; } - - private function processGreater(Greater $greater, Expr $expr): bool + private function processGreater(\PhpParser\Node\Expr\BinaryOp\Greater $greater, \PhpParser\Node\Expr $expr) : bool { - if (! $this->isNumber($greater->right, 0)) { - return false; + if (!$this->isNumber($greater->right, 0)) { + return \false; } - return $this->isCountWithExpression($greater->left, $expr); } - - private function processGreaterOrEqual(GreaterOrEqual $greaterOrEqual, Expr $expr): bool + private function processGreaterOrEqual(\PhpParser\Node\Expr\BinaryOp\GreaterOrEqual $greaterOrEqual, \PhpParser\Node\Expr $expr) : bool { - if (! $this->isNumber($greaterOrEqual->right, 1)) { - return false; + if (!$this->isNumber($greaterOrEqual->right, 1)) { + return \false; } - return $this->isCountWithExpression($greaterOrEqual->left, $expr); } - - private function processSmaller(Smaller $smaller, Expr $expr): bool + private function processSmaller(\PhpParser\Node\Expr\BinaryOp\Smaller $smaller, \PhpParser\Node\Expr $expr) : bool { - if (! $this->isNumber($smaller->left, 0)) { - return false; + if (!$this->isNumber($smaller->left, 0)) { + return \false; } - return $this->isCountWithExpression($smaller->right, $expr); } - - private function processSmallerOrEqual(SmallerOrEqual $smallerOrEqual, Expr $expr): bool + private function processSmallerOrEqual(\PhpParser\Node\Expr\BinaryOp\SmallerOrEqual $smallerOrEqual, \PhpParser\Node\Expr $expr) : bool { - if (! $this->isNumber($smallerOrEqual->left, 1)) { - return false; + if (!$this->isNumber($smallerOrEqual->left, 1)) { + return \false; } - return $this->isCountWithExpression($smallerOrEqual->right, $expr); } - - private function isNumber(Node $node, int $value): bool + private function isNumber(\PhpParser\Node $node, int $value) : bool { - if (! $node instanceof LNumber) { - return false; + if (!$node instanceof \PhpParser\Node\Scalar\LNumber) { + return \false; } - return $node->value === $value; } - - private function isCountWithExpression(Node $node, Expr $expr): bool + private function isCountWithExpression(\PhpParser\Node $node, \PhpParser\Node\Expr $expr) : bool { - if (! $node instanceof FuncCall) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - - if (! $this->nodeNameResolver->isName($node, 'count')) { - return false; + if (!$this->nodeNameResolver->isName($node, 'count')) { + return \false; } - $countedExpr = $node->args[0]->value; - return $this->nodeComparator->areNodesEqual($countedExpr, $expr); } } diff --git a/rules/DeadCode/NodeManipulator/LivingCodeManipulator.php b/rules/DeadCode/NodeManipulator/LivingCodeManipulator.php index 18ed27c986d..3715badccbb 100644 --- a/rules/DeadCode/NodeManipulator/LivingCodeManipulator.php +++ b/rules/DeadCode/NodeManipulator/LivingCodeManipulator.php @@ -1,7 +1,6 @@ nodesToAddCollector = $nodesToAddCollector; } - - public function addLivingCodeBeforeNode(Expr $expr, Node $addBeforeThisNode): void + public function addLivingCodeBeforeNode(\PhpParser\Node\Expr $expr, \PhpParser\Node $addBeforeThisNode) : void { $livinExprs = $this->keepLivingCodeFromExpr($expr); foreach ($livinExprs as $livinExpr) { - $this->nodesToAddCollector->addNodeBeforeNode(new Expression($livinExpr), $addBeforeThisNode); + $this->nodesToAddCollector->addNodeBeforeNode(new \PhpParser\Node\Stmt\Expression($livinExpr), $addBeforeThisNode); } } - /** * @param Node|int|string|null $expr * @return Expr[]|mixed[] */ - public function keepLivingCodeFromExpr($expr): array + public function keepLivingCodeFromExpr($expr) : array { - if (! $expr instanceof Expr) { + if (!$expr instanceof \PhpParser\Node\Expr) { return []; } - - if ($expr instanceof Closure || $expr instanceof Scalar || $expr instanceof ConstFetch) { + if ($expr instanceof \PhpParser\Node\Expr\Closure || $expr instanceof \PhpParser\Node\Scalar || $expr instanceof \PhpParser\Node\Expr\ConstFetch) { return []; } - if ($this->isNestedExpr($expr)) { return $this->keepLivingCodeFromExpr($expr->expr); } - - if ($expr instanceof Variable) { + if ($expr instanceof \PhpParser\Node\Expr\Variable) { return $this->keepLivingCodeFromExpr($expr->name); } - - if ($expr instanceof PropertyFetch) { - return array_merge( - $this->keepLivingCodeFromExpr($expr->var), - $this->keepLivingCodeFromExpr($expr->name) - ); + if ($expr instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \array_merge($this->keepLivingCodeFromExpr($expr->var), $this->keepLivingCodeFromExpr($expr->name)); } - - if ($expr instanceof ArrayDimFetch) { - return array_merge( - $this->keepLivingCodeFromExpr($expr->var), - $this->keepLivingCodeFromExpr($expr->dim) - ); + if ($expr instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + return \array_merge($this->keepLivingCodeFromExpr($expr->var), $this->keepLivingCodeFromExpr($expr->dim)); } - - if ($expr instanceof ClassConstFetch || $expr instanceof StaticPropertyFetch) { - return array_merge( - $this->keepLivingCodeFromExpr($expr->class), - $this->keepLivingCodeFromExpr($expr->name) - ); + if ($expr instanceof \PhpParser\Node\Expr\ClassConstFetch || $expr instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { + return \array_merge($this->keepLivingCodeFromExpr($expr->class), $this->keepLivingCodeFromExpr($expr->name)); } - if ($this->isBinaryOpWithoutChange($expr)) { /** @var BinaryOp $binaryOp */ $binaryOp = $expr; return $this->processBinary($binaryOp); } - - if ($expr instanceof Instanceof_) { - return array_merge( - $this->keepLivingCodeFromExpr($expr->expr), - $this->keepLivingCodeFromExpr($expr->class) - ); + if ($expr instanceof \PhpParser\Node\Expr\Instanceof_) { + return \array_merge($this->keepLivingCodeFromExpr($expr->expr), $this->keepLivingCodeFromExpr($expr->class)); } - - if ($expr instanceof Isset_) { + if ($expr instanceof \PhpParser\Node\Expr\Isset_) { return $this->processIsset($expr); } - return [$expr]; } - - private function isNestedExpr(Expr $expr): bool + private function isNestedExpr(\PhpParser\Node\Expr $expr) : bool { - return $expr instanceof Cast || - $expr instanceof Empty_ || - $expr instanceof UnaryMinus || - $expr instanceof UnaryPlus || - $expr instanceof BitwiseNot || - $expr instanceof BooleanNot || - $expr instanceof Clone_; + return $expr instanceof \PhpParser\Node\Expr\Cast || $expr instanceof \PhpParser\Node\Expr\Empty_ || $expr instanceof \PhpParser\Node\Expr\UnaryMinus || $expr instanceof \PhpParser\Node\Expr\UnaryPlus || $expr instanceof \PhpParser\Node\Expr\BitwiseNot || $expr instanceof \PhpParser\Node\Expr\BooleanNot || $expr instanceof \PhpParser\Node\Expr\Clone_; } - - private function isBinaryOpWithoutChange(Expr $expr): bool + private function isBinaryOpWithoutChange(\PhpParser\Node\Expr $expr) : bool { - if (! $expr instanceof BinaryOp) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\BinaryOp) { + return \false; } - - return ! ( - $expr instanceof LogicalAnd || - $expr instanceof BooleanAnd || - $expr instanceof LogicalOr || - $expr instanceof BooleanOr || - $expr instanceof Coalesce - ); + return !($expr instanceof \PhpParser\Node\Expr\BinaryOp\LogicalAnd || $expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd || $expr instanceof \PhpParser\Node\Expr\BinaryOp\LogicalOr || $expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr || $expr instanceof \PhpParser\Node\Expr\BinaryOp\Coalesce); } - /** * @return Expr[] */ - private function processBinary(BinaryOp $binaryOp): array + private function processBinary(\PhpParser\Node\Expr\BinaryOp $binaryOp) : array { - return array_merge( - $this->keepLivingCodeFromExpr($binaryOp->left), - $this->keepLivingCodeFromExpr($binaryOp->right) - ); + return \array_merge($this->keepLivingCodeFromExpr($binaryOp->left), $this->keepLivingCodeFromExpr($binaryOp->right)); } - /** * @return mixed[] */ - private function processIsset(Isset_ $isset): array + private function processIsset(\PhpParser\Node\Expr\Isset_ $isset) : array { $livingExprs = []; foreach ($isset->vars as $expr) { - $livingExprs = array_merge($livingExprs, $this->keepLivingCodeFromExpr($expr)); + $livingExprs = \array_merge($livingExprs, $this->keepLivingCodeFromExpr($expr)); } - return $livingExprs; } } diff --git a/rules/DeadCode/NodeManipulator/VariadicFunctionLikeDetector.php b/rules/DeadCode/NodeManipulator/VariadicFunctionLikeDetector.php index afa2022ec2e..2c94efe0899 100644 --- a/rules/DeadCode/NodeManipulator/VariadicFunctionLikeDetector.php +++ b/rules/DeadCode/NodeManipulator/VariadicFunctionLikeDetector.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - - public function isVariadic(FunctionLike $functionLike): bool + public function isVariadic(\PhpParser\Node\FunctionLike $functionLike) : bool { - $isVariadic = false; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $functionLike->getStmts(), - function (Node $node) use (&$isVariadic): ?int { - if (! $node instanceof FuncCall) { - return null; - } - - if (! $this->nodeNameResolver->isNames($node, self::VARIADIC_FUNCTION_NAMES)) { - return null; - } - - $isVariadic = true; - - return NodeTraverser::STOP_TRAVERSAL; + $isVariadic = \false; + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $functionLike->getStmts(), function (\PhpParser\Node $node) use(&$isVariadic) : ?int { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { + return null; } - ); - + if (!$this->nodeNameResolver->isNames($node, self::VARIADIC_FUNCTION_NAMES)) { + return null; + } + $isVariadic = \true; + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; + }); return $isVariadic; } } diff --git a/rules/DeadCode/PhpDoc/DeadParamTagValueNodeAnalyzer.php b/rules/DeadCode/PhpDoc/DeadParamTagValueNodeAnalyzer.php index ce855755cf0..b428bbb814d 100644 --- a/rules/DeadCode/PhpDoc/DeadParamTagValueNodeAnalyzer.php +++ b/rules/DeadCode/PhpDoc/DeadParamTagValueNodeAnalyzer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->typeComparator = $typeComparator; } - - public function isDead(ParamTagValueNode $paramTagValueNode, FunctionLike $functionLike): bool + public function isDead(\PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode $paramTagValueNode, \PhpParser\Node\FunctionLike $functionLike) : bool { $param = $this->matchParamByName($paramTagValueNode->parameterName, $functionLike); - if (! $param instanceof Param) { - return false; + if (!$param instanceof \PhpParser\Node\Param) { + return \false; } - if ($param->type === null) { - return false; + return \false; } - - if (! $this->typeComparator->arePhpParserAndPhpStanPhpDocTypesEqual( - $param->type, - $paramTagValueNode->type, - $functionLike - )) { - return false; + if (!$this->typeComparator->arePhpParserAndPhpStanPhpDocTypesEqual($param->type, $paramTagValueNode->type, $functionLike)) { + return \false; } - - if ($paramTagValueNode->type instanceof GenericTypeNode) { - return false; + if ($paramTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\GenericTypeNode) { + return \false; } - return $paramTagValueNode->description === ''; } - - private function matchParamByName(string $desiredParamName, FunctionLike $functionLike): ?Param + private function matchParamByName(string $desiredParamName, \PhpParser\Node\FunctionLike $functionLike) : ?\PhpParser\Node\Param { foreach ($functionLike->getParams() as $param) { $paramName = $this->nodeNameResolver->getName($param); if ('$' . $paramName !== $desiredParamName) { continue; } - return $param; } - return null; } } diff --git a/rules/DeadCode/PhpDoc/DeadReturnTagValueNodeAnalyzer.php b/rules/DeadCode/PhpDoc/DeadReturnTagValueNodeAnalyzer.php index c5e7f6b7cc9..c3c2e2b4cb7 100644 --- a/rules/DeadCode/PhpDoc/DeadReturnTagValueNodeAnalyzer.php +++ b/rules/DeadCode/PhpDoc/DeadReturnTagValueNodeAnalyzer.php @@ -1,45 +1,34 @@ typeComparator = $typeComparator; } - - public function isDead(ReturnTagValueNode $returnTagValueNode, FunctionLike $functionLike): bool + public function isDead(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode $returnTagValueNode, \PhpParser\Node\FunctionLike $functionLike) : bool { $returnType = $functionLike->getReturnType(); if ($returnType === null) { - return false; + return \false; } - - if (! $this->typeComparator->arePhpParserAndPhpStanPhpDocTypesEqual( - $returnType, - $returnTagValueNode->type, - $functionLike - )) { - return false; + if (!$this->typeComparator->arePhpParserAndPhpStanPhpDocTypesEqual($returnType, $returnTagValueNode->type, $functionLike)) { + return \false; } - - if ($returnTagValueNode->type instanceof GenericTypeNode) { - return false; + if ($returnTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\GenericTypeNode) { + return \false; } - return $returnTagValueNode->description === ''; } } diff --git a/rules/DeadCode/PhpDoc/DeadVarTagValueNodeAnalyzer.php b/rules/DeadCode/PhpDoc/DeadVarTagValueNodeAnalyzer.php index 5997264fff4..7a6a81cce7d 100644 --- a/rules/DeadCode/PhpDoc/DeadVarTagValueNodeAnalyzer.php +++ b/rules/DeadCode/PhpDoc/DeadVarTagValueNodeAnalyzer.php @@ -1,39 +1,29 @@ typeComparator = $typeComparator; } - - public function isDead(VarTagValueNode $varTagValueNode, Property $property): bool + public function isDead(\PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode $varTagValueNode, \PhpParser\Node\Stmt\Property $property) : bool { if ($property->type === null) { - return false; + return \false; } - - if (! $this->typeComparator->arePhpParserAndPhpStanPhpDocTypesEqual( - $property->type, - $varTagValueNode->type, - $property - )) { - return false; + if (!$this->typeComparator->arePhpParserAndPhpStanPhpDocTypesEqual($property->type, $varTagValueNode->type, $property)) { + return \false; } - return $varTagValueNode->description === ''; } } diff --git a/rules/DeadCode/PhpDoc/TagRemover/ParamTagRemover.php b/rules/DeadCode/PhpDoc/TagRemover/ParamTagRemover.php index a218f6e90dd..31c67c4ccfd 100644 --- a/rules/DeadCode/PhpDoc/TagRemover/ParamTagRemover.php +++ b/rules/DeadCode/PhpDoc/TagRemover/ParamTagRemover.php @@ -1,7 +1,6 @@ deadParamTagValueNodeAnalyzer = $deadParamTagValueNodeAnalyzer; $this->phpDocTagRemover = $phpDocTagRemover; } - - public function removeParamTagsIfUseless(PhpDocInfo $phpDocInfo, FunctionLike $functionLike): void + public function removeParamTagsIfUseless(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \PhpParser\Node\FunctionLike $functionLike) : void { foreach ($phpDocInfo->getParamTagValueNodes() as $paramTagValueNode) { $paramName = $paramTagValueNode->parameterName; - // remove existing type - $paramTagValueNode = $phpDocInfo->getParamTagValueByName($paramName); - - if (! $paramTagValueNode instanceof ParamTagValueNode) { + if (!$paramTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode) { continue; } - $isParamTagValueDead = $this->deadParamTagValueNodeAnalyzer->isDead($paramTagValueNode, $functionLike); - if (! $isParamTagValueDead) { + if (!$isParamTagValueDead) { continue; } - $this->phpDocTagRemover->removeTagValueFromNode($phpDocInfo, $paramTagValueNode); } } diff --git a/rules/DeadCode/PhpDoc/TagRemover/ReturnTagRemover.php b/rules/DeadCode/PhpDoc/TagRemover/ReturnTagRemover.php index 3eae2c06262..93f6a61b949 100644 --- a/rules/DeadCode/PhpDoc/TagRemover/ReturnTagRemover.php +++ b/rules/DeadCode/PhpDoc/TagRemover/ReturnTagRemover.php @@ -1,7 +1,6 @@ deadReturnTagValueNodeAnalyzer = $deadReturnTagValueNodeAnalyzer; } - - public function removeReturnTagIfUseless(PhpDocInfo $phpDocInfo, FunctionLike $functionLike): void + public function removeReturnTagIfUseless(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \PhpParser\Node\FunctionLike $functionLike) : void { // remove existing type $returnTagValueNode = $phpDocInfo->getReturnTagValue(); - if (! $returnTagValueNode instanceof ReturnTagValueNode) { + if (!$returnTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode) { return; } - $isReturnTagValueDead = $this->deadReturnTagValueNodeAnalyzer->isDead($returnTagValueNode, $functionLike); - if (! $isReturnTagValueDead) { + if (!$isReturnTagValueDead) { return; } - - $phpDocInfo->removeByType(ReturnTagValueNode::class); + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode::class); } } diff --git a/rules/DeadCode/PhpDoc/TagRemover/VarTagRemover.php b/rules/DeadCode/PhpDoc/TagRemover/VarTagRemover.php index 9d8d859a3aa..3a3d13d423b 100644 --- a/rules/DeadCode/PhpDoc/TagRemover/VarTagRemover.php +++ b/rules/DeadCode/PhpDoc/TagRemover/VarTagRemover.php @@ -1,7 +1,6 @@ doctrineTypeAnalyzer = $doctrineTypeAnalyzer; $this->staticTypeMapper = $staticTypeMapper; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->classLikeExistenceChecker = $classLikeExistenceChecker; $this->deadVarTagValueNodeAnalyzer = $deadVarTagValueNodeAnalyzer; } - - public function removeVarTagIfUseless(PhpDocInfo $phpDocInfo, Property $property): void + public function removeVarTagIfUseless(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \PhpParser\Node\Stmt\Property $property) : void { $varTagValueNode = $phpDocInfo->getVarTagValueNode(); - if (! $varTagValueNode instanceof VarTagValueNode) { + if (!$varTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode) { return; } - $isVarTagValueDead = $this->deadVarTagValueNodeAnalyzer->isDead($varTagValueNode, $property); - if (! $isVarTagValueDead) { + if (!$isVarTagValueDead) { return; } - - $phpDocInfo->removeByType(VarTagValueNode::class); + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode::class); } - /** * @param Expression|Property|Param $node */ - public function removeVarPhpTagValueNodeIfNotComment(Node $node, Type $type): void + public function removeVarPhpTagValueNodeIfNotComment(\PhpParser\Node $node, \PHPStan\Type\Type $type) : void { // keep doctrine collection narrow type if ($this->doctrineTypeAnalyzer->isDoctrineCollectionWithIterableUnionType($type)) { return; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - $varTagValueNode = $phpDocInfo->getVarTagValueNode(); - if (! $varTagValueNode instanceof VarTagValueNode) { + if (!$varTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode) { return; } - // has description? keep it if ($varTagValueNode->description !== '') { return; } - // keep generic types - if ($varTagValueNode->type instanceof GenericTypeNode) { + if ($varTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\GenericTypeNode) { return; } - // keep string[] etc. if ($this->isNonBasicArrayType($node, $varTagValueNode)) { return; } - - $phpDocInfo->removeByType(VarTagValueNode::class); + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode::class); } - /** * @param Expression|Param|Property $node */ - private function isNonBasicArrayType(Node $node, VarTagValueNode $varTagValueNode): bool + private function isNonBasicArrayType(\PhpParser\Node $node, \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode $varTagValueNode) : bool { - if ($varTagValueNode->type instanceof BracketsAwareUnionTypeNode) { + if ($varTagValueNode->type instanceof \Rector\BetterPhpDocParser\ValueObject\Type\BracketsAwareUnionTypeNode) { foreach ($varTagValueNode->type->types as $type) { - if ($type instanceof SpacingAwareArrayTypeNode && $this->isArrayOfExistingClassNode($node, $type)) { - return true; + if ($type instanceof \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode && $this->isArrayOfExistingClassNode($node, $type)) { + return \true; } } } - - if (! $this->isArrayTypeNode($varTagValueNode)) { - return false; + if (!$this->isArrayTypeNode($varTagValueNode)) { + return \false; } - return (string) $varTagValueNode->type !== 'array'; } - - private function isArrayTypeNode(VarTagValueNode $varTagValueNode): bool + private function isArrayTypeNode(\PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode $varTagValueNode) : bool { - return $varTagValueNode->type instanceof ArrayTypeNode; + return $varTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; } - - private function isArrayOfExistingClassNode( - Node $node, - SpacingAwareArrayTypeNode $spacingAwareArrayTypeNode - ): bool { - $staticType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType( - $spacingAwareArrayTypeNode, - $node - ); - - if (! $staticType instanceof ArrayType) { - return false; + private function isArrayOfExistingClassNode(\PhpParser\Node $node, \Rector\BetterPhpDocParser\ValueObject\Type\SpacingAwareArrayTypeNode $spacingAwareArrayTypeNode) : bool + { + $staticType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType($spacingAwareArrayTypeNode, $node); + if (!$staticType instanceof \PHPStan\Type\ArrayType) { + return \false; } - $itemType = $staticType->getItemType(); - if (! $itemType instanceof ObjectType) { - return false; + if (!$itemType instanceof \PHPStan\Type\ObjectType) { + return \false; } - $className = $itemType->getClassName(); - return $this->classLikeExistenceChecker->doesClassLikeExist($className); } } diff --git a/rules/DeadCode/Rector/Array_/RemoveDuplicatedArrayKeyRector.php b/rules/DeadCode/Rector/Array_/RemoveDuplicatedArrayKeyRector.php index 0c0467958b2..7958dc7d0ce 100644 --- a/rules/DeadCode/Rector/Array_/RemoveDuplicatedArrayKeyRector.php +++ b/rules/DeadCode/Rector/Array_/RemoveDuplicatedArrayKeyRector.php @@ -1,7 +1,6 @@ 'A', 1 => 'B' ]; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $item = [ 1 => 'B' ]; CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Array_::class]; + return [\PhpParser\Node\Expr\Array_::class]; } - /** * @param Array_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $arrayItemsWithDuplicatedKey = $this->getArrayItemsWithDuplicatedKey($node); if ($arrayItemsWithDuplicatedKey === []) { return null; } - foreach ($arrayItemsWithDuplicatedKey as $arrayItemWithDuplicatedKey) { // keep last item - array_pop($arrayItemWithDuplicatedKey); + \array_pop($arrayItemWithDuplicatedKey); $this->removeNodes($arrayItemWithDuplicatedKey); } - return $node; } - /** * @return ArrayItem[][] */ - private function getArrayItemsWithDuplicatedKey(Array_ $array): array + private function getArrayItemsWithDuplicatedKey(\PhpParser\Node\Expr\Array_ $array) : array { $arrayItemsByKeys = []; - foreach ($array->items as $arrayItem) { - if (! $arrayItem instanceof ArrayItem) { + if (!$arrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - if ($arrayItem->key === null) { continue; } - $keyValue = $this->print($arrayItem->key); $arrayItemsByKeys[$keyValue][] = $arrayItem; } - return $this->filterItemsWithSameKey($arrayItemsByKeys); } - /** * @param ArrayItem[][] $arrayItemsByKeys * @return ArrayItem[][] */ - private function filterItemsWithSameKey(array $arrayItemsByKeys): array + private function filterItemsWithSameKey(array $arrayItemsByKeys) : array { /** @var ArrayItem[][] $arrayItemsByKeys */ - $arrayItemsByKeys = array_filter($arrayItemsByKeys, function (array $arrayItems): bool { - return count($arrayItems) > 1; + $arrayItemsByKeys = \array_filter($arrayItemsByKeys, function (array $arrayItems) : bool { + return \count($arrayItems) > 1; }); - - return array_filter($arrayItemsByKeys, function (array $arrayItems): bool { - return count($arrayItems) > 1; + return \array_filter($arrayItemsByKeys, function (array $arrayItems) : bool { + return \count($arrayItems) > 1; }); } } diff --git a/rules/DeadCode/Rector/Assign/RemoveAssignOfVoidReturnFunctionRector.php b/rules/DeadCode/Rector/Assign/RemoveAssignOfVoidReturnFunctionRector.php index bd0ee73cbdf..e0227e454dd 100644 --- a/rules/DeadCode/Rector/Assign/RemoveAssignOfVoidReturnFunctionRector.php +++ b/rules/DeadCode/Rector/Assign/RemoveAssignOfVoidReturnFunctionRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof FuncCall && ! $node->expr instanceof MethodCall && ! $node->expr instanceof StaticCall) { + if (!$node->expr instanceof \PhpParser\Node\Expr\FuncCall && !$node->expr instanceof \PhpParser\Node\Expr\MethodCall && !$node->expr instanceof \PhpParser\Node\Expr\StaticCall) { return null; } - $exprType = $this->nodeTypeResolver->resolve($node->expr); - if (! $exprType instanceof VoidType) { + if (!$exprType instanceof \PHPStan\Type\VoidType) { return null; } - return $node->expr; } } diff --git a/rules/DeadCode/Rector/Assign/RemoveDoubleAssignRector.php b/rules/DeadCode/Rector/Assign/RemoveDoubleAssignRector.php index 5f7d1555bdd..0dd38610962 100644 --- a/rules/DeadCode/Rector/Assign/RemoveDoubleAssignRector.php +++ b/rules/DeadCode/Rector/Assign/RemoveDoubleAssignRector.php @@ -1,7 +1,6 @@ scopeNestingComparator = $scopeNestingComparator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Simplify useless double assigns', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Simplify useless double assigns', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $value = 1; $value = 1; CODE_SAMPLE - , - '$value = 1;' - ), - ]); +, '$value = 1;')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->var instanceof Variable && ! $node->var instanceof PropertyFetch && ! $node->var instanceof StaticPropertyFetch) { + if (!$node->var instanceof \PhpParser\Node\Expr\Variable && !$node->var instanceof \PhpParser\Node\Expr\PropertyFetch && !$node->var instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { return null; } - - $previousStatement = $node->getAttribute(AttributeKey::PREVIOUS_STATEMENT); - if (! $previousStatement instanceof Expression) { + $previousStatement = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT); + if (!$previousStatement instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - if (! $previousStatement->expr instanceof Assign) { + if (!$previousStatement->expr instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $this->nodeComparator->areNodesEqual($previousStatement->expr->var, $node->var)) { + if (!$this->nodeComparator->areNodesEqual($previousStatement->expr->var, $node->var)) { return null; } - if ($this->isCall($previousStatement->expr->expr)) { return null; } - if ($this->shouldSkipForDifferentScope($node, $previousStatement)) { return null; } - if ($this->isSelfReferencing($node)) { return null; } - // no calls on right, could hide e.g. array_pop()|array_shift() $this->removeNode($previousStatement); - return $node; } - - private function isCall(Expr $expr): bool + private function isCall(\PhpParser\Node\Expr $expr) : bool { - return $expr instanceof FuncCall || $expr instanceof StaticCall || $expr instanceof MethodCall; + return $expr instanceof \PhpParser\Node\Expr\FuncCall || $expr instanceof \PhpParser\Node\Expr\StaticCall || $expr instanceof \PhpParser\Node\Expr\MethodCall; } - - private function shouldSkipForDifferentScope(Assign $assign, Expression $expression): bool + private function shouldSkipForDifferentScope(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Stmt\Expression $expression) : bool { - if (! $this->areInSameClassMethod($assign, $expression)) { - return true; + if (!$this->areInSameClassMethod($assign, $expression)) { + return \true; } - - return ! $this->scopeNestingComparator->areScopeNestingEqual($assign, $expression); + return !$this->scopeNestingComparator->areScopeNestingEqual($assign, $expression); } - - private function isSelfReferencing(Assign $assign): bool + private function isSelfReferencing(\PhpParser\Node\Expr\Assign $assign) : bool { - return (bool) $this->betterNodeFinder->findFirst($assign->expr, function (Node $subNode) use ($assign): bool { + return (bool) $this->betterNodeFinder->findFirst($assign->expr, function (\PhpParser\Node $subNode) use($assign) : bool { return $this->nodeComparator->areNodesEqual($assign->var, $subNode); }); } - - private function areInSameClassMethod(Assign $assign, Expression $previousExpression): bool + private function areInSameClassMethod(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Stmt\Expression $previousExpression) : bool { - return $this->nodeComparator->areNodesEqual( - $assign->getAttribute(AttributeKey::METHOD_NODE), - $previousExpression->getAttribute(AttributeKey::METHOD_NODE) - ); + return $this->nodeComparator->areNodesEqual($assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE), $previousExpression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE)); } } diff --git a/rules/DeadCode/Rector/Assign/RemoveUnusedAssignVariableRector.php b/rules/DeadCode/Rector/Assign/RemoveUnusedAssignVariableRector.php index 028f7c11b48..4efe33ebf05 100644 --- a/rules/DeadCode/Rector/Assign/RemoveUnusedAssignVariableRector.php +++ b/rules/DeadCode/Rector/Assign/RemoveUnusedAssignVariableRector.php @@ -1,7 +1,6 @@ sideEffectNodeDetector = $sideEffectNodeDetector; $this->previousVariableAssignNodeFinder = $previousVariableAssignNodeFinder; $this->scopeNestingComparator = $scopeNestingComparator; $this->nextVariableUsageNodeFinder = $nextVariableUsageNodeFinder; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove assigned unused variable', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove assigned unused variable', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -81,8 +67,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -97,83 +82,67 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipAssign($node)) { return null; } - - if ($this->isVariableTypeInScope($node) && ! $this->isPreviousVariablePartOfOverridingAssign($node)) { + if ($this->isVariableTypeInScope($node) && !$this->isPreviousVariablePartOfOverridingAssign($node)) { return null; } - // is scalar assign? remove whole - if (! $this->sideEffectNodeDetector->detect($node->expr)) { + if (!$this->sideEffectNodeDetector->detect($node->expr)) { $this->removeNode($node); return null; } - return $node->expr; } - - private function shouldSkipAssign(Assign $assign): bool + private function shouldSkipAssign(\PhpParser\Node\Expr\Assign $assign) : bool { - if (! $assign->var instanceof Variable) { - return true; + if (!$assign->var instanceof \PhpParser\Node\Expr\Variable) { + return \true; } - // unable to resolve name $variableName = $this->getName($assign->var); if ($variableName === null) { - return true; + return \true; } - if ($this->isNestedAssign($assign)) { - return true; + return \true; } - $nextUsedVariable = $this->nextVariableUsageNodeFinder->find($assign); return $nextUsedVariable !== null; } - - private function isVariableTypeInScope(Assign $assign): bool + private function isVariableTypeInScope(\PhpParser\Node\Expr\Assign $assign) : bool { - $scope = $assign->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - /** @var string $variableName */ $variableName = $this->getName($assign->var); - - return ! $scope->hasVariableType($variableName) - ->no(); + return !$scope->hasVariableType($variableName)->no(); } - - private function isPreviousVariablePartOfOverridingAssign(Assign $assign): bool + private function isPreviousVariablePartOfOverridingAssign(\PhpParser\Node\Expr\Assign $assign) : bool { // is previous variable node as part of assign? $previousVariableAssign = $this->previousVariableAssignNodeFinder->find($assign); - if (! $previousVariableAssign instanceof Node) { - return false; + if (!$previousVariableAssign instanceof \PhpParser\Node) { + return \false; } - return $this->scopeNestingComparator->areScopeNestingEqual($assign, $previousVariableAssign); } - /** * Nested assign, e.g "$oldValues = <$values> = 5;" */ - private function isNestedAssign(Assign $assign): bool + private function isNestedAssign(\PhpParser\Node\Expr\Assign $assign) : bool { - $parent = $assign->getAttribute(AttributeKey::PARENT_NODE); - return $parent instanceof Assign; + $parent = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + return $parent instanceof \PhpParser\Node\Expr\Assign; } } diff --git a/rules/DeadCode/Rector/Assign/RemoveUnusedVariableAssignRector.php b/rules/DeadCode/Rector/Assign/RemoveUnusedVariableAssignRector.php index 1bf17c9a795..791c229aec2 100644 --- a/rules/DeadCode/Rector/Assign/RemoveUnusedVariableAssignRector.php +++ b/rules/DeadCode/Rector/Assign/RemoveUnusedVariableAssignRector.php @@ -1,7 +1,6 @@ reservedKeywordAnalyzer = $reservedKeywordAnalyzer; $this->compactFuncCallAnalyzer = $compactFuncCallAnalyzer; $this->conditionSearcher = $conditionSearcher; $this->usedVariableNameAnalyzer = $usedVariableNameAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove unused assigns to variables', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove unused assigns to variables', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -76,8 +63,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -85,167 +71,125 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $variable = $node->var; - if (! $variable instanceof Variable) { + if (!$variable instanceof \PhpParser\Node\Expr\Variable) { return null; } - $variableName = $this->getName($variable); if ($variableName !== null && $this->reservedKeywordAnalyzer->isNativeVariable($variableName)) { return null; } - // variable is used if ($this->isUsed($node, $variable)) { return $this->refactorUsedVariable($node); } - - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Expression) { + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - if ($node->expr instanceof MethodCall || $node->expr instanceof StaticCall) { + if ($node->expr instanceof \PhpParser\Node\Expr\MethodCall || $node->expr instanceof \PhpParser\Node\Expr\StaticCall) { // keep the expr, can have side effect return $node->expr; } - $this->removeNode($node); return $node; } - - private function shouldSkip(Assign $assign): bool + private function shouldSkip(\PhpParser\Node\Expr\Assign $assign) : bool { - $classMethod = $assign->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof FunctionLike) { - return true; + $classMethod = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\FunctionLike) { + return \true; } - $variable = $assign->var; - if (! $variable instanceof Variable) { - return true; + if (!$variable instanceof \PhpParser\Node\Expr\Variable) { + return \true; } - - return $variable->name instanceof Variable && $this->betterNodeFinder->findFirstNext( - $assign, - function (Node $node): bool { - return $node instanceof Variable; - } - ); + return $variable->name instanceof \PhpParser\Node\Expr\Variable && $this->betterNodeFinder->findFirstNext($assign, function (\PhpParser\Node $node) : bool { + return $node instanceof \PhpParser\Node\Expr\Variable; + }); } - - private function isUsed(Assign $assign, Variable $variable): bool + private function isUsed(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Expr\Variable $variable) : bool { - $isUsedPrev = (bool) $this->betterNodeFinder->findFirstPreviousOfNode($variable, function (Node $node) use ( - $variable - ): bool { + $isUsedPrev = (bool) $this->betterNodeFinder->findFirstPreviousOfNode($variable, function (\PhpParser\Node $node) use($variable) : bool { return $this->usedVariableNameAnalyzer->isVariableNamed($node, $variable); }); - if ($isUsedPrev) { - return true; + return \true; } - if ($this->isUsedNext($variable)) { - return true; + return \true; } - /** @var FuncCall|MethodCall|New_|NullsafeMethodCall|StaticCall $expr */ $expr = $assign->expr; - if (! $this->isCall($expr)) { - return false; + if (!$this->isCall($expr)) { + return \false; } - return $this->isUsedInAssignExpr($expr, $assign); } - - private function isUsedNext(Variable $variable): bool + private function isUsedNext(\PhpParser\Node\Expr\Variable $variable) : bool { - return (bool) $this->betterNodeFinder->findFirstNext($variable, function (Node $node) use ( - $variable - ): bool { + return (bool) $this->betterNodeFinder->findFirstNext($variable, function (\PhpParser\Node $node) use($variable) : bool { if ($this->usedVariableNameAnalyzer->isVariableNamed($node, $variable)) { - return true; + return \true; } - - if ($node instanceof FuncCall) { + if ($node instanceof \PhpParser\Node\Expr\FuncCall) { return $this->compactFuncCallAnalyzer->isInCompact($node, $variable); } - - return $node instanceof Include_; + return $node instanceof \PhpParser\Node\Expr\Include_; }); } - /** * @param FuncCall|MethodCall|New_|NullsafeMethodCall|StaticCall $expr */ - private function isUsedInAssignExpr(Expr $expr, Assign $assign): bool + private function isUsedInAssignExpr(\PhpParser\Node\Expr $expr, \PhpParser\Node\Expr\Assign $assign) : bool { foreach ($expr->args as $arg) { $variable = $arg->value; - if (! $variable instanceof Variable) { + if (!$variable instanceof \PhpParser\Node\Expr\Variable) { continue; } - - $previousAssign = $this->betterNodeFinder->findFirstPreviousOfNode($assign, function (Node $node) use ( - $variable - ): bool { - return $node instanceof Assign && $this->usedVariableNameAnalyzer->isVariableNamed( - $node->var, - $variable - ); + $previousAssign = $this->betterNodeFinder->findFirstPreviousOfNode($assign, function (\PhpParser\Node $node) use($variable) : bool { + return $node instanceof \PhpParser\Node\Expr\Assign && $this->usedVariableNameAnalyzer->isVariableNamed($node->var, $variable); }); - - if ($previousAssign instanceof Assign) { + if ($previousAssign instanceof \PhpParser\Node\Expr\Assign) { return $this->isUsed($assign, $variable); } } - - return false; + return \false; } - - private function isCall(Expr $expr): bool + private function isCall(\PhpParser\Node\Expr $expr) : bool { - return $expr instanceof FuncCall || $expr instanceof MethodCall || $expr instanceof New_ || $expr instanceof NullsafeMethodCall || $expr instanceof StaticCall; + return $expr instanceof \PhpParser\Node\Expr\FuncCall || $expr instanceof \PhpParser\Node\Expr\MethodCall || $expr instanceof \PhpParser\Node\Expr\New_ || $expr instanceof \PhpParser\Node\Expr\NullsafeMethodCall || $expr instanceof \PhpParser\Node\Expr\StaticCall; } - - private function refactorUsedVariable(Assign $assign): ?Assign + private function refactorUsedVariable(\PhpParser\Node\Expr\Assign $assign) : ?\PhpParser\Node\Expr\Assign { - $parentNode = $assign->getAttribute(AttributeKey::PARENT_NODE); - - $if = $parentNode->getAttribute(AttributeKey::NEXT_NODE); - + $parentNode = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + $if = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); // check if next node is if - if (! $if instanceof If_) { + if (!$if instanceof \PhpParser\Node\Stmt\If_) { return null; } - if ($this->conditionSearcher->searchIfAndElseForVariableRedeclaration($assign, $if)) { $this->removeNode($assign); return $assign; } - return null; } } diff --git a/rules/DeadCode/Rector/BinaryOp/RemoveDuplicatedInstanceOfRector.php b/rules/DeadCode/Rector/BinaryOp/RemoveDuplicatedInstanceOfRector.php index 56a2371d7ab..3f5198b8f1f 100644 --- a/rules/DeadCode/Rector/BinaryOp/RemoveDuplicatedInstanceOfRector.php +++ b/rules/DeadCode/Rector/BinaryOp/RemoveDuplicatedInstanceOfRector.php @@ -1,7 +1,6 @@ instanceOfUniqueKeyResolver = $instanceOfUniqueKeyResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove duplicated instanceof in one call', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove duplicated instanceof in one call', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -41,8 +35,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($value): void @@ -52,58 +45,47 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [BinaryOp::class]; + return [\PhpParser\Node\Expr\BinaryOp::class]; } - /** * @param BinaryOp $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $duplicatedInstanceOfs = $this->resolveDuplicatedInstancesOf($node); if ($duplicatedInstanceOfs === []) { return null; } - $this->removeNodes($duplicatedInstanceOfs); - return $node; } - /** * @return Instanceof_[] */ - private function resolveDuplicatedInstancesOf(BinaryOp $binaryOp): array + private function resolveDuplicatedInstancesOf(\PhpParser\Node\Expr\BinaryOp $binaryOp) : array { $duplicatedInstanceOfs = []; - /** @var Instanceof_[] $instanceOfs */ - $instanceOfs = $this->betterNodeFinder->findInstanceOf($binaryOp, Instanceof_::class); - + $instanceOfs = $this->betterNodeFinder->findInstanceOf($binaryOp, \PhpParser\Node\Expr\Instanceof_::class); $uniqueInstanceOfKeys = []; foreach ($instanceOfs as $instanceOf) { $uniqueKey = $this->instanceOfUniqueKeyResolver->resolve($instanceOf); if ($uniqueKey === null) { continue; } - // already present before → duplicated - if (in_array($uniqueKey, $uniqueInstanceOfKeys, true)) { + if (\in_array($uniqueKey, $uniqueInstanceOfKeys, \true)) { $duplicatedInstanceOfs[] = $instanceOf; } - $uniqueInstanceOfKeys[] = $uniqueKey; } - return $duplicatedInstanceOfs; } } diff --git a/rules/DeadCode/Rector/BooleanAnd/RemoveAndTrueRector.php b/rules/DeadCode/Rector/BooleanAnd/RemoveAndTrueRector.php index 825d5c4b075..4860e0db8d6 100644 --- a/rules/DeadCode/Rector/BooleanAnd/RemoveAndTrueRector.php +++ b/rules/DeadCode/Rector/BooleanAnd/RemoveAndTrueRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [BooleanAnd::class]; + return [\PhpParser\Node\Expr\BinaryOp\BooleanAnd::class]; } - /** * @param BooleanAnd $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->isTrueOrBooleanAndTrues($node->left)) { return $node->right; } - if ($this->isTrueOrBooleanAndTrues($node->right)) { return $node->left; } - return null; } - - private function isTrueOrBooleanAndTrues(Node $node): bool + private function isTrueOrBooleanAndTrues(\PhpParser\Node $node) : bool { if ($this->valueResolver->isTrue($node)) { - return true; + return \true; } - - if (! $node instanceof BooleanAnd) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { + return \false; } - - if (! $this->isTrueOrBooleanAndTrues($node->left)) { - return false; + if (!$this->isTrueOrBooleanAndTrues($node->left)) { + return \false; } - return $this->isTrueOrBooleanAndTrues($node->right); } } diff --git a/rules/DeadCode/Rector/Cast/RecastingRemovalRector.php b/rules/DeadCode/Rector/Cast/RecastingRemovalRector.php index de81ecce440..c8ff0a321b9 100644 --- a/rules/DeadCode/Rector/Cast/RecastingRemovalRector.php +++ b/rules/DeadCode/Rector/Cast/RecastingRemovalRector.php @@ -1,7 +1,6 @@ , class-string> */ - private const CAST_CLASS_TO_NODE_TYPE = [ - String_::class => StringType::class, - Bool_::class => BooleanType::class, - Array_::class => ArrayType::class, - Int_::class => IntegerType::class, - Object_::class => ObjectType::class, - Double::class => FloatType::class, - ]; - - public function getRuleDefinition(): RuleDefinition + private const CAST_CLASS_TO_NODE_TYPE = [\PhpParser\Node\Expr\Cast\String_::class => \PHPStan\Type\StringType::class, \PhpParser\Node\Expr\Cast\Bool_::class => \PHPStan\Type\BooleanType::class, \PhpParser\Node\Expr\Cast\Array_::class => \PHPStan\Type\ArrayType::class, \PhpParser\Node\Expr\Cast\Int_::class => \PHPStan\Type\IntegerType::class, \PhpParser\Node\Expr\Cast\Object_::class => \PHPStan\Type\ObjectType::class, \PhpParser\Node\Expr\Cast\Double::class => \PHPStan\Type\FloatType::class]; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Removes recasting of the same type', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removes recasting of the same type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $string = ''; $string = (string) $string; $array = []; $array = (array) $array; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $string = ''; $string = $string; $array = []; $array = $array; CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Cast::class]; + return [\PhpParser\Node\Expr\Cast::class]; } - /** * @param Cast $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $nodeClass = get_class($node); - if (! isset(self::CAST_CLASS_TO_NODE_TYPE[$nodeClass])) { + $nodeClass = \get_class($node); + if (!isset(self::CAST_CLASS_TO_NODE_TYPE[$nodeClass])) { return null; } - $nodeType = $this->getStaticType($node->expr); - if ($nodeType instanceof MixedType) { + if ($nodeType instanceof \PHPStan\Type\MixedType) { return null; } - $sameNodeType = self::CAST_CLASS_TO_NODE_TYPE[$nodeClass]; - if (! is_a($nodeType, $sameNodeType, true)) { + if (!\is_a($nodeType, $sameNodeType, \true)) { return null; } - return $node->expr; } } diff --git a/rules/DeadCode/Rector/ClassConst/RemoveUnusedPrivateClassConstantRector.php b/rules/DeadCode/Rector/ClassConst/RemoveUnusedPrivateClassConstantRector.php index 9fb326d2b2d..05452a9988f 100644 --- a/rules/DeadCode/Rector/ClassConst/RemoveUnusedPrivateClassConstantRector.php +++ b/rules/DeadCode/Rector/ClassConst/RemoveUnusedPrivateClassConstantRector.php @@ -1,7 +1,6 @@ classConstManipulator = $classConstManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove unused class constants', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove unused class constants', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private const SOME_CONST = 'dead'; @@ -46,8 +40,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -55,94 +48,74 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassConst::class]; + return [\PhpParser\Node\Stmt\ClassConst::class]; } - /** * @param ClassConst $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - $classLike = $this->nodeRepository->findClassLike($classReflection->getName()); - if (! $classLike instanceof ClassLike) { + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { return null; } - - $classObjectType = new ObjectType($classReflection->getName()); - + $classObjectType = new \PHPStan\Type\ObjectType($classReflection->getName()); /** @var ClassConstFetch[] $classConstFetches */ - $classConstFetches = $this->betterNodeFinder->findInstanceOf($classLike->stmts, ClassConstFetch::class); + $classConstFetches = $this->betterNodeFinder->findInstanceOf($classLike->stmts, \PhpParser\Node\Expr\ClassConstFetch::class); foreach ($classConstFetches as $classConstFetch) { - if (! $this->nodeNameResolver->areNamesEqual($classConstFetch->name, $node->consts[0]->name)) { + if (!$this->nodeNameResolver->areNamesEqual($classConstFetch->name, $node->consts[0]->name)) { continue; } - $constFetchClassType = $this->nodeTypeResolver->resolve($classConstFetch->class); - // constant is used! if ($constFetchClassType->isSuperTypeOf($classObjectType)->yes()) { return null; } } - $this->removeNode($node); - return null; } - - private function shouldSkip(ClassConst $classConst): bool + private function shouldSkip(\PhpParser\Node\Stmt\ClassConst $classConst) : bool { - if (! $classConst->isPrivate()) { - return true; + if (!$classConst->isPrivate()) { + return \true; } - - if (count($classConst->consts) !== 1) { - return true; + if (\count($classConst->consts) !== 1) { + return \true; } - if ($this->classConstManipulator->isEnum($classConst)) { - return true; + return \true; } - if ($this->classConstManipulator->hasClassConstFetch($classConst)) { - return true; + return \true; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classConst); if ($phpDocInfo->hasByName('api')) { - return true; + return \true; } - - $classLike = $classConst->getAttribute(AttributeKey::CLASS_NODE); - - if ($classLike instanceof ClassLike) { + $classLike = $classConst->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if ($classLike instanceof \PhpParser\Node\Stmt\ClassLike) { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classLike); return $phpDocInfo->hasByName('api'); } - - return false; + return \false; } } diff --git a/rules/DeadCode/Rector/ClassLike/RemoveAnnotationRector.php b/rules/DeadCode/Rector/ClassLike/RemoveAnnotationRector.php index cb572c6765c..344f437e8e8 100644 --- a/rules/DeadCode/Rector/ClassLike/RemoveAnnotationRector.php +++ b/rules/DeadCode/Rector/ClassLike/RemoveAnnotationRector.php @@ -1,7 +1,6 @@ phpDocTagRemover = $phpDocTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove annotation by names', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove annotation by names', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' /** * @method getName() */ @@ -55,63 +47,48 @@ final class SomeClass { } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { } CODE_SAMPLE -, - [ - self::ANNOTATIONS_TO_REMOVE => ['method'], - ] - ), - ]); +, [self::ANNOTATIONS_TO_REMOVE => ['method']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassLike::class, FunctionLike::class, Property::class, ClassConst::class]; + return [\PhpParser\Node\Stmt\ClassLike::class, \PhpParser\Node\FunctionLike::class, \PhpParser\Node\Stmt\Property::class, \PhpParser\Node\Stmt\ClassConst::class]; } - /** * @param ClassLike|FunctionLike|Property|ClassConst $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->annotationsToRemove === []) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - foreach ($this->annotationsToRemove as $annotationToRemove) { $this->phpDocTagRemover->removeByName($phpDocInfo, $annotationToRemove); - - if (is_a($annotationToRemove, PhpDocTagValueNode::class, true)) { + if (\is_a($annotationToRemove, \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode::class, \true)) { $phpDocInfo->removeByType($annotationToRemove); } } - if ($phpDocInfo->hasChanged()) { - $node->setAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, true); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, \true); return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $annotationsToRemove = $configuration[self::ANNOTATIONS_TO_REMOVE] ?? []; - Assert::allString($annotationsToRemove); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allString($annotationsToRemove); $this->annotationsToRemove = $annotationsToRemove; } } diff --git a/rules/DeadCode/Rector/ClassMethod/RemoveDeadConstructorRector.php b/rules/DeadCode/Rector/ClassMethod/RemoveDeadConstructorRector.php index 80c02862bff..7e6490fba58 100644 --- a/rules/DeadCode/Rector/ClassMethod/RemoveDeadConstructorRector.php +++ b/rules/DeadCode/Rector/ClassMethod/RemoveDeadConstructorRector.php @@ -1,7 +1,6 @@ classMethodManipulator = $classMethodManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove empty constructor', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove empty constructor', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function __construct() @@ -41,59 +35,49 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - if ($this->shouldSkipPropertyPromotion($node)) { return null; } - $this->removeNode($node); - return null; } - - private function shouldSkipPropertyPromotion(ClassMethod $classMethod): bool + private function shouldSkipPropertyPromotion(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - if (! $this->isName($classMethod, MethodName::CONSTRUCT)) { - return true; + if (!$this->isName($classMethod, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { + return \true; } if ($classMethod->stmts === null) { - return true; + return \true; } if ($classMethod->stmts !== []) { - return true; + return \true; } - if ($this->classMethodManipulator->isPropertyPromotion($classMethod)) { - return true; + return \true; } - return $this->classMethodManipulator->isNamedConstructor($classMethod); } } diff --git a/rules/DeadCode/Rector/ClassMethod/RemoveDelegatingParentCallRector.php b/rules/DeadCode/Rector/ClassMethod/RemoveDelegatingParentCallRector.php index 955cca0b8f5..a8d614bbce1 100644 --- a/rules/DeadCode/Rector/ClassMethod/RemoveDelegatingParentCallRector.php +++ b/rules/DeadCode/Rector/ClassMethod/RemoveDelegatingParentCallRector.php @@ -1,7 +1,6 @@ currentAndParentClassMethodComparator = $currentAndParentClassMethodComparator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Removed dead parent call, that does not change anything', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removed dead parent call, that does not change anything', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function prettyPrint(array $stmts): string @@ -47,104 +39,84 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); if ($this->shouldSkipClass($classLike)) { return null; } if ($node->stmts === null) { return null; } - if (count($node->stmts) !== 1) { + if (\count($node->stmts) !== 1) { return null; } - - $stmtsValues = array_values($node->stmts); + $stmtsValues = \array_values($node->stmts); $onlyStmt = $this->unwrapExpression($stmtsValues[0]); - // are both return? - if ($this->isMethodReturnType($node, 'void') && ! $onlyStmt instanceof Return_) { + if ($this->isMethodReturnType($node, 'void') && !$onlyStmt instanceof \PhpParser\Node\Stmt\Return_) { return null; } - $staticCall = $this->matchStaticCall($onlyStmt); - if (! $staticCall instanceof StaticCall) { + if (!$staticCall instanceof \PhpParser\Node\Expr\StaticCall) { return null; } - - if (! $this->currentAndParentClassMethodComparator->isParentCallMatching($node, $staticCall)) { + if (!$this->currentAndParentClassMethodComparator->isParentCallMatching($node, $staticCall)) { return null; } - if ($this->hasRequiredAnnotation($node)) { return null; } - // the method is just delegation, nothing extra $this->removeNode($node); - return null; } - - private function shouldSkipClass(?ClassLike $classLike): bool + private function shouldSkipClass(?\PhpParser\Node\Stmt\ClassLike $classLike) : bool { - if (! $classLike instanceof Class_) { - return true; + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \true; } return $classLike->extends === null; } - - private function isMethodReturnType(ClassMethod $classMethod, string $type): bool + private function isMethodReturnType(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $type) : bool { if ($classMethod->returnType === null) { - return false; + return \false; } - return $this->isName($classMethod->returnType, $type); } - - private function matchStaticCall(Node $node): ?StaticCall + private function matchStaticCall(\PhpParser\Node $node) : ?\PhpParser\Node\Expr\StaticCall { // must be static call - if ($node instanceof Return_) { - if ($node->expr instanceof StaticCall) { + if ($node instanceof \PhpParser\Node\Stmt\Return_) { + if ($node->expr instanceof \PhpParser\Node\Expr\StaticCall) { return $node->expr; } - return null; } - - if ($node instanceof StaticCall) { + if ($node instanceof \PhpParser\Node\Expr\StaticCall) { return $node; } - return null; } - - private function hasRequiredAnnotation(ClassMethod $classMethod): bool + private function hasRequiredAnnotation(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); return $phpDocInfo->hasByName('required'); diff --git a/rules/DeadCode/Rector/ClassMethod/RemoveEmptyClassMethodRector.php b/rules/DeadCode/Rector/ClassMethod/RemoveEmptyClassMethodRector.php index 5d1884a79f3..d1d25542043 100644 --- a/rules/DeadCode/Rector/ClassMethod/RemoveEmptyClassMethodRector.php +++ b/rules/DeadCode/Rector/ClassMethod/RemoveEmptyClassMethodRector.php @@ -1,7 +1,6 @@ classMethodManipulator = $classMethodManipulator; $this->controllerClassMethodManipulator = $controllerClassMethodManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove empty class methods not required by parents', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove empty class methods not required by parents', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class OrphanClass { public function __construct() @@ -51,91 +40,71 @@ class OrphanClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class OrphanClass { } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - if ($node->stmts !== null && $node->stmts !== []) { return null; } - if ($node->isAbstract()) { return null; } - - if ($node->isFinal() && ! $classLike->isFinal()) { + if ($node->isFinal() && !$classLike->isFinal()) { return null; } - if ($this->shouldSkipNonFinalNonPrivateClassMethod($classLike, $node)) { return null; } - if ($this->shouldSkipClassMethod($node)) { return null; } - $this->removeNode($node); - return $node; } - - private function shouldSkipNonFinalNonPrivateClassMethod(Class_ $class, ClassMethod $classMethod): bool + private function shouldSkipNonFinalNonPrivateClassMethod(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { if ($class->isFinal()) { - return false; + return \false; } - if ($classMethod->isMagic()) { - return false; + return \false; } - if ($classMethod->isProtected()) { - return true; + return \true; } - return $classMethod->isPublic(); } - - private function shouldSkipClassMethod(ClassMethod $classMethod): bool + private function shouldSkipClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { if ($this->classMethodManipulator->isNamedConstructor($classMethod)) { - return true; + return \true; } - if ($this->classMethodManipulator->hasParentMethodOrInterfaceMethod($classMethod)) { - return true; + return \true; } - if ($this->classMethodManipulator->isPropertyPromotion($classMethod)) { - return true; + return \true; } - return $this->controllerClassMethodManipulator->isControllerClassMethodWithBehaviorAnnotation($classMethod); } } diff --git a/rules/DeadCode/Rector/ClassMethod/RemoveUnusedConstructorParamRector.php b/rules/DeadCode/Rector/ClassMethod/RemoveUnusedConstructorParamRector.php index f65d7effa4f..bccde444e22 100644 --- a/rules/DeadCode/Rector/ClassMethod/RemoveUnusedConstructorParamRector.php +++ b/rules/DeadCode/Rector/ClassMethod/RemoveUnusedConstructorParamRector.php @@ -1,7 +1,6 @@ paramAnalyzer = $paramAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove unused parameter in constructor', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove unused parameter in constructor', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { private $hey; @@ -44,9 +38,7 @@ final class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { private $hey; @@ -57,52 +49,42 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, MethodName::CONSTRUCT)) { + if (!$this->isName($node, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { return null; } - if ($node->params === []) { return null; } - if ($this->paramAnalyzer->hasPropertyPromotion($node->params)) { return null; } - - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if ($classLike instanceof Interface_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if ($classLike instanceof \PhpParser\Node\Stmt\Interface_) { return null; } - if ($node->isAbstract()) { return null; } - foreach ($node->params as $param) { if ($this->paramAnalyzer->isParamUsedInClassMethod($node, $param)) { continue; } - $this->nodeRemover->removeParam($node, $param); } - return null; } } diff --git a/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodParameterRector.php b/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodParameterRector.php index 666a97c3a8a..5decf19e42e 100644 --- a/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodParameterRector.php +++ b/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodParameterRector.php @@ -1,7 +1,6 @@ variadicFunctionLikeDetector = $variadicFunctionLikeDetector; $this->unusedParameterResolver = $unusedParameterResolver; $this->phpDocTagRemover = $phpDocTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove unused parameter, if not required by interface or parent class', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove unused parameter, if not required by interface or parent class', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private function run($value, $value2) @@ -61,8 +48,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { private function run($value) @@ -71,77 +57,61 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var string|null $className */ - $className = $node->getAttribute(AttributeKey::CLASS_NAME); + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { return null; } - $unusedParameters = $this->unusedParameterResolver->resolve($node); $this->removeNodes($unusedParameters); - $this->clearPhpDocInfo($node, $unusedParameters); - return $node; } - - private function shouldSkip(ClassMethod $classMethod): bool + private function shouldSkip(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - if (! $classMethod->isPrivate()) { - return true; + if (!$classMethod->isPrivate()) { + return \true; } - if ($classMethod->params === []) { - return true; + return \true; } - return $this->variadicFunctionLikeDetector->isVariadic($classMethod); } - /** * @param Param[] $unusedParameters */ - private function clearPhpDocInfo(ClassMethod $classMethod, array $unusedParameters): void + private function clearPhpDocInfo(\PhpParser\Node\Stmt\ClassMethod $classMethod, array $unusedParameters) : void { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); - foreach ($unusedParameters as $unusedParameter) { $parameterName = $this->getName($unusedParameter->var); if ($parameterName === null) { continue; } - $paramTagValueNode = $phpDocInfo->getParamTagValueByName($parameterName); - if (! $paramTagValueNode instanceof ParamTagValueNode) { + if (!$paramTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode) { continue; } - if ($paramTagValueNode->parameterName !== '$' . $parameterName) { continue; } - $this->phpDocTagRemover->removeTagValueFromNode($phpDocInfo, $paramTagValueNode); } } diff --git a/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector.php b/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector.php index 0c0f3d530ac..92e999653bd 100644 --- a/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector.php +++ b/rules/DeadCode/Rector/ClassMethod/RemoveUnusedPrivateMethodRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $calls = $this->nodeRepository->findCallsByClassMethod($node); if ($calls !== []) { return null; } - $this->removeNode($node); - return $node; } - - private function shouldSkip(ClassMethod $classMethod): bool + private function shouldSkip(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return true; + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \true; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return true; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \true; } - // unreliable to detect trait, interface doesn't make sense if ($classReflection->isTrait()) { - return true; + return \true; } - if ($classReflection->isInterface()) { - return true; + return \true; } - if ($classReflection->isAnonymous()) { - return true; + return \true; } - // skips interfaces by default too - if (! $classMethod->isPrivate()) { - return true; + if (!$classMethod->isPrivate()) { + return \true; } - // skip magic methods - @see https://www.php.net/manual/en/language.oop5.magic.php if ($classMethod->isMagic()) { - return true; + return \true; } - return $classReflection->hasMethod('__call'); } } diff --git a/rules/DeadCode/Rector/ClassMethod/RemoveUselessParamTagRector.php b/rules/DeadCode/Rector/ClassMethod/RemoveUselessParamTagRector.php index 54de5d5bc8d..8e952ae9b0c 100644 --- a/rules/DeadCode/Rector/ClassMethod/RemoveUselessParamTagRector.php +++ b/rules/DeadCode/Rector/ClassMethod/RemoveUselessParamTagRector.php @@ -1,7 +1,6 @@ deadParamTagValueNodeAnalyzer = $deadParamTagValueNodeAnalyzer; $this->phpDocTagRemover = $phpDocTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove @param docblock with same type as parameter type', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove @param docblock with same type as parameter type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -54,8 +43,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -66,39 +54,31 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - foreach ($phpDocInfo->getParamTagValueNodes() as $paramTagValueNode) { - if (! $this->deadParamTagValueNodeAnalyzer->isDead($paramTagValueNode, $node)) { + if (!$this->deadParamTagValueNodeAnalyzer->isDead($paramTagValueNode, $node)) { continue; } - $this->phpDocTagRemover->removeTagValueFromNode($phpDocInfo, $paramTagValueNode); } - if ($phpDocInfo->hasChanged()) { - $node->setAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, true); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, \true); return $node; } - return null; } } diff --git a/rules/DeadCode/Rector/ClassMethod/RemoveUselessReturnTagRector.php b/rules/DeadCode/Rector/ClassMethod/RemoveUselessReturnTagRector.php index fa22a5dc51d..0e1ce4df080 100644 --- a/rules/DeadCode/Rector/ClassMethod/RemoveUselessReturnTagRector.php +++ b/rules/DeadCode/Rector/ClassMethod/RemoveUselessReturnTagRector.php @@ -1,7 +1,6 @@ returnTagRemover = $returnTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove @return docblock with same type as defined in PHP', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove @return docblock with same type as defined in PHP', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' use stdClass; class SomeClass @@ -46,8 +38,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use stdClass; class SomeClass @@ -57,32 +48,26 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); $this->returnTagRemover->removeReturnTagIfUseless($phpDocInfo, $node); - if ($phpDocInfo->hasChanged()) { - $node->setAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, true); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, \true); return $node; } - return null; } } diff --git a/rules/DeadCode/Rector/Concat/RemoveConcatAutocastRector.php b/rules/DeadCode/Rector/Concat/RemoveConcatAutocastRector.php index 028ae14473c..43b22348ad1 100644 --- a/rules/DeadCode/Rector/Concat/RemoveConcatAutocastRector.php +++ b/rules/DeadCode/Rector/Concat/RemoveConcatAutocastRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Concat::class]; + return [\PhpParser\Node\Expr\BinaryOp\Concat::class]; } - /** * @param Concat $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->left instanceof String_ && ! $node->right instanceof String_) { + if (!$node->left instanceof \PhpParser\Node\Expr\Cast\String_ && !$node->right instanceof \PhpParser\Node\Expr\Cast\String_) { return null; } - $node->left = $this->removeStringCast($node->left); $node->right = $this->removeStringCast($node->right); - return $node; } - - private function removeStringCast(Expr $expr): Expr + private function removeStringCast(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { - return $expr instanceof String_ ? $expr->expr : $expr; + return $expr instanceof \PhpParser\Node\Expr\Cast\String_ ? $expr->expr : $expr; } } diff --git a/rules/DeadCode/Rector/Expression/RemoveDeadStmtRector.php b/rules/DeadCode/Rector/Expression/RemoveDeadStmtRector.php index fc4010105c3..47b1049966e 100644 --- a/rules/DeadCode/Rector/Expression/RemoveDeadStmtRector.php +++ b/rules/DeadCode/Rector/Expression/RemoveDeadStmtRector.php @@ -1,7 +1,6 @@ livingCodeManipulator = $livingCodeManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Removes dead code statements', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removes dead code statements', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $value = 5; $value; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $value = 5; CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Expression::class]; + return [\PhpParser\Node\Stmt\Expression::class]; } - /** * @param Expression $node * @return Node[]|Node|null */ - public function refactor(Node $node) + public function refactor(\PhpParser\Node $node) { $livingCode = $this->livingCodeManipulator->keepLivingCodeFromExpr($node->expr); if ($livingCode === []) { return $this->removeNodeAndKeepComments($node); } - - $firstExpr = array_shift($livingCode); + $firstExpr = \array_shift($livingCode); $node->expr = $firstExpr; - $newNodes = []; foreach ($livingCode as $singleLivingCode) { - $newNodes[] = new Expression($singleLivingCode); + $newNodes[] = new \PhpParser\Node\Stmt\Expression($singleLivingCode); } - $newNodes[] = $node; - return $newNodes; } - - private function removeNodeAndKeepComments(Expression $expression): ?Node + private function removeNodeAndKeepComments(\PhpParser\Node\Stmt\Expression $expression) : ?\PhpParser\Node { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($expression); - if ($expression->getComments() !== []) { - $nop = new Nop(); - $nop->setAttribute(AttributeKey::PHP_DOC_INFO, $phpDocInfo); - + $nop = new \PhpParser\Node\Stmt\Nop(); + $nop->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, $phpDocInfo); $this->phpDocInfoFactory->createFromNode($nop); - return $nop; } - $this->removeNode($expression); - return null; } } diff --git a/rules/DeadCode/Rector/Expression/SimplifyMirrorAssignRector.php b/rules/DeadCode/Rector/Expression/SimplifyMirrorAssignRector.php index 32fdd25b345..67a07923e84 100644 --- a/rules/DeadCode/Rector/Expression/SimplifyMirrorAssignRector.php +++ b/rules/DeadCode/Rector/Expression/SimplifyMirrorAssignRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Expression::class]; + return [\PhpParser\Node\Stmt\Expression::class]; } - /** * @param Expression $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof Assign) { + if (!$node->expr instanceof \PhpParser\Node\Expr\Assign) { return null; } - /** @var Assign $assignNode */ $assignNode = $node->expr; - if ($this->nodeComparator->areNodesEqual($assignNode->var, $assignNode->expr)) { $this->removeNode($node); } - return null; } } diff --git a/rules/DeadCode/Rector/For_/RemoveDeadIfForeachForRector.php b/rules/DeadCode/Rector/For_/RemoveDeadIfForeachForRector.php index 9cbdbc4ed16..c7b62548b79 100644 --- a/rules/DeadCode/Rector/For_/RemoveDeadIfForeachForRector.php +++ b/rules/DeadCode/Rector/For_/RemoveDeadIfForeachForRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [For_::class, If_::class, Foreach_::class]; + return [\PhpParser\Node\Stmt\For_::class, \PhpParser\Node\Stmt\If_::class, \PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param For_|If_|Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof If_) { + if ($node instanceof \PhpParser\Node\Stmt\If_) { $this->processIf($node); return null; } - - if ($node instanceof Foreach_) { + if ($node instanceof \PhpParser\Node\Stmt\Foreach_) { $this->processForeach($node); return null; } - // For if ($node->stmts !== []) { return null; } - $this->removeNode($node); - return null; } - - private function processIf(If_ $if): void + private function processIf(\PhpParser\Node\Stmt\If_ $if) : void { if ($if->stmts !== []) { return; } - if ($if->else !== null) { return; } - if ($if->elseifs !== []) { return; } - if ($this->isNodeWithSideEffect($if->cond)) { return; } - $this->removeNode($if); } - - private function processForeach(Foreach_ $foreach): void + private function processForeach(\PhpParser\Node\Stmt\Foreach_ $foreach) : void { if ($foreach->stmts !== []) { return; } - if ($this->isNodeWithSideEffect($foreach->expr)) { return; } - $this->removeNode($foreach); } - - private function isNodeWithSideEffect(Expr $expr): bool + private function isNodeWithSideEffect(\PhpParser\Node\Expr $expr) : bool { - if ($expr instanceof Variable) { - return false; + if ($expr instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - - if ($expr instanceof Scalar) { - return false; + if ($expr instanceof \PhpParser\Node\Scalar) { + return \false; } - return ! $this->valueResolver->isTrueOrFalse($expr); + return !$this->valueResolver->isTrueOrFalse($expr); } } diff --git a/rules/DeadCode/Rector/For_/RemoveDeadLoopRector.php b/rules/DeadCode/Rector/For_/RemoveDeadLoopRector.php index e1c7f764290..c97d6e98490 100644 --- a/rules/DeadCode/Rector/For_/RemoveDeadLoopRector.php +++ b/rules/DeadCode/Rector/For_/RemoveDeadLoopRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Do_::class, For_::class, Foreach_::class, While_::class]; + return [\PhpParser\Node\Stmt\Do_::class, \PhpParser\Node\Stmt\For_::class, \PhpParser\Node\Stmt\Foreach_::class, \PhpParser\Node\Stmt\While_::class]; } - /** * @param Do_|For_|Foreach_|While_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->stmts !== []) { return null; } - $this->removeNode($node); return $node; } diff --git a/rules/DeadCode/Rector/Foreach_/RemoveUnusedForeachKeyRector.php b/rules/DeadCode/Rector/Foreach_/RemoveUnusedForeachKeyRector.php index 13c833f063e..c24f5e872fe 100644 --- a/rules/DeadCode/Rector/Foreach_/RemoveUnusedForeachKeyRector.php +++ b/rules/DeadCode/Rector/Foreach_/RemoveUnusedForeachKeyRector.php @@ -1,7 +1,6 @@ $value) { $result = $value; } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $items = []; foreach ($items as $value) { $result = $value; } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Foreach_::class]; + return [\PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->keyVar === null) { return null; } - $keyVar = $node->keyVar; - - $isNodeUsed = (bool) $this->betterNodeFinder->findFirst($node->stmts, function (Node $node) use ( - $keyVar - ): bool { + $isNodeUsed = (bool) $this->betterNodeFinder->findFirst($node->stmts, function (\PhpParser\Node $node) use($keyVar) : bool { return $this->nodeComparator->areNodesEqual($node, $keyVar); }); - if ($isNodeUsed) { return null; } - $node->keyVar = null; - return $node; } } diff --git a/rules/DeadCode/Rector/FunctionLike/RemoveCodeAfterReturnRector.php b/rules/DeadCode/Rector/FunctionLike/RemoveCodeAfterReturnRector.php index 262b8c66b2e..9a1675fcf9b 100644 --- a/rules/DeadCode/Rector/FunctionLike/RemoveCodeAfterReturnRector.php +++ b/rules/DeadCode/Rector/FunctionLike/RemoveCodeAfterReturnRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Closure::class, ClassMethod::class, Function_::class]; + return [\PhpParser\Node\Expr\Closure::class, \PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class]; } - /** * @param Closure|ClassMethod|Function_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->stmts === null) { return null; } - - $isDeadAfterReturn = false; + $isDeadAfterReturn = \false; foreach ($node->stmts as $key => $stmt) { if ($isDeadAfterReturn) { - if (! isset($node->stmts[$key])) { - throw new ShouldNotHappenException(); + if (!isset($node->stmts[$key])) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - // keep comment /** @var int $key */ - if ($node->stmts[$key] instanceof Nop) { + if ($node->stmts[$key] instanceof \PhpParser\Node\Stmt\Nop) { continue; } - $this->nodeRemover->removeStmt($node, $key); } - - if ($stmt instanceof Return_) { - $isDeadAfterReturn = true; + if ($stmt instanceof \PhpParser\Node\Stmt\Return_) { + $isDeadAfterReturn = \true; } } - return null; } } diff --git a/rules/DeadCode/Rector/FunctionLike/RemoveDeadReturnRector.php b/rules/DeadCode/Rector/FunctionLike/RemoveDeadReturnRector.php index 1b09f6a734d..acd536635a5 100644 --- a/rules/DeadCode/Rector/FunctionLike/RemoveDeadReturnRector.php +++ b/rules/DeadCode/Rector/FunctionLike/RemoveDeadReturnRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Function_::class, Closure::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Expr\Closure::class]; } - /** * @param ClassMethod|Function_|Closure $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->stmts === []) { return null; @@ -77,20 +66,15 @@ CODE_SAMPLE if ($node->stmts === null) { return null; } - - $stmtValues = array_values($node->stmts); - $lastStmt = end($stmtValues); - - if (! $lastStmt instanceof Return_) { + $stmtValues = \array_values($node->stmts); + $lastStmt = \end($stmtValues); + if (!$lastStmt instanceof \PhpParser\Node\Stmt\Return_) { return null; } - if ($lastStmt->expr !== null) { return null; } - $this->removeNode($lastStmt); - return $node; } } diff --git a/rules/DeadCode/Rector/FunctionLike/RemoveDuplicatedIfReturnRector.php b/rules/DeadCode/Rector/FunctionLike/RemoveDuplicatedIfReturnRector.php index 421cb0dbfd8..78aa08d33b1 100644 --- a/rules/DeadCode/Rector/FunctionLike/RemoveDuplicatedIfReturnRector.php +++ b/rules/DeadCode/Rector/FunctionLike/RemoveDuplicatedIfReturnRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->modifiedVariableNamesCollector = $modifiedVariableNamesCollector; $this->nodeComparator = $nodeComparator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove duplicated if stmt with return in function/method body', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove duplicated if stmt with return in function/method body', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -68,8 +56,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($value) @@ -82,109 +69,84 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FunctionLike::class]; + return [\PhpParser\Node\FunctionLike::class]; } - /** * @param FunctionLike $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $ifWithOnlyReturnsByHash = $this->collectDuplicatedIfWithOnlyReturnByHash($node); if ($ifWithOnlyReturnsByHash === []) { return null; } - foreach ($ifWithOnlyReturnsByHash as $ifWithOnlyReturns) { // keep first one - array_shift($ifWithOnlyReturns); - + \array_shift($ifWithOnlyReturns); foreach ($ifWithOnlyReturns as $ifWithOnlyReturn) { $this->removeNode($ifWithOnlyReturn); } } - return $node; } - /** * @return If_[][] */ - private function collectDuplicatedIfWithOnlyReturnByHash(FunctionLike $functionLike): array + private function collectDuplicatedIfWithOnlyReturnByHash(\PhpParser\Node\FunctionLike $functionLike) : array { $ifWithOnlyReturnsByHash = []; $modifiedVariableNames = []; - foreach ((array) $functionLike->getStmts() as $stmt) { - if (! $this->ifManipulator->isIfWithOnly($stmt, Return_::class)) { + if (!$this->ifManipulator->isIfWithOnly($stmt, \PhpParser\Node\Stmt\Return_::class)) { // variable modification - $modifiedVariableNames = array_merge( - $modifiedVariableNames, - $this->modifiedVariableNamesCollector->collectModifiedVariableNames($stmt) - ); + $modifiedVariableNames = \array_merge($modifiedVariableNames, $this->modifiedVariableNamesCollector->collectModifiedVariableNames($stmt)); continue; } - if ($this->containsVariableNames($stmt, $modifiedVariableNames)) { continue; } - /** @var If_ $stmt */ $hash = $this->nodeComparator->printWithoutComments($stmt); $ifWithOnlyReturnsByHash[$hash][] = $stmt; } - return $this->filterOutSingleItemStmts($ifWithOnlyReturnsByHash); } - /** * @param string[] $modifiedVariableNames */ - private function containsVariableNames(Stmt $stmt, array $modifiedVariableNames): bool + private function containsVariableNames(\PhpParser\Node\Stmt $stmt, array $modifiedVariableNames) : bool { if ($modifiedVariableNames === []) { - return false; + return \false; } - - $containsVariableNames = false; - $this->traverseNodesWithCallable($stmt, function (Node $node) use ( - $modifiedVariableNames, - &$containsVariableNames - ): ?int { - if (! $node instanceof Variable) { + $containsVariableNames = \false; + $this->traverseNodesWithCallable($stmt, function (\PhpParser\Node $node) use($modifiedVariableNames, &$containsVariableNames) : ?int { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { return null; } - - if (! $this->isNames($node, $modifiedVariableNames)) { + if (!$this->isNames($node, $modifiedVariableNames)) { return null; } - - $containsVariableNames = true; - - return NodeTraverser::STOP_TRAVERSAL; + $containsVariableNames = \true; + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; }); - return $containsVariableNames; } - /** * @param array $ifWithOnlyReturnsByHash * @return array */ - private function filterOutSingleItemStmts(array $ifWithOnlyReturnsByHash): array + private function filterOutSingleItemStmts(array $ifWithOnlyReturnsByHash) : array { - return array_filter($ifWithOnlyReturnsByHash, function (array $stmts): bool { - return count($stmts) >= 2; + return \array_filter($ifWithOnlyReturnsByHash, function (array $stmts) : bool { + return \count($stmts) >= 2; }); } } diff --git a/rules/DeadCode/Rector/FunctionLike/RemoveOverriddenValuesRector.php b/rules/DeadCode/Rector/FunctionLike/RemoveOverriddenValuesRector.php index e7caea737d8..42b2ca7a79f 100644 --- a/rules/DeadCode/Rector/FunctionLike/RemoveOverriddenValuesRector.php +++ b/rules/DeadCode/Rector/FunctionLike/RemoveOverriddenValuesRector.php @@ -1,7 +1,6 @@ contextAnalyzer = $contextAnalyzer; $this->nodeByTypeAndPositionCollector = $nodeByTypeAndPositionCollector; $this->variableUseFinder = $variableUseFinder; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove initial assigns of overridden values', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove initial assigns of overridden values', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeController { public function run() @@ -64,8 +51,7 @@ final class SomeController } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeController { public function run() @@ -75,83 +61,65 @@ final class SomeController } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FunctionLike::class]; + return [\PhpParser\Node\FunctionLike::class]; } - /** * @param FunctionLike $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { // 1. collect assigns $assignedVariables = $this->resolveAssignedVariables($node); $assignedVariableNames = $this->getNodeNames($assignedVariables); - // 2. collect use of those variables $assignedVariablesUse = $this->variableUseFinder->resolveUsedVariables($node, $assignedVariables); - - $nodesByTypeAndPosition = $this->nodeByTypeAndPositionCollector->collectNodesByTypeAndPosition( - $assignedVariables, - $assignedVariablesUse, - $node - ); - + $nodesByTypeAndPosition = $this->nodeByTypeAndPositionCollector->collectNodesByTypeAndPosition($assignedVariables, $assignedVariablesUse, $node); $nodesToRemove = $this->resolveNodesToRemove($assignedVariableNames, $nodesByTypeAndPosition); if ($nodesToRemove === []) { return null; } - $this->removeNodes($nodesToRemove); - return $node; } - /** * @return Variable[] */ - private function resolveAssignedVariables(FunctionLike $functionLike): array + private function resolveAssignedVariables(\PhpParser\Node\FunctionLike $functionLike) : array { - return $this->betterNodeFinder->find($functionLike, function (Node $node): bool { - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Assign) { - return false; + return $this->betterNodeFinder->find($functionLike, function (\PhpParser\Node $node) : bool { + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - if (! $node instanceof Variable) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - // skin in if if ($this->contextAnalyzer->isInIf($node)) { - return false; + return \false; } - // is variable on the left /** @var Assign $assignNode */ - $assignNode = $node->getAttribute(AttributeKey::PARENT_NODE); + $assignNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); if ($assignNode->var !== $node) { - return false; + return \false; } // simple variable only - return is_string($node->name); + return \is_string($node->name); }); } - /** * @param Node[] $nodes * @return string[] */ - private function getNodeNames(array $nodes): array + private function getNodeNames(array $nodes) : array { $nodeNames = []; foreach ($nodes as $node) { @@ -160,35 +128,28 @@ CODE_SAMPLE $nodeNames[] = $nodeName; } } - - return array_unique($nodeNames); + return \array_unique($nodeNames); } - /** * @param string[] $assignedVariableNames * @param VariableNodeUse[] $nodesByTypeAndPosition * @return Node[] */ - private function resolveNodesToRemove(array $assignedVariableNames, array $nodesByTypeAndPosition): array + private function resolveNodesToRemove(array $assignedVariableNames, array $nodesByTypeAndPosition) : array { $nodesToRemove = []; - foreach ($assignedVariableNames as $assignedVariableName) { $previousNode = null; - foreach ($nodesByTypeAndPosition as $nodes) { $variableNode = $nodes->getVariableNode(); - $comments = $variableNode->getAttribute(AttributeKey::COMMENTS); - + $comments = $variableNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS); if ($comments !== null) { continue; } $nodesIsName = $nodes->isName($assignedVariableName); - - if (! $nodesIsName) { + if (!$nodesIsName) { continue; } - if ($this->isAssignNodeUsed($previousNode, $nodes)) { // continue // instant override → remove @@ -196,63 +157,45 @@ CODE_SAMPLE /** @var VariableNodeUse $previousNode */ $nodesToRemove[] = $previousNode->getParentNode(); } - $previousNode = $nodes; } } - return $nodesToRemove; } - - private function isAssignNodeUsed( - ?VariableNodeUse $previousNode, - VariableNodeUse $nodeByTypeAndPosition - ): bool { + private function isAssignNodeUsed(?\Rector\DeadCode\ValueObject\VariableNodeUse $previousNode, \Rector\DeadCode\ValueObject\VariableNodeUse $nodeByTypeAndPosition) : bool + { // this node was just used, skip to next one - if (! $previousNode instanceof VariableNodeUse) { - return false; + if (!$previousNode instanceof \Rector\DeadCode\ValueObject\VariableNodeUse) { + return \false; } - - if (! $previousNode->isType(VariableNodeUse::TYPE_ASSIGN)) { - return false; + if (!$previousNode->isType(\Rector\DeadCode\ValueObject\VariableNodeUse::TYPE_ASSIGN)) { + return \false; } - - return $nodeByTypeAndPosition->isType(VariableNodeUse::TYPE_USE); + return $nodeByTypeAndPosition->isType(\Rector\DeadCode\ValueObject\VariableNodeUse::TYPE_USE); } - - private function shouldRemoveAssignNode( - ?VariableNodeUse $previousNode, - VariableNodeUse $nodeByTypeAndPosition - ): bool { + private function shouldRemoveAssignNode(?\Rector\DeadCode\ValueObject\VariableNodeUse $previousNode, \Rector\DeadCode\ValueObject\VariableNodeUse $nodeByTypeAndPosition) : bool + { if ($previousNode === null) { - return false; + return \false; } - - if (! $previousNode->isType(VariableNodeUse::TYPE_ASSIGN)) { - return false; + if (!$previousNode->isType(\Rector\DeadCode\ValueObject\VariableNodeUse::TYPE_ASSIGN)) { + return \false; } - - if (! $nodeByTypeAndPosition->isType(VariableNodeUse::TYPE_ASSIGN)) { - return false; + if (!$nodeByTypeAndPosition->isType(\Rector\DeadCode\ValueObject\VariableNodeUse::TYPE_ASSIGN)) { + return \false; } - // check the nesting level, e.g. call in if/while/else etc. if ($previousNode->getNestingHash() !== $nodeByTypeAndPosition->getNestingHash()) { - return false; + return \false; } - // check previous node doesn't contain the node on the right, e.g. // $someNode = 1; // $someNode = $someNode ?: 1; /** @var Assign $assignNode */ $assignNode = $nodeByTypeAndPosition->getParentNode(); - - $isVariableAssigned = (bool) $this->betterNodeFinder->findFirst($assignNode->expr, function (Node $node) use ( - $nodeByTypeAndPosition - ): bool { + $isVariableAssigned = (bool) $this->betterNodeFinder->findFirst($assignNode->expr, function (\PhpParser\Node $node) use($nodeByTypeAndPosition) : bool { return $this->nodeComparator->areNodesEqual($node, $nodeByTypeAndPosition->getVariableNode()); }); - - return ! $isVariableAssigned; + return !$isVariableAssigned; } } diff --git a/rules/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector.php b/rules/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector.php index dca9bd5c5da..10a32a81768 100644 --- a/rules/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector.php +++ b/rules/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->else !== null) { return null; } - // just one if - if (count($node->elseifs) !== 0) { + if (\count($node->elseifs) !== 0) { return null; } - $conditionStaticType = $this->getStaticType($node->cond); - if (! $conditionStaticType instanceof ConstantBooleanType) { + if (!$conditionStaticType instanceof \PHPStan\Type\Constant\ConstantBooleanType) { return null; } - - if (! $conditionStaticType->getValue()) { + if (!$conditionStaticType->getValue()) { return null; } - - if (count($node->stmts) !== 1) { + if (\count($node->stmts) !== 1) { // unable to handle now return null; } - return $node->stmts[0]; } } diff --git a/rules/DeadCode/Rector/If_/RemoveDeadInstanceOfRector.php b/rules/DeadCode/Rector/If_/RemoveDeadInstanceOfRector.php index db564a0ac4e..e6de5417fa2 100644 --- a/rules/DeadCode/Rector/If_/RemoveDeadInstanceOfRector.php +++ b/rules/DeadCode/Rector/If_/RemoveDeadInstanceOfRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove dead instanceof check on type hinted variable', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove dead instanceof check on type hinted variable', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function go(stdClass $stdClass) @@ -47,8 +41,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function go(stdClass $stdClass) @@ -57,63 +50,49 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $scope = $node->getAttribute(AttributeKey::SCOPE); - + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); // a trait - if (! $scope instanceof Scope) { + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - - if (! $this->ifManipulator->isIfWithoutElseAndElseIfs($node)) { + if (!$this->ifManipulator->isIfWithoutElseAndElseIfs($node)) { return null; } - - if ($node->cond instanceof BooleanNot && $node->cond->expr instanceof Instanceof_) { + if ($node->cond instanceof \PhpParser\Node\Expr\BooleanNot && $node->cond->expr instanceof \PhpParser\Node\Expr\Instanceof_) { return $this->processMayDeadInstanceOf($node, $node->cond->expr); } - - if ($node->cond instanceof Instanceof_) { + if ($node->cond instanceof \PhpParser\Node\Expr\Instanceof_) { return $this->processMayDeadInstanceOf($node, $node->cond); } - return $node; } - - private function processMayDeadInstanceOf(If_ $if, Instanceof_ $instanceof): ?If_ + private function processMayDeadInstanceOf(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node\Expr\Instanceof_ $instanceof) : ?\PhpParser\Node\Stmt\If_ { $classType = $this->nodeTypeResolver->resolve($instanceof->class); $exprType = $this->nodeTypeResolver->resolve($instanceof->expr); - - $isSameStaticTypeOrSubtype = $classType->equals($exprType) || $classType->isSuperTypeOf($exprType) - ->yes(); - if (! $isSameStaticTypeOrSubtype) { + $isSameStaticTypeOrSubtype = $classType->equals($exprType) || $classType->isSuperTypeOf($exprType)->yes(); + if (!$isSameStaticTypeOrSubtype) { return null; } - if ($if->cond === $instanceof) { $this->unwrapStmts($if->stmts, $if); $this->removeNode($if); - return null; } - $this->removeNode($if); return $if; } diff --git a/rules/DeadCode/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector.php b/rules/DeadCode/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector.php index 24d15dfe57a..53719778ce7 100644 --- a/rules/DeadCode/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector.php +++ b/rules/DeadCode/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->uselessIfCondBeforeForeachDetector = $uselessIfCondBeforeForeachDetector; $this->countManipulator = $countManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove unused if check to non-empty array before foreach of the array', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove unused if check to non-empty array before foreach of the array', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -64,8 +51,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -77,49 +63,39 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isUselessBeforeForeachCheck($node)) { + if (!$this->isUselessBeforeForeachCheck($node)) { return null; } - return $node->stmts[0]; } - - private function isUselessBeforeForeachCheck(If_ $if): bool + private function isUselessBeforeForeachCheck(\PhpParser\Node\Stmt\If_ $if) : bool { - if (! $this->ifManipulator->isIfWithOnly($if, Foreach_::class)) { - return false; + if (!$this->ifManipulator->isIfWithOnly($if, \PhpParser\Node\Stmt\Foreach_::class)) { + return \false; } - /** @var Foreach_ $foreach */ $foreach = $if->stmts[0]; $foreachExpr = $foreach->expr; - if ($this->uselessIfCondBeforeForeachDetector->isMatchingNotIdenticalEmptyArray($if, $foreachExpr)) { - return true; + return \true; } - if ($this->uselessIfCondBeforeForeachDetector->isMatchingNotEmpty($if, $foreachExpr)) { - return true; + return \true; } - return $this->countManipulator->isCounterHigherThanOne($if->cond, $foreachExpr); } } diff --git a/rules/DeadCode/Rector/If_/SimplifyIfElseWithSameContentRector.php b/rules/DeadCode/Rector/If_/SimplifyIfElseWithSameContentRector.php index cac2dbd3082..003fba1284c 100644 --- a/rules/DeadCode/Rector/If_/SimplifyIfElseWithSameContentRector.php +++ b/rules/DeadCode/Rector/If_/SimplifyIfElseWithSameContentRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->else === null) { return null; } - - if (! $this->isIfWithConstantReturns($node)) { + if (!$this->isIfWithConstantReturns($node)) { return null; } - foreach ($node->stmts as $stmt) { $this->addNodeBeforeNode($stmt, $node); } - $this->removeNode($node); - return $node; } - - private function isIfWithConstantReturns(If_ $if): bool + private function isIfWithConstantReturns(\PhpParser\Node\Stmt\If_ $if) : bool { $possibleContents = []; $possibleContents[] = $this->print($if->stmts); - foreach ($if->elseifs as $elseif) { $possibleContents[] = $this->print($elseif->stmts); } - $else = $if->else; - if (! $else instanceof Else_) { - throw new ShouldNotHappenException(); + if (!$else instanceof \PhpParser\Node\Stmt\Else_) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $possibleContents[] = $this->print($else->stmts); - - $uniqueContents = array_unique($possibleContents); - + $uniqueContents = \array_unique($possibleContents); // only one content for all - return count($uniqueContents) === 1; + return \count($uniqueContents) === 1; } } diff --git a/rules/DeadCode/Rector/If_/UnwrapFutureCompatibleIfFunctionExistsRector.php b/rules/DeadCode/Rector/If_/UnwrapFutureCompatibleIfFunctionExistsRector.php index 76dace95947..747d7fa9cae 100644 --- a/rules/DeadCode/Rector/If_/UnwrapFutureCompatibleIfFunctionExistsRector.php +++ b/rules/DeadCode/Rector/If_/UnwrapFutureCompatibleIfFunctionExistsRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->functionSupportResolver = $functionSupportResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove functions exists if with else for always existing', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove functions exists if with else for always existing', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -57,8 +48,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -68,59 +58,47 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $match = $this->ifManipulator->isIfOrIfElseWithFunctionCondition($node, 'function_exists'); - if (! $match) { + if (!$match) { return null; } - /** @var FuncCall $funcCall */ $funcCall = $node->cond; - $functionToExistName = $this->valueResolver->getValue($funcCall->args[0]->value); - if (! is_string($functionToExistName)) { + if (!\is_string($functionToExistName)) { return null; } - - if (! $this->functionSupportResolver->isFunctionSupported($functionToExistName)) { + if (!$this->functionSupportResolver->isFunctionSupported($functionToExistName)) { return null; } - $this->unwrapStmts($node->stmts, $node); $this->removeNode($node); - return null; } - - private function shouldSkip(If_ $if): bool + private function shouldSkip(\PhpParser\Node\Stmt\If_ $if) : bool { - $classLike = $if->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { - return false; + $classLike = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { + return \false; } - // skip rector rules, as they decided if function exists in that particular projects - return $this->isObjectType($classLike, new ObjectType('Rector\Core\Contract\Rector\RectorInterface')); + return $this->isObjectType($classLike, new \PHPStan\Type\ObjectType('Rector\\Core\\Contract\\Rector\\RectorInterface')); } } diff --git a/rules/DeadCode/Rector/If_/UnwrapFutureCompatibleIfPhpVersionRector.php b/rules/DeadCode/Rector/If_/UnwrapFutureCompatibleIfPhpVersionRector.php index 48bc4d8e848..9e5f964f28d 100644 --- a/rules/DeadCode/Rector/If_/UnwrapFutureCompatibleIfPhpVersionRector.php +++ b/rules/DeadCode/Rector/If_/UnwrapFutureCompatibleIfPhpVersionRector.php @@ -1,7 +1,6 @@ conditionEvaluator = $conditionEvaluator; $this->conditionResolver = $conditionResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove php version checks if they are passed', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove php version checks if they are passed', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' // current PHP: 7.2 if (version_compare(PHP_VERSION, '7.2', '<')) { return 'is PHP 7.1-'; @@ -50,75 +41,60 @@ if (version_compare(PHP_VERSION, '7.2', '<')) { return 'is PHP 7.2+'; } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' // current PHP: 7.2 return 'is PHP 7.2+'; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ((bool) $node->elseifs) { return null; } - $condition = $this->conditionResolver->resolveFromExpr($node->cond); - if (! $condition instanceof ConditionInterface) { + if (!$condition instanceof \Rector\DeadCode\Contract\ConditionInterface) { return null; } - $result = $this->conditionEvaluator->evaluate($condition); if ($result === null) { return null; } - // if is skipped if ($result) { $this->refactorIsMatch($node); } else { $this->refactorIsNotMatch($node); } - return $node; } - - private function refactorIsMatch(If_ $if): void + private function refactorIsMatch(\PhpParser\Node\Stmt\If_ $if) : void { if ((bool) $if->elseifs) { return; } - $this->unwrapStmts($if->stmts, $if); - $this->removeNode($if); } - - private function refactorIsNotMatch(If_ $if): void + private function refactorIsNotMatch(\PhpParser\Node\Stmt\If_ $if) : void { // no else → just remove the node if ($if->else === null) { $this->removeNode($if); return; } - // else is always used $this->unwrapStmts($if->else->stmts, $if); - $this->removeNode($if); } } diff --git a/rules/DeadCode/Rector/MethodCall/RemoveEmptyMethodCallRector.php b/rules/DeadCode/Rector/MethodCall/RemoveEmptyMethodCallRector.php index 2b7a496ae0c..21b6db993f9 100644 --- a/rules/DeadCode/Rector/MethodCall/RemoveEmptyMethodCallRector.php +++ b/rules/DeadCode/Rector/MethodCall/RemoveEmptyMethodCallRector.php @@ -1,7 +1,6 @@ classReflectionToAstResolver = $classReflectionToAstResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove empty method call', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove empty method call', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function callThis() @@ -52,8 +46,7 @@ class SomeClass $some = new SomeClass(); $some->callThis(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function callThis() @@ -63,92 +56,74 @@ class SomeClass $some = new SomeClass(); CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $scope = $node->var->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->var->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $type = $scope->getType($node->var); - if ($type instanceof ThisType) { + if ($type instanceof \PHPStan\Type\ThisType) { $type = $type->getStaticObjectType(); } - - if (! $type instanceof ObjectType) { + if (!$type instanceof \PHPStan\Type\ObjectType) { return null; } - $class = $this->classReflectionToAstResolver->getClassFromObjectType($type); if ($this->shouldSkipClassMethod($class, $node)) { return null; } - // if->cond cannot removed, it has to be replaced with false, see https://3v4l.org/U9S9i - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof If_ && $parent->cond === $node) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Stmt\If_ && $parent->cond === $node) { return $this->nodeFactory->createFalse(); } - - if ($parent instanceof Assign) { + if ($parent instanceof \PhpParser\Node\Expr\Assign) { return $this->nodeFactory->createFalse(); } - - if ($parent instanceof ArrowFunction && $this->nodeComparator->areNodesEqual($parent->expr, $node)) { + if ($parent instanceof \PhpParser\Node\Expr\ArrowFunction && $this->nodeComparator->areNodesEqual($parent->expr, $node)) { return $this->processArrowFunction($parent, $node); } - $this->removeNode($node); - return $node; } - - private function shouldSkipClassMethod(?Class_ $class, MethodCall $methodCall): bool + private function shouldSkipClassMethod(?\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Expr\MethodCall $methodCall) : bool { - if (! $class instanceof Class_) { - return true; + if (!$class instanceof \PhpParser\Node\Stmt\Class_) { + return \true; } - $methodName = $this->getName($methodCall->name); if ($methodName === null) { - return true; + return \true; } - $classMethod = $class->getMethod($methodName); - if (! $classMethod instanceof ClassMethod) { - return true; + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \true; } - if ($classMethod->isAbstract()) { - return true; + return \true; } - - return count((array) $classMethod->stmts) !== 0; + return \count((array) $classMethod->stmts) !== 0; } - - private function processArrowFunction(ArrowFunction $arrowFunction, MethodCall $methodCall): Expr + private function processArrowFunction(\PhpParser\Node\Expr\ArrowFunction $arrowFunction, \PhpParser\Node\Expr\MethodCall $methodCall) : \PhpParser\Node\Expr { - $parentOfParent = $arrowFunction->getAttribute(AttributeKey::PARENT_NODE); - if ($parentOfParent instanceof Expression) { + $parentOfParent = $arrowFunction->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentOfParent instanceof \PhpParser\Node\Stmt\Expression) { $this->removeNode($arrowFunction); return $methodCall; } - return $this->nodeFactory->createFalse(); } } diff --git a/rules/DeadCode/Rector/Node/RemoveNonExistingVarAnnotationRector.php b/rules/DeadCode/Rector/Node/RemoveNonExistingVarAnnotationRector.php index 5711bd55b5f..9b196c6a978 100644 --- a/rules/DeadCode/Rector/Node/RemoveNonExistingVarAnnotationRector.php +++ b/rules/DeadCode/Rector/Node/RemoveNonExistingVarAnnotationRector.php @@ -1,7 +1,6 @@ > */ - private const NODES_TO_MATCH = [ - Assign::class, - AssignRef::class, - Foreach_::class, - Static_::class, - Echo_::class, - Return_::class, - Expression::class, - Throw_::class, - If_::class, - While_::class, - Switch_::class, - Nop::class, - ]; - + private const NODES_TO_MATCH = [\PhpParser\Node\Expr\Assign::class, \PhpParser\Node\Expr\AssignRef::class, \PhpParser\Node\Stmt\Foreach_::class, \PhpParser\Node\Stmt\Static_::class, \PhpParser\Node\Stmt\Echo_::class, \PhpParser\Node\Stmt\Return_::class, \PhpParser\Node\Stmt\Expression::class, \PhpParser\Node\Stmt\Throw_::class, \PhpParser\Node\Stmt\If_::class, \PhpParser\Node\Stmt\While_::class, \PhpParser\Node\Stmt\Switch_::class, \PhpParser\Node\Stmt\Nop::class]; /** * @var TypeChecker */ private $typeChecker; - /** * @var CommentRemover */ private $commentRemover; - - public function __construct(TypeChecker $typeChecker, CommentRemover $commentRemover) + public function __construct(\RectorPrefix20210509\Symplify\PackageBuilder\Php\TypeChecker $typeChecker, \Rector\Comments\CommentRemover $commentRemover) { $this->typeChecker = $typeChecker; $this->commentRemover = $commentRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Removes non-existing @var annotations above the code', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removes non-existing @var annotations above the code', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function get() @@ -83,8 +60,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function get() @@ -93,64 +69,53 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Node::class]; + return [\PhpParser\Node::class]; } - - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); $varTagValueNode = $phpDocInfo->getVarTagValueNode(); - if (! $varTagValueNode instanceof VarTagValueNode) { + if (!$varTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode) { return null; } - - $variableName = ltrim($varTagValueNode->variableName, '$'); + $variableName = \ltrim($varTagValueNode->variableName, '$'); if ($this->hasVariableName($node, $variableName)) { return null; } - $comments = $node->getComments(); - if (isset($comments[1]) && $comments[1] instanceof Comment) { + if (isset($comments[1]) && $comments[1] instanceof \PhpParser\Comment) { $this->commentRemover->rollbackComments($node, $comments[1]); return $node; } - - $phpDocInfo->removeByType(VarTagValueNode::class); + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode::class); return $node; } - - private function shouldSkip(Node $node): bool + private function shouldSkip(\PhpParser\Node $node) : bool { - if (! $node instanceof Nop) { - return ! $this->typeChecker->isInstanceOf($node, self::NODES_TO_MATCH); + if (!$node instanceof \PhpParser\Node\Stmt\Nop) { + return !$this->typeChecker->isInstanceOf($node, self::NODES_TO_MATCH); } - if (count($node->getComments()) <= 1) { - return ! $this->typeChecker->isInstanceOf($node, self::NODES_TO_MATCH); + if (\count($node->getComments()) <= 1) { + return !$this->typeChecker->isInstanceOf($node, self::NODES_TO_MATCH); } - return true; + return \true; } - - private function hasVariableName(Node $node, string $variableName): bool + private function hasVariableName(\PhpParser\Node $node, string $variableName) : bool { - return (bool) $this->betterNodeFinder->findFirst($node, function (Node $node) use ($variableName): bool { - if (! $node instanceof Variable) { - return false; + return (bool) $this->betterNodeFinder->findFirst($node, function (\PhpParser\Node $node) use($variableName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->isName($node, $variableName); }); } diff --git a/rules/DeadCode/Rector/Plus/RemoveDeadZeroAndOneOperationRector.php b/rules/DeadCode/Rector/Plus/RemoveDeadZeroAndOneOperationRector.php index c7376f68017..ebb62e3f020 100644 --- a/rules/DeadCode/Rector/Plus/RemoveDeadZeroAndOneOperationRector.php +++ b/rules/DeadCode/Rector/Plus/RemoveDeadZeroAndOneOperationRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ - Plus::class, - Minus::class, - Mul::class, - Div::class, - AssignPlus::class, - AssignMinus::class, - AssignMul::class, - AssignDiv::class, - ]; + return [\PhpParser\Node\Expr\BinaryOp\Plus::class, \PhpParser\Node\Expr\BinaryOp\Minus::class, \PhpParser\Node\Expr\BinaryOp\Mul::class, \PhpParser\Node\Expr\BinaryOp\Div::class, \PhpParser\Node\Expr\AssignOp\Plus::class, \PhpParser\Node\Expr\AssignOp\Minus::class, \PhpParser\Node\Expr\AssignOp\Mul::class, \PhpParser\Node\Expr\AssignOp\Div::class]; } - /** * @param Plus|Minus|Mul|Div|AssignPlus|AssignMinus|AssignMul|AssignDiv $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $changedNode = null; $previousNode = $node; - - if ($node instanceof AssignOp) { + if ($node instanceof \PhpParser\Node\Expr\AssignOp) { $changedNode = $this->processAssignOp($node); } - // -, + - if ($node instanceof BinaryOp) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp) { $changedNode = $this->processBinaryOp($node); } - // recurse nested combinations - while ($changedNode !== null && ! $this->nodeComparator->areNodesEqual($previousNode, $changedNode)) { + while ($changedNode !== null && !$this->nodeComparator->areNodesEqual($previousNode, $changedNode)) { $previousNode = $changedNode; - - if ($changedNode instanceof BinaryOp || $changedNode instanceof AssignOp) { + if ($changedNode instanceof \PhpParser\Node\Expr\BinaryOp || $changedNode instanceof \PhpParser\Node\Expr\AssignOp) { $changedNode = $this->refactor($changedNode); } - // nothing more to change, return last node - if (! $changedNode instanceof Node) { + if (!$changedNode instanceof \PhpParser\Node) { return $previousNode; } } - return $changedNode; } - - private function processAssignOp(Node $node): ?Expr + private function processAssignOp(\PhpParser\Node $node) : ?\PhpParser\Node\Expr { // +=, -= - if ($node instanceof AssignPlus || $node instanceof AssignMinus) { - if (! $this->valueResolver->isValue($node->expr, 0)) { + if ($node instanceof \PhpParser\Node\Expr\AssignOp\Plus || $node instanceof \PhpParser\Node\Expr\AssignOp\Minus) { + if (!$this->valueResolver->isValue($node->expr, 0)) { return null; } - if ($this->nodeTypeResolver->isNumberType($node->var)) { return $node->var; } } - // *, / - if ($node instanceof AssignMul || $node instanceof AssignDiv) { - if (! $this->valueResolver->isValue($node->expr, 1)) { + if ($node instanceof \PhpParser\Node\Expr\AssignOp\Mul || $node instanceof \PhpParser\Node\Expr\AssignOp\Div) { + if (!$this->valueResolver->isValue($node->expr, 1)) { return null; } if ($this->nodeTypeResolver->isNumberType($node->var)) { return $node->var; } } - return null; } - - private function processBinaryOp(Node $node): ?Expr + private function processBinaryOp(\PhpParser\Node $node) : ?\PhpParser\Node\Expr { - if ($node instanceof Plus || $node instanceof Minus) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Plus || $node instanceof \PhpParser\Node\Expr\BinaryOp\Minus) { return $this->processBinaryPlusAndMinus($node); } - // *, / - if ($node instanceof Mul) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Mul) { return $this->processBinaryMulAndDiv($node); } - if ($node instanceof Div) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Div) { return $this->processBinaryMulAndDiv($node); } return null; } - /** * @param Plus|Minus $binaryOp */ - private function processBinaryPlusAndMinus(BinaryOp $binaryOp): ?Expr + private function processBinaryPlusAndMinus(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\PhpParser\Node\Expr { - if ($this->valueResolver->isValue($binaryOp->left, 0) && $this->nodeTypeResolver->isNumberType( - $binaryOp->right - )) { - if ($binaryOp instanceof Minus) { - return new UnaryMinus($binaryOp->right); + if ($this->valueResolver->isValue($binaryOp->left, 0) && $this->nodeTypeResolver->isNumberType($binaryOp->right)) { + if ($binaryOp instanceof \PhpParser\Node\Expr\BinaryOp\Minus) { + return new \PhpParser\Node\Expr\UnaryMinus($binaryOp->right); } return $binaryOp->right; } - - if (! $this->valueResolver->isValue($binaryOp->right, 0)) { + if (!$this->valueResolver->isValue($binaryOp->right, 0)) { return null; } - - if (! $this->nodeTypeResolver->isNumberType($binaryOp->left)) { + if (!$this->nodeTypeResolver->isNumberType($binaryOp->left)) { return null; } - return $binaryOp->left; } - /** * @param Mul|Div $binaryOp */ - private function processBinaryMulAndDiv(BinaryOp $binaryOp): ?Expr + private function processBinaryMulAndDiv(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\PhpParser\Node\Expr { - if ($binaryOp instanceof Mul && $this->valueResolver->isValue( - $binaryOp->left, - 1 - ) && $this->nodeTypeResolver->isNumberType($binaryOp->right)) { + if ($binaryOp instanceof \PhpParser\Node\Expr\BinaryOp\Mul && $this->valueResolver->isValue($binaryOp->left, 1) && $this->nodeTypeResolver->isNumberType($binaryOp->right)) { return $binaryOp->right; } - - if (! $this->valueResolver->isValue($binaryOp->right, 1)) { + if (!$this->valueResolver->isValue($binaryOp->right, 1)) { return null; } - - if (! $this->nodeTypeResolver->isNumberType($binaryOp->left)) { + if (!$this->nodeTypeResolver->isNumberType($binaryOp->left)) { return null; } - return $binaryOp->left; } } diff --git a/rules/DeadCode/Rector/Property/RemoveSetterOnlyPropertyAndMethodCallRector.php b/rules/DeadCode/Rector/Property/RemoveSetterOnlyPropertyAndMethodCallRector.php index 016397c9d52..f712122488f 100644 --- a/rules/DeadCode/Rector/Property/RemoveSetterOnlyPropertyAndMethodCallRector.php +++ b/rules/DeadCode/Rector/Property/RemoveSetterOnlyPropertyAndMethodCallRector.php @@ -1,7 +1,6 @@ propertyManipulator = $propertyManipulator; $this->vendorLockResolver = $vendorLockResolver; $this->propertyFetchFinder = $propertyFetchFinder; $this->complexNodeRemover = $complexNodeRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Removes method that set values that are never used', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removes method that set values that are never used', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private $name; @@ -86,8 +71,7 @@ class ActiveOnlySetter } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { } @@ -100,129 +84,103 @@ class ActiveOnlySetter } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipProperty($node)) { return null; } - $propertyFetches = $this->propertyFetchFinder->findPrivatePropertyFetches($node); $classMethodsToCheck = $this->collectClassMethodsToCheck($propertyFetches); $vendorLockedClassMethodNames = $this->getVendorLockedClassMethodNames($classMethodsToCheck); - $this->complexNodeRemover->removePropertyAndUsages($node, $vendorLockedClassMethodNames); - foreach ($classMethodsToCheck as $classMethodToCheck) { - if (! $this->hasMethodSomeStmtsLeft($classMethodToCheck)) { + if (!$this->hasMethodSomeStmtsLeft($classMethodToCheck)) { continue; } - $classMethodName = $this->getName($classMethodToCheck->name); - if (in_array($classMethodName, $vendorLockedClassMethodNames, true)) { + if (\in_array($classMethodName, $vendorLockedClassMethodNames, \true)) { continue; } - $this->complexNodeRemover->removeClassMethodAndUsages($classMethodToCheck); } - return $node; } - - private function shouldSkipProperty(Property $property): bool + private function shouldSkipProperty(\PhpParser\Node\Stmt\Property $property) : bool { - if (count($property->props) !== 1) { - return true; + if (\count($property->props) !== 1) { + return \true; } - - if (! $property->isPrivate()) { - return true; + if (!$property->isPrivate()) { + return \true; } - /** @var Class_|Interface_|Trait_|null $classLike */ - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); if ($classLike === null) { - return true; + return \true; } - - if ($classLike instanceof Trait_) { - return true; + if ($classLike instanceof \PhpParser\Node\Stmt\Trait_) { + return \true; } - - if ($classLike instanceof Interface_) { - return true; + if ($classLike instanceof \PhpParser\Node\Stmt\Interface_) { + return \true; } - return $this->propertyManipulator->isPropertyUsedInReadContext($property); } - /** * @param PropertyFetch[]|StaticPropertyFetch[] $propertyFetches * @return ClassMethod[] */ - private function collectClassMethodsToCheck(array $propertyFetches): array + private function collectClassMethodsToCheck(array $propertyFetches) : array { $classMethodsToCheck = []; - foreach ($propertyFetches as $propertyFetch) { - $classMethod = $propertyFetch->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { - throw new ShouldNotHappenException(); + $classMethod = $propertyFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - // this rector does not remove empty constructors - if ($this->nodeNameResolver->isName($classMethod, MethodName::CONSTRUCT)) { + if ($this->nodeNameResolver->isName($classMethod, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { continue; } - $methodName = $this->getName($classMethod); $classMethodsToCheck[$methodName] = $classMethod; } - return $classMethodsToCheck; } - /** * @param array $methodsToCheck * @return string[] */ - private function getVendorLockedClassMethodNames(array $methodsToCheck): array + private function getVendorLockedClassMethodNames(array $methodsToCheck) : array { $vendorLockedClassMethodsNames = []; foreach ($methodsToCheck as $methodToCheck) { - if (! $this->vendorLockResolver->isClassMethodRemovalVendorLocked($methodToCheck)) { + if (!$this->vendorLockResolver->isClassMethodRemovalVendorLocked($methodToCheck)) { continue; } - $vendorLockedClassMethodsNames[] = $this->getName($methodToCheck); } - return $vendorLockedClassMethodsNames; } - - private function hasMethodSomeStmtsLeft(ClassMethod $classMethod): bool + private function hasMethodSomeStmtsLeft(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { foreach ((array) $classMethod->stmts as $stmt) { - if (! $this->nodesToRemoveCollector->isNodeRemoved($stmt)) { - return false; + if (!$this->nodesToRemoveCollector->isNodeRemoved($stmt)) { + return \false; } } - - return true; + return \true; } } diff --git a/rules/DeadCode/Rector/Property/RemoveUnusedPrivatePropertyRector.php b/rules/DeadCode/Rector/Property/RemoveUnusedPrivatePropertyRector.php index a3e024c53cc..d84cf85aed5 100644 --- a/rules/DeadCode/Rector/Property/RemoveUnusedPrivatePropertyRector.php +++ b/rules/DeadCode/Rector/Property/RemoveUnusedPrivatePropertyRector.php @@ -1,7 +1,6 @@ propertyManipulator = $propertyManipulator; $this->complexNodeRemover = $complexNodeRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove unused private properties', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove unused private properties', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private $property; } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipProperty($node)) { return null; } - if ($this->propertyManipulator->isPropertyUsedInReadContext($node)) { return null; } - $this->complexNodeRemover->removePropertyAndUsages($node); - return $node; } - - private function shouldSkipProperty(Property $property): bool + private function shouldSkipProperty(\PhpParser\Node\Stmt\Property $property) : bool { - if (count($property->props) !== 1) { - return true; + if (\count($property->props) !== 1) { + return \true; } - - if (! $property->isPrivate()) { - return true; + if (!$property->isPrivate()) { + return \true; } - /** @var Class_|Interface_|Trait_|null $classLike */ - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - return ! $classLike instanceof Class_; + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + return !$classLike instanceof \PhpParser\Node\Stmt\Class_; } } diff --git a/rules/DeadCode/Rector/Property/RemoveUselessVarTagRector.php b/rules/DeadCode/Rector/Property/RemoveUselessVarTagRector.php index cdecf1970bd..723e3ec879a 100644 --- a/rules/DeadCode/Rector/Property/RemoveUselessVarTagRector.php +++ b/rules/DeadCode/Rector/Property/RemoveUselessVarTagRector.php @@ -1,7 +1,6 @@ varTagRemover = $varTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove unused @var annotation for properties', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove unused @var annotation for properties', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { /** @@ -40,39 +34,32 @@ final class SomeClass public string $name = 'name'; } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public string $name = 'name'; } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); $this->varTagRemover->removeVarTagIfUseless($phpDocInfo, $node); - if ($phpDocInfo->hasChanged()) { - $node->setAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, true); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, \true); return $node; } - return null; } } diff --git a/rules/DeadCode/Rector/PropertyProperty/RemoveNullPropertyInitializationRector.php b/rules/DeadCode/Rector/PropertyProperty/RemoveNullPropertyInitializationRector.php index 28375cf8338..b7d365c84a5 100644 --- a/rules/DeadCode/Rector/PropertyProperty/RemoveNullPropertyInitializationRector.php +++ b/rules/DeadCode/Rector/PropertyProperty/RemoveNullPropertyInitializationRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [PropertyProperty::class]; + return [\PhpParser\Node\Stmt\PropertyProperty::class]; } - /** * @param PropertyProperty $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $defaultValueNode = $node->default; - if (! $defaultValueNode instanceof Expr) { + if (!$defaultValueNode instanceof \PhpParser\Node\Expr) { return null; } - - if (! ($defaultValueNode instanceof ConstFetch)) { + if (!$defaultValueNode instanceof \PhpParser\Node\Expr\ConstFetch) { return null; } - - if (strtolower((string) $defaultValueNode->name) !== 'null') { + if (\strtolower((string) $defaultValueNode->name) !== 'null') { return null; } - $nodeNode = $node->getAttribute(AttributeKey::PREVIOUS_NODE); - - if ($nodeNode instanceof NullableType) { + $nodeNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if ($nodeNode instanceof \PhpParser\Node\NullableType) { return null; } - $node->default = null; - return $node; } } diff --git a/rules/DeadCode/Rector/Return_/RemoveDeadConditionAboveReturnRector.php b/rules/DeadCode/Rector/Return_/RemoveDeadConditionAboveReturnRector.php index e25d7464898..5c666172878 100644 --- a/rules/DeadCode/Rector/Return_/RemoveDeadConditionAboveReturnRector.php +++ b/rules/DeadCode/Rector/Return_/RemoveDeadConditionAboveReturnRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Return_::class]; + return [\PhpParser\Node\Stmt\Return_::class]; } - /** * @param Return_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $previousNode = $node->getAttribute(AttributeKey::PREVIOUS_NODE); - if (! $previousNode instanceof If_) { + $previousNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if (!$previousNode instanceof \PhpParser\Node\Stmt\If_) { return null; } - if ($previousNode->elseifs !== []) { return null; } - - if ($previousNode->else instanceof Else_) { + if ($previousNode->else instanceof \PhpParser\Node\Stmt\Else_) { return null; } - - $countStmt = count($previousNode->stmts); + $countStmt = \count($previousNode->stmts); if ($countStmt === 0) { $this->removeNode($previousNode); return $node; } - if ($countStmt > 1) { return null; } - $stmt = $previousNode->stmts[0]; - if (! $stmt instanceof Return_) { + if (!$stmt instanceof \PhpParser\Node\Stmt\Return_) { return null; } - - if (! $this->nodeComparator->areNodesEqual($stmt, $node)) { + if (!$this->nodeComparator->areNodesEqual($stmt, $node)) { return null; } - $this->removeNode($previousNode); return $node; } diff --git a/rules/DeadCode/Rector/StaticCall/RemoveParentCallWithoutParentRector.php b/rules/DeadCode/Rector/StaticCall/RemoveParentCallWithoutParentRector.php index 69bd2a1d6a0..754a0290594 100644 --- a/rules/DeadCode/Rector/StaticCall/RemoveParentCallWithoutParentRector.php +++ b/rules/DeadCode/Rector/StaticCall/RemoveParentCallWithoutParentRector.php @@ -1,7 +1,6 @@ classMethodManipulator = $classMethodManipulator; $this->parentClassScopeResolver = $parentClassScopeResolver; $this->classAnalyzer = $classAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove unused parent call with no parent class', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove unused parent call with no parent class', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class OrphanClass { public function __construct() @@ -62,8 +49,7 @@ class OrphanClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class OrphanClass { public function __construct() @@ -71,60 +57,48 @@ class OrphanClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - - if (! $node->class instanceof Name) { + if (!$node->class instanceof \PhpParser\Node\Name) { return null; } - - if (! $this->isName($node->class, 'parent')) { + if (!$this->isName($node->class, 'parent')) { return null; } - $parentClassName = $this->parentClassScopeResolver->resolveParentClassName($node); if ($parentClassName === null) { $this->removeNode($node); return null; } - - $classMethod = $node->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { + $classMethod = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - if ($this->classAnalyzer->isAnonymousClass($classLike)) { // currently the classMethodManipulator isn't able to find usages of anonymous classes return null; } - $calledMethodName = $this->getName($node->name); if ($this->classMethodManipulator->hasParentMethodOrInterfaceMethod($classMethod, $calledMethodName)) { return null; } - $this->removeNode($node); - return null; } } diff --git a/rules/DeadCode/Rector/Stmt/RemoveUnreachableStatementRector.php b/rules/DeadCode/Rector/Stmt/RemoveUnreachableStatementRector.php index 6ac9c7ec63c..3ff86060ef6 100644 --- a/rules/DeadCode/Rector/Stmt/RemoveUnreachableStatementRector.php +++ b/rules/DeadCode/Rector/Stmt/RemoveUnreachableStatementRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Stmt::class]; + return [\PhpParser\Node\Stmt::class]; } - /** * @param Stmt $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipNode($node)) { return null; } - // might be PHPStan false positive, better skip - $previousStatement = $node->getAttribute(AttributeKey::PREVIOUS_STATEMENT); - if ($previousStatement instanceof If_) { - $node->setAttribute( - AttributeKey::IS_UNREACHABLE, - $previousStatement->getAttribute(AttributeKey::IS_UNREACHABLE) - ); + $previousStatement = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT); + if ($previousStatement instanceof \PhpParser\Node\Stmt\If_) { + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_UNREACHABLE, $previousStatement->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_UNREACHABLE)); } - - if ($previousStatement instanceof While_) { - $node->setAttribute( - AttributeKey::IS_UNREACHABLE, - $previousStatement->getAttribute(AttributeKey::IS_UNREACHABLE) - ); + if ($previousStatement instanceof \PhpParser\Node\Stmt\While_) { + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_UNREACHABLE, $previousStatement->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_UNREACHABLE)); } - - if (! $this->isUnreachable($node)) { + if (!$this->isUnreachable($node)) { return null; } - if ($this->isAfterMarkTestSkippedMethodCall($node)) { - $node->setAttribute(AttributeKey::IS_UNREACHABLE, false); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_UNREACHABLE, \false); return null; } - $this->removeNode($node); - return null; } - - private function shouldSkipNode(Stmt $stmt): bool + private function shouldSkipNode(\PhpParser\Node\Stmt $stmt) : bool { - if ($stmt instanceof Nop) { - return true; + if ($stmt instanceof \PhpParser\Node\Stmt\Nop) { + return \true; } - - if ($stmt instanceof ClassLike) { - return true; + if ($stmt instanceof \PhpParser\Node\Stmt\ClassLike) { + return \true; } - - return $stmt instanceof FunctionLike; + return $stmt instanceof \PhpParser\Node\FunctionLike; } - - private function isUnreachable(Stmt $stmt): bool + private function isUnreachable(\PhpParser\Node\Stmt $stmt) : bool { - $isUnreachable = $stmt->getAttribute(AttributeKey::IS_UNREACHABLE); - if ($isUnreachable === true) { - return true; + $isUnreachable = $stmt->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_UNREACHABLE); + if ($isUnreachable === \true) { + return \true; } - // traverse up for unreachable node in the same scope - $previousNode = $stmt->getAttribute(AttributeKey::PREVIOUS_STATEMENT); - - while ($previousNode instanceof Stmt && ! $this->isBreakingScopeNode($previousNode)) { - $isUnreachable = $previousNode->getAttribute(AttributeKey::IS_UNREACHABLE); - if ($isUnreachable === true) { - return true; + $previousNode = $stmt->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT); + while ($previousNode instanceof \PhpParser\Node\Stmt && !$this->isBreakingScopeNode($previousNode)) { + $isUnreachable = $previousNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_UNREACHABLE); + if ($isUnreachable === \true) { + return \true; } - - $previousNode = $previousNode->getAttribute(AttributeKey::PREVIOUS_STATEMENT); + $previousNode = $previousNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT); } - - return false; + return \false; } - /** * Keep content after markTestSkipped(), intentional temporary */ - private function isAfterMarkTestSkippedMethodCall(Stmt $stmt): bool + private function isAfterMarkTestSkippedMethodCall(\PhpParser\Node\Stmt $stmt) : bool { - return (bool) $this->betterNodeFinder->findFirstPrevious($stmt, function (Node $node): bool { - if (! $node instanceof MethodCall) { - return false; + return (bool) $this->betterNodeFinder->findFirstPrevious($stmt, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - - if ($node->name instanceof MethodCall) { - return false; + if ($node->name instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - - if ($node->name instanceof StaticCall) { - return false; + if ($node->name instanceof \PhpParser\Node\Expr\StaticCall) { + return \false; } - return $this->isName($node->name, 'markTestSkipped'); }); } - /** * Check nodes that breaks scope while traversing up */ - private function isBreakingScopeNode(Stmt $stmt): bool + private function isBreakingScopeNode(\PhpParser\Node\Stmt $stmt) : bool { - if ($stmt instanceof ClassLike) { - return true; + if ($stmt instanceof \PhpParser\Node\Stmt\ClassLike) { + return \true; } - - if ($stmt instanceof ClassMethod) { - return true; + if ($stmt instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \true; } - - if ($stmt instanceof Function_) { - return true; + if ($stmt instanceof \PhpParser\Node\Stmt\Function_) { + return \true; } - - if ($stmt instanceof Namespace_) { - return true; + if ($stmt instanceof \PhpParser\Node\Stmt\Namespace_) { + return \true; } - - return $stmt instanceof Else_; + return $stmt instanceof \PhpParser\Node\Stmt\Else_; } } diff --git a/rules/DeadCode/Rector/Switch_/RemoveDuplicatedCaseInSwitchRector.php b/rules/DeadCode/Rector/Switch_/RemoveDuplicatedCaseInSwitchRector.php index 4bba06ab13e..dfef72b3330 100644 --- a/rules/DeadCode/Rector/Switch_/RemoveDuplicatedCaseInSwitchRector.php +++ b/rules/DeadCode/Rector/Switch_/RemoveDuplicatedCaseInSwitchRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Switch_::class]; + return [\PhpParser\Node\Stmt\Switch_::class]; } - /** * @param Switch_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (count($node->cases) < 2) { + if (\count($node->cases) < 2) { return null; } - /** @var Case_|null $previousCase */ $previousCase = null; foreach ($node->cases as $case) { if ($previousCase && $this->areSwitchStmtsEqualsAndWithBreak($case, $previousCase)) { $previousCase->stmts = []; } - $previousCase = $case; } - return $node; } - - private function areSwitchStmtsEqualsAndWithBreak(Case_ $currentCase, Case_ $previousCase): bool + private function areSwitchStmtsEqualsAndWithBreak(\PhpParser\Node\Stmt\Case_ $currentCase, \PhpParser\Node\Stmt\Case_ $previousCase) : bool { - if (! $this->nodeComparator->areNodesEqual($currentCase->stmts, $previousCase->stmts)) { - return false; + if (!$this->nodeComparator->areNodesEqual($currentCase->stmts, $previousCase->stmts)) { + return \false; } - foreach ($currentCase->stmts as $stmt) { - if ($stmt instanceof Break_) { - return true; + if ($stmt instanceof \PhpParser\Node\Stmt\Break_) { + return \true; } - - if ($stmt instanceof Return_) { - return true; + if ($stmt instanceof \PhpParser\Node\Stmt\Return_) { + return \true; } } - - return false; + return \false; } } diff --git a/rules/DeadCode/Rector/Ternary/TernaryToBooleanOrFalseToBooleanAndRector.php b/rules/DeadCode/Rector/Ternary/TernaryToBooleanOrFalseToBooleanAndRector.php index 7463bce9243..6c636f0d929 100644 --- a/rules/DeadCode/Rector/Ternary/TernaryToBooleanOrFalseToBooleanAndRector.php +++ b/rules/DeadCode/Rector/Ternary/TernaryToBooleanOrFalseToBooleanAndRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->if === null) { return null; } - - if (! $this->valueResolver->isFalse($node->else)) { + if (!$this->valueResolver->isFalse($node->else)) { return null; } - if ($this->valueResolver->isTrue($node->if)) { return null; } - $ifType = $this->getStaticType($node->if); - if (! $ifType instanceof BooleanType) { + if (!$ifType instanceof \PHPStan\Type\BooleanType) { return null; } - - return new BooleanAnd($node->cond, $node->if); + return new \PhpParser\Node\Expr\BinaryOp\BooleanAnd($node->cond, $node->if); } } diff --git a/rules/DeadCode/Rector/TryCatch/RemoveDeadTryCatchRector.php b/rules/DeadCode/Rector/TryCatch/RemoveDeadTryCatchRector.php index 2ef56891699..2c47a22f466 100644 --- a/rules/DeadCode/Rector/TryCatch/RemoveDeadTryCatchRector.php +++ b/rules/DeadCode/Rector/TryCatch/RemoveDeadTryCatchRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [TryCatch::class]; + return [\PhpParser\Node\Stmt\TryCatch::class]; } - /** * @param TryCatch $node * @return Stmt[]|null */ - public function refactor(Node $node) + public function refactor(\PhpParser\Node $node) { - if (count($node->catches) !== 1) { + if (\count($node->catches) !== 1) { return null; } - /** @var Catch_ $onlyCatch */ $onlyCatch = $node->catches[0]; - if (count($onlyCatch->stmts) !== 1) { + if (\count($onlyCatch->stmts) !== 1) { return null; } - if ($node->finally !== null && $node->finally->stmts !== []) { return null; } - $onlyCatchStmt = $onlyCatch->stmts[0]; - if (! $onlyCatchStmt instanceof Throw_) { + if (!$onlyCatchStmt instanceof \PhpParser\Node\Stmt\Throw_) { return null; } - - if (! $this->nodeComparator->areNodesEqual($onlyCatch->var, $onlyCatchStmt->expr)) { + if (!$this->nodeComparator->areNodesEqual($onlyCatch->var, $onlyCatchStmt->expr)) { return null; } - return $node->stmts; } } diff --git a/rules/DeadCode/SideEffect/PureFunctionDetector.php b/rules/DeadCode/SideEffect/PureFunctionDetector.php index 0b7de4da76a..3294dd3233f 100644 --- a/rules/DeadCode/SideEffect/PureFunctionDetector.php +++ b/rules/DeadCode/SideEffect/PureFunctionDetector.php @@ -1,12 +1,10 @@ nodeNameResolver = $nodeNameResolver; } - - public function detect(FuncCall $funcCall): bool + public function detect(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - return ! $this->nodeNameResolver->isNames($funcCall, self::IMPURE_FUNCTIONS); + return !$this->nodeNameResolver->isNames($funcCall, self::IMPURE_FUNCTIONS); } } diff --git a/rules/DeadCode/SideEffect/SideEffectNodeDetector.php b/rules/DeadCode/SideEffect/SideEffectNodeDetector.php index b36f413234f..10492322d69 100644 --- a/rules/DeadCode/SideEffect/SideEffectNodeDetector.php +++ b/rules/DeadCode/SideEffect/SideEffectNodeDetector.php @@ -1,7 +1,6 @@ > */ - private const SIDE_EFFECT_NODE_TYPES = [Encapsed::class, New_::class, Concat::class, PropertyFetch::class]; - + private const SIDE_EFFECT_NODE_TYPES = [\PhpParser\Node\Scalar\Encapsed::class, \PhpParser\Node\Expr\New_::class, \PhpParser\Node\Expr\BinaryOp\Concat::class, \PhpParser\Node\Expr\PropertyFetch::class]; /** * @var PureFunctionDetector */ private $pureFunctionDetector; - /** * @var NodeTypeResolver */ private $nodeTypeResolver; - - public function __construct(NodeTypeResolver $nodeTypeResolver, PureFunctionDetector $pureFunctionDetector) + public function __construct(\Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver, \Rector\DeadCode\SideEffect\PureFunctionDetector $pureFunctionDetector) { $this->pureFunctionDetector = $pureFunctionDetector; $this->nodeTypeResolver = $nodeTypeResolver; } - - public function detect(Expr $expr): bool + public function detect(\PhpParser\Node\Expr $expr) : bool { - if ($expr instanceof Assign) { - return true; + if ($expr instanceof \PhpParser\Node\Expr\Assign) { + return \true; } - $exprStaticType = $this->nodeTypeResolver->resolve($expr); - if ($exprStaticType instanceof ConstantType) { - return false; + if ($exprStaticType instanceof \PHPStan\Type\ConstantType) { + return \false; } - foreach (self::SIDE_EFFECT_NODE_TYPES as $sideEffectNodeType) { - if (is_a($expr, $sideEffectNodeType, true)) { - return false; + if (\is_a($expr, $sideEffectNodeType, \true)) { + return \false; } } - - if ($expr instanceof FuncCall) { - return ! $this->pureFunctionDetector->detect($expr); + if ($expr instanceof \PhpParser\Node\Expr\FuncCall) { + return !$this->pureFunctionDetector->detect($expr); } - - if ($expr instanceof Variable || $expr instanceof ArrayDimFetch) { + if ($expr instanceof \PhpParser\Node\Expr\Variable || $expr instanceof \PhpParser\Node\Expr\ArrayDimFetch) { $variable = $this->resolveVariable($expr); // variables don't have side effects - return ! $variable instanceof Variable; + return !$variable instanceof \PhpParser\Node\Expr\Variable; } - - return true; + return \true; } - - private function resolveVariable(Expr $expr): ?Variable + private function resolveVariable(\PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr\Variable { - while ($expr instanceof ArrayDimFetch) { + while ($expr instanceof \PhpParser\Node\Expr\ArrayDimFetch) { $expr = $expr->var; } - - if (! $expr instanceof Variable) { + if (!$expr instanceof \PhpParser\Node\Expr\Variable) { return null; } - return $expr; } } diff --git a/rules/DeadCode/UselessIfCondBeforeForeachDetector.php b/rules/DeadCode/UselessIfCondBeforeForeachDetector.php index 218f9a3a1b0..4bf4ece07a8 100644 --- a/rules/DeadCode/UselessIfCondBeforeForeachDetector.php +++ b/rules/DeadCode/UselessIfCondBeforeForeachDetector.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->nodeComparator = $nodeComparator; } - /** * Matches: * !empty($values) */ - public function isMatchingNotEmpty(If_ $if, Expr $foreachExpr): bool + public function isMatchingNotEmpty(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node\Expr $foreachExpr) : bool { $cond = $if->cond; - if (! $cond instanceof BooleanNot) { - return false; + if (!$cond instanceof \PhpParser\Node\Expr\BooleanNot) { + return \false; } - - if (! $cond->expr instanceof Empty_) { - return false; + if (!$cond->expr instanceof \PhpParser\Node\Expr\Empty_) { + return \false; } - /** @var Empty_ $empty */ $empty = $cond->expr; - - if (! $this->nodeComparator->areNodesEqual($empty->expr, $foreachExpr)) { - return false; + if (!$this->nodeComparator->areNodesEqual($empty->expr, $foreachExpr)) { + return \false; } - // is array though? $arrayType = $this->nodeTypeResolver->resolve($empty->expr); - - return ! $arrayType instanceof MixedType; + return !$arrayType instanceof \PHPStan\Type\MixedType; } - /** * Matches: * $values !== [] @@ -69,45 +58,37 @@ final class UselessIfCondBeforeForeachDetector * [] !== $values * [] != $values */ - public function isMatchingNotIdenticalEmptyArray(If_ $if, Expr $foreachExpr): bool + public function isMatchingNotIdenticalEmptyArray(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node\Expr $foreachExpr) : bool { - if (! $if->cond instanceof NotIdentical && ! $if->cond instanceof NotEqual) { - return false; + if (!$if->cond instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical && !$if->cond instanceof \PhpParser\Node\Expr\BinaryOp\NotEqual) { + return \false; } - /** @var NotIdentical|NotEqual $notIdentical */ $notIdentical = $if->cond; - return $this->isMatchingNotBinaryOp($notIdentical, $foreachExpr); } - /** * @param NotIdentical|NotEqual $binaryOp */ - private function isMatchingNotBinaryOp(BinaryOp $binaryOp, Expr $foreachExpr): bool + private function isMatchingNotBinaryOp(\PhpParser\Node\Expr\BinaryOp $binaryOp, \PhpParser\Node\Expr $foreachExpr) : bool { if ($this->isEmptyArrayAndForeachedVariable($binaryOp->left, $binaryOp->right, $foreachExpr)) { - return true; + return \true; } - return $this->isEmptyArrayAndForeachedVariable($binaryOp->right, $binaryOp->left, $foreachExpr); } - - private function isEmptyArrayAndForeachedVariable(Expr $leftExpr, Expr $rightExpr, Expr $foreachExpr): bool + private function isEmptyArrayAndForeachedVariable(\PhpParser\Node\Expr $leftExpr, \PhpParser\Node\Expr $rightExpr, \PhpParser\Node\Expr $foreachExpr) : bool { - if (! $this->isEmptyArray($leftExpr)) { - return false; + if (!$this->isEmptyArray($leftExpr)) { + return \false; } - return $this->nodeComparator->areNodesEqual($foreachExpr, $rightExpr); } - - private function isEmptyArray(Expr $expr): bool + private function isEmptyArray(\PhpParser\Node\Expr $expr) : bool { - if (! $expr instanceof Array_) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\Array_) { + return \false; } - return $expr->items === []; } } diff --git a/rules/DeadCode/ValueObject/BinaryToVersionCompareCondition.php b/rules/DeadCode/ValueObject/BinaryToVersionCompareCondition.php index 0672abac6a0..99c0cf0bb62 100644 --- a/rules/DeadCode/ValueObject/BinaryToVersionCompareCondition.php +++ b/rules/DeadCode/ValueObject/BinaryToVersionCompareCondition.php @@ -1,51 +1,40 @@ versionCompareCondition = $versionCompareCondition; $this->binaryClass = $binaryClass; $this->expectedValue = $expectedValue; } - - public function getVersionCompareCondition(): VersionCompareCondition + public function getVersionCompareCondition() : \Rector\DeadCode\ValueObject\VersionCompareCondition { return $this->versionCompareCondition; } - - public function getBinaryClass(): string + public function getBinaryClass() : string { return $this->binaryClass; } - /** * @return mixed */ diff --git a/rules/DeadCode/ValueObject/VariableNodeUse.php b/rules/DeadCode/ValueObject/VariableNodeUse.php index cf6ab95fe2f..90f6ba4b02c 100644 --- a/rules/DeadCode/ValueObject/VariableNodeUse.php +++ b/rules/DeadCode/ValueObject/VariableNodeUse.php @@ -1,96 +1,75 @@ startTokenPosition = $startTokenPosition; $this->variableName = $variableName; $this->type = $type; $this->variable = $variable; $this->nestingHash = $nestingHash; } - - public function isName(string $name): bool + public function isName(string $name) : bool { return $this->variableName === $name; } - - public function getStartTokenPosition(): int + public function getStartTokenPosition() : int { return $this->startTokenPosition; } - - public function isType(string $type): bool + public function isType(string $type) : bool { return $this->type === $type; } - - public function getVariableNode(): Variable + public function getVariableNode() : \PhpParser\Node\Expr\Variable { return $this->variable; } - - public function getParentNode(): Node + public function getParentNode() : \PhpParser\Node { - $parentNode = $this->variable->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Node) { - throw new ShouldNotHappenException(); + $parentNode = $this->variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - return $parentNode; } - - public function getNestingHash(): ?string + public function getNestingHash() : ?string { return $this->nestingHash; } diff --git a/rules/DeadCode/ValueObject/VersionCompareCondition.php b/rules/DeadCode/ValueObject/VersionCompareCondition.php index a97a260d7d5..7015625e762 100644 --- a/rules/DeadCode/ValueObject/VersionCompareCondition.php +++ b/rules/DeadCode/ValueObject/VersionCompareCondition.php @@ -1,46 +1,38 @@ firstVersion = $firstVersion; $this->secondVersion = $secondVersion; $this->compareSign = $compareSign; } - - public function getFirstVersion(): int + public function getFirstVersion() : int { return $this->firstVersion; } - - public function getSecondVersion(): int + public function getSecondVersion() : int { return $this->secondVersion; } - - public function getCompareSign(): ?string + public function getCompareSign() : ?string { return $this->compareSign; } diff --git a/rules/Defluent/ConflictGuard/ParentClassMethodTypeOverrideGuard.php b/rules/Defluent/ConflictGuard/ParentClassMethodTypeOverrideGuard.php index 60719e56efa..41ae35f2b83 100644 --- a/rules/Defluent/ConflictGuard/ParentClassMethodTypeOverrideGuard.php +++ b/rules/Defluent/ConflictGuard/ParentClassMethodTypeOverrideGuard.php @@ -1,7 +1,6 @@ nodeRepository = $nodeRepository; $this->nodeNameResolver = $nodeNameResolver; } - - public function hasParentMethodOutsideVendor(ClassMethod $classMethod): bool + public function hasParentMethodOutsideVendor(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - $methodName = $classMethod->name->toString(); - foreach ($classReflection->getAncestors() as $ancestorClassReflection) { if ($classReflection === $ancestorClassReflection) { continue; } - - if (! $ancestorClassReflection->hasMethod($methodName)) { + if (!$ancestorClassReflection->hasMethod($methodName)) { continue; } - $parentClassMethodReflection = $ancestorClassReflection->getMethod($methodName, $scope); - $parentClassMethod = $this->nodeRepository->findClassMethodByMethodReflection( - $parentClassMethodReflection - ); - - if (! $parentClassMethod instanceof ClassMethod) { - return true; + $parentClassMethod = $this->nodeRepository->findClassMethodByMethodReflection($parentClassMethodReflection); + if (!$parentClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \true; } } - - return false; + return \false; } - - public function isReturnTypeChangeAllowed(ClassMethod $classMethod): bool + public function isReturnTypeChangeAllowed(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { // make sure return type is not protected by parent contract $parentClassMethodReflection = $this->getParentClassMethod($classMethod); - // nothign to check - if (! $parentClassMethodReflection instanceof MethodReflection) { - return true; + if (!$parentClassMethodReflection instanceof \PHPStan\Reflection\MethodReflection) { + return \true; } - - $parentClassMethod = $this->nodeRepository->findClassMethodByMethodReflection( - $parentClassMethodReflection - ); - + $parentClassMethod = $this->nodeRepository->findClassMethodByMethodReflection($parentClassMethodReflection); // if null, we're unable to override → skip it - if (! $parentClassMethod instanceof ClassMethod) { - return true; + if (!$parentClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \true; } - return $parentClassMethod->returnType === null; } - - private function getParentClassMethod(ClassMethod $classMethod): ?MethodReflection + private function getParentClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PHPStan\Reflection\MethodReflection { - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - /** @var string $methodName */ $methodName = $this->nodeNameResolver->getName($classMethod); - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - foreach ($classReflection->getAncestors() as $parentClassReflection) { if ($classReflection === $parentClassReflection) { continue; } - - if (! $parentClassReflection->hasMethod($methodName)) { + if (!$parentClassReflection->hasMethod($methodName)) { continue; } - return $parentClassReflection->getNativeMethod($methodName); } - return null; } } diff --git a/rules/Defluent/Contract/ValueObject/FirstCallFactoryAwareInterface.php b/rules/Defluent/Contract/ValueObject/FirstCallFactoryAwareInterface.php index 428451dfdbd..71b3541fe50 100644 --- a/rules/Defluent/Contract/ValueObject/FirstCallFactoryAwareInterface.php +++ b/rules/Defluent/Contract/ValueObject/FirstCallFactoryAwareInterface.php @@ -1,10 +1,9 @@ fluentChainMethodCallNodeAnalyzer = $fluentChainMethodCallNodeAnalyzer; $this->fluentChainMethodCallRootExtractor = $fluentChainMethodCallRootExtractor; $this->nonFluentChainMethodCallFactory = $nonFluentChainMethodCallFactory; $this->sameClassMethodCallAnalyzer = $sameClassMethodCallAnalyzer; $this->fluentMethodCallSkipper = $fluentMethodCallSkipper; } - - public function match(MethodCall $methodCall, string $kind): ?AssignAndRootExprAndNodesToAdd + public function match(\PhpParser\Node\Expr\MethodCall $methodCall, string $kind) : ?\Rector\Defluent\ValueObject\AssignAndRootExprAndNodesToAdd { $chainMethodCalls = $this->fluentChainMethodCallNodeAnalyzer->collectAllMethodCallsInChain($methodCall); - if (! $this->sameClassMethodCallAnalyzer->haveSingleClass($chainMethodCalls)) { + if (!$this->sameClassMethodCallAnalyzer->haveSingleClass($chainMethodCalls)) { return null; } - - $assignAndRootExpr = $this->fluentChainMethodCallRootExtractor->extractFromMethodCalls( - $chainMethodCalls, - $kind - ); - - if (! $assignAndRootExpr instanceof AssignAndRootExpr) { + $assignAndRootExpr = $this->fluentChainMethodCallRootExtractor->extractFromMethodCalls($chainMethodCalls, $kind); + if (!$assignAndRootExpr instanceof \Rector\Defluent\ValueObject\AssignAndRootExpr) { return null; } - if ($this->fluentMethodCallSkipper->shouldSkipMethodCalls($assignAndRootExpr, $chainMethodCalls)) { return null; } - - $nodesToAdd = $this->nonFluentChainMethodCallFactory->createFromAssignObjectAndMethodCalls( - $assignAndRootExpr, - $chainMethodCalls, - $kind - ); - - return new AssignAndRootExprAndNodesToAdd($assignAndRootExpr, $nodesToAdd); + $nodesToAdd = $this->nonFluentChainMethodCallFactory->createFromAssignObjectAndMethodCalls($assignAndRootExpr, $chainMethodCalls, $kind); + return new \Rector\Defluent\ValueObject\AssignAndRootExprAndNodesToAdd($assignAndRootExpr, $nodesToAdd); } } diff --git a/rules/Defluent/NodeAnalyzer/ExprStringTypeResolver.php b/rules/Defluent/NodeAnalyzer/ExprStringTypeResolver.php index ae919b79186..fdb67f2dca4 100644 --- a/rules/Defluent/NodeAnalyzer/ExprStringTypeResolver.php +++ b/rules/Defluent/NodeAnalyzer/ExprStringTypeResolver.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->typeUnwrapper = $typeUnwrapper; } - - public function resolve(Expr $expr): ?string + public function resolve(\PhpParser\Node\Expr $expr) : ?string { $exprStaticType = $this->nodeTypeResolver->getStaticType($expr); $exprStaticType = $this->typeUnwrapper->unwrapNullableType($exprStaticType); - - if (! $exprStaticType instanceof TypeWithClassName) { + if (!$exprStaticType instanceof \PHPStan\Type\TypeWithClassName) { // nothing we can do, unless return null; } - - if ($exprStaticType instanceof AliasedObjectType) { + if ($exprStaticType instanceof \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType) { return $exprStaticType->getFullyQualifiedClass(); } - return $exprStaticType->getClassName(); } } diff --git a/rules/Defluent/NodeAnalyzer/FluentCallStaticTypeResolver.php b/rules/Defluent/NodeAnalyzer/FluentCallStaticTypeResolver.php index e06e1b6562b..731d2dfbfd5 100644 --- a/rules/Defluent/NodeAnalyzer/FluentCallStaticTypeResolver.php +++ b/rules/Defluent/NodeAnalyzer/FluentCallStaticTypeResolver.php @@ -1,49 +1,42 @@ exprStringTypeResolver = $exprStringTypeResolver; $this->reflectionProvider = $reflectionProvider; } - /** * @param MethodCall[] $chainMethodCalls * @return string[] */ - public function resolveCalleeUniqueTypes(array $chainMethodCalls): array + public function resolveCalleeUniqueTypes(array $chainMethodCalls) : array { $callerClassTypes = []; - - $lastMethodCallKey = array_key_last($chainMethodCalls); + \end($chainMethodCalls); + $lastMethodCallKey = \key($chainMethodCalls); $lastMethodCall = $chainMethodCalls[$lastMethodCallKey]; - $rootType = $this->exprStringTypeResolver->resolve($lastMethodCall->var); if ($rootType !== null) { $callerClassTypes[] = $rootType; } - + \reset($chainMethodCalls); // chain method calls are inversed - $lastChainMethodCallKey = array_key_first($chainMethodCalls); - + $lastChainMethodCallKey = \key($chainMethodCalls); foreach ($chainMethodCalls as $key => $chainMethodCall) { $chainMethodCallType = $this->exprStringTypeResolver->resolve($chainMethodCall); if ($chainMethodCallType === null) { @@ -51,37 +44,30 @@ final class FluentCallStaticTypeResolver if ($lastChainMethodCallKey === $key) { continue; } - return []; } - $callerClassTypes[] = $chainMethodCallType; } - - $uniqueCallerClassTypes = array_unique($callerClassTypes); + $uniqueCallerClassTypes = \array_unique($callerClassTypes); return $this->filterOutAlreadyPresentParentClasses($uniqueCallerClassTypes); } - /** * If a child class is with the parent class in the list, count them as 1 * * @param class-string[] $types * @return class-string[] */ - private function filterOutAlreadyPresentParentClasses(array $types): array + private function filterOutAlreadyPresentParentClasses(array $types) : array { $secondTypes = $types; - foreach ($types as $key => $type) { foreach ($secondTypes as $secondType) { if ($type === $secondType) { continue; } - - if (! $this->reflectionProvider->hasClass($type)) { + if (!$this->reflectionProvider->hasClass($type)) { continue; } - $firstClassReflection = $this->reflectionProvider->getClass($type); if ($firstClassReflection->isSubclassOf($secondType)) { unset($types[$key]); @@ -89,7 +75,6 @@ final class FluentCallStaticTypeResolver } } } - - return array_values($types); + return \array_values($types); } } diff --git a/rules/Defluent/NodeAnalyzer/FluentChainMethodCallNodeAnalyzer.php b/rules/Defluent/NodeAnalyzer/FluentChainMethodCallNodeAnalyzer.php index 6bdf0665a46..97c39e4b749 100644 --- a/rules/Defluent/NodeAnalyzer/FluentChainMethodCallNodeAnalyzer.php +++ b/rules/Defluent/NodeAnalyzer/FluentChainMethodCallNodeAnalyzer.php @@ -1,7 +1,6 @@ methodCall()->chainedMethodCall()" @@ -33,40 +31,30 @@ final class FluentChainMethodCallNodeAnalyzer * * @var class-string[] */ - private const KNOWN_FACTORY_FLUENT_TYPES = ['PHPStan\Analyser\MutatingScope']; - + private const KNOWN_FACTORY_FLUENT_TYPES = ['PHPStan\\Analyser\\MutatingScope']; /** * @var NodeTypeResolver */ private $nodeTypeResolver; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var NodeFinder */ private $nodeFinder; - /** * @var MethodCallToClassMethodParser */ private $methodCallToClassMethodParser; - - public function __construct( - NodeNameResolver $nodeNameResolver, - NodeTypeResolver $nodeTypeResolver, - NodeFinder $nodeFinder, - MethodCallToClassMethodParser $methodCallToClassMethodParser - ) { + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver, \PhpParser\NodeFinder $nodeFinder, \Rector\Defluent\Reflection\MethodCallToClassMethodParser $methodCallToClassMethodParser) + { $this->nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; $this->nodeFinder = $nodeFinder; $this->methodCallToClassMethodParser = $methodCallToClassMethodParser; } - /** * Checks that in: * $this->someCall(); @@ -77,195 +65,155 @@ final class FluentChainMethodCallNodeAnalyzer * return $this; * } */ - public function isFluentClassMethodOfMethodCall(MethodCall $methodCall): bool + public function isFluentClassMethodOfMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { if ($this->isCall($methodCall->var)) { - return false; + return \false; } - $calleeStaticType = $this->nodeTypeResolver->getStaticType($methodCall->var); - // we're not sure - if ($calleeStaticType instanceof MixedType) { - return false; + if ($calleeStaticType instanceof \PHPStan\Type\MixedType) { + return \false; } - $methodReturnStaticType = $this->nodeTypeResolver->getStaticType($methodCall); - // is fluent type - if (! $calleeStaticType->equals($methodReturnStaticType)) { - return false; + if (!$calleeStaticType->equals($methodReturnStaticType)) { + return \false; } - - if ($calleeStaticType instanceof ObjectType) { + if ($calleeStaticType instanceof \PHPStan\Type\ObjectType) { foreach (self::KNOWN_FACTORY_FLUENT_TYPES as $knownFactoryFluentType) { if ($calleeStaticType->isInstanceOf($knownFactoryFluentType)->yes()) { - return false; + return \false; } } } - - return ! $this->isMethodCallCreatingNewInstance($methodCall); + return !$this->isMethodCallCreatingNewInstance($methodCall); } - - public function isLastChainMethodCall(MethodCall $methodCall): bool + public function isLastChainMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { // is chain method call - if (! $methodCall->var instanceof MethodCall && ! $methodCall->var instanceof New_) { - return false; + if (!$methodCall->var instanceof \PhpParser\Node\Expr\MethodCall && !$methodCall->var instanceof \PhpParser\Node\Expr\New_) { + return \false; } - - $nextNode = $methodCall->getAttribute(AttributeKey::NEXT_NODE); - + $nextNode = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); // is last chain call - return ! $nextNode instanceof Node; + return !$nextNode instanceof \PhpParser\Node; } - /** * @return string[]|null[] */ - public function collectMethodCallNamesInChain(MethodCall $desiredMethodCall): array + public function collectMethodCallNamesInChain(\PhpParser\Node\Expr\MethodCall $desiredMethodCall) : array { $methodCalls = $this->collectAllMethodCallsInChain($desiredMethodCall); - $methodNames = []; foreach ($methodCalls as $methodCall) { $methodNames[] = $this->nodeNameResolver->getName($methodCall->name); } - return $methodNames; } - /** * @return MethodCall[] */ - public function collectAllMethodCallsInChain(MethodCall $methodCall): array + public function collectAllMethodCallsInChain(\PhpParser\Node\Expr\MethodCall $methodCall) : array { $chainMethodCalls = [$methodCall]; - // traverse up $currentNode = $methodCall->var; - while ($currentNode instanceof MethodCall) { + while ($currentNode instanceof \PhpParser\Node\Expr\MethodCall) { $chainMethodCalls[] = $currentNode; $currentNode = $currentNode->var; } - // traverse down - if (count($chainMethodCalls) === 1) { - $currentNode = $methodCall->getAttribute(AttributeKey::PARENT_NODE); - while ($currentNode instanceof MethodCall) { + if (\count($chainMethodCalls) === 1) { + $currentNode = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + while ($currentNode instanceof \PhpParser\Node\Expr\MethodCall) { $chainMethodCalls[] = $currentNode; - $currentNode = $currentNode->getAttribute(AttributeKey::PARENT_NODE); + $currentNode = $currentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); } } - return $chainMethodCalls; } - /** * @return MethodCall[] */ - public function collectAllMethodCallsInChainWithoutRootOne(MethodCall $methodCall): array + public function collectAllMethodCallsInChainWithoutRootOne(\PhpParser\Node\Expr\MethodCall $methodCall) : array { $chainMethodCalls = $this->collectAllMethodCallsInChain($methodCall); - foreach ($chainMethodCalls as $key => $chainMethodCall) { - if (! $chainMethodCall->var instanceof MethodCall && ! $chainMethodCall->var instanceof New_) { + if (!$chainMethodCall->var instanceof \PhpParser\Node\Expr\MethodCall && !$chainMethodCall->var instanceof \PhpParser\Node\Expr\New_) { unset($chainMethodCalls[$key]); break; } } - - return array_values($chainMethodCalls); + return \array_values($chainMethodCalls); } - /** * Checks "$this->someMethod()->anotherMethod()" * * @param string[] $methods */ - public function isTypeAndChainCalls(Node $node, Type $type, array $methods): bool + public function isTypeAndChainCalls(\PhpParser\Node $node, \PHPStan\Type\Type $type, array $methods) : bool { - if (! $node instanceof MethodCall) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - // node chaining is in reverse order than code - $methods = array_reverse($methods); - + $methods = \array_reverse($methods); foreach ($methods as $method) { - if (! $this->nodeNameResolver->isName($node->name, $method)) { - return false; + if (!$this->nodeNameResolver->isName($node->name, $method)) { + return \false; } - $node = $node->var; } - $variableType = $this->nodeTypeResolver->resolve($node); - if ($variableType instanceof MixedType) { - return false; + if ($variableType instanceof \PHPStan\Type\MixedType) { + return \false; } - - return $variableType->isSuperTypeOf($type) - ->yes(); + return $variableType->isSuperTypeOf($type)->yes(); } - - public function resolveRootExpr(MethodCall $methodCall): Node + public function resolveRootExpr(\PhpParser\Node\Expr\MethodCall $methodCall) : \PhpParser\Node { $callerNode = $methodCall->var; - - while ($callerNode instanceof MethodCall || $callerNode instanceof StaticCall) { - $callerNode = $callerNode instanceof StaticCall ? $callerNode->class : $callerNode->var; + while ($callerNode instanceof \PhpParser\Node\Expr\MethodCall || $callerNode instanceof \PhpParser\Node\Expr\StaticCall) { + $callerNode = $callerNode instanceof \PhpParser\Node\Expr\StaticCall ? $callerNode->class : $callerNode->var; } - return $callerNode; } - - public function resolveRootMethodCall(MethodCall $methodCall): ?MethodCall + public function resolveRootMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node\Expr\MethodCall { $callerNode = $methodCall->var; - - while ($callerNode instanceof MethodCall && $callerNode->var instanceof MethodCall) { + while ($callerNode instanceof \PhpParser\Node\Expr\MethodCall && $callerNode->var instanceof \PhpParser\Node\Expr\MethodCall) { $callerNode = $callerNode->var; } - - if ($callerNode instanceof MethodCall) { + if ($callerNode instanceof \PhpParser\Node\Expr\MethodCall) { return $callerNode; } - return null; } - - private function isCall(Expr $expr): bool + private function isCall(\PhpParser\Node\Expr $expr) : bool { - if ($expr instanceof MethodCall) { - return true; + if ($expr instanceof \PhpParser\Node\Expr\MethodCall) { + return \true; } - - return $expr instanceof StaticCall; + return $expr instanceof \PhpParser\Node\Expr\StaticCall; } - - private function isMethodCallCreatingNewInstance(MethodCall $methodCall): bool + private function isMethodCallCreatingNewInstance(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { $classMethod = $this->methodCallToClassMethodParser->parseMethodCall($methodCall); - if (! $classMethod instanceof ClassMethod) { - return false; + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - /** @var Return_[] $returns */ - $returns = $this->nodeFinder->findInstanceOf($classMethod, Return_::class); - + $returns = $this->nodeFinder->findInstanceOf($classMethod, \PhpParser\Node\Stmt\Return_::class); foreach ($returns as $return) { - if (! $return->expr instanceof New_) { + if (!$return->expr instanceof \PhpParser\Node\Expr\New_) { continue; } - $new = $return->expr; if ($this->nodeNameResolver->isName($new->class, 'self')) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/Defluent/NodeAnalyzer/FluentChainMethodCallRootExtractor.php b/rules/Defluent/NodeAnalyzer/FluentChainMethodCallRootExtractor.php index 784f8a156a2..8e114b4160c 100644 --- a/rules/Defluent/NodeAnalyzer/FluentChainMethodCallRootExtractor.php +++ b/rules/Defluent/NodeAnalyzer/FluentChainMethodCallRootExtractor.php @@ -1,7 +1,6 @@ propertyNaming = $propertyNaming; $this->betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; @@ -73,123 +59,97 @@ final class FluentChainMethodCallRootExtractor $this->exprStringTypeResolver = $exprStringTypeResolver; $this->nodeTypeResolver = $nodeTypeResolver; } - /** * @param MethodCall[] $methodCalls */ - public function extractFromMethodCalls(array $methodCalls, string $kind): ?AssignAndRootExpr + public function extractFromMethodCalls(array $methodCalls, string $kind) : ?\Rector\Defluent\ValueObject\AssignAndRootExpr { // we need at least 2 method call for fluent - if (count($methodCalls) < 2) { + if (\count($methodCalls) < 2) { return null; } - foreach ($methodCalls as $methodCall) { - if ($methodCall->var instanceof Variable || $methodCall->var instanceof PropertyFetch) { + if ($methodCall->var instanceof \PhpParser\Node\Expr\Variable || $methodCall->var instanceof \PhpParser\Node\Expr\PropertyFetch) { return $this->createAssignAndRootExprForVariableOrPropertyFetch($methodCall); } - - if ($methodCall->var instanceof New_) { + if ($methodCall->var instanceof \PhpParser\Node\Expr\New_) { // direct = no parent - if ($kind === FluentCallsKind::IN_ARGS) { + if ($kind === \Rector\Defluent\ValueObject\FluentCallsKind::IN_ARGS) { return $this->resolveKindInArgs($methodCall); } - return $this->matchMethodCallOnNew($methodCall->var); } } - return null; } - /** * beware: fluent vs. factory * A. FLUENT: $cook->bake()->serve() // only "Cook" * B. FACTORY: $food = $cook->bake()->warmUp(); // only "Food" */ - public function resolveIsFirstMethodCallFactory(MethodCall $methodCall): bool + public function resolveIsFirstMethodCallFactory(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { $variableStaticType = $this->exprStringTypeResolver->resolve($methodCall->var); $calledMethodStaticType = $this->exprStringTypeResolver->resolve($methodCall); - // get next method call - $nextMethodCall = $methodCall->getAttribute(AttributeKey::PARENT_NODE); - if (! $nextMethodCall instanceof MethodCall) { - return false; + $nextMethodCall = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$nextMethodCall instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - $nestedCallStaticType = $this->exprStringTypeResolver->resolve($nextMethodCall); if ($nestedCallStaticType === null) { - return false; + return \false; } - if ($nestedCallStaticType !== $calledMethodStaticType) { - return false; + return \false; } - return $variableStaticType !== $calledMethodStaticType; } - - private function createAssignAndRootExprForVariableOrPropertyFetch(MethodCall $methodCall): AssignAndRootExpr + private function createAssignAndRootExprForVariableOrPropertyFetch(\PhpParser\Node\Expr\MethodCall $methodCall) : \Rector\Defluent\ValueObject\AssignAndRootExpr { $isFirstCallFactory = $this->resolveIsFirstMethodCallFactory($methodCall); - // the method call, does not belong to the $staticType = $this->nodeTypeResolver->getStaticType($methodCall); - $parentNode = $methodCall->getAttribute(AttributeKey::PARENT_NODE); - + $parentNode = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // no assign - if ($parentNode instanceof Expression) { + if ($parentNode instanceof \PhpParser\Node\Stmt\Expression) { $variableName = $this->propertyNaming->fqnToVariableName($staticType); - // the assign expresison must be break // pesuero code bsaed on type - $variable = new Variable($variableName); - return new AssignAndRootExpr($methodCall->var, $methodCall->var, $variable, $isFirstCallFactory); + $variable = new \PhpParser\Node\Expr\Variable($variableName); + return new \Rector\Defluent\ValueObject\AssignAndRootExpr($methodCall->var, $methodCall->var, $variable, $isFirstCallFactory); } - - return new AssignAndRootExpr($methodCall->var, $methodCall->var, null, $isFirstCallFactory); + return new \Rector\Defluent\ValueObject\AssignAndRootExpr($methodCall->var, $methodCall->var, null, $isFirstCallFactory); } - - private function resolveKindInArgs(MethodCall $methodCall): AssignAndRootExpr + private function resolveKindInArgs(\PhpParser\Node\Expr\MethodCall $methodCall) : \Rector\Defluent\ValueObject\AssignAndRootExpr { $variableName = $this->variableNaming->resolveFromNode($methodCall->var); if ($variableName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $silentVariable = new Variable($variableName); - return new AssignAndRootExpr($methodCall->var, $methodCall->var, $silentVariable); + $silentVariable = new \PhpParser\Node\Expr\Variable($variableName); + return new \Rector\Defluent\ValueObject\AssignAndRootExpr($methodCall->var, $methodCall->var, $silentVariable); } - - private function matchMethodCallOnNew(New_ $new): ?AssignAndRootExpr + private function matchMethodCallOnNew(\PhpParser\Node\Expr\New_ $new) : ?\Rector\Defluent\ValueObject\AssignAndRootExpr { // we need assigned left variable here - $previousAssignOrReturn = $this->betterNodeFinder->findFirstPreviousOfTypes( - $new, - [Assign::class, Return_::class] - ); - - if ($previousAssignOrReturn instanceof Assign) { - return new AssignAndRootExpr($previousAssignOrReturn->var, $new); + $previousAssignOrReturn = $this->betterNodeFinder->findFirstPreviousOfTypes($new, [\PhpParser\Node\Expr\Assign::class, \PhpParser\Node\Stmt\Return_::class]); + if ($previousAssignOrReturn instanceof \PhpParser\Node\Expr\Assign) { + return new \Rector\Defluent\ValueObject\AssignAndRootExpr($previousAssignOrReturn->var, $new); } - - if ($previousAssignOrReturn instanceof Return_) { + if ($previousAssignOrReturn instanceof \PhpParser\Node\Stmt\Return_) { $className = $this->nodeNameResolver->getName($new->class); if ($className === null) { return null; } - - $fullyQualifiedObjectType = new FullyQualifiedObjectType($className); + $fullyQualifiedObjectType = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($className); $expectedName = $this->propertyNaming->getExpectedNameFromType($fullyQualifiedObjectType); - if (! $expectedName instanceof ExpectedName) { + if (!$expectedName instanceof \Rector\Naming\ValueObject\ExpectedName) { return null; } - - $variable = new Variable($expectedName->getName()); - return new AssignAndRootExpr($new, $new, $variable); + $variable = new \PhpParser\Node\Expr\Variable($expectedName->getName()); + return new \Rector\Defluent\ValueObject\AssignAndRootExpr($new, $new, $variable); } - // no assign, just standalone call return null; } diff --git a/rules/Defluent/NodeAnalyzer/GetterMethodCallAnalyzer.php b/rules/Defluent/NodeAnalyzer/GetterMethodCallAnalyzer.php index 20e819587c8..a971e3bd08f 100644 --- a/rules/Defluent/NodeAnalyzer/GetterMethodCallAnalyzer.php +++ b/rules/Defluent/NodeAnalyzer/GetterMethodCallAnalyzer.php @@ -1,34 +1,28 @@ nodeTypeResolver = $nodeTypeResolver; } - - public function isGetterMethodCall(MethodCall $methodCall): bool + public function isGetterMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { - if ($methodCall->var instanceof MethodCall) { - return false; + if ($methodCall->var instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - $methodCallStaticType = $this->nodeTypeResolver->getStaticType($methodCall); $methodCallVarStaticType = $this->nodeTypeResolver->getStaticType($methodCall->var); - // getter short call type - return ! $methodCallStaticType->equals($methodCallVarStaticType); + return !$methodCallStaticType->equals($methodCallVarStaticType); } } diff --git a/rules/Defluent/NodeAnalyzer/MethodCallSkipAnalyzer.php b/rules/Defluent/NodeAnalyzer/MethodCallSkipAnalyzer.php index 102e1175039..2445abfd8d4 100644 --- a/rules/Defluent/NodeAnalyzer/MethodCallSkipAnalyzer.php +++ b/rules/Defluent/NodeAnalyzer/MethodCallSkipAnalyzer.php @@ -1,40 +1,32 @@ fluentMethodCallSkipper = $fluentMethodCallSkipper; $this->fluentChainMethodCallNodeAnalyzer = $fluentChainMethodCallNodeAnalyzer; } - - public function shouldSkipMethodCallIncludingNew(MethodCall $methodCall): bool + public function shouldSkipMethodCallIncludingNew(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { if ($this->fluentMethodCallSkipper->shouldSkipRootMethodCall($methodCall)) { - return true; + return \true; } - $chainRootExpr = $this->fluentChainMethodCallNodeAnalyzer->resolveRootExpr($methodCall); - return $chainRootExpr instanceof New_; + return $chainRootExpr instanceof \PhpParser\Node\Expr\New_; } } diff --git a/rules/Defluent/NodeAnalyzer/NewFluentChainMethodCallNodeAnalyzer.php b/rules/Defluent/NodeAnalyzer/NewFluentChainMethodCallNodeAnalyzer.php index 28b86fda7fb..237e27d8245 100644 --- a/rules/Defluent/NodeAnalyzer/NewFluentChainMethodCallNodeAnalyzer.php +++ b/rules/Defluent/NodeAnalyzer/NewFluentChainMethodCallNodeAnalyzer.php @@ -1,61 +1,51 @@ nodeTypeResolver = $nodeTypeResolver; } - - public function isNewMethodCallReturningSelf(MethodCall $methodCall): bool + public function isNewMethodCallReturningSelf(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { $newStaticType = $this->nodeTypeResolver->getStaticType($methodCall->var); $methodCallStaticType = $this->nodeTypeResolver->getStaticType($methodCall); - return $methodCallStaticType->equals($newStaticType); } - /** * Method call with "new X", that returns "X"? * e.g. * * $this->setItem(new Item) // → returns "Item" */ - public function matchNewInFluentSetterMethodCall(MethodCall $methodCall): ?New_ + public function matchNewInFluentSetterMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node\Expr\New_ { - if (count($methodCall->args) !== 1) { + if (\count($methodCall->args) !== 1) { return null; } - $onlyArgValue = $methodCall->args[0]->value; - if (! $onlyArgValue instanceof New_) { + if (!$onlyArgValue instanceof \PhpParser\Node\Expr\New_) { return null; } - $newType = $this->nodeTypeResolver->resolve($onlyArgValue); - if ($newType instanceof MixedType) { + if ($newType instanceof \PHPStan\Type\MixedType) { return null; } - $parentMethodCallReturnType = $this->nodeTypeResolver->resolve($methodCall); - if (! $newType->equals($parentMethodCallReturnType)) { + if (!$newType->equals($parentMethodCallReturnType)) { return null; } - return $onlyArgValue; } } diff --git a/rules/Defluent/NodeAnalyzer/SameClassMethodCallAnalyzer.php b/rules/Defluent/NodeAnalyzer/SameClassMethodCallAnalyzer.php index e3ba551e599..735f9a689fc 100644 --- a/rules/Defluent/NodeAnalyzer/SameClassMethodCallAnalyzer.php +++ b/rules/Defluent/NodeAnalyzer/SameClassMethodCallAnalyzer.php @@ -1,7 +1,6 @@ nodeRepository = $nodeRepository; } - /** * @param MethodCall[] $chainMethodCalls */ - public function haveSingleClass(array $chainMethodCalls): bool + public function haveSingleClass(array $chainMethodCalls) : bool { // are method calls located in the same class? $classOfClassMethod = []; foreach ($chainMethodCalls as $chainMethodCall) { $classMethod = $this->nodeRepository->findClassMethodByMethodCall($chainMethodCall); - if ($classMethod instanceof ClassMethod) { - $classOfClassMethod[] = $classMethod->getAttribute(AttributeKey::CLASS_NAME); + if ($classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + $classOfClassMethod[] = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); } else { $classOfClassMethod[] = null; } } - - $uniqueClasses = array_unique($classOfClassMethod); - return count($uniqueClasses) < 2; + $uniqueClasses = \array_unique($classOfClassMethod); + return \count($uniqueClasses) < 2; } - /** * @param string[] $calleeUniqueTypes */ - public function isCorrectTypeCount( - array $calleeUniqueTypes, - FirstCallFactoryAwareInterface $firstCallFactoryAware - ): bool { + public function isCorrectTypeCount(array $calleeUniqueTypes, \Rector\Defluent\Contract\ValueObject\FirstCallFactoryAwareInterface $firstCallFactoryAware) : bool + { if ($calleeUniqueTypes === []) { - return false; + return \false; } - // in case of factory method, 2 methods are allowed if ($firstCallFactoryAware->isFirstCallFactory()) { - return count($calleeUniqueTypes) === 2; + return \count($calleeUniqueTypes) === 2; } - - return count($calleeUniqueTypes) === 1; + return \count($calleeUniqueTypes) === 1; } } diff --git a/rules/Defluent/NodeFactory/FluentMethodCallAsArgFactory.php b/rules/Defluent/NodeFactory/FluentMethodCallAsArgFactory.php index 38632441dd6..d4556d89e2f 100644 --- a/rules/Defluent/NodeFactory/FluentMethodCallAsArgFactory.php +++ b/rules/Defluent/NodeFactory/FluentMethodCallAsArgFactory.php @@ -1,26 +1,22 @@ getAttribute(AttributeKey::PARENT_NODE); + $parent = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); /** @var MethodCall $parentParent */ - $parentParent = $parent->getAttribute(AttributeKey::PARENT_NODE); - - $lastMethodCall = new MethodCall($parentParent->var, $parentParent->name); - $lastMethodCall->args[] = new Arg($variable); - + $parentParent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + $lastMethodCall = new \PhpParser\Node\Expr\MethodCall($parentParent->var, $parentParent->name); + $lastMethodCall->args[] = new \PhpParser\Node\Arg($variable); return $lastMethodCall; } } diff --git a/rules/Defluent/NodeFactory/NonFluentChainMethodCallFactory.php b/rules/Defluent/NodeFactory/NonFluentChainMethodCallFactory.php index 8b93a70f6f2..f2f9b4cabad 100644 --- a/rules/Defluent/NodeFactory/NonFluentChainMethodCallFactory.php +++ b/rules/Defluent/NodeFactory/NonFluentChainMethodCallFactory.php @@ -1,7 +1,6 @@ fluentChainMethodCallNodeAnalyzer = $fluentChainMethodCallNodeAnalyzer; $this->variableNaming = $variableNaming; $this->firstMethodCallVarResolver = $firstMethodCallVarResolver; } - /** * @return Expression[] */ - public function createFromNewAndRootMethodCall(New_ $new, MethodCall $rootMethodCall): array + public function createFromNewAndRootMethodCall(\PhpParser\Node\Expr\New_ $new, \PhpParser\Node\Expr\MethodCall $rootMethodCall) : array { $variableName = $this->variableNaming->resolveFromNode($new); if ($variableName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $newVariable = new Variable($variableName); - + $newVariable = new \PhpParser\Node\Expr\Variable($variableName); $newStmts = []; $newStmts[] = $this->createAssignExpression($newVariable, $new); - // resolve chain calls - $chainMethodCalls = $this->fluentChainMethodCallNodeAnalyzer->collectAllMethodCallsInChainWithoutRootOne( - $rootMethodCall - ); - - $chainMethodCalls = array_reverse($chainMethodCalls); + $chainMethodCalls = $this->fluentChainMethodCallNodeAnalyzer->collectAllMethodCallsInChainWithoutRootOne($rootMethodCall); + $chainMethodCalls = \array_reverse($chainMethodCalls); foreach ($chainMethodCalls as $chainMethodCall) { - $methodCall = new MethodCall($newVariable, $chainMethodCall->name, $chainMethodCall->args); - $newStmts[] = new Expression($methodCall); + $methodCall = new \PhpParser\Node\Expr\MethodCall($newVariable, $chainMethodCall->name, $chainMethodCall->args); + $newStmts[] = new \PhpParser\Node\Stmt\Expression($methodCall); } - return $newStmts; } - /** * @param MethodCall[] $chainMethodCalls * @return Assign[]|MethodCall[]|Return_[] */ - public function createFromAssignObjectAndMethodCalls( - AssignAndRootExpr $assignAndRootExpr, - array $chainMethodCalls, - string $kind - ): array { + public function createFromAssignObjectAndMethodCalls(\Rector\Defluent\ValueObject\AssignAndRootExpr $assignAndRootExpr, array $chainMethodCalls, string $kind) : array + { $nodesToAdd = []; - $isNewNodeNeeded = $this->isNewNodeNeeded($assignAndRootExpr); if ($isNewNodeNeeded) { $nodesToAdd[] = $assignAndRootExpr->createFirstAssign(); } - - $decoupledMethodCalls = $this->createNonFluentMethodCalls( - $chainMethodCalls, - $assignAndRootExpr, - $isNewNodeNeeded - ); - - $nodesToAdd = array_merge($nodesToAdd, $decoupledMethodCalls); - - if ($assignAndRootExpr->getSilentVariable() !== null && $kind !== FluentCallsKind::IN_ARGS) { + $decoupledMethodCalls = $this->createNonFluentMethodCalls($chainMethodCalls, $assignAndRootExpr, $isNewNodeNeeded); + $nodesToAdd = \array_merge($nodesToAdd, $decoupledMethodCalls); + if ($assignAndRootExpr->getSilentVariable() !== null && $kind !== \Rector\Defluent\ValueObject\FluentCallsKind::IN_ARGS) { $nodesToAdd[] = $assignAndRootExpr->getReturnSilentVariable(); } - return $nodesToAdd; } - - private function createAssignExpression(Variable $newVariable, New_ $new): Expression + private function createAssignExpression(\PhpParser\Node\Expr\Variable $newVariable, \PhpParser\Node\Expr\New_ $new) : \PhpParser\Node\Stmt\Expression { - $assign = new Assign($newVariable, $new); - return new Expression($assign); + $assign = new \PhpParser\Node\Expr\Assign($newVariable, $new); + return new \PhpParser\Node\Stmt\Expression($assign); } - - private function isNewNodeNeeded(AssignAndRootExpr $assignAndRootExpr): bool + private function isNewNodeNeeded(\Rector\Defluent\ValueObject\AssignAndRootExpr $assignAndRootExpr) : bool { if ($assignAndRootExpr->isFirstCallFactory()) { - return true; + return \true; } - if ($assignAndRootExpr->getRootExpr() === $assignAndRootExpr->getAssignExpr()) { - return false; + return \false; } - - return $assignAndRootExpr->getRootExpr() instanceof New_; + return $assignAndRootExpr->getRootExpr() instanceof \PhpParser\Node\Expr\New_; } - /** * @param MethodCall[] $chainMethodCalls * @return Assign[]|MethodCall[] */ - private function createNonFluentMethodCalls( - array $chainMethodCalls, - AssignAndRootExpr $assignAndRootExpr, - bool $isNewNodeNeeded - ): array { + private function createNonFluentMethodCalls(array $chainMethodCalls, \Rector\Defluent\ValueObject\AssignAndRootExpr $assignAndRootExpr, bool $isNewNodeNeeded) : array + { $decoupledMethodCalls = []; - - $lastKey = array_key_last($chainMethodCalls); - + \end($chainMethodCalls); + $lastKey = \key($chainMethodCalls); foreach ($chainMethodCalls as $key => $chainMethodCall) { // skip first, already handled if ($key === $lastKey && $assignAndRootExpr->isFirstCallFactory() && $isNewNodeNeeded) { continue; } - $chainMethodCall->var = $this->firstMethodCallVarResolver->resolve($assignAndRootExpr, $key); $decoupledMethodCalls[] = $chainMethodCall; } - - if ($assignAndRootExpr->getRootExpr() instanceof New_ && $assignAndRootExpr->getSilentVariable() !== null) { - $decoupledMethodCalls[] = new Assign( - $assignAndRootExpr->getSilentVariable(), - $assignAndRootExpr->getRootExpr() - ); + if ($assignAndRootExpr->getRootExpr() instanceof \PhpParser\Node\Expr\New_ && $assignAndRootExpr->getSilentVariable() !== null) { + $decoupledMethodCalls[] = new \PhpParser\Node\Expr\Assign($assignAndRootExpr->getSilentVariable(), $assignAndRootExpr->getRootExpr()); } - - return array_reverse($decoupledMethodCalls); + return \array_reverse($decoupledMethodCalls); } } diff --git a/rules/Defluent/NodeFactory/ReturnFluentMethodCallFactory.php b/rules/Defluent/NodeFactory/ReturnFluentMethodCallFactory.php index 3c6736df5e0..ffadd548ed3 100644 --- a/rules/Defluent/NodeFactory/ReturnFluentMethodCallFactory.php +++ b/rules/Defluent/NodeFactory/ReturnFluentMethodCallFactory.php @@ -1,7 +1,6 @@ fluentChainMethodCallRootExtractor = $fluentChainMethodCallRootExtractor; $this->nodeTypeResolver = $nodeTypeResolver; $this->propertyNaming = $propertyNaming; } - - public function createFromFluentMethodCalls(FluentMethodCalls $fluentMethodCalls): ?FirstAssignFluentCall + public function createFromFluentMethodCalls(\Rector\Defluent\ValueObject\FluentMethodCalls $fluentMethodCalls) : ?\Rector\Defluent\ValueObject\FirstAssignFluentCall { $rootMethodCall = $fluentMethodCalls->getRootMethodCall(); - // this means the 1st method creates different object then it runs on // e.g. $sheet->getRow(), creates a "Row" object - $isFirstMethodCallFactory = $this->fluentChainMethodCallRootExtractor->resolveIsFirstMethodCallFactory( - $rootMethodCall - ); - + $isFirstMethodCallFactory = $this->fluentChainMethodCallRootExtractor->resolveIsFirstMethodCallFactory($rootMethodCall); $lastMethodCall = $fluentMethodCalls->getRootMethodCall(); - - if ($lastMethodCall->var instanceof PropertyFetch) { + if ($lastMethodCall->var instanceof \PhpParser\Node\Expr\PropertyFetch) { $assignExpr = $lastMethodCall->var; } else { // we need a variable to assign the stuff into // the method call, does not belong to the $staticType = $this->nodeTypeResolver->getStaticType($rootMethodCall); - if (! $staticType instanceof ObjectType) { + if (!$staticType instanceof \PHPStan\Type\ObjectType) { return null; } - $variableName = $this->propertyNaming->fqnToVariableName($staticType); - $assignExpr = new Variable($variableName); + $assignExpr = new \PhpParser\Node\Expr\Variable($variableName); } - - return new FirstAssignFluentCall( - $assignExpr, - $rootMethodCall, - $isFirstMethodCallFactory, - $fluentMethodCalls - ); + return new \Rector\Defluent\ValueObject\FirstAssignFluentCall($assignExpr, $rootMethodCall, $isFirstMethodCallFactory, $fluentMethodCalls); } } diff --git a/rules/Defluent/NodeFactory/SeparateReturnMethodCallFactory.php b/rules/Defluent/NodeFactory/SeparateReturnMethodCallFactory.php index 789c8326d86..fe7b9dac8e8 100644 --- a/rules/Defluent/NodeFactory/SeparateReturnMethodCallFactory.php +++ b/rules/Defluent/NodeFactory/SeparateReturnMethodCallFactory.php @@ -1,7 +1,6 @@ firstMethodCallVarResolver = $firstMethodCallVarResolver; } - /** * @return Node[] */ - public function createReturnFromFirstAssignFluentCallAndFluentMethodCalls( - FirstAssignFluentCall $firstAssignFluentCall, - FluentMethodCalls $fluentMethodCalls - ): array { + public function createReturnFromFirstAssignFluentCallAndFluentMethodCalls(\Rector\Defluent\ValueObject\FirstAssignFluentCall $firstAssignFluentCall, \Rector\Defluent\ValueObject\FluentMethodCalls $fluentMethodCalls) : array + { $nodesToAdd = []; - - if (! $firstAssignFluentCall->getAssignExpr() instanceof PropertyFetch) { + if (!$firstAssignFluentCall->getAssignExpr() instanceof \PhpParser\Node\Expr\PropertyFetch) { $nodesToAdd[] = $firstAssignFluentCall->createFirstAssign(); } - - $decoupledMethodCalls = $this->createNonFluentMethodCalls( - $fluentMethodCalls->getFluentMethodCalls(), - $firstAssignFluentCall, - true - ); - - $nodesToAdd = array_merge($nodesToAdd, $decoupledMethodCalls); - + $decoupledMethodCalls = $this->createNonFluentMethodCalls($fluentMethodCalls->getFluentMethodCalls(), $firstAssignFluentCall, \true); + $nodesToAdd = \array_merge($nodesToAdd, $decoupledMethodCalls); // return the first value - $nodesToAdd[] = new Return_($firstAssignFluentCall->getAssignExpr()); - + $nodesToAdd[] = new \PhpParser\Node\Stmt\Return_($firstAssignFluentCall->getAssignExpr()); return $nodesToAdd; } - /** * @param MethodCall[] $chainMethodCalls * @return MethodCall[] */ - private function createNonFluentMethodCalls( - array $chainMethodCalls, - FirstAssignFluentCall $firstAssignFluentCall, - bool $isNewNodeNeeded - ): array { + private function createNonFluentMethodCalls(array $chainMethodCalls, \Rector\Defluent\ValueObject\FirstAssignFluentCall $firstAssignFluentCall, bool $isNewNodeNeeded) : array + { $decoupledMethodCalls = []; - - $lastKey = array_key_last($chainMethodCalls); - + \end($chainMethodCalls); + $lastKey = \key($chainMethodCalls); foreach ($chainMethodCalls as $key => $chainMethodCall) { // skip first, already handled if ($key === $lastKey && $firstAssignFluentCall->isFirstCallFactory() && $isNewNodeNeeded) { continue; } - $chainMethodCall->var = $this->firstMethodCallVarResolver->resolve($firstAssignFluentCall, $key); $decoupledMethodCalls[] = $chainMethodCall; } - - return array_reverse($decoupledMethodCalls); + return \array_reverse($decoupledMethodCalls); } } diff --git a/rules/Defluent/NodeFactory/VariableFromNewFactory.php b/rules/Defluent/NodeFactory/VariableFromNewFactory.php index a051fe89a76..68678acf535 100644 --- a/rules/Defluent/NodeFactory/VariableFromNewFactory.php +++ b/rules/Defluent/NodeFactory/VariableFromNewFactory.php @@ -1,33 +1,28 @@ variableNaming = $variableNaming; } - - public function create(New_ $new): Variable + public function create(\PhpParser\Node\Expr\New_ $new) : \PhpParser\Node\Expr\Variable { $variableName = $this->variableNaming->resolveFromNode($new); if ($variableName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - return new Variable($variableName); + return new \PhpParser\Node\Expr\Variable($variableName); } } diff --git a/rules/Defluent/NodeResolver/FirstMethodCallVarResolver.php b/rules/Defluent/NodeResolver/FirstMethodCallVarResolver.php index 7d1eb6750f5..1afaf0bf020 100644 --- a/rules/Defluent/NodeResolver/FirstMethodCallVarResolver.php +++ b/rules/Defluent/NodeResolver/FirstMethodCallVarResolver.php @@ -1,30 +1,26 @@ isFirstCallFactory()) { + if (!$firstCallFactoryAware->isFirstCallFactory()) { return $firstCallFactoryAware->getCallerExpr(); } - // very first call if ($key !== 0) { return $firstCallFactoryAware->getCallerExpr(); } - return $firstCallFactoryAware->getFactoryAssignVariable(); } } diff --git a/rules/Defluent/Rector/ClassMethod/NormalToFluentRector.php b/rules/Defluent/Rector/ClassMethod/NormalToFluentRector.php index 4fb33ec63de..143f5249d15 100644 --- a/rules/Defluent/Rector/ClassMethod/NormalToFluentRector.php +++ b/rules/Defluent/Rector/ClassMethod/NormalToFluentRector.php @@ -1,7 +1,6 @@ someFunction(); $someObject->otherFunction(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someObject = new SomeClass(); $someObject->someFunction() ->otherFunction(); CODE_SAMPLE - , - [ - self::CALLS_TO_FLUENT => [new NormalToFluent('SomeClass', ['someFunction', 'otherFunction'])], - ] - ), - ]); +, [self::CALLS_TO_FLUENT => [new \Rector\Defluent\ValueObject\NormalToFluent('SomeClass', ['someFunction', 'otherFunction'])]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { // process only existing statements if ($node->stmts === null) { return null; } - - $classMethodStatementCount = count($node->stmts); - + $classMethodStatementCount = \count($node->stmts); // iterate from bottom to up, so we can merge for ($i = $classMethodStatementCount - 1; $i >= 0; --$i) { - if (! isset($node->stmts[$i])) { + if (!isset($node->stmts[$i])) { continue; } - /** @var Expression $stmt */ $stmt = $node->stmts[$i]; if ($this->shouldSkipPreviousStmt($node, $i)) { continue; } - /** @var Expression $prevStmt */ $prevStmt = $node->stmts[$i - 1]; - // here are 2 method calls statements in a row, while current one is first one - if (! $this->isBothMethodCallMatch($stmt, $prevStmt)) { - if (count($this->collectedMethodCalls) >= 2) { + if (!$this->isBothMethodCallMatch($stmt, $prevStmt)) { + if (\count($this->collectedMethodCalls) >= 2) { $this->fluentizeCollectedMethodCalls($node); } - // reset for new type $this->collectedMethodCalls = []; continue; } - // add all matching fluent calls /** @var MethodCall $currentMethodCall */ $currentMethodCall = $stmt->expr; $this->collectedMethodCalls[$i] = $currentMethodCall; - /** @var MethodCall $previousMethodCall */ $previousMethodCall = $prevStmt->expr; $this->collectedMethodCalls[$i - 1] = $previousMethodCall; } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $callsToFluent = $configuration[self::CALLS_TO_FLUENT] ?? []; - Assert::allIsInstanceOf($callsToFluent, NormalToFluent::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($callsToFluent, \Rector\Defluent\ValueObject\NormalToFluent::class); $this->callsToFluent = $callsToFluent; } - - private function shouldSkipPreviousStmt(ClassMethod $classMethod, int $i): bool + private function shouldSkipPreviousStmt(\PhpParser\Node\Stmt\ClassMethod $classMethod, int $i) : bool { // we look only for 2+ stmts - if (! isset($classMethod->stmts[$i - 1])) { - return true; + if (!isset($classMethod->stmts[$i - 1])) { + return \true; } - $prevStmt = $classMethod->stmts[$i - 1]; - - return ! $prevStmt instanceof Expression; + return !$prevStmt instanceof \PhpParser\Node\Stmt\Expression; } - - private function isBothMethodCallMatch(Expression $firstExpression, Expression $secondExpression): bool + private function isBothMethodCallMatch(\PhpParser\Node\Stmt\Expression $firstExpression, \PhpParser\Node\Stmt\Expression $secondExpression) : bool { - if (! $firstExpression->expr instanceof MethodCall) { - return false; + if (!$firstExpression->expr instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - - if (! $secondExpression->expr instanceof MethodCall) { - return false; + if (!$secondExpression->expr instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - $firstMethodCallMatchObjectType = $this->matchMethodCall($firstExpression->expr); - if (! $firstMethodCallMatchObjectType instanceof ObjectType) { - return false; + if (!$firstMethodCallMatchObjectType instanceof \PHPStan\Type\ObjectType) { + return \false; } - $secondMethodCallMatchObjectType = $this->matchMethodCall($secondExpression->expr); - if (! $secondMethodCallMatchObjectType instanceof ObjectType) { - return false; + if (!$secondMethodCallMatchObjectType instanceof \PHPStan\Type\ObjectType) { + return \false; } - // is the same type return $firstMethodCallMatchObjectType->equals($secondMethodCallMatchObjectType); } - - private function fluentizeCollectedMethodCalls(ClassMethod $classMethod): void + private function fluentizeCollectedMethodCalls(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { $i = 0; $fluentMethodCallIndex = null; @@ -179,43 +145,31 @@ CODE_SAMPLE // next method calls, unset them unset($classMethod->stmts[$statementIndex]); } - ++$i; } - $stmt = $classMethod->stmts[$fluentMethodCallIndex]; - if (! $stmt instanceof Expression) { - throw new ShouldNotHappenException(); + if (!$stmt instanceof \PhpParser\Node\Stmt\Expression) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - /** @var MethodCall $fluentMethodCall */ $fluentMethodCall = $stmt->expr; - // they are added in reversed direction - $methodCallsToAdd = array_reverse($methodCallsToAdd); - + $methodCallsToAdd = \array_reverse($methodCallsToAdd); foreach ($methodCallsToAdd as $methodCallToAdd) { // make var a parent method call - $fluentMethodCall->var = new MethodCall( - $fluentMethodCall->var, - $methodCallToAdd->name, - $methodCallToAdd->args - ); + $fluentMethodCall->var = new \PhpParser\Node\Expr\MethodCall($fluentMethodCall->var, $methodCallToAdd->name, $methodCallToAdd->args); } } - - private function matchMethodCall(MethodCall $methodCall): ?ObjectType + private function matchMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PHPStan\Type\ObjectType { foreach ($this->callsToFluent as $callToFluent) { - if (! $this->isObjectType($methodCall->var, $callToFluent->getObjectType())) { + if (!$this->isObjectType($methodCall->var, $callToFluent->getObjectType())) { continue; } - if ($this->isNames($methodCall->name, $callToFluent->getMethodNames())) { return $callToFluent->getObjectType(); } } - return null; } } diff --git a/rules/Defluent/Rector/ClassMethod/ReturnThisRemoveRector.php b/rules/Defluent/Rector/ClassMethod/ReturnThisRemoveRector.php index 8837195b75c..7565989f2e3 100644 --- a/rules/Defluent/Rector/ClassMethod/ReturnThisRemoveRector.php +++ b/rules/Defluent/Rector/ClassMethod/ReturnThisRemoveRector.php @@ -1,7 +1,6 @@ parentClassMethodTypeOverrideGuard = $parentClassMethodTypeOverrideGuard; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Removes "return $this;" from *fluent interfaces* for specified classes.', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removes "return $this;" from *fluent interfaces* for specified classes.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeExampleClass { public function someFunction() @@ -53,8 +45,7 @@ class SomeExampleClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeExampleClass { public function someFunction() @@ -66,90 +57,71 @@ class SomeExampleClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $returnThis = $this->matchSingleReturnThis($node); - if (! $returnThis instanceof Return_) { + if (!$returnThis instanceof \PhpParser\Node\Stmt\Return_) { return null; } - if ($this->shouldSkip($returnThis, $node)) { return null; } - $this->removeNode($returnThis); - - $classMethod = $node->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { - throw new ShouldNotHappenException(); + $classMethod = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - if ($this->isAtLeastPhpVersion(PhpVersionFeature::VOID_TYPE)) { - $classMethod->returnType = new Identifier('void'); + if ($this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::VOID_TYPE)) { + $classMethod->returnType = new \PhpParser\Node\Identifier('void'); } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - $phpDocInfo->removeByType(ReturnTagValueNode::class); - + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode::class); return null; } - /** * Matches only 1st level "return $this;" */ - private function matchSingleReturnThis(ClassMethod $classMethod): ?Return_ + private function matchSingleReturnThis(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PhpParser\Node\Stmt\Return_ { /** @var Return_[] $returns */ - $returns = $this->betterNodeFinder->findInstanceOf($classMethod, Return_::class); - + $returns = $this->betterNodeFinder->findInstanceOf($classMethod, \PhpParser\Node\Stmt\Return_::class); // can be only 1 return - if (count($returns) !== 1) { + if (\count($returns) !== 1) { return null; } - $return = $returns[0]; - if (! $return->expr instanceof Variable) { + if (!$return->expr instanceof \PhpParser\Node\Expr\Variable) { return null; } - - if (! $this->nodeNameResolver->isName($return->expr, 'this')) { + if (!$this->nodeNameResolver->isName($return->expr, 'this')) { return null; } - - $parentNode = $return->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $return->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); if ($parentNode !== $classMethod) { return null; } - return $return; } - - private function shouldSkip(Return_ $return, ClassMethod $classMethod): bool + private function shouldSkip(\PhpParser\Node\Stmt\Return_ $return, \PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { if ($this->parentClassMethodTypeOverrideGuard->hasParentMethodOutsideVendor($classMethod)) { - return true; + return \true; } - if ($return->expr === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - return false; + return \false; } } diff --git a/rules/Defluent/Rector/MethodCall/FluentChainMethodCallToNormalMethodCallRector.php b/rules/Defluent/Rector/MethodCall/FluentChainMethodCallToNormalMethodCallRector.php index 360f71d9b90..b3690e8f868 100644 --- a/rules/Defluent/Rector/MethodCall/FluentChainMethodCallToNormalMethodCallRector.php +++ b/rules/Defluent/Rector/MethodCall/FluentChainMethodCallToNormalMethodCallRector.php @@ -1,7 +1,6 @@ fluentNodeRemover = $fluentNodeRemover; $this->methodCallSkipAnalyzer = $methodCallSkipAnalyzer; $this->assignAndRootExprAndNodesToAddMatcher = $assignAndRootExprAndNodesToAddMatcher; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Turns fluent interface calls to classic ones.', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns fluent interface calls to classic ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $someClass = new SomeClass(); $someClass->someFunction() ->otherFunction(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someClass = new SomeClass(); $someClass->someFunction(); $someClass->otherFunction(); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->isHandledByAnotherRule($node)) { return null; } - if ($this->methodCallSkipAnalyzer->shouldSkipMethodCallIncludingNew($node)) { return null; } - - $assignAndRootExprAndNodesToAdd = $this->assignAndRootExprAndNodesToAddMatcher->match( - $node, - FluentCallsKind::NORMAL - ); - - if (! $assignAndRootExprAndNodesToAdd instanceof AssignAndRootExprAndNodesToAdd) { + $assignAndRootExprAndNodesToAdd = $this->assignAndRootExprAndNodesToAddMatcher->match($node, \Rector\Defluent\ValueObject\FluentCallsKind::NORMAL); + if (!$assignAndRootExprAndNodesToAdd instanceof \Rector\Defluent\ValueObject\AssignAndRootExprAndNodesToAdd) { return null; } - $this->fluentNodeRemover->removeCurrentNode($node); $this->addNodesAfterNode($assignAndRootExprAndNodesToAdd->getNodesToAdd(), $node); - return null; } - /** * Is handled by: * @see DefluentReturnMethodCallRector * @see InArgFluentChainMethodCallToStandaloneMethodCallRector */ - private function isHandledByAnotherRule(MethodCall $methodCall): bool + private function isHandledByAnotherRule(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { - $parent = $methodCall->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Return_) { - return true; + $parent = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Stmt\Return_) { + return \true; } - - return $parent instanceof Arg; + return $parent instanceof \PhpParser\Node\Arg; } } diff --git a/rules/Defluent/Rector/MethodCall/InArgFluentChainMethodCallToStandaloneMethodCallRector.php b/rules/Defluent/Rector/MethodCall/InArgFluentChainMethodCallToStandaloneMethodCallRector.php index a34070f772f..2569bcd13f8 100644 --- a/rules/Defluent/Rector/MethodCall/InArgFluentChainMethodCallToStandaloneMethodCallRector.php +++ b/rules/Defluent/Rector/MethodCall/InArgFluentChainMethodCallToStandaloneMethodCallRector.php @@ -1,7 +1,6 @@ newFluentChainMethodCallNodeAnalyzer = $newFluentChainMethodCallNodeAnalyzer; $this->variableFromNewFactory = $variableFromNewFactory; $this->fluentMethodCallAsArgFactory = $fluentMethodCallAsArgFactory; @@ -71,14 +57,9 @@ final class InArgFluentChainMethodCallToStandaloneMethodCallRector extends Abstr $this->fluentChainMethodCallNodeAnalyzer = $fluentChainMethodCallNodeAnalyzer; $this->nonFluentChainMethodCallFactory = $nonFluentChainMethodCallFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Turns fluent interface calls to classic ones.', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns fluent interface calls to classic ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class UsedAsParameter { public function someFunction(FluentClass $someClass) @@ -92,8 +73,7 @@ class UsedAsParameter } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class UsedAsParameter { public function someFunction(FluentClass $someClass) @@ -108,81 +88,60 @@ class UsedAsParameter } } CODE_SAMPLE - ), - - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Arg) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Arg) { return null; } - - $parentMethodCall = $parent->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentMethodCall instanceof MethodCall) { + $parentMethodCall = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentMethodCall instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - - if (! $this->fluentChainMethodCallNodeAnalyzer->isLastChainMethodCall($node)) { + if (!$this->fluentChainMethodCallNodeAnalyzer->isLastChainMethodCall($node)) { return null; } - // create instances from (new ...)->call, re-use from - if ($node->var instanceof New_) { + if ($node->var instanceof \PhpParser\Node\Expr\New_) { $this->refactorNew($node, $node->var); return null; } - - $assignAndRootExprAndNodesToAdd = $this->assignAndRootExprAndNodesToAddMatcher->match( - $node, - FluentCallsKind::IN_ARGS - ); - - if (! $assignAndRootExprAndNodesToAdd instanceof AssignAndRootExprAndNodesToAdd) { + $assignAndRootExprAndNodesToAdd = $this->assignAndRootExprAndNodesToAddMatcher->match($node, \Rector\Defluent\ValueObject\FluentCallsKind::IN_ARGS); + if (!$assignAndRootExprAndNodesToAdd instanceof \Rector\Defluent\ValueObject\AssignAndRootExprAndNodesToAdd) { return null; } - $this->addNodesBeforeNode($assignAndRootExprAndNodesToAdd->getNodesToAdd(), $node); return $assignAndRootExprAndNodesToAdd->getRootCallerExpr(); } - - private function refactorNew(MethodCall $methodCall, New_ $new): void + private function refactorNew(\PhpParser\Node\Expr\MethodCall $methodCall, \PhpParser\Node\Expr\New_ $new) : void { - if (! $this->newFluentChainMethodCallNodeAnalyzer->isNewMethodCallReturningSelf($methodCall)) { + if (!$this->newFluentChainMethodCallNodeAnalyzer->isNewMethodCallReturningSelf($methodCall)) { return; } - $nodesToAdd = $this->nonFluentChainMethodCallFactory->createFromNewAndRootMethodCall($new, $methodCall); - $newVariable = $this->variableFromNewFactory->create($new); $nodesToAdd[] = $this->fluentMethodCallAsArgFactory->createFluentAsArg($methodCall, $newVariable); - $this->addNodesBeforeNode($nodesToAdd, $methodCall); $this->removeParentParent($methodCall); } - - private function removeParentParent(MethodCall $methodCall): void + private function removeParentParent(\PhpParser\Node\Expr\MethodCall $methodCall) : void { /** @var Arg $parent */ - $parent = $methodCall->getAttribute(AttributeKey::PARENT_NODE); - + $parent = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); /** @var MethodCall $parentParent */ - $parentParent = $parent->getAttribute(AttributeKey::PARENT_NODE); - + $parentParent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); $this->removeNode($parentParent); } } diff --git a/rules/Defluent/Rector/MethodCall/MethodCallOnSetterMethodCallToStandaloneAssignRector.php b/rules/Defluent/Rector/MethodCall/MethodCallOnSetterMethodCallToStandaloneAssignRector.php index 76fb71e28bf..78a2a9e5a4a 100644 --- a/rules/Defluent/Rector/MethodCall/MethodCallOnSetterMethodCallToStandaloneAssignRector.php +++ b/rules/Defluent/Rector/MethodCall/MethodCallOnSetterMethodCallToStandaloneAssignRector.php @@ -1,7 +1,6 @@ newFluentChainMethodCallNodeAnalyzer = $newFluentChainMethodCallNodeAnalyzer; $this->variableFromNewFactory = $variableFromNewFactory; $this->nonFluentChainMethodCallFactory = $nonFluentChainMethodCallFactory; $this->fluentMethodCallSkipper = $fluentMethodCallSkipper; $this->fluentChainMethodCallNodeAnalyzer = $fluentChainMethodCallNodeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change method call on setter to standalone assign before the setter', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change method call on setter to standalone assign before the setter', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function some() @@ -82,8 +65,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function some() @@ -98,45 +80,36 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->fluentMethodCallSkipper->shouldSkipRootMethodCall($node)) { return null; } - $rootMethodCall = $this->fluentChainMethodCallNodeAnalyzer->resolveRootMethodCall($node); - if (! $rootMethodCall instanceof MethodCall) { + if (!$rootMethodCall instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - $new = $this->newFluentChainMethodCallNodeAnalyzer->matchNewInFluentSetterMethodCall($rootMethodCall); - if (! $new instanceof New_) { + if (!$new instanceof \PhpParser\Node\Expr\New_) { return null; } - $newStmts = $this->nonFluentChainMethodCallFactory->createFromNewAndRootMethodCall($new, $node); $this->addNodesBeforeNode($newStmts, $node); - // change new arg to root variable $newVariable = $this->variableFromNewFactory->create($new); - $rootMethodCall->args = [new Arg($newVariable)]; - + $rootMethodCall->args = [new \PhpParser\Node\Arg($newVariable)]; return $rootMethodCall; } } diff --git a/rules/Defluent/Rector/MethodCall/NewFluentChainMethodCallToNonFluentRector.php b/rules/Defluent/Rector/MethodCall/NewFluentChainMethodCallToNonFluentRector.php index aa7b85590cd..282e4ab13ec 100644 --- a/rules/Defluent/Rector/MethodCall/NewFluentChainMethodCallToNonFluentRector.php +++ b/rules/Defluent/Rector/MethodCall/NewFluentChainMethodCallToNonFluentRector.php @@ -1,7 +1,6 @@ typeChecker = $typeChecker; $this->fluentNodeRemover = $fluentNodeRemover; $this->assignAndRootExprAndNodesToAddMatcher = $assignAndRootExprAndNodesToAddMatcher; $this->fluentMethodCallSkipper = $fluentMethodCallSkipper; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Turns fluent interface calls to classic ones.', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns fluent interface calls to classic ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' (new SomeClass())->someFunction() ->otherFunction(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someClass = new SomeClass(); $someClass->someFunction(); $someClass->otherFunction(); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { // handled by another rule - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($this->typeChecker->isInstanceOf($parent, [Return_::class, Arg::class])) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($this->typeChecker->isInstanceOf($parent, [\PhpParser\Node\Stmt\Return_::class, \PhpParser\Node\Arg::class])) { return null; } - if ($this->fluentMethodCallSkipper->shouldSkipRootMethodCall($node)) { return null; } - - $assignAndRootExprAndNodesToAdd = $this->assignAndRootExprAndNodesToAddMatcher->match( - $node, - FluentCallsKind::NORMAL - ); - if (! $assignAndRootExprAndNodesToAdd instanceof AssignAndRootExprAndNodesToAdd) { + $assignAndRootExprAndNodesToAdd = $this->assignAndRootExprAndNodesToAddMatcher->match($node, \Rector\Defluent\ValueObject\FluentCallsKind::NORMAL); + if (!$assignAndRootExprAndNodesToAdd instanceof \Rector\Defluent\ValueObject\AssignAndRootExprAndNodesToAdd) { return null; } - $this->fluentNodeRemover->removeCurrentNode($node); $this->addNodesAfterNode($assignAndRootExprAndNodesToAdd->getNodesToAdd(), $node); - return null; } } diff --git a/rules/Defluent/Rector/Return_/DefluentReturnMethodCallRector.php b/rules/Defluent/Rector/Return_/DefluentReturnMethodCallRector.php index dc122b482c0..0560fe1914d 100644 --- a/rules/Defluent/Rector/Return_/DefluentReturnMethodCallRector.php +++ b/rules/Defluent/Rector/Return_/DefluentReturnMethodCallRector.php @@ -1,7 +1,6 @@ fluentChainMethodCallNodeAnalyzer = $fluentChainMethodCallNodeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Turns return of fluent, to standalone call line and return of value', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns return of fluent, to standalone call line and return of value', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $someClass = new SomeClass(); return $someClass->someFunction(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someClass = new SomeClass(); $someClass->someFunction(); return $someClass; CODE_SAMPLE - ), - - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Return_::class]; + return [\PhpParser\Node\Stmt\Return_::class]; } - /** * @param Return_ $node * @return null|Expression[]|Return_[] */ - public function refactor(Node $node) + public function refactor(\PhpParser\Node $node) { - if (! $node->expr instanceof MethodCall) { + if (!$node->expr instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - $methodCall = $node->expr; - if (! $methodCall->var instanceof Variable) { + if (!$methodCall->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - - if (! $this->fluentChainMethodCallNodeAnalyzer->isFluentClassMethodOfMethodCall($methodCall)) { + if (!$this->fluentChainMethodCallNodeAnalyzer->isFluentClassMethodOfMethodCall($methodCall)) { return null; } - - $variableReturn = new Return_($methodCall->var); - - return [new Expression($methodCall), $variableReturn]; + $variableReturn = new \PhpParser\Node\Stmt\Return_($methodCall->var); + return [new \PhpParser\Node\Stmt\Expression($methodCall), $variableReturn]; } } diff --git a/rules/Defluent/Rector/Return_/ReturnFluentChainMethodCallToNormalMethodCallRector.php b/rules/Defluent/Rector/Return_/ReturnFluentChainMethodCallToNormalMethodCallRector.php index 2694295f817..1f9cf11be36 100644 --- a/rules/Defluent/Rector/Return_/ReturnFluentChainMethodCallToNormalMethodCallRector.php +++ b/rules/Defluent/Rector/Return_/ReturnFluentChainMethodCallToNormalMethodCallRector.php @@ -1,7 +1,6 @@ returnFluentMethodCallFactory = $returnFluentMethodCallFactory; $this->fluentMethodCallsFactory = $fluentMethodCallsFactory; $this->separateReturnMethodCallFactory = $separateReturnMethodCallFactory; @@ -71,98 +57,75 @@ final class ReturnFluentChainMethodCallToNormalMethodCallRector extends Abstract $this->methodCallSkipAnalyzer = $methodCallSkipAnalyzer; $this->fluentMethodCallSkipper = $fluentMethodCallSkipper; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turns fluent interface calls to classic ones.', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns fluent interface calls to classic ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $someClass = new SomeClass(); return $someClass->someFunction() ->otherFunction(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someClass = new SomeClass(); $someClass->someFunction(); $someClass->otherFunction(); return $someClass; CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Return_::class]; + return [\PhpParser\Node\Stmt\Return_::class]; } - /** * @param Return_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $methodCall = $this->matchReturnMethodCall($node); - if (! $methodCall instanceof MethodCall) { + if (!$methodCall instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - if ($this->methodCallSkipAnalyzer->shouldSkipMethodCallIncludingNew($methodCall)) { return null; } - $nodesToAdd = $this->createStandaloneNodesToAddFromReturnFluentMethodCalls($methodCall); if ($nodesToAdd === []) { return null; } - $this->fluentNodeRemover->removeCurrentNode($node); $this->addNodesAfterNode($nodesToAdd, $node); - return null; } - /** * @return Node[] */ - private function createStandaloneNodesToAddFromReturnFluentMethodCalls(MethodCall $methodCall): array + private function createStandaloneNodesToAddFromReturnFluentMethodCalls(\PhpParser\Node\Expr\MethodCall $methodCall) : array { $fluentMethodCalls = $this->fluentMethodCallsFactory->createFromLastMethodCall($methodCall); - if (! $fluentMethodCalls instanceof FluentMethodCalls) { + if (!$fluentMethodCalls instanceof \Rector\Defluent\ValueObject\FluentMethodCalls) { return []; } - - $firstAssignFluentCall = $this->returnFluentMethodCallFactory->createFromFluentMethodCalls( - $fluentMethodCalls - ); - - if (! $firstAssignFluentCall instanceof FirstAssignFluentCall) { + $firstAssignFluentCall = $this->returnFluentMethodCallFactory->createFromFluentMethodCalls($fluentMethodCalls); + if (!$firstAssignFluentCall instanceof \Rector\Defluent\ValueObject\FirstAssignFluentCall) { return []; } - // should be skipped? if ($this->fluentMethodCallSkipper->shouldSkipFirstAssignFluentCall($firstAssignFluentCall)) { return []; } - - return $this->separateReturnMethodCallFactory->createReturnFromFirstAssignFluentCallAndFluentMethodCalls( - $firstAssignFluentCall, - $fluentMethodCalls - ); + return $this->separateReturnMethodCallFactory->createReturnFromFirstAssignFluentCallAndFluentMethodCalls($firstAssignFluentCall, $fluentMethodCalls); } - - private function matchReturnMethodCall(Return_ $return): ?MethodCall + private function matchReturnMethodCall(\PhpParser\Node\Stmt\Return_ $return) : ?\PhpParser\Node\Expr\MethodCall { $returnExpr = $return->expr; - if (! $returnExpr instanceof MethodCall) { + if (!$returnExpr instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - return $returnExpr; } } diff --git a/rules/Defluent/Rector/Return_/ReturnNewFluentChainMethodCallToNonFluentRector.php b/rules/Defluent/Rector/Return_/ReturnNewFluentChainMethodCallToNonFluentRector.php index 3e9b7ba104a..1a32d45ba81 100644 --- a/rules/Defluent/Rector/Return_/ReturnNewFluentChainMethodCallToNonFluentRector.php +++ b/rules/Defluent/Rector/Return_/ReturnNewFluentChainMethodCallToNonFluentRector.php @@ -1,7 +1,6 @@ fluentNodeRemover = $fluentNodeRemover; $this->assignAndRootExprAndNodesToAddMatcher = $assignAndRootExprAndNodesToAddMatcher; $this->fluentMethodCallSkipper = $fluentMethodCallSkipper; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Turns fluent interface calls to classic ones.', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns fluent interface calls to classic ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' return (new SomeClass())->someFunction() ->otherFunction(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someClass = new SomeClass(); $someClass->someFunction(); $someClass->otherFunction(); return $someClass; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Return_::class]; + return [\PhpParser\Node\Stmt\Return_::class]; } - /** * @param Return_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $methodCall = $this->matchReturnMethodCall($node); - if (! $methodCall instanceof MethodCall) { + if (!$methodCall instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - if ($this->fluentMethodCallSkipper->shouldSkipRootMethodCall($methodCall)) { return null; } - - $assignAndRootExprAndNodesToAdd = $this->assignAndRootExprAndNodesToAddMatcher->match( - $methodCall, - FluentCallsKind::NORMAL - ); - - if (! $assignAndRootExprAndNodesToAdd instanceof AssignAndRootExprAndNodesToAdd) { + $assignAndRootExprAndNodesToAdd = $this->assignAndRootExprAndNodesToAddMatcher->match($methodCall, \Rector\Defluent\ValueObject\FluentCallsKind::NORMAL); + if (!$assignAndRootExprAndNodesToAdd instanceof \Rector\Defluent\ValueObject\AssignAndRootExprAndNodesToAdd) { return null; } - $this->fluentNodeRemover->removeCurrentNode($node); $this->addNodesAfterNode($assignAndRootExprAndNodesToAdd->getNodesToAdd(), $node); - return null; } - - private function matchReturnMethodCall(Return_ $return): ?Expr + private function matchReturnMethodCall(\PhpParser\Node\Stmt\Return_ $return) : ?\PhpParser\Node\Expr { if ($return->expr === null) { return null; } - - if (! $return->expr instanceof MethodCall) { + if (!$return->expr instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - return $return->expr; } } diff --git a/rules/Defluent/Reflection/MethodCallToClassMethodParser.php b/rules/Defluent/Reflection/MethodCallToClassMethodParser.php index 007bce5cde2..d614a3cd66b 100644 --- a/rules/Defluent/Reflection/MethodCallToClassMethodParser.php +++ b/rules/Defluent/Reflection/MethodCallToClassMethodParser.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; $this->functionLikeReflectionParser = $functionLikeReflectionParser; } - - public function parseMethodCall(MethodCall $methodCall): ?ClassMethod + public function parseMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node\Stmt\ClassMethod { $callerStaticType = $this->nodeTypeResolver->getStaticType($methodCall->var); - if (! $callerStaticType instanceof TypeWithClassName) { + if (!$callerStaticType instanceof \PHPStan\Type\TypeWithClassName) { return null; } - $callerClassReflection = $this->reflectionProvider->getClass($callerStaticType->getClassName()); $methodName = $this->nodeNameResolver->getName($methodCall->name); if ($methodName === null) { return null; } - $methodReflection = $callerClassReflection->getNativeMethod($methodName); - return $this->functionLikeReflectionParser->parseMethodReflection($methodReflection); } } diff --git a/rules/Defluent/Skipper/FluentMethodCallSkipper.php b/rules/Defluent/Skipper/FluentMethodCallSkipper.php index e416e74f93b..7f63817f501 100644 --- a/rules/Defluent/Skipper/FluentMethodCallSkipper.php +++ b/rules/Defluent/Skipper/FluentMethodCallSkipper.php @@ -1,7 +1,6 @@ fluentCallStaticTypeResolver = $fluentCallStaticTypeResolver; $this->sameClassMethodCallAnalyzer = $sameClassMethodCallAnalyzer; $this->fluentChainMethodCallNodeAnalyzer = $fluentChainMethodCallNodeAnalyzer; $this->getterMethodCallAnalyzer = $getterMethodCallAnalyzer; } - - public function shouldSkipRootMethodCall(MethodCall $methodCall): bool + public function shouldSkipRootMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { - if (! $this->fluentChainMethodCallNodeAnalyzer->isLastChainMethodCall($methodCall)) { - return true; + if (!$this->fluentChainMethodCallNodeAnalyzer->isLastChainMethodCall($methodCall)) { + return \true; } - return $this->getterMethodCallAnalyzer->isGetterMethodCall($methodCall); } - - public function shouldSkipFirstAssignFluentCall(FirstAssignFluentCall $firstAssignFluentCall): bool + public function shouldSkipFirstAssignFluentCall(\Rector\Defluent\ValueObject\FirstAssignFluentCall $firstAssignFluentCall) : bool { - $calleeUniqueTypes = $this->fluentCallStaticTypeResolver->resolveCalleeUniqueTypes( - $firstAssignFluentCall->getFluentMethodCalls() - ); - - if (! $this->sameClassMethodCallAnalyzer->isCorrectTypeCount($calleeUniqueTypes, $firstAssignFluentCall)) { - return true; + $calleeUniqueTypes = $this->fluentCallStaticTypeResolver->resolveCalleeUniqueTypes($firstAssignFluentCall->getFluentMethodCalls()); + if (!$this->sameClassMethodCallAnalyzer->isCorrectTypeCount($calleeUniqueTypes, $firstAssignFluentCall)) { + return \true; } - $calleeUniqueType = $this->resolveCalleeUniqueType($firstAssignFluentCall, $calleeUniqueTypes); return $this->isAllowedType($calleeUniqueType); } - /** * @param MethodCall[] $fluentMethodCalls */ - public function shouldSkipMethodCalls(AssignAndRootExpr $assignAndRootExpr, array $fluentMethodCalls): bool + public function shouldSkipMethodCalls(\Rector\Defluent\ValueObject\AssignAndRootExpr $assignAndRootExpr, array $fluentMethodCalls) : bool { $calleeUniqueTypes = $this->fluentCallStaticTypeResolver->resolveCalleeUniqueTypes($fluentMethodCalls); - if (! $this->sameClassMethodCallAnalyzer->isCorrectTypeCount($calleeUniqueTypes, $assignAndRootExpr)) { - return true; + if (!$this->sameClassMethodCallAnalyzer->isCorrectTypeCount($calleeUniqueTypes, $assignAndRootExpr)) { + return \true; } - $calleeUniqueType = $this->resolveCalleeUniqueType($assignAndRootExpr, $calleeUniqueTypes); return $this->isAllowedType($calleeUniqueType); } - /** * @param string[] $calleeUniqueTypes */ - private function resolveCalleeUniqueType( - FirstCallFactoryAwareInterface $firstCallFactoryAware, - array $calleeUniqueTypes - ): string { - if (! $firstCallFactoryAware->isFirstCallFactory()) { + private function resolveCalleeUniqueType(\Rector\Defluent\Contract\ValueObject\FirstCallFactoryAwareInterface $firstCallFactoryAware, array $calleeUniqueTypes) : string + { + if (!$firstCallFactoryAware->isFirstCallFactory()) { return $calleeUniqueTypes[0]; } - return $calleeUniqueTypes[1] ?? $calleeUniqueTypes[0]; } - - private function isAllowedType(string $class): bool + private function isAllowedType(string $class) : bool { - $objectType = new ObjectType($class); - + $objectType = new \PHPStan\Type\ObjectType($class); foreach (self::ALLOWED_FLUENT_TYPES as $allowedFluentType) { - $allowedObjectType = new ObjectType($allowedFluentType); + $allowedObjectType = new \PHPStan\Type\ObjectType($allowedFluentType); if ($allowedObjectType->isSuperTypeOf($objectType)->yes()) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/Defluent/ValueObject/AbstractRootExpr.php b/rules/Defluent/ValueObject/AbstractRootExpr.php index 92577846018..840122e5361 100644 --- a/rules/Defluent/ValueObject/AbstractRootExpr.php +++ b/rules/Defluent/ValueObject/AbstractRootExpr.php @@ -1,7 +1,6 @@ isFirstCallFactory && $this->getFirstAssign() !== null) { return $this->createFactoryAssign(); } - return $this->createAssign($this->assignExpr, $this->rootExpr); } - - protected function createAssign(Expr $assignVar, Expr $assignExpr): Assign + protected function createAssign(\PhpParser\Node\Expr $assignVar, \PhpParser\Node\Expr $assignExpr) : \PhpParser\Node\Expr\Assign { if ($assignVar === $assignExpr) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - return new Assign($assignVar, $assignExpr); + return new \PhpParser\Node\Expr\Assign($assignVar, $assignExpr); } - - protected function getFirstAssign(): ?Assign + protected function getFirstAssign() : ?\PhpParser\Node\Expr\Assign { - $currentStmt = $this->assignExpr->getAttribute(AttributeKey::CURRENT_STATEMENT); - if (! $currentStmt instanceof Expression) { + $currentStmt = $this->assignExpr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); + if (!$currentStmt instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $currentExpr = $currentStmt->expr; - - if ($currentExpr instanceof Assign) { + if ($currentExpr instanceof \PhpParser\Node\Expr\Assign) { return $currentExpr; } - return null; } - - private function createFactoryAssign(): Assign + private function createFactoryAssign() : \PhpParser\Node\Expr\Assign { /** @var Assign $firstAssign */ $firstAssign = $this->getFirstAssign(); $currentMethodCall = $firstAssign->expr; - - if (! $currentMethodCall instanceof MethodCall) { - throw new ShouldNotHappenException(); + if (!$currentMethodCall instanceof \PhpParser\Node\Expr\MethodCall) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $currentMethodCall = $this->resolveLastMethodCall($currentMethodCall); - // ensure var and expr are different $assignVar = $firstAssign->var; $assignExpr = $currentMethodCall; - return $this->createAssign($assignVar, $assignExpr); } - - private function resolveLastMethodCall(MethodCall $currentMethodCall): MethodCall + private function resolveLastMethodCall(\PhpParser\Node\Expr\MethodCall $currentMethodCall) : \PhpParser\Node\Expr\MethodCall { - while ($currentMethodCall->var instanceof MethodCall) { + while ($currentMethodCall->var instanceof \PhpParser\Node\Expr\MethodCall) { $currentMethodCall = $currentMethodCall->var; } - return $currentMethodCall; } } diff --git a/rules/Defluent/ValueObject/AssignAndRootExpr.php b/rules/Defluent/ValueObject/AssignAndRootExpr.php index e2ebe9c090b..04e63995a12 100644 --- a/rules/Defluent/ValueObject/AssignAndRootExpr.php +++ b/rules/Defluent/ValueObject/AssignAndRootExpr.php @@ -1,7 +1,6 @@ assignExpr = $assignExpr; $this->rootExpr = $rootExpr; $this->silentVariable = $silentVariable; $this->isFirstCallFactory = $isFirstCallFactory; } - - public function getAssignExpr(): Expr + public function getAssignExpr() : \PhpParser\Node\Expr { return $this->assignExpr; } - - public function getRootExpr(): Expr + public function getRootExpr() : \PhpParser\Node\Expr { return $this->rootExpr; } - - public function getSilentVariable(): ?Variable + public function getSilentVariable() : ?\PhpParser\Node\Expr\Variable { return $this->silentVariable; } - - public function getReturnSilentVariable(): Return_ + public function getReturnSilentVariable() : \PhpParser\Node\Stmt\Return_ { - if (! $this->silentVariable instanceof Variable) { - throw new ShouldNotHappenException(); + if (!$this->silentVariable instanceof \PhpParser\Node\Expr\Variable) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - return new Return_($this->silentVariable); + return new \PhpParser\Node\Stmt\Return_($this->silentVariable); } - - public function getCallerExpr(): Expr + public function getCallerExpr() : \PhpParser\Node\Expr { if ($this->silentVariable !== null) { return $this->silentVariable; } - return $this->assignExpr; } - - public function isFirstCallFactory(): bool + public function isFirstCallFactory() : bool { return $this->isFirstCallFactory; } - - public function getFactoryAssignVariable(): Expr + public function getFactoryAssignVariable() : \PhpParser\Node\Expr { $firstAssign = $this->getFirstAssign(); - if (! $firstAssign instanceof Assign) { + if (!$firstAssign instanceof \PhpParser\Node\Expr\Assign) { return $this->getCallerExpr(); } - return $firstAssign->var; } } diff --git a/rules/Defluent/ValueObject/AssignAndRootExprAndNodesToAdd.php b/rules/Defluent/ValueObject/AssignAndRootExprAndNodesToAdd.php index e8fdc3b9742..07dafbde716 100644 --- a/rules/Defluent/ValueObject/AssignAndRootExprAndNodesToAdd.php +++ b/rules/Defluent/ValueObject/AssignAndRootExprAndNodesToAdd.php @@ -1,42 +1,36 @@ */ private $nodesToAdd = []; - /** * @var AssignAndRootExpr */ private $assignAndRootExpr; - /** * @param array $nodesToAdd */ - public function __construct(AssignAndRootExpr $assignAndRootExpr, array $nodesToAdd) + public function __construct(\Rector\Defluent\ValueObject\AssignAndRootExpr $assignAndRootExpr, array $nodesToAdd) { $this->assignAndRootExpr = $assignAndRootExpr; $this->nodesToAdd = $nodesToAdd; } - /** * @return Expr[]|Return_[] */ - public function getNodesToAdd(): array + public function getNodesToAdd() : array { return $this->nodesToAdd; } - - public function getRootCallerExpr(): Expr + public function getRootCallerExpr() : \PhpParser\Node\Expr { return $this->assignAndRootExpr->getCallerExpr(); } diff --git a/rules/Defluent/ValueObject/FirstAssignFluentCall.php b/rules/Defluent/ValueObject/FirstAssignFluentCall.php index a949e76d9e9..ca52bf6658e 100644 --- a/rules/Defluent/ValueObject/FirstAssignFluentCall.php +++ b/rules/Defluent/ValueObject/FirstAssignFluentCall.php @@ -1,7 +1,6 @@ assignExpr = $assignExpr; $this->rootExpr = $rootExpr; $this->isFirstCallFactory = $isFirstCallFactory; $this->fluentMethodCalls = $fluentMethodCalls; } - - public function getAssignExpr(): Expr + public function getAssignExpr() : \PhpParser\Node\Expr { return $this->assignExpr; } - - public function getRootExpr(): Expr + public function getRootExpr() : \PhpParser\Node\Expr { return $this->rootExpr; } - - public function getCallerExpr(): Expr + public function getCallerExpr() : \PhpParser\Node\Expr { return $this->assignExpr; } - - public function isFirstCallFactory(): bool + public function isFirstCallFactory() : bool { return $this->isFirstCallFactory; } - - public function getFactoryAssignVariable(): Expr + public function getFactoryAssignVariable() : \PhpParser\Node\Expr { $firstAssign = $this->getFirstAssign(); - if (! $firstAssign instanceof Assign) { + if (!$firstAssign instanceof \PhpParser\Node\Expr\Assign) { return $this->assignExpr; } - return $firstAssign->var; } - /** * @return MethodCall[] */ - public function getFluentMethodCalls(): array + public function getFluentMethodCalls() : array { return $this->fluentMethodCalls->getFluentMethodCalls(); } diff --git a/rules/Defluent/ValueObject/FluentCallsKind.php b/rules/Defluent/ValueObject/FluentCallsKind.php index 0ff758ca785..d27c08f493f 100644 --- a/rules/Defluent/ValueObject/FluentCallsKind.php +++ b/rules/Defluent/ValueObject/FluentCallsKind.php @@ -1,7 +1,6 @@ rootMethodCall = $rootMethodCall; $this->fluentMethodCalls = $fluentMethodCalls; $this->lastMethodCall = $lastMethodCall; } - - public function getRootMethodCall(): MethodCall + public function getRootMethodCall() : \PhpParser\Node\Expr\MethodCall { return $this->rootMethodCall; } - /** * @return MethodCall[] */ - public function getFluentMethodCalls(): array + public function getFluentMethodCalls() : array { return $this->fluentMethodCalls; } - - public function getLastMethodCall(): MethodCall + public function getLastMethodCall() : \PhpParser\Node\Expr\MethodCall { return $this->lastMethodCall; } diff --git a/rules/Defluent/ValueObject/NormalToFluent.php b/rules/Defluent/ValueObject/NormalToFluent.php index d3d3f28726c..e27540f533b 100644 --- a/rules/Defluent/ValueObject/NormalToFluent.php +++ b/rules/Defluent/ValueObject/NormalToFluent.php @@ -1,23 +1,19 @@ class = $class; $this->methodNames = $methodNames; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - /** * @return string[] */ - public function getMethodNames(): array + public function getMethodNames() : array { return $this->methodNames; } diff --git a/rules/Defluent/ValueObjectFactory/FluentMethodCallsFactory.php b/rules/Defluent/ValueObjectFactory/FluentMethodCallsFactory.php index 24484d683b7..49d244479b8 100644 --- a/rules/Defluent/ValueObjectFactory/FluentMethodCallsFactory.php +++ b/rules/Defluent/ValueObjectFactory/FluentMethodCallsFactory.php @@ -1,57 +1,47 @@ fluentChainMethodCallNodeAnalyzer = $fluentChainMethodCallNodeAnalyzer; $this->sameClassMethodCallAnalyzer = $sameClassMethodCallAnalyzer; } - - public function createFromLastMethodCall(MethodCall $lastMethodCall): ?FluentMethodCalls + public function createFromLastMethodCall(\PhpParser\Node\Expr\MethodCall $lastMethodCall) : ?\Rector\Defluent\ValueObject\FluentMethodCalls { $chainMethodCalls = $this->fluentChainMethodCallNodeAnalyzer->collectAllMethodCallsInChain($lastMethodCall); - if (! $this->sameClassMethodCallAnalyzer->haveSingleClass($chainMethodCalls)) { + if (!$this->sameClassMethodCallAnalyzer->haveSingleClass($chainMethodCalls)) { return null; } - // we need at least 2 method call for fluent - if (count($chainMethodCalls) < 2) { + if (\count($chainMethodCalls) < 2) { return null; } - $rootMethodCall = $this->resolveRootMethodCall($chainMethodCalls); - - return new FluentMethodCalls($rootMethodCall, $chainMethodCalls, $lastMethodCall); + return new \Rector\Defluent\ValueObject\FluentMethodCalls($rootMethodCall, $chainMethodCalls, $lastMethodCall); } - /** * @param MethodCall[] $chainMethodCalls */ - private function resolveRootMethodCall(array $chainMethodCalls): MethodCall + private function resolveRootMethodCall(array $chainMethodCalls) : \PhpParser\Node\Expr\MethodCall { - $lastKey = array_key_last($chainMethodCalls); + \end($chainMethodCalls); + $lastKey = \key($chainMethodCalls); return $chainMethodCalls[$lastKey]; } } diff --git a/rules/DependencyInjection/Collector/VariablesToPropertyFetchCollection.php b/rules/DependencyInjection/Collector/VariablesToPropertyFetchCollection.php index f87effd901e..e9ef13974ac 100644 --- a/rules/DependencyInjection/Collector/VariablesToPropertyFetchCollection.php +++ b/rules/DependencyInjection/Collector/VariablesToPropertyFetchCollection.php @@ -1,27 +1,23 @@ variableNameAndType[$name] = $type; } - /** * @return Type[] */ - public function getVariableNamesAndTypes(): array + public function getVariableNamesAndTypes() : array { return $this->variableNameAndType; } diff --git a/rules/DependencyInjection/NodeFactory/InjectMethodFactory.php b/rules/DependencyInjection/NodeFactory/InjectMethodFactory.php index dca93b6cdb6..94d2bb2e7f9 100644 --- a/rules/DependencyInjection/NodeFactory/InjectMethodFactory.php +++ b/rules/DependencyInjection/NodeFactory/InjectMethodFactory.php @@ -1,7 +1,6 @@ phpDocInfoFactory = $phpDocInfoFactory; $this->propertyNaming = $propertyNaming; $this->classNaming = $classNaming; $this->typeFactory = $typeFactory; $this->nodeFactory = $nodeFactory; } - /** * @param ObjectType[] $objectTypes */ - public function createFromTypes(array $objectTypes, string $className, string $framework): ClassMethod + public function createFromTypes(array $objectTypes, string $className, string $framework) : \PhpParser\Node\Stmt\ClassMethod { $objectTypes = $this->typeFactory->uniquateTypes($objectTypes); - $shortClassName = $this->classNaming->getShortName($className); - - $methodBuilder = new MethodBuilder('inject' . $shortClassName); + $methodBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\MethodBuilder('inject' . $shortClassName); $methodBuilder->makePublic(); - foreach ($objectTypes as $objectType) { /** @var ObjectType $objectType */ $propertyName = $this->propertyNaming->fqnToVariableName($objectType); - - $paramBuilder = new ParamBuilder($propertyName); - $paramBuilder->setType(new FullyQualified($objectType->getClassName())); + $paramBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\ParamBuilder($propertyName); + $paramBuilder->setType(new \PhpParser\Node\Name\FullyQualified($objectType->getClassName())); $methodBuilder->addParam($paramBuilder); - $assign = $this->nodeFactory->createPropertyAssignment($propertyName); - $methodBuilder->addStmt($assign); } - $classMethod = $methodBuilder->getNode(); - - if ($framework === FrameworkName::SYMFONY) { + if ($framework === \Rector\Core\ValueObject\FrameworkName::SYMFONY) { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); - $phpDocInfo->addPhpDocTagNode(new PhpDocTagNode('@required', new GenericTagValueNode(''))); + $phpDocInfo->addPhpDocTagNode(new \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode('@required', new \PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode(''))); } - return $classMethod; } } diff --git a/rules/DependencyInjection/NodeManipulator/PropertyConstructorInjectionManipulator.php b/rules/DependencyInjection/NodeManipulator/PropertyConstructorInjectionManipulator.php index 31017eef6ef..88630cdf414 100644 --- a/rules/DependencyInjection/NodeManipulator/PropertyConstructorInjectionManipulator.php +++ b/rules/DependencyInjection/NodeManipulator/PropertyConstructorInjectionManipulator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->phpDocTypeChanger = $phpDocTypeChanger; $this->phpDocTagRemover = $phpDocTagRemover; $this->propertyAdder = $propertyAdder; } - - public function refactor( - Property $property, - Type $type, - DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode - ): void { + public function refactor(\PhpParser\Node\Stmt\Property $property, \PHPStan\Type\Type $type, \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode) : void + { $propertyName = $this->nodeNameResolver->getName($property); $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); - $this->phpDocTypeChanger->changeVarType($phpDocInfo, $type); $this->phpDocTagRemover->removeTagValueFromNode($phpDocInfo, $doctrineAnnotationTagValueNode); - - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - throw new ShouldNotHappenException(); + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $this->propertyAdder->addConstructorDependencyToClass($classLike, $type, $propertyName, $property->flags); } } diff --git a/rules/DependencyInjection/NodeRemover/ClassMethodNodeRemover.php b/rules/DependencyInjection/NodeRemover/ClassMethodNodeRemover.php index 08d78ec0c11..de565211f39 100644 --- a/rules/DependencyInjection/NodeRemover/ClassMethodNodeRemover.php +++ b/rules/DependencyInjection/NodeRemover/ClassMethodNodeRemover.php @@ -1,7 +1,6 @@ nodesToRemoveCollector = $nodesToRemoveCollector; $this->nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - - public function removeClassMethodIfUseless(ClassMethod $classMethod): void + public function removeClassMethodIfUseless(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { if ($classMethod->params !== []) { return; } - if ((array) $classMethod->stmts !== []) { return; } - $this->nodesToRemoveCollector->addNodeToRemove($classMethod); } - - public function removeParamFromMethodBody(ClassMethod $classMethod, Param $param): void + public function removeParamFromMethodBody(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Param $param) : void { /** @var string $paramName */ $paramName = $this->nodeNameResolver->getName($param->var); - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $classMethod->stmts, - function (Node $node) use ($paramName) { - if (! $this->isParentConstructStaticCall($node)) { - return null; - } - - /** @var StaticCall $node */ - $this->removeParamFromArgs($node, $paramName); - - if ($node->args === []) { - $this->nodesToRemoveCollector->addNodeToRemove($node); - } - + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->stmts, function (\PhpParser\Node $node) use($paramName) { + if (!$this->isParentConstructStaticCall($node)) { return null; } - ); - + /** @var StaticCall $node */ + $this->removeParamFromArgs($node, $paramName); + if ($node->args === []) { + $this->nodesToRemoveCollector->addNodeToRemove($node); + } + return null; + }); foreach ((array) $classMethod->stmts as $key => $stmt) { - if ($stmt instanceof Expression) { + if ($stmt instanceof \PhpParser\Node\Stmt\Expression) { $stmt = $stmt->expr; } - - if (! $this->isParentConstructStaticCall($stmt)) { + if (!$this->isParentConstructStaticCall($stmt)) { continue; } - /** @var StaticCall $stmt */ if ($stmt->args !== []) { continue; } - unset($classMethod->stmts[$key]); } - $this->removeParamFromAssign($classMethod, $paramName); } - - private function isParentConstructStaticCall(Node $node): bool + private function isParentConstructStaticCall(\PhpParser\Node $node) : bool { - return $this->isStaticCallNamed($node, 'parent', MethodName::CONSTRUCT); + return $this->isStaticCallNamed($node, 'parent', \Rector\Core\ValueObject\MethodName::CONSTRUCT); } - - private function removeParamFromArgs(StaticCall $staticCall, string $paramName): void + private function removeParamFromArgs(\PhpParser\Node\Expr\StaticCall $staticCall, string $paramName) : void { foreach ($staticCall->args as $key => $arg) { - if (! $this->nodeNameResolver->isName($arg->value, $paramName)) { + if (!$this->nodeNameResolver->isName($arg->value, $paramName)) { continue; } - unset($staticCall->args[$key]); } } - - private function removeParamFromAssign(ClassMethod $classMethod, string $paramName): void + private function removeParamFromAssign(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $paramName) : void { foreach ((array) $classMethod->stmts as $key => $stmt) { - if ($stmt instanceof Expression) { + if ($stmt instanceof \PhpParser\Node\Stmt\Expression) { $stmt = $stmt->expr; } - - if (! $stmt instanceof Assign) { + if (!$stmt instanceof \PhpParser\Node\Expr\Assign) { continue; } - - if (! $stmt->expr instanceof Variable) { + if (!$stmt->expr instanceof \PhpParser\Node\Expr\Variable) { continue; } - - if (! $this->nodeNameResolver->isName($stmt->expr, $paramName)) { + if (!$this->nodeNameResolver->isName($stmt->expr, $paramName)) { continue; } - unset($classMethod->stmts[$key]); } } - - private function isStaticCallNamed(Node $node, string $class, string $method): bool + private function isStaticCallNamed(\PhpParser\Node $node, string $class, string $method) : bool { - if (! $node instanceof StaticCall) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\StaticCall) { + return \false; } - - if (! $this->nodeNameResolver->isName($node->class, $class)) { - return false; + if (!$this->nodeNameResolver->isName($node->class, $class)) { + return \false; } - return $this->nodeNameResolver->isName($node->name, $method); } } diff --git a/rules/DependencyInjection/Rector/ClassMethod/AddMethodParentCallRector.php b/rules/DependencyInjection/Rector/ClassMethod/AddMethodParentCallRector.php index f07c5ec26ba..9df6c147493 100644 --- a/rules/DependencyInjection/Rector/ClassMethod/AddMethodParentCallRector.php +++ b/rules/DependencyInjection/Rector/ClassMethod/AddMethodParentCallRector.php @@ -1,7 +1,6 @@ */ private $methodByParentTypes = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Add method parent call, in case new parent method is added', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add method parent call, in case new parent method is added', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SunshineCommand extends ParentClassWithNewConstructor { public function __construct() @@ -47,8 +39,7 @@ class SunshineCommand extends ParentClassWithNewConstructor } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SunshineCommand extends ParentClassWithNewConstructor { public function __construct() @@ -59,99 +50,73 @@ class SunshineCommand extends ParentClassWithNewConstructor } } CODE_SAMPLE - , - [ - self::METHODS_BY_PARENT_TYPES => [ - 'ParentClassWithNewConstructor' => MethodName::CONSTRUCT, - ], - ] - ), - ] - ); +, [self::METHODS_BY_PARENT_TYPES => ['ParentClassWithNewConstructor' => \Rector\Core\ValueObject\MethodName::CONSTRUCT]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { return null; } - /** @var string $className */ - $className = $node->getAttribute(AttributeKey::CLASS_NAME); - + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); foreach ($this->methodByParentTypes as $type => $method) { - if (! $this->isObjectType($classLike, new ObjectType($type))) { + if (!$this->isObjectType($classLike, new \PHPStan\Type\ObjectType($type))) { continue; } - // not itself if ($className === $type) { continue; } - if ($this->shouldSkipMethod($node, $method)) { continue; } - $node->stmts[] = $this->createParentStaticCall($method); - return $node; } - return null; } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->methodByParentTypes = $configuration[self::METHODS_BY_PARENT_TYPES] ?? []; } - - private function shouldSkipMethod(ClassMethod $classMethod, string $method): bool + private function shouldSkipMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $method) : bool { - if (! $this->isName($classMethod, $method)) { - return true; + if (!$this->isName($classMethod, $method)) { + return \true; } - return $this->hasParentCallOfMethod($classMethod, $method); } - - private function createParentStaticCall(string $method): Expression + private function createParentStaticCall(string $method) : \PhpParser\Node\Stmt\Expression { $staticCall = $this->nodeFactory->createStaticCall('parent', $method); - return new Expression($staticCall); + return new \PhpParser\Node\Stmt\Expression($staticCall); } - /** * Looks for "parent:: */ - private function hasParentCallOfMethod(ClassMethod $classMethod, string $method): bool + private function hasParentCallOfMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $method) : bool { - return (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (Node $node) use ( - $method - ): bool { - if (! $node instanceof StaticCall) { - return false; + return (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (\PhpParser\Node $node) use($method) : bool { + if (!$node instanceof \PhpParser\Node\Expr\StaticCall) { + return \false; } - - if (! $this->isName($node->class, 'parent')) { - return false; + if (!$this->isName($node->class, 'parent')) { + return \false; } - return $this->isName($node->name, $method); }); } diff --git a/rules/DependencyInjection/Rector/Class_/ActionInjectionToConstructorInjectionRector.php b/rules/DependencyInjection/Rector/Class_/ActionInjectionToConstructorInjectionRector.php index ee29eec68a2..6d63fbef80b 100644 --- a/rules/DependencyInjection/Rector/Class_/ActionInjectionToConstructorInjectionRector.php +++ b/rules/DependencyInjection/Rector/Class_/ActionInjectionToConstructorInjectionRector.php @@ -1,7 +1,6 @@ variablesToPropertyFetchCollection = $variablesToPropertyFetchCollection; $this->applicationServiceMapProvider = $applicationServiceMapProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Turns action injection in Controllers to constructor injection', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns action injection in Controllers to constructor injection', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeController { public function default(ProductRepository $productRepository) @@ -53,8 +42,7 @@ final class SomeController } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeController { /** @@ -72,72 +60,56 @@ final class SomeController } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, '*Controller')) { + if (!$this->isName($node, '*Controller')) { return null; } - foreach ($node->getMethods() as $classMethod) { $this->processClassMethod($node, $classMethod); } - return $node; } - - private function processClassMethod(Class_ $class, ClassMethod $classMethod): void + private function processClassMethod(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt\ClassMethod $classMethod) : void { foreach ($classMethod->params as $key => $paramNode) { - if (! $this->isActionInjectedParamNode($paramNode)) { + if (!$this->isActionInjectedParamNode($paramNode)) { continue; } - $paramNodeType = $this->getObjectType($paramNode); - /** @var string $paramName */ $paramName = $this->getName($paramNode->var); $this->addConstructorDependencyToClass($class, $paramNodeType, $paramName); - $this->nodeRemover->removeParam($classMethod, $key); - $this->variablesToPropertyFetchCollection->addVariableNameAndType($paramName, $paramNodeType); } } - - private function isActionInjectedParamNode(Param $param): bool + private function isActionInjectedParamNode(\PhpParser\Node\Param $param) : bool { if ($param->type === null) { - return false; + return \false; } - $typehint = $this->getName($param->type); if ($typehint === null) { - return false; + return \false; } - $paramStaticType = $this->getObjectType($param); - if (! $paramStaticType instanceof ObjectType) { - return false; + if (!$paramStaticType instanceof \PHPStan\Type\ObjectType) { + return \false; } - $serviceMap = $this->applicationServiceMapProvider->provide(); - return $serviceMap->hasService($paramStaticType->getClassName()); } } diff --git a/rules/DependencyInjection/Rector/Class_/MultiParentingToAbstractDependencyRector.php b/rules/DependencyInjection/Rector/Class_/MultiParentingToAbstractDependencyRector.php index 460314bb39c..dc042323c3e 100644 --- a/rules/DependencyInjection/Rector/Class_/MultiParentingToAbstractDependencyRector.php +++ b/rules/DependencyInjection/Rector/Class_/MultiParentingToAbstractDependencyRector.php @@ -1,7 +1,6 @@ injectMethodFactory = $injectMethodFactory; $this->classMethodNodeRemover = $classMethodNodeRemover; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->classInsertManipulator = $classInsertManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Move dependency passed to all children to parent as @inject/@required dependency', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Move dependency passed to all children to parent as @inject/@required dependency', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' abstract class AbstractParentClass { private $someDependency; @@ -103,8 +86,7 @@ class SecondChild extends AbstractParentClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' abstract class AbstractParentClass { /** @@ -122,176 +104,130 @@ class SecondChild extends AbstractParentClass { } CODE_SAMPLE -, - [ - self::FRAMEWORK => FrameworkName::NETTE, - ] - ), - ] - ); +, [self::FRAMEWORK => \Rector\Core\ValueObject\FrameworkName::NETTE])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->isAbstract()) { + if (!$node->isAbstract()) { return null; } - /** @var string|null $className */ - $className = $node->getAttribute(AttributeKey::CLASS_NAME); + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { return null; } - $childrenClasses = $this->nodeRepository->findChildrenOfClass($className); - if (count($childrenClasses) < 2) { + if (\count($childrenClasses) < 2) { return null; } - - $classMethod = $node->getMethod(MethodName::CONSTRUCT); - if (! $classMethod instanceof ClassMethod) { + $classMethod = $node->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - $abstractClassConstructorParamTypes = $this->resolveConstructorParamClassTypes($node); - // process $this->injectObjectTypes = []; - foreach ($childrenClasses as $childClass) { - $constructorClassMethod = $childClass->getMethod(MethodName::CONSTRUCT); - if (! $constructorClassMethod instanceof ClassMethod) { + $constructorClassMethod = $childClass->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructorClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { continue; } - $this->refactorChildConstructorClassMethod($constructorClassMethod, $abstractClassConstructorParamTypes); - $this->classMethodNodeRemover->removeClassMethodIfUseless($constructorClassMethod); } - // 2. remove from abstract class $this->clearAbstractClassConstructor($classMethod); - // 3. add inject*/@required to abstract property $this->addInjectOrRequiredClassMethod($node); - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->framework = $configuration[self::FRAMEWORK]; } - /** * @return ObjectType[] */ - private function resolveConstructorParamClassTypes(Class_ $class): array + private function resolveConstructorParamClassTypes(\PhpParser\Node\Stmt\Class_ $class) : array { - $constructorClassMethod = $class->getMethod(MethodName::CONSTRUCT); - if (! $constructorClassMethod instanceof ClassMethod) { + $constructorClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructorClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return []; } - $objectTypes = []; foreach ($constructorClassMethod->getParams() as $param) { $paramType = $this->getObjectType($param); $paramType = $this->popFirstObjectTypeFromUnionType($paramType); - - if (! $paramType instanceof ObjectType) { + if (!$paramType instanceof \PHPStan\Type\ObjectType) { continue; } - $objectTypes[] = $paramType; } - return $objectTypes; } - /** * @param ObjectType[] $abstractClassConstructorParamTypes */ - private function refactorChildConstructorClassMethod( - ClassMethod $classMethod, - array $abstractClassConstructorParamTypes - ): void { + private function refactorChildConstructorClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, array $abstractClassConstructorParamTypes) : void + { foreach ($classMethod->getParams() as $key => $param) { $paramType = $this->getStaticType($param); $paramType = $this->popFirstObjectTypeFromUnionType($paramType); - - if (! $paramType instanceof ObjectType) { + if (!$paramType instanceof \PHPStan\Type\ObjectType) { continue; } - - if (! $this->nodeTypeResolver->isSameObjectTypes($paramType, $abstractClassConstructorParamTypes)) { + if (!$this->nodeTypeResolver->isSameObjectTypes($paramType, $abstractClassConstructorParamTypes)) { continue; } - $this->nodeRemover->removeParam($classMethod, $key); $this->classMethodNodeRemover->removeParamFromMethodBody($classMethod, $param); - $this->injectObjectTypes[] = $paramType; } } - - private function clearAbstractClassConstructor(ClassMethod $classMethod): void + private function clearAbstractClassConstructor(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { foreach ($classMethod->getParams() as $key => $param) { - if (! $this->nodeTypeResolver->isObjectTypes($param, $this->injectObjectTypes)) { + if (!$this->nodeTypeResolver->isObjectTypes($param, $this->injectObjectTypes)) { continue; } - unset($classMethod->params[$key]); $this->classMethodNodeRemover->removeParamFromMethodBody($classMethod, $param); } - $this->classMethodNodeRemover->removeClassMethodIfUseless($classMethod); } - - private function addInjectOrRequiredClassMethod(Class_ $class): void + private function addInjectOrRequiredClassMethod(\PhpParser\Node\Stmt\Class_ $class) : void { /** @var string $className */ - $className = $class->getAttribute(AttributeKey::CLASS_NAME); - + $className = $class->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($this->injectObjectTypes === []) { return; } - - $injectClassMethod = $this->injectMethodFactory->createFromTypes( - $this->injectObjectTypes, - $className, - $this->framework - ); - + $injectClassMethod = $this->injectMethodFactory->createFromTypes($this->injectObjectTypes, $className, $this->framework); $this->classInsertManipulator->addAsFirstMethod($class, $injectClassMethod); } - - private function popFirstObjectTypeFromUnionType(Type $paramType): Type + private function popFirstObjectTypeFromUnionType(\PHPStan\Type\Type $paramType) : \PHPStan\Type\Type { - if (! $paramType instanceof UnionType) { + if (!$paramType instanceof \PHPStan\Type\UnionType) { return $paramType; } - foreach ($paramType->getTypes() as $unionedType) { - if ($unionedType instanceof ObjectType) { + if ($unionedType instanceof \PHPStan\Type\ObjectType) { return $unionedType; } } - return $paramType; } } diff --git a/rules/DependencyInjection/Rector/Variable/ReplaceVariableByPropertyFetchRector.php b/rules/DependencyInjection/Rector/Variable/ReplaceVariableByPropertyFetchRector.php index 9a83fb47370..c2d35206993 100644 --- a/rules/DependencyInjection/Rector/Variable/ReplaceVariableByPropertyFetchRector.php +++ b/rules/DependencyInjection/Rector/Variable/ReplaceVariableByPropertyFetchRector.php @@ -1,10 +1,9 @@ variablesToPropertyFetchCollection = $variablesToPropertyFetchCollection; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Turns variable in controller action to property fetch, as follow up to action injection variable to property change.', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns variable in controller action to property fetch, as follow up to action injection variable to property change.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeController { /** @@ -55,8 +47,7 @@ final class SomeController } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeController { /** @@ -75,61 +66,49 @@ final class SomeController } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Variable::class]; + return [\PhpParser\Node\Expr\Variable::class]; } - /** * @param Variable $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isInControllerActionMethod($node)) { + if (!$this->isInControllerActionMethod($node)) { return null; } - foreach ($this->variablesToPropertyFetchCollection->getVariableNamesAndTypes() as $name => $type) { - if (! $this->isName($node, $name)) { + if (!$this->isName($node, $name)) { continue; } - /** @var ObjectType $type */ - if (! $this->isObjectType($node, $type)) { + if (!$this->isObjectType($node, $type)) { continue; } - return $this->nodeFactory->createPropertyFetch('this', $name); } - return null; } - - private function isInControllerActionMethod(Variable $variable): bool + private function isInControllerActionMethod(\PhpParser\Node\Expr\Variable $variable) : bool { /** @var string|null $className */ - $className = $variable->getAttribute(AttributeKey::CLASS_NAME); + $className = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { - return false; + return \false; } - - if (! Strings::endsWith($className, 'Controller')) { - return false; + if (!\RectorPrefix20210509\Nette\Utils\Strings::endsWith($className, 'Controller')) { + return \false; } - - $classMethod = $variable->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { - return false; + $classMethod = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - // is probably in controller action return $classMethod->isPublic(); } diff --git a/rules/DowngradePhp53/Rector/Dir/DirConstToFileConstRector.php b/rules/DowngradePhp53/Rector/Dir/DirConstToFileConstRector.php index 87b735b437e..d78627e3e84 100644 --- a/rules/DowngradePhp53/Rector/Dir/DirConstToFileConstRector.php +++ b/rules/DowngradePhp53/Rector/Dir/DirConstToFileConstRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Dir::class]; + return [\PhpParser\Node\Scalar\MagicConst\Dir::class]; } - /** * @param Dir $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - return $this->nodeFactory->createFuncCall('dirname', [new File()]); + return $this->nodeFactory->createFuncCall('dirname', [new \PhpParser\Node\Scalar\MagicConst\File()]); } } diff --git a/rules/DowngradePhp70/NodeFactory/ClassFromAnonymousFactory.php b/rules/DowngradePhp70/NodeFactory/ClassFromAnonymousFactory.php index 3a727006727..b4c94842477 100644 --- a/rules/DowngradePhp70/NodeFactory/ClassFromAnonymousFactory.php +++ b/rules/DowngradePhp70/NodeFactory/ClassFromAnonymousFactory.php @@ -1,21 +1,13 @@ $newClass->flags, - 'extends' => $newClass->extends, - 'implements' => $newClass->implements, - 'stmts' => $newClass->stmts, - 'attrGroups' => $newClass->attrGroups, - ]); + return new \PhpParser\Node\Stmt\Class_($className, ['flags' => $newClass->flags, 'extends' => $newClass->extends, 'implements' => $newClass->implements, 'stmts' => $newClass->stmts, 'attrGroups' => $newClass->attrGroups]); } } diff --git a/rules/DowngradePhp70/Rector/Coalesce/DowngradeNullCoalesceRector.php b/rules/DowngradePhp70/Rector/Coalesce/DowngradeNullCoalesceRector.php index 8d9b4eb327f..e23a279f64a 100644 --- a/rules/DowngradePhp70/Rector/Coalesce/DowngradeNullCoalesceRector.php +++ b/rules/DowngradePhp70/Rector/Coalesce/DowngradeNullCoalesceRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Coalesce::class]; + return [\PhpParser\Node\Expr\BinaryOp\Coalesce::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change null coalesce to isset ternary check', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change null coalesce to isset ternary check', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $username = $_GET['user'] ?? 'nobody'; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param Coalesce $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $if = $node->left; $else = $node->right; - - if ($if instanceof Variable || $if instanceof ArrayDimFetch) { - $cond = new Isset_([$if]); + if ($if instanceof \PhpParser\Node\Expr\Variable || $if instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + $cond = new \PhpParser\Node\Expr\Isset_([$if]); } else { - $cond = new NotIdentical($if, $this->nodeFactory->createNull()); + $cond = new \PhpParser\Node\Expr\BinaryOp\NotIdentical($if, $this->nodeFactory->createNull()); } - - return new Ternary($cond, $if, $else); + return new \PhpParser\Node\Expr\Ternary($cond, $if, $else); } } diff --git a/rules/DowngradePhp70/Rector/Declare_/DowngradeStrictTypeDeclarationRector.php b/rules/DowngradePhp70/Rector/Declare_/DowngradeStrictTypeDeclarationRector.php index 977fa938150..b616f0b18ea 100644 --- a/rules/DowngradePhp70/Rector/Declare_/DowngradeStrictTypeDeclarationRector.php +++ b/rules/DowngradePhp70/Rector/Declare_/DowngradeStrictTypeDeclarationRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Declare_::class]; + return [\PhpParser\Node\Stmt\Declare_::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove the declare(strict_types=1)', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove the declare(strict_types=1)', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' declare(strict_types=1); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param Declare_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $this->removeNode($node); return $node; } - - private function shouldSkip(Declare_ $declare): bool + private function shouldSkip(\PhpParser\Node\Stmt\Declare_ $declare) : bool { $declares = $declare->declares; - foreach ($declares as $declare) { if ($this->isName($declare->key, 'strict_types')) { - return false; + return \false; } } - - return true; + return \true; } } diff --git a/rules/DowngradePhp70/Rector/Expression/DowngradeDefineArrayConstantRector.php b/rules/DowngradePhp70/Rector/Expression/DowngradeDefineArrayConstantRector.php index ffcef5cdbe4..fc26e81ed0c 100644 --- a/rules/DowngradePhp70/Rector/Expression/DowngradeDefineArrayConstantRector.php +++ b/rules/DowngradePhp70/Rector/Expression/DowngradeDefineArrayConstantRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Expression::class]; + return [\PhpParser\Node\Stmt\Expression::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change array contant definition via define to const', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change array contant definition via define to const', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' define('ANIMALS', [ 'dog', 'cat', 'bird' ]); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' const ANIMALS = [ 'dog', 'cat', 'bird' ]; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param Expression $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof FuncCall) { + if (!$node->expr instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - $funcCall = $node->expr; - if ($this->shouldSkip($funcCall)) { return null; } - /** @var String_ $arg0 */ $arg0 = $funcCall->args[0]->value; $arg0Value = $arg0->value; - /** @var Array_ $arg1Value */ $arg1Value = $funcCall->args[1]->value; - - return new Node\Stmt\Const_([new Const_($arg0Value, $arg1Value)]); + return new \PhpParser\Node\Stmt\Const_([new \PhpParser\Node\Const_($arg0Value, $arg1Value)]); } - - private function shouldSkip(FuncCall $funcCall): bool + private function shouldSkip(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - if (! $this->isName($funcCall, 'define')) { - return true; + if (!$this->isName($funcCall, 'define')) { + return \true; } - $args = $funcCall->args; - if (! $args[0]->value instanceof String_) { - return true; + if (!$args[0]->value instanceof \PhpParser\Node\Scalar\String_) { + return \true; } - - if (! $args[1]->value instanceof Array_) { - return true; + if (!$args[1]->value instanceof \PhpParser\Node\Expr\Array_) { + return \true; } - - return (bool) $this->betterNodeFinder->findParentTypes($funcCall, [ClassMethod::class, Function_::class]); + return (bool) $this->betterNodeFinder->findParentTypes($funcCall, [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class]); } } diff --git a/rules/DowngradePhp70/Rector/FuncCall/DowngradeSessionStartArrayOptionsRector.php b/rules/DowngradePhp70/Rector/FuncCall/DowngradeSessionStartArrayOptionsRector.php index 4a8665dd4d2..0c7368e37b7 100644 --- a/rules/DowngradePhp70/Rector/FuncCall/DowngradeSessionStartArrayOptionsRector.php +++ b/rules/DowngradePhp70/Rector/FuncCall/DowngradeSessionStartArrayOptionsRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Move array option of session_start($options) to before statement\'s ini_set()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Move array option of session_start($options) to before statement\'s ini_set()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' session_start([ 'cache_limiter' => 'private', ]); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' ini_set('session.cache_limiter', 'private'); session_start(); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - - $currentStatement = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); - + $currentStatement = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); /** @var Array_ $options */ $options = $node->args[0]->value; - foreach ($options->items as $option) { - if (! $option instanceof ArrayItem) { + if (!$option instanceof \PhpParser\Node\Expr\ArrayItem) { return null; } - - if (! $option->key instanceof String_) { + if (!$option->key instanceof \PhpParser\Node\Scalar\String_) { return null; } - - if (! $this->valueResolver->isTrueOrFalse($option->value) && ! $option->value instanceof String_) { + if (!$this->valueResolver->isTrueOrFalse($option->value) && !$option->value instanceof \PhpParser\Node\Scalar\String_) { return null; } - - $sessionKey = new String_('session.' . $option->key->value); - $funcName = new Name('ini_set'); - $iniSet = new FuncCall($funcName, [new Arg($sessionKey), new Arg($option->value)]); - - $this->addNodeBeforeNode(new Expression($iniSet), $currentStatement); + $sessionKey = new \PhpParser\Node\Scalar\String_('session.' . $option->key->value); + $funcName = new \PhpParser\Node\Name('ini_set'); + $iniSet = new \PhpParser\Node\Expr\FuncCall($funcName, [new \PhpParser\Node\Arg($sessionKey), new \PhpParser\Node\Arg($option->value)]); + $this->addNodeBeforeNode(new \PhpParser\Node\Stmt\Expression($iniSet), $currentStatement); } - unset($node->args[0]); return $node; } - - private function shouldSkip(FuncCall $funcCall): bool + private function shouldSkip(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - if (! $this->isName($funcCall, 'session_start')) { - return true; + if (!$this->isName($funcCall, 'session_start')) { + return \true; } - - if (! isset($funcCall->args[0])) { - return true; + if (!isset($funcCall->args[0])) { + return \true; } - - return ! $funcCall->args[0]->value instanceof Array_; + return !$funcCall->args[0]->value instanceof \PhpParser\Node\Expr\Array_; } } diff --git a/rules/DowngradePhp70/Rector/FunctionLike/DowngradeScalarTypeDeclarationRector.php b/rules/DowngradePhp70/Rector/FunctionLike/DowngradeScalarTypeDeclarationRector.php index f8ea9ea6cf0..130339f6ccc 100644 --- a/rules/DowngradePhp70/Rector/FunctionLike/DowngradeScalarTypeDeclarationRector.php +++ b/rules/DowngradePhp70/Rector/FunctionLike/DowngradeScalarTypeDeclarationRector.php @@ -1,7 +1,6 @@ phpDocFromTypeDeclarationDecorator = $phpDocFromTypeDeclarationDecorator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, ClassMethod::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove the type params and return type, add @param and @return tags instead', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove the type params and return type, add @param and @return tags instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run(string $input): string @@ -66,8 +57,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -79,93 +69,70 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param Function_|ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $recastAssigns = []; foreach ($node->params as $param) { if ($param->type === null) { continue; } - - $this->phpDocFromTypeDeclarationDecorator->decorateParam( - $param, - $node, - [StringType::class, IntegerType::class, BooleanType::class, FloatType::class] - ); - + $this->phpDocFromTypeDeclarationDecorator->decorateParam($param, $node, [\PHPStan\Type\StringType::class, \PHPStan\Type\IntegerType::class, \PHPStan\Type\BooleanType::class, \PHPStan\Type\FloatType::class]); $recastAssign = $this->resolveRecastAssign($param, $node); - if ($recastAssign instanceof Expression) { + if ($recastAssign instanceof \PhpParser\Node\Stmt\Expression) { $recastAssigns[] = $recastAssign; } } - if ($recastAssigns !== []) { - $node->stmts = array_merge($recastAssigns, (array) $node->stmts); + $node->stmts = \array_merge($recastAssigns, (array) $node->stmts); } - - if (! $this->phpDocFromTypeDeclarationDecorator->decorate($node)) { + if (!$this->phpDocFromTypeDeclarationDecorator->decorate($node)) { return null; } - return $node; } - /** * @param Function_|ClassMethod $functionLike */ - private function resolveRecastAssign(Param $param, FunctionLike $functionLike): ?Expression + private function resolveRecastAssign(\PhpParser\Node\Param $param, \PhpParser\Node\FunctionLike $functionLike) : ?\PhpParser\Node\Stmt\Expression { if ($functionLike->stmts === null) { return null; } - if ($functionLike->stmts === []) { return null; } - // add possible object with __toString() re-type to keep original behavior // @see https://twitter.com/VotrubaT/status/1390974218108538887 - /** @var string $paramName */ $paramName = $this->getName($param->var); - $variable = new Variable($paramName); - + $variable = new \PhpParser\Node\Expr\Variable($paramName); $paramType = $this->getStaticType($param); $recastedVariable = $this->recastVariabletIfScalarType($variable, $paramType); - if (! $recastedVariable instanceof Cast) { + if (!$recastedVariable instanceof \PhpParser\Node\Expr\Cast) { return null; } - - $assign = new Assign($variable, $recastedVariable); - return new Expression($assign); + $assign = new \PhpParser\Node\Expr\Assign($variable, $recastedVariable); + return new \PhpParser\Node\Stmt\Expression($assign); } - - private function recastVariabletIfScalarType(Variable $variable, Type $type): ?Cast + private function recastVariabletIfScalarType(\PhpParser\Node\Expr\Variable $variable, \PHPStan\Type\Type $type) : ?\PhpParser\Node\Expr\Cast { - if ($type instanceof StringType) { - return new String_($variable); + if ($type instanceof \PHPStan\Type\StringType) { + return new \PhpParser\Node\Expr\Cast\String_($variable); } - - if ($type instanceof IntegerType) { - return new Int_($variable); + if ($type instanceof \PHPStan\Type\IntegerType) { + return new \PhpParser\Node\Expr\Cast\Int_($variable); } - - if ($type instanceof FloatType) { - return new Double($variable); + if ($type instanceof \PHPStan\Type\FloatType) { + return new \PhpParser\Node\Expr\Cast\Double($variable); } - - if ($type instanceof BooleanType) { - return new Bool_($variable); + if ($type instanceof \PHPStan\Type\BooleanType) { + return new \PhpParser\Node\Expr\Cast\Bool_($variable); } - return null; } } diff --git a/rules/DowngradePhp70/Rector/GroupUse/SplitGroupedUseImportsRector.php b/rules/DowngradePhp70/Rector/GroupUse/SplitGroupedUseImportsRector.php index 8b59cd744fe..9a0e3126332 100644 --- a/rules/DowngradePhp70/Rector/GroupUse/SplitGroupedUseImportsRector.php +++ b/rules/DowngradePhp70/Rector/GroupUse/SplitGroupedUseImportsRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [GroupUse::class]; + return [\PhpParser\Node\Stmt\GroupUse::class]; } - /** * @param GroupUse $node * @return Use_[]|null */ - public function refactor(Node $node) + public function refactor(\PhpParser\Node $node) { $prefix = $this->getName($node->prefix); - $uses = []; foreach ($node->uses as $useUse) { - $useUse->name = new Name($prefix . '\\' . $this->getName($useUse->name)); - $uses[] = new Use_([$useUse], $node->type); + $useUse->name = new \PhpParser\Node\Name($prefix . '\\' . $this->getName($useUse->name)); + $uses[] = new \PhpParser\Node\Stmt\Use_([$useUse], $node->type); } - return $uses; } } diff --git a/rules/DowngradePhp70/Rector/New_/DowngradeAnonymousClassRector.php b/rules/DowngradePhp70/Rector/New_/DowngradeAnonymousClassRector.php index 5e1c2db2360..16d122cd234 100644 --- a/rules/DowngradePhp70/Rector/New_/DowngradeAnonymousClassRector.php +++ b/rules/DowngradePhp70/Rector/New_/DowngradeAnonymousClassRector.php @@ -1,7 +1,6 @@ classAnalyzer = $classAnalyzer; $this->classFromAnonymousFactory = $classFromAnonymousFactory; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [New_::class]; + return [\PhpParser\Node\Expr\New_::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove anonymous class', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove anonymous class', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -74,8 +60,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class Anonymous { public function execute() @@ -90,21 +75,17 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param Node[] $nodes * @return Node[]|null */ - public function beforeTraverse(array $nodes): ?array + public function beforeTraverse(array $nodes) : ?array { $this->classes = []; return parent::beforeTraverse($nodes); } - /** * @param Node[] $nodes * @return Node[] @@ -114,33 +95,26 @@ CODE_SAMPLE if ($this->classes === []) { return $nodes; } - - return array_merge($nodes, $this->classes); + return \array_merge($nodes, $this->classes); } - /** * @param New_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->classAnalyzer->isAnonymousClass($node->class)) { + if (!$this->classAnalyzer->isAnonymousClass($node->class)) { return null; } - - if (! $node->class instanceof Class_) { + if (!$node->class instanceof \PhpParser\Node\Stmt\Class_) { return null; } - $className = $this->createAnonymousClassName(); $this->classes[] = $this->classFromAnonymousFactory->create($className, $node->class); - - return new New_(new Name($className), $node->args); + return new \PhpParser\Node\Expr\New_(new \PhpParser\Node\Name($className), $node->args); } - - private function createAnonymousClassName(): string + private function createAnonymousClassName() : string { $fileInfo = $this->file->getSmartFileInfo(); - - return self::ANONYMOUS_CLASS_PREFIX . md5($fileInfo->getRealPath()) . '__' . count($this->classes); + return self::ANONYMOUS_CLASS_PREFIX . \md5($fileInfo->getRealPath()) . '__' . \count($this->classes); } } diff --git a/rules/DowngradePhp70/Rector/Spaceship/DowngradeSpaceshipRector.php b/rules/DowngradePhp70/Rector/Spaceship/DowngradeSpaceshipRector.php index 5964a7fcffa..edc878344cc 100644 --- a/rules/DowngradePhp70/Rector/Spaceship/DowngradeSpaceshipRector.php +++ b/rules/DowngradePhp70/Rector/Spaceship/DowngradeSpaceshipRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Spaceship::class]; + return [\PhpParser\Node\Expr\BinaryOp\Spaceship::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change spaceship with check equal, and ternary to result 0, -1, 1', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change spaceship with check equal, and ternary to result 0, -1, 1', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' return $a <=> $b; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $battleShipcompare = function ($left, $right) { if ($left === $right) { return 0; @@ -67,66 +57,48 @@ $battleShipcompare = function ($left, $right) { }; return $battleShipcompare($a, $b); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param Spaceship $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $leftVariableParam = new Variable('left'); - $rightVariableParam = new Variable('right'); - - $anonymousFunction = new Closure(); - $leftParam = new Param($leftVariableParam); - $rightParam = new Param($rightVariableParam); + $leftVariableParam = new \PhpParser\Node\Expr\Variable('left'); + $rightVariableParam = new \PhpParser\Node\Expr\Variable('right'); + $anonymousFunction = new \PhpParser\Node\Expr\Closure(); + $leftParam = new \PhpParser\Node\Param($leftVariableParam); + $rightParam = new \PhpParser\Node\Param($rightVariableParam); $anonymousFunction->params = [$leftParam, $rightParam]; - - $if = $this->ifManipulator->createIfExpr( - new Identical($leftVariableParam, $rightVariableParam), - new Return_(new LNumber(0)) - ); + $if = $this->ifManipulator->createIfExpr(new \PhpParser\Node\Expr\BinaryOp\Identical($leftVariableParam, $rightVariableParam), new \PhpParser\Node\Stmt\Return_(new \PhpParser\Node\Scalar\LNumber(0))); $anonymousFunction->stmts[0] = $if; - - $smaller = new Smaller($leftVariableParam, $rightVariableParam); - $ternaryIf = new LNumber(-1); - $ternaryElse = new LNumber(1); - $ternary = new Ternary($smaller, $ternaryIf, $ternaryElse); - $anonymousFunction->stmts[1] = new Return_($ternary); - - $currentStatement = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); + $smaller = new \PhpParser\Node\Expr\BinaryOp\Smaller($leftVariableParam, $rightVariableParam); + $ternaryIf = new \PhpParser\Node\Scalar\LNumber(-1); + $ternaryElse = new \PhpParser\Node\Scalar\LNumber(1); + $ternary = new \PhpParser\Node\Expr\Ternary($smaller, $ternaryIf, $ternaryElse); + $anonymousFunction->stmts[1] = new \PhpParser\Node\Stmt\Return_($ternary); + $currentStatement = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); $variableAssign = $this->getVariableAssign($currentStatement); $assignExpression = $this->getAssignExpression($anonymousFunction, $variableAssign); $this->addNodeBeforeNode($assignExpression, $currentStatement); - - return new FuncCall($variableAssign, [new Arg($node->left), new Arg($node->right)]); + return new \PhpParser\Node\Expr\FuncCall($variableAssign, [new \PhpParser\Node\Arg($node->left), new \PhpParser\Node\Arg($node->right)]); } - - private function getAssignExpression(Closure $closure, Variable $variable): Expression + private function getAssignExpression(\PhpParser\Node\Expr\Closure $closure, \PhpParser\Node\Expr\Variable $variable) : \PhpParser\Node\Stmt\Expression { - return new Expression(new Assign($variable, $closure)); + return new \PhpParser\Node\Stmt\Expression(new \PhpParser\Node\Expr\Assign($variable, $closure)); } - - private function getVariableAssign(Stmt $stmt, string $variableName = 'battleShipcompare'): Variable + private function getVariableAssign(\PhpParser\Node\Stmt $stmt, string $variableName = 'battleShipcompare') : \PhpParser\Node\Expr\Variable { - $variable = new Variable($variableName); - - $isFoundPrevious = (bool) $this->betterNodeFinder->findFirstPreviousOfNode($stmt, function (Node $node) use ( - $variable - ): bool { - return $node instanceof Variable && $this->nodeComparator->areNodesEqual($node, $variable); + $variable = new \PhpParser\Node\Expr\Variable($variableName); + $isFoundPrevious = (bool) $this->betterNodeFinder->findFirstPreviousOfNode($stmt, function (\PhpParser\Node $node) use($variable) : bool { + return $node instanceof \PhpParser\Node\Expr\Variable && $this->nodeComparator->areNodesEqual($node, $variable); }); - $count = 0; if ($isFoundPrevious) { ++$count; $variableName .= (string) $count; return $this->getVariableAssign($stmt, $variableName); } - return $variable; } } diff --git a/rules/DowngradePhp70/Rector/String_/DowngradeGeneratedScalarTypesRector.php b/rules/DowngradePhp70/Rector/String_/DowngradeGeneratedScalarTypesRector.php index a05a889bbd2..06e946cd4fa 100644 --- a/rules/DowngradePhp70/Rector/String_/DowngradeGeneratedScalarTypesRector.php +++ b/rules/DowngradePhp70/Rector/String_/DowngradeGeneratedScalarTypesRector.php @@ -1,10 +1,9 @@ phpRectors = [$downgradeScalarTypeDeclarationRector, $downgradeVoidTypeDeclarationRector]; $this->inlineCodeParser = $inlineCodeParser; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Refactor scalar types in PHP code in string snippets, e.g. generated container code from symfony/dependency-injection', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Refactor scalar types in PHP code in string snippets, e.g. generated container code from symfony/dependency-injection', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $code = <<<'EOF' public function getParameter(string $name) { @@ -70,9 +57,7 @@ $code = <<<'EOF' } EOF; CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $code = <<<'EOF' /** * @param string @@ -83,92 +68,74 @@ $code = <<<'EOF' } EOF; CODE_SAMPLE - ), - - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [String_::class]; + return [\PhpParser\Node\Scalar\String_::class]; } - /** * @param String_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $fileInfo = $this->file->getSmartFileInfo(); - // this rule is parsing strings, so it heavy on performance; to lower it, we'll process only known opt-in files - if (! $this->isRelevantFileInfo($fileInfo)) { + if (!$this->isRelevantFileInfo($fileInfo)) { return null; } - - $stringKind = $node->getAttribute(AttributeKey::KIND); - if (! in_array($stringKind, [String_::KIND_NOWDOC, String_::KIND_HEREDOC], true)) { + $stringKind = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND); + if (!\in_array($stringKind, [\PhpParser\Node\Scalar\String_::KIND_NOWDOC, \PhpParser\Node\Scalar\String_::KIND_HEREDOC], \true)) { return null; } - // we assume its a function list - see https://github.com/symfony/symfony/blob/ad91659ea9b2a964f933bf27d0d1f1ef60fe9417/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php#L1513-L1560 - try { $nodes = $this->inlineCodeParser->parse('value . ' }'); - } catch (Error $error) { + } catch (\PhpParser\Error $error) { // nothing we can do return null; } - if ($nodes === []) { return null; } - // * replace scalar types with docs // * remove return type // somehow we want to call all Rector rules here $nodeTraverser = $this->createNodeTraverser(); $changedNodes = $nodeTraverser->traverse($nodes); - if (! $changedNodes[0] instanceof Class_) { + if (!$changedNodes[0] instanceof \PhpParser\Node\Stmt\Class_) { return null; } - $node->value = $this->printClassStmts($changedNodes[0]); return $node; } - - private function isRelevantFileInfo(SmartFileInfo $fileInfo): bool + private function isRelevantFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo) : bool { // for tests - if (StaticPHPUnitEnvironment::isPHPUnitRun()) { - return true; + if (\Rector\Testing\PHPUnit\StaticPHPUnitEnvironment::isPHPUnitRun()) { + return \true; } - foreach (self::FILES_TO_INCLUDE as $fileToInclude) { - if (Strings::endsWith($fileInfo->getRealPath(), $fileToInclude)) { - return true; + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($fileInfo->getRealPath(), $fileToInclude)) { + return \true; } } - - return false; + return \false; } - - private function printClassStmts(Class_ $class): string + private function printClassStmts(\PhpParser\Node\Stmt\Class_ $class) : string { $refactoredContent = ''; foreach ($class->stmts as $classStmt) { - $refactoredContent .= $this->betterStandardPrinter->prettyPrint([$classStmt]) . PHP_EOL; + $refactoredContent .= $this->betterStandardPrinter->prettyPrint([$classStmt]) . \PHP_EOL; } - return $refactoredContent; } - - private function createNodeTraverser(): NodeTraverser + private function createNodeTraverser() : \PhpParser\NodeTraverser { - $nodeTraverser = new NodeTraverser(); + $nodeTraverser = new \PhpParser\NodeTraverser(); foreach ($this->phpRectors as $phpRector) { $nodeTraverser->addVisitor($phpRector); } diff --git a/rules/DowngradePhp71/Rector/Array_/SymmetricArrayDestructuringToListRector.php b/rules/DowngradePhp71/Rector/Array_/SymmetricArrayDestructuringToListRector.php index 368572f322a..43e90fe5ec8 100644 --- a/rules/DowngradePhp71/Rector/Array_/SymmetricArrayDestructuringToListRector.php +++ b/rules/DowngradePhp71/Rector/Array_/SymmetricArrayDestructuringToListRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Array_::class]; + return [\PhpParser\Node\Expr\Array_::class]; } - /** * @param Array_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Assign && $this->nodeComparator->areNodesEqual($node, $parentNode->var)) { + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\Assign && $this->nodeComparator->areNodesEqual($node, $parentNode->var)) { return $this->processToList($node); } - if (! $parentNode instanceof Foreach_) { + if (!$parentNode instanceof \PhpParser\Node\Stmt\Foreach_) { return null; } - if (! $this->nodeComparator->areNodesEqual($node, $parentNode->valueVar)) { + if (!$this->nodeComparator->areNodesEqual($node, $parentNode->valueVar)) { return null; } return $this->processToList($node); } - - private function processToList(Array_ $array): FuncCall + private function processToList(\PhpParser\Node\Expr\Array_ $array) : \PhpParser\Node\Expr\FuncCall { $args = []; foreach ($array->items as $arrayItem) { - $args[] = $arrayItem instanceof ArrayItem ? new Arg($arrayItem->value) : null; + $args[] = $arrayItem instanceof \PhpParser\Node\Expr\ArrayItem ? new \PhpParser\Node\Arg($arrayItem->value) : null; } - - return new FuncCall(new Name('list'), $args); + return new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('list'), $args); } } diff --git a/rules/DowngradePhp71/Rector/ClassConst/DowngradeClassConstantVisibilityRector.php b/rules/DowngradePhp71/Rector/ClassConst/DowngradeClassConstantVisibilityRector.php index 8eaf1d982d5..88d63e1b3b7 100644 --- a/rules/DowngradePhp71/Rector/ClassConst/DowngradeClassConstantVisibilityRector.php +++ b/rules/DowngradePhp71/Rector/ClassConst/DowngradeClassConstantVisibilityRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassConst::class]; + return [\PhpParser\Node\Stmt\ClassConst::class]; } - /** * @param ClassConst $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $this->visibilityManipulator->removeVisibility($node); - return $node; } } diff --git a/rules/DowngradePhp71/Rector/FuncCall/DowngradeIsIterableRector.php b/rules/DowngradePhp71/Rector/FuncCall/DowngradeIsIterableRector.php index 361194b665a..b8ed320ad23 100644 --- a/rules/DowngradePhp71/Rector/FuncCall/DowngradeIsIterableRector.php +++ b/rules/DowngradePhp71/Rector/FuncCall/DowngradeIsIterableRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change is_iterable with array and Traversable object type check', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change is_iterable with array and Traversable object type check', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($obj) @@ -43,8 +36,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($obj) @@ -53,25 +45,20 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'is_iterable')) { + if (!$this->isName($node, 'is_iterable')) { return null; } - /** @var mixed $arg */ $arg = $node->args[0]->value; $funcCall = $this->nodeFactory->createFuncCall('is_array', [$arg]); - $instanceOf = new Instanceof_($arg, new FullyQualified('Traversable')); - - return new BooleanOr($funcCall, $instanceOf); + $instanceOf = new \PhpParser\Node\Expr\Instanceof_($arg, new \PhpParser\Node\Name\FullyQualified('Traversable')); + return new \PhpParser\Node\Expr\BinaryOp\BooleanOr($funcCall, $instanceOf); } } diff --git a/rules/DowngradePhp71/Rector/FunctionLike/DowngradeIterablePseudoTypeDeclarationRector.php b/rules/DowngradePhp71/Rector/FunctionLike/DowngradeIterablePseudoTypeDeclarationRector.php index 1f9764b4dfa..9754060f57d 100644 --- a/rules/DowngradePhp71/Rector/FunctionLike/DowngradeIterablePseudoTypeDeclarationRector.php +++ b/rules/DowngradePhp71/Rector/FunctionLike/DowngradeIterablePseudoTypeDeclarationRector.php @@ -1,7 +1,6 @@ phpDocFromTypeDeclarationDecorator = $phpDocFromTypeDeclarationDecorator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, ClassMethod::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove the iterable pseudo type params and returns, add @param and @return tags instead', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove the iterable pseudo type params and returns, add @param and @return tags instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run(iterable $iterator): iterable @@ -54,8 +45,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -68,26 +58,20 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param Function_|ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $iterableType = new IterableType(new MixedType(), new MixedType()); - + $iterableType = new \PHPStan\Type\IterableType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); foreach ($node->params as $param) { $this->phpDocFromTypeDeclarationDecorator->decorateParamWithSpecificType($param, $node, $iterableType); } - - if (! $this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $iterableType)) { + if (!$this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $iterableType)) { return null; } - return $node; } } diff --git a/rules/DowngradePhp71/Rector/FunctionLike/DowngradeNullableTypeDeclarationRector.php b/rules/DowngradePhp71/Rector/FunctionLike/DowngradeNullableTypeDeclarationRector.php index f2d02a38716..1e449471f4f 100644 --- a/rules/DowngradePhp71/Rector/FunctionLike/DowngradeNullableTypeDeclarationRector.php +++ b/rules/DowngradePhp71/Rector/FunctionLike/DowngradeNullableTypeDeclarationRector.php @@ -1,7 +1,6 @@ phpDocTypeChanger = $phpDocTypeChanger; $this->phpDocFromTypeDeclarationDecorator = $phpDocFromTypeDeclarationDecorator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, ClassMethod::class, Closure::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\Closure::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove the nullable type params, add @param tags instead', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove the nullable type params, add @param tags instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run(?string $input): ?string @@ -61,8 +51,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -74,80 +63,63 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @param ClassMethod|Function_|Closure $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $hasChanged = false; + $hasChanged = \false; foreach ($node->params as $param) { if ($this->refactorParamType($param, $node)) { - $hasChanged = true; + $hasChanged = \true; } } - - if ($node->returnType instanceof NullableType && $this->phpDocFromTypeDeclarationDecorator->decorate( - $node - )) { - $hasChanged = true; + if ($node->returnType instanceof \PhpParser\Node\NullableType && $this->phpDocFromTypeDeclarationDecorator->decorate($node)) { + $hasChanged = \true; } - if ($hasChanged) { return $node; } - return null; } - - private function isNullableParam(Param $param): bool + private function isNullableParam(\PhpParser\Node\Param $param) : bool { if ($param->variadic) { - return false; + return \false; } - if ($param->type === null) { - return false; + return \false; } - // Check it is the union type - return $param->type instanceof NullableType; + return $param->type instanceof \PhpParser\Node\NullableType; } - /** * @param ClassMethod|Function_|Closure $functionLike */ - private function refactorParamType(Param $param, FunctionLike $functionLike): bool + private function refactorParamType(\PhpParser\Node\Param $param, \PhpParser\Node\FunctionLike $functionLike) : bool { - if (! $this->isNullableParam($param)) { - return false; + if (!$this->isNullableParam($param)) { + return \false; } - $this->decorateWithDocBlock($functionLike, $param); $param->type = null; - - return true; + return \true; } - /** * @param ClassMethod|Function_|Closure $functionLike */ - private function decorateWithDocBlock(FunctionLike $functionLike, Param $param): void + private function decorateWithDocBlock(\PhpParser\Node\FunctionLike $functionLike, \PhpParser\Node\Param $param) : void { if ($param->type === null) { return; } - $type = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); - $paramName = $this->getName($param->var); if ($paramName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($functionLike); $this->phpDocTypeChanger->changeParamType($phpDocInfo, $type, $param, $paramName); } diff --git a/rules/DowngradePhp71/Rector/FunctionLike/DowngradeVoidTypeDeclarationRector.php b/rules/DowngradePhp71/Rector/FunctionLike/DowngradeVoidTypeDeclarationRector.php index d2089a52425..be8ba5e30ce 100644 --- a/rules/DowngradePhp71/Rector/FunctionLike/DowngradeVoidTypeDeclarationRector.php +++ b/rules/DowngradePhp71/Rector/FunctionLike/DowngradeVoidTypeDeclarationRector.php @@ -1,7 +1,6 @@ phpDocFromTypeDeclarationDecorator = $phpDocFromTypeDeclarationDecorator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, ClassMethod::class, Closure::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\Closure::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove "void" return type, add a "@return void" tag instead', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove "void" return type, add a "@return void" tag instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run(): void @@ -53,8 +44,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -65,22 +55,17 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param ClassMethod|Function_|Closure $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $voidType = new VoidType(); - - if (! $this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $voidType)) { + $voidType = new \PHPStan\Type\VoidType(); + if (!$this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $voidType)) { return null; } - return $node; } } diff --git a/rules/DowngradePhp71/Rector/List_/DowngradeKeysInListRector.php b/rules/DowngradePhp71/Rector/List_/DowngradeKeysInListRector.php index 2917f3c0d15..582a8158c2e 100644 --- a/rules/DowngradePhp71/Rector/List_/DowngradeKeysInListRector.php +++ b/rules/DowngradePhp71/Rector/List_/DowngradeKeysInListRector.php @@ -1,7 +1,6 @@ inflectorSingularResolver = $inflectorSingularResolver; $this->foreachAnalyzer = $foreachAnalyzer; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [List_::class, Array_::class]; + return [\PhpParser\Node\Expr\List_::class, \PhpParser\Node\Expr\Array_::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Extract keys in list to its own variable assignment', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Extract keys in list to its own variable assignment', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run(): void @@ -69,8 +59,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run(): void @@ -84,115 +73,89 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param List_|Array_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Node) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node) { return null; } - - $parentExpression = $parent->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentExpression instanceof Node) { + $parentExpression = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentExpression instanceof \PhpParser\Node) { return null; } - $assignExpressions = $this->processExtractToItsOwnVariable($node, $parent, $parentExpression); if ($assignExpressions === []) { return null; } - - if ($parent instanceof Assign) { + if ($parent instanceof \PhpParser\Node\Expr\Assign) { $this->mirrorComments($assignExpressions[0], $parentExpression); $this->addNodesBeforeNode($assignExpressions, $node); $this->removeNode($parentExpression); - return $node; } - - if ($parent instanceof Foreach_) { + if ($parent instanceof \PhpParser\Node\Stmt\Foreach_) { $newValueVar = $this->getNewValueVar($parent); - $parent->valueVar = new Variable($newValueVar); + $parent->valueVar = new \PhpParser\Node\Expr\Variable($newValueVar); $stmts = $parent->stmts; - if ($stmts === []) { $parent->stmts = $assignExpressions; } else { $this->addNodesBeforeNode($assignExpressions, $parent->stmts[0]); } - return $parent->valueVar; } - return null; } - /** * @param List_|Array_ $node * @return Expression[] */ - private function processExtractToItsOwnVariable(Node $node, Node $parent, Node $parentExpression): array + private function processExtractToItsOwnVariable(\PhpParser\Node $node, \PhpParser\Node $parent, \PhpParser\Node $parentExpression) : array { $items = $node->items; $assignExpressions = []; - foreach ($items as $item) { - if (! $item instanceof ArrayItem) { + if (!$item instanceof \PhpParser\Node\Expr\ArrayItem) { return []; } - /** keyed and not keyed cannot be mixed, return early */ - if (! $item->key instanceof Expr) { + if (!$item->key instanceof \PhpParser\Node\Expr) { return []; } - - if ($parentExpression instanceof Expression && $parent instanceof Assign && $parent->var === $node) { - $assignExpressions[] = new Expression( - new Assign($item->value, new ArrayDimFetch($parent->expr, $item->key)) - ); + if ($parentExpression instanceof \PhpParser\Node\Stmt\Expression && $parent instanceof \PhpParser\Node\Expr\Assign && $parent->var === $node) { + $assignExpressions[] = new \PhpParser\Node\Stmt\Expression(new \PhpParser\Node\Expr\Assign($item->value, new \PhpParser\Node\Expr\ArrayDimFetch($parent->expr, $item->key))); } - - if (! $parent instanceof Foreach_) { + if (!$parent instanceof \PhpParser\Node\Stmt\Foreach_) { continue; } - if ($parent->valueVar !== $node) { continue; } - $assignExpressions[] = $this->getExpressionFromForeachValue($parent, $item); } - return $assignExpressions; } - - private function getExpressionFromForeachValue(Foreach_ $foreach, ArrayItem $arrayItem): Expression + private function getExpressionFromForeachValue(\PhpParser\Node\Stmt\Foreach_ $foreach, \PhpParser\Node\Expr\ArrayItem $arrayItem) : \PhpParser\Node\Stmt\Expression { $newValueVar = $this->getNewValueVar($foreach); - $assign = new Assign($arrayItem->value, new ArrayDimFetch(new Variable($newValueVar), $arrayItem->key)); - - return new Expression($assign); + $assign = new \PhpParser\Node\Expr\Assign($arrayItem->value, new \PhpParser\Node\Expr\ArrayDimFetch(new \PhpParser\Node\Expr\Variable($newValueVar), $arrayItem->key)); + return new \PhpParser\Node\Stmt\Expression($assign); } - - private function getNewValueVar(Foreach_ $foreach, ?string $newValueVar = null): string + private function getNewValueVar(\PhpParser\Node\Stmt\Foreach_ $foreach, ?string $newValueVar = null) : string { if ($newValueVar === null) { $newValueVar = $this->inflectorSingularResolver->resolve((string) $this->getName($foreach->expr)); } - $count = 0; if ($this->foreachAnalyzer->isValueVarUsed($foreach, $newValueVar)) { $newValueVar .= (string) ++$count; return $this->getNewValueVar($foreach, $newValueVar); } - return $newValueVar; } } diff --git a/rules/DowngradePhp71/Rector/String_/DowngradeNegativeStringOffsetToStrlenRector.php b/rules/DowngradePhp71/Rector/String_/DowngradeNegativeStringOffsetToStrlenRector.php index 16397933788..0899b0fe5a3 100644 --- a/rules/DowngradePhp71/Rector/String_/DowngradeNegativeStringOffsetToStrlenRector.php +++ b/rules/DowngradePhp71/Rector/String_/DowngradeNegativeStringOffsetToStrlenRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class, String_::class, Variable::class, PropertyFetch::class, StaticPropertyFetch::class]; + return [\PhpParser\Node\Expr\FuncCall::class, \PhpParser\Node\Scalar\String_::class, \PhpParser\Node\Expr\Variable::class, \PhpParser\Node\Expr\PropertyFetch::class, \PhpParser\Node\Expr\StaticPropertyFetch::class]; } - /** * @param FuncCall|String_|Variable|PropertyFetch|StaticPropertyFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof FuncCall) { + if ($node instanceof \PhpParser\Node\Expr\FuncCall) { return $this->processForFuncCall($node); } - return $this->processForStringOrVariableOrProperty($node); } - /** * @param String_|Variable|PropertyFetch|StaticPropertyFetch $expr */ - private function processForStringOrVariableOrProperty(Expr $expr): ?Expr + private function processForStringOrVariableOrProperty(\PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr { - $nextNode = $expr->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextNode instanceof UnaryMinus) { + $nextNode = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextNode instanceof \PhpParser\Node\Expr\UnaryMinus) { return null; } - - $parentOfNextNode = $nextNode->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentOfNextNode instanceof ArrayDimFetch) { + $parentOfNextNode = $nextNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentOfNextNode instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return null; } - if (! $this->nodeComparator->areNodesEqual($parentOfNextNode->dim, $nextNode)) { + if (!$this->nodeComparator->areNodesEqual($parentOfNextNode->dim, $nextNode)) { return null; } - /** @var UnaryMinus $dim */ $dim = $parentOfNextNode->dim; - $strlenFuncCall = $this->nodeFactory->createFuncCall('strlen', [$expr]); - $parentOfNextNode->dim = new Minus($strlenFuncCall, $dim->expr); - + $parentOfNextNode->dim = new \PhpParser\Node\Expr\BinaryOp\Minus($strlenFuncCall, $dim->expr); return $expr; } - - private function processForFuncCall(FuncCall $funcCall): ?FuncCall + private function processForFuncCall(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr\FuncCall { $name = $this->getName($funcCall); if ($name !== 'strpos') { return null; } - $args = $funcCall->args; - if (! isset($args[2])) { + if (!isset($args[2])) { return null; } - - if (! $args[2]->value instanceof UnaryMinus) { + if (!$args[2]->value instanceof \PhpParser\Node\Expr\UnaryMinus) { return null; } - $strlenFuncCall = $this->nodeFactory->createFuncCall('strlen', [$args[0]]); - $funcCall->args[2]->value = new Minus($strlenFuncCall, $args[2]->value->expr); - + $funcCall->args[2]->value = new \PhpParser\Node\Expr\BinaryOp\Minus($strlenFuncCall, $args[2]->value->expr); return $funcCall; } } diff --git a/rules/DowngradePhp71/Rector/TryCatch/DowngradePipeToMultiCatchExceptionRector.php b/rules/DowngradePhp71/Rector/TryCatch/DowngradePipeToMultiCatchExceptionRector.php index cd6638cece0..e6ea442fca4 100644 --- a/rules/DowngradePhp71/Rector/TryCatch/DowngradePipeToMultiCatchExceptionRector.php +++ b/rules/DowngradePhp71/Rector/TryCatch/DowngradePipeToMultiCatchExceptionRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [TryCatch::class]; + return [\PhpParser\Node\Stmt\TryCatch::class]; } - /** * @param TryCatch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $originalCatches = $node->catches; foreach ($node->catches as $key => $catch) { - if (count($catch->types) === 1) { + if (\count($catch->types) === 1) { continue; } - $types = $catch->types; $node->catches[$key]->types = [$catch->types[0]]; foreach ($types as $keyCatchType => $catchType) { if ($keyCatchType === 0) { continue; } - - $this->addNodeAfterNode(new Catch_([$catchType], $catch->var, $catch->stmts), $node->catches[$key]); + $this->addNodeAfterNode(new \PhpParser\Node\Stmt\Catch_([$catchType], $catch->var, $catch->stmts), $node->catches[$key]); } } - if ($this->nodeComparator->areNodesEqual($originalCatches, $node->catches)) { return null; } - return $node; } } diff --git a/rules/DowngradePhp71/TypeDeclaration/PhpDocFromTypeDeclarationDecorator.php b/rules/DowngradePhp71/TypeDeclaration/PhpDocFromTypeDeclarationDecorator.php index c2a9e1b67e0..78cfe58abd1 100644 --- a/rules/DowngradePhp71/TypeDeclaration/PhpDocFromTypeDeclarationDecorator.php +++ b/rules/DowngradePhp71/TypeDeclaration/PhpDocFromTypeDeclarationDecorator.php @@ -1,7 +1,6 @@ staticTypeMapper = $staticTypeMapper; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->nodeNameResolver = $nodeNameResolver; $this->phpDocTypeChanger = $phpDocTypeChanger; $this->typeUnwrapper = $typeUnwrapper; } - /** * @param ClassMethod|Function_|Closure $functionLike * @return bool True if node was changed */ - public function decorate(FunctionLike $functionLike): bool + public function decorate(\PhpParser\Node\FunctionLike $functionLike) : bool { if ($functionLike->returnType === null) { - return false; + return \false; } - $type = $this->staticTypeMapper->mapPhpParserNodePHPStanType($functionLike->returnType); $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($functionLike); $this->phpDocTypeChanger->changeReturnType($phpDocInfo, $type); - $functionLike->returnType = null; - - return true; + return \true; } - /** * @param ClassMethod|Function_ $functionLike * @param array> $requiredTypes */ - public function decorateParam(Param $param, FunctionLike $functionLike, array $requiredTypes): void + public function decorateParam(\PhpParser\Node\Param $param, \PhpParser\Node\FunctionLike $functionLike, array $requiredTypes) : void { if ($param->type === null) { return; } - $type = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); - - if (! $this->isMatchingType($type, $requiredTypes)) { + if (!$this->isMatchingType($type, $requiredTypes)) { return; } - $this->moveParamTypeToParamDoc($functionLike, $param, $type); } - /** * @param ClassMethod|Function_ $functionLike */ - public function decorateParamWithSpecificType( - Param $param, - FunctionLike $functionLike, - Type $requireType - ): void { + public function decorateParamWithSpecificType(\PhpParser\Node\Param $param, \PhpParser\Node\FunctionLike $functionLike, \PHPStan\Type\Type $requireType) : void + { if ($param->type === null) { return; } - - if (! $this->isTypeMatchOrSubType($param->type, $requireType)) { + if (!$this->isTypeMatchOrSubType($param->type, $requireType)) { return; } - $type = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); $this->moveParamTypeToParamDoc($functionLike, $param, $type); } - /** * @param ClassMethod|Function_|Closure $functionLike * @return bool True if node was changed */ - public function decorateReturnWithSpecificType(FunctionLike $functionLike, Type $requireType): bool + public function decorateReturnWithSpecificType(\PhpParser\Node\FunctionLike $functionLike, \PHPStan\Type\Type $requireType) : bool { if ($functionLike->returnType === null) { - return false; + return \false; } - - if (! $this->isTypeMatchOrSubType($functionLike->returnType, $requireType)) { - return false; + if (!$this->isTypeMatchOrSubType($functionLike->returnType, $requireType)) { + return \false; } - return $this->decorate($functionLike); } - - private function isTypeMatchOrSubType(Node $typeNode, Type $requireType): bool + private function isTypeMatchOrSubType(\PhpParser\Node $typeNode, \PHPStan\Type\Type $requireType) : bool { $returnType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($typeNode); - // cover nullable union types - if ($returnType instanceof UnionType) { + if ($returnType instanceof \PHPStan\Type\UnionType) { $returnType = $this->typeUnwrapper->unwrapNullableType($returnType); } - return is_a($returnType, get_class($requireType), true); + return \is_a($returnType, \get_class($requireType), \true); } - /** * @param ClassMethod|Function_ $functionLike */ - private function moveParamTypeToParamDoc(FunctionLike $functionLike, Param $param, Type $type): void + private function moveParamTypeToParamDoc(\PhpParser\Node\FunctionLike $functionLike, \PhpParser\Node\Param $param, \PHPStan\Type\Type $type) : void { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($functionLike); $paramName = $this->nodeNameResolver->getName($param); $this->phpDocTypeChanger->changeParamType($phpDocInfo, $type, $param, $paramName); - $param->type = null; } - /** * @param array> $requiredTypes */ - private function isMatchingType(Type $type, array $requiredTypes): bool + private function isMatchingType(\PHPStan\Type\Type $type, array $requiredTypes) : bool { foreach ($requiredTypes as $requiredType) { - if (is_a($type, $requiredType, true)) { - return true; + if (\is_a($type, $requiredType, \true)) { + return \true; } } - - return false; + return \false; } } diff --git a/rules/DowngradePhp72/Contract/Rector/DowngradeTypeRectorInterface.php b/rules/DowngradePhp72/Contract/Rector/DowngradeTypeRectorInterface.php index 8529ddc1aab..ca369048cbe 100644 --- a/rules/DowngradePhp72/Contract/Rector/DowngradeTypeRectorInterface.php +++ b/rules/DowngradePhp72/Contract/Rector/DowngradeTypeRectorInterface.php @@ -1,7 +1,6 @@ nodeRepository = $nodeRepository; } - /** * @return array */ - public function resolveFromClassReflection(ClassReflection $classReflection): array + public function resolveFromClassReflection(\PHPStan\Reflection\ClassReflection $classReflection) : array { $parentClassLikes = []; - foreach ($classReflection->getAncestors() as $ancestorClassReflectoin) { $parentClass = $this->nodeRepository->findClass($ancestorClassReflectoin->getName()); - if ($parentClass instanceof Class_) { + if ($parentClass instanceof \PhpParser\Node\Stmt\Class_) { $parentClassLikes[] = $parentClass; } - $parentInterface = $this->nodeRepository->findInterface($ancestorClassReflectoin->getName()); - if ($parentInterface instanceof Interface_) { + if ($parentInterface instanceof \PhpParser\Node\Stmt\Interface_) { $parentClassLikes[] = $parentInterface; } } - return $parentClassLikes; } } diff --git a/rules/DowngradePhp72/NodeAnalyzer/ClassLikeWithTraitsClassMethodResolver.php b/rules/DowngradePhp72/NodeAnalyzer/ClassLikeWithTraitsClassMethodResolver.php index f37f9330230..46276ae021b 100644 --- a/rules/DowngradePhp72/NodeAnalyzer/ClassLikeWithTraitsClassMethodResolver.php +++ b/rules/DowngradePhp72/NodeAnalyzer/ClassLikeWithTraitsClassMethodResolver.php @@ -1,7 +1,6 @@ nodeRepository = $nodeRepository; } - /** * @param Class_|Interface_ $classLike * @return ClassMethod[] */ - public function resolve(ClassLike $classLike): array + public function resolve(\PhpParser\Node\Stmt\ClassLike $classLike) : array { - $scope = $classLike->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $classLike->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return []; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return []; } - $classMethods = []; foreach ($classReflection->getAncestors() as $ancestorClassReflection) { $ancestorClassLike = $this->nodeRepository->findClassLike($ancestorClassReflection->getName()); - if (! $ancestorClassLike instanceof ClassLike) { + if (!$ancestorClassLike instanceof \PhpParser\Node\Stmt\ClassLike) { continue; } - - $classMethods = array_merge($classMethods, $ancestorClassLike->getMethods()); + $classMethods = \array_merge($classMethods, $ancestorClassLike->getMethods()); } - return $classMethods; } } diff --git a/rules/DowngradePhp72/NodeAnalyzer/NativeTypeClassTreeResolver.php b/rules/DowngradePhp72/NodeAnalyzer/NativeTypeClassTreeResolver.php index a2c4a2c50b6..cccd004cd95 100644 --- a/rules/DowngradePhp72/NodeAnalyzer/NativeTypeClassTreeResolver.php +++ b/rules/DowngradePhp72/NodeAnalyzer/NativeTypeClassTreeResolver.php @@ -1,7 +1,6 @@ staticTypeMapper = $staticTypeMapper; $this->privatesAccessor = $privatesAccessor; } - - public function resolveParameterReflectionType( - ClassReflection $classReflection, - string $methodName, - int $position - ): Type { + public function resolveParameterReflectionType(\PHPStan\Reflection\ClassReflection $classReflection, string $methodName, int $position) : \PHPStan\Type\Type + { $nativeReflectionClass = $classReflection->getNativeReflection(); - $reflectionMethod = $nativeReflectionClass->getMethod($methodName); $parameterReflection = $reflectionMethod->getParameters()[$position] ?? null; - if (! $parameterReflection instanceof \ReflectionParameter) { - return new MixedType(); + if (!$parameterReflection instanceof \ReflectionParameter) { + return new \PHPStan\Type\MixedType(); } - // "native" reflection from PHPStan removes the type, so we need to check with both reflection and php-paser $nativeType = $this->resolveNativeType($parameterReflection); - if (! $nativeType instanceof MixedType) { + if (!$nativeType instanceof \PHPStan\Type\MixedType) { return $nativeType; } - - return TypehintHelper::decideTypeFromReflection( - $parameterReflection->getType(), - null, - $classReflection->getName(), - $parameterReflection->isVariadic() - ); + return \PHPStan\Type\TypehintHelper::decideTypeFromReflection($parameterReflection->getType(), null, $classReflection->getName(), $parameterReflection->isVariadic()); } - - private function resolveNativeType(\ReflectionParameter $reflectionParameter): Type + private function resolveNativeType(\ReflectionParameter $reflectionParameter) : \PHPStan\Type\Type { - if (! $reflectionParameter instanceof ReflectionParameter) { - return new MixedType(); + if (!$reflectionParameter instanceof \PHPStan\BetterReflection\Reflection\Adapter\ReflectionParameter) { + return new \PHPStan\Type\MixedType(); } - - $betterReflectionParameter = $this->privatesAccessor->getPrivateProperty( - $reflectionParameter, - 'betterReflectionParameter' - ); - + $betterReflectionParameter = $this->privatesAccessor->getPrivateProperty($reflectionParameter, 'betterReflectionParameter'); $param = $this->privatesAccessor->getPrivateProperty($betterReflectionParameter, 'node'); - if (! $param instanceof Param) { - return new MixedType(); + if (!$param instanceof \PhpParser\Node\Param) { + return new \PHPStan\Type\MixedType(); } - - if (! $param->type instanceof Node) { - return new MixedType(); + if (!$param->type instanceof \PhpParser\Node) { + return new \PHPStan\Type\MixedType(); } - return $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); } } diff --git a/rules/DowngradePhp72/NodeAnalyzer/ParamContravariantDetector.php b/rules/DowngradePhp72/NodeAnalyzer/ParamContravariantDetector.php index a40d63ad2fe..3ff31d8ba82 100644 --- a/rules/DowngradePhp72/NodeAnalyzer/ParamContravariantDetector.php +++ b/rules/DowngradePhp72/NodeAnalyzer/ParamContravariantDetector.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->nodeRepository = $nodeRepository; } - - public function hasParentMethod(ClassMethod $classMethod, Scope $scope): bool + public function hasParentMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Analyser\Scope $scope) : bool { $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - foreach ($classReflection->getAncestors() as $ancestorClassReflection) { if ($classReflection === $ancestorClassReflection) { continue; } - $classMethodName = $this->nodeNameResolver->getName($classMethod); if ($ancestorClassReflection->hasMethod($classMethodName)) { - return true; + return \true; } } - - return false; + return \false; } - - public function hasChildMethod(ClassMethod $classMethod, Scope $classScope): bool + public function hasChildMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Analyser\Scope $classScope) : bool { $classReflection = $classScope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - $methodName = $this->nodeNameResolver->getName($classMethod); - $classLikes = $this->nodeRepository->findClassesAndInterfacesByType($classReflection->getName()); foreach ($classLikes as $classLike) { $currentClassMethod = $classLike->getMethod($methodName); if ($currentClassMethod !== null) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/DowngradePhp72/NodeAnalyzer/ParentChildClassMethodTypeResolver.php b/rules/DowngradePhp72/NodeAnalyzer/ParentChildClassMethodTypeResolver.php index 103c716e376..e7c2c2a4dd1 100644 --- a/rules/DowngradePhp72/NodeAnalyzer/ParentChildClassMethodTypeResolver.php +++ b/rules/DowngradePhp72/NodeAnalyzer/ParentChildClassMethodTypeResolver.php @@ -1,7 +1,6 @@ nativeTypeClassTreeResolver = $nativeTypeClassTreeResolver; $this->nodeRepository = $nodeRepository; $this->reflectionProvider = $reflectionProvider; $this->nodeNameResolver = $nodeNameResolver; } - /** * @return array */ - public function resolve( - ClassReflection $classReflection, - string $methodName, - int $paramPosition, - Scope $scope - ): array { + public function resolve(\PHPStan\Reflection\ClassReflection $classReflection, string $methodName, int $paramPosition, \PHPStan\Analyser\Scope $scope) : array + { $parameterTypesByClassName = []; - // include types of class scope in case of trait if ($classReflection->isTrait()) { - $parameterTypesByInterfaceName = $this->resolveInterfaceTypeByClassName( - $scope, - $methodName, - $paramPosition - ); - $parameterTypesByClassName = array_merge($parameterTypesByClassName, $parameterTypesByInterfaceName); + $parameterTypesByInterfaceName = $this->resolveInterfaceTypeByClassName($scope, $methodName, $paramPosition); + $parameterTypesByClassName = \array_merge($parameterTypesByClassName, $parameterTypesByInterfaceName); } - foreach ($classReflection->getAncestors() as $ancestorClassReflection) { - if (! $ancestorClassReflection->hasMethod($methodName)) { + if (!$ancestorClassReflection->hasMethod($methodName)) { continue; } - - $parameterType = $this->nativeTypeClassTreeResolver->resolveParameterReflectionType( - $ancestorClassReflection, - $methodName, - $paramPosition - ); - + $parameterType = $this->nativeTypeClassTreeResolver->resolveParameterReflectionType($ancestorClassReflection, $methodName, $paramPosition); $parameterTypesByClassName[$ancestorClassReflection->getName()] = $parameterType; - // collect other children if ($ancestorClassReflection->isInterface() || $ancestorClassReflection->isClass()) { - $interfaceParameterTypesByClassName = $this->collectInterfaceImplenters( - $ancestorClassReflection, - $methodName, - $paramPosition - ); - - $parameterTypesByClassName = array_merge( - $parameterTypesByClassName, - $interfaceParameterTypesByClassName - ); + $interfaceParameterTypesByClassName = $this->collectInterfaceImplenters($ancestorClassReflection, $methodName, $paramPosition); + $parameterTypesByClassName = \array_merge($parameterTypesByClassName, $interfaceParameterTypesByClassName); } } - return $parameterTypesByClassName; } - /** * @return array */ - private function resolveInterfaceTypeByClassName(Scope $scope, string $methodName, int $position): array + private function resolveInterfaceTypeByClassName(\PHPStan\Analyser\Scope $scope, string $methodName, int $position) : array { $typesByClassName = []; - $currentClassReflection = $scope->getClassReflection(); - if (! $currentClassReflection instanceof ClassReflection) { + if (!$currentClassReflection instanceof \PHPStan\Reflection\ClassReflection) { return []; } - foreach ($currentClassReflection->getInterfaces() as $interfaceClassReflection) { - if (! $interfaceClassReflection->hasMethod($methodName)) { + if (!$interfaceClassReflection->hasMethod($methodName)) { continue; } - - $parameterType = $this->nativeTypeClassTreeResolver->resolveParameterReflectionType( - $interfaceClassReflection, - $methodName, - $position - ); - + $parameterType = $this->nativeTypeClassTreeResolver->resolveParameterReflectionType($interfaceClassReflection, $methodName, $position); $typesByClassName[$interfaceClassReflection->getName()] = $parameterType; } - return $typesByClassName; } - /** * @return array */ - private function collectInterfaceImplenters( - ClassReflection $ancestorClassReflection, - string $methodName, - int $paramPosition - ): array { + private function collectInterfaceImplenters(\PHPStan\Reflection\ClassReflection $ancestorClassReflection, string $methodName, int $paramPosition) : array + { $parameterTypesByClassName = []; - - $interfaceImplementerClassLikes = $this->nodeRepository->findClassesAndInterfacesByType( - $ancestorClassReflection->getName() - ); - + $interfaceImplementerClassLikes = $this->nodeRepository->findClassesAndInterfacesByType($ancestorClassReflection->getName()); foreach ($interfaceImplementerClassLikes as $interfaceImplementerClassLike) { $interfaceImplementerClassLikeName = $this->nodeNameResolver->getName($interfaceImplementerClassLike); if ($interfaceImplementerClassLikeName === null) { continue; } - /** @var class-string $interfaceImplementerClassLikeName */ - if (! $this->reflectionProvider->hasClass($interfaceImplementerClassLikeName)) { + if (!$this->reflectionProvider->hasClass($interfaceImplementerClassLikeName)) { continue; } - - $interfaceImplementerClassReflection = $this->reflectionProvider->getClass( - $interfaceImplementerClassLikeName - ); - $parameterType = $this->nativeTypeClassTreeResolver->resolveParameterReflectionType( - $interfaceImplementerClassReflection, - $methodName, - $paramPosition - ); - + $interfaceImplementerClassReflection = $this->reflectionProvider->getClass($interfaceImplementerClassLikeName); + $parameterType = $this->nativeTypeClassTreeResolver->resolveParameterReflectionType($interfaceImplementerClassReflection, $methodName, $paramPosition); $parameterTypesByClassName[$interfaceImplementerClassLikeName] = $parameterType; } - return $parameterTypesByClassName; } } diff --git a/rules/DowngradePhp72/PhpDoc/NativeParamToPhpDocDecorator.php b/rules/DowngradePhp72/PhpDoc/NativeParamToPhpDocDecorator.php index 8090d90103b..4ae84cb6875 100644 --- a/rules/DowngradePhp72/PhpDoc/NativeParamToPhpDocDecorator.php +++ b/rules/DowngradePhp72/PhpDoc/NativeParamToPhpDocDecorator.php @@ -1,7 +1,6 @@ phpDocInfoFactory = $phpDocInfoFactory; $this->nodeNameResolver = $nodeNameResolver; $this->staticTypeMapper = $staticTypeMapper; $this->phpDocTypeChanger = $phpDocTypeChanger; $this->valueResolver = $valueResolver; } - - public function decorate(ClassMethod $classMethod, Param $param): void + public function decorate(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Param $param) : void { if ($param->type === null) { return; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); - $paramName = $this->nodeNameResolver->getName($param); $mappedCurrentParamType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); - // add default null type - if ($param->default !== null && $this->valueResolver->isNull($param->default) && ! TypeCombinator::containsNull( - $mappedCurrentParamType - )) { - $mappedCurrentParamType = new UnionType([$mappedCurrentParamType, new NullType()]); + if ($param->default !== null && $this->valueResolver->isNull($param->default) && !\PHPStan\Type\TypeCombinator::containsNull($mappedCurrentParamType)) { + $mappedCurrentParamType = new \PHPStan\Type\UnionType([$mappedCurrentParamType, new \PHPStan\Type\NullType()]); } - $this->phpDocTypeChanger->changeParamType($phpDocInfo, $mappedCurrentParamType, $param, $paramName); } } diff --git a/rules/DowngradePhp72/Rector/Class_/DowngradeParameterTypeWideningRector.php b/rules/DowngradePhp72/Rector/Class_/DowngradeParameterTypeWideningRector.php index 6b83671cc25..5cf48853b15 100644 --- a/rules/DowngradePhp72/Rector/Class_/DowngradeParameterTypeWideningRector.php +++ b/rules/DowngradePhp72/Rector/Class_/DowngradeParameterTypeWideningRector.php @@ -1,7 +1,6 @@ classLikeWithTraitsClassMethodResolver = $classLikeWithTraitsClassMethodResolver; $this->parentChildClassMethodTypeResolver = $parentChildClassMethodTypeResolver; $this->nativeParamToPhpDocDecorator = $nativeParamToPhpDocDecorator; $this->paramContravariantDetector = $paramContravariantDetector; $this->typeFactory = $typeFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change param type to match the lowest type in whole family tree', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change param type to match the lowest type in whole family tree', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' interface SomeInterface { public function test(array $input); @@ -86,8 +71,7 @@ final class SomeClass implements SomeInterface } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' interface SomeInterface { /** @@ -103,143 +87,112 @@ final class SomeClass implements SomeInterface } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class, Interface_::class]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Stmt\Interface_::class]; } - /** * @param Class_|Interface_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - if ($this->isEmptyClassReflection($scope)) { return null; } - - $hasChanged = false; + $hasChanged = \false; $classMethods = $this->classLikeWithTraitsClassMethodResolver->resolve($node); - foreach ($classMethods as $classMethod) { if ($this->skipClassMethod($classMethod, $scope)) { continue; } - // refactor here if ($this->refactorClassMethod($classMethod, $scope) !== null) { - $hasChanged = true; + $hasChanged = \true; } } - if ($hasChanged) { return $node; } - return null; } - /** * The topmost class is the source of truth, so we go only down to avoid up/down collission */ - private function refactorClassMethod(ClassMethod $classMethod, Scope $scope): ?ClassMethod + private function refactorClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Analyser\Scope $scope) : ?\PhpParser\Node\Stmt\ClassMethod { $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - /** @var string $methodName */ $methodName = $this->nodeNameResolver->getName($classMethod); - - $hasChanged = false; + $hasChanged = \false; foreach ($classMethod->params as $position => $param) { - if (! is_int($position)) { - throw new ShouldNotHappenException(); + if (!\is_int($position)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - // Resolve the types in: // - all ancestors + their descendant classes // @todo - all implemented interfaces + their implementing classes - $parameterTypesByParentClassLikes = $this->parentChildClassMethodTypeResolver->resolve( - $classReflection, - $methodName, - $position, - $scope - ); - + $parameterTypesByParentClassLikes = $this->parentChildClassMethodTypeResolver->resolve($classReflection, $methodName, $position, $scope); $uniqueTypes = $this->typeFactory->uniquateTypes($parameterTypesByParentClassLikes); - if (count($uniqueTypes) <= 1) { + if (\count($uniqueTypes) <= 1) { continue; } - $this->removeParamTypeFromMethod($classMethod, $param); - $hasChanged = true; + $hasChanged = \true; } - if ($hasChanged) { return $classMethod; } - return null; } - - private function removeParamTypeFromMethod(ClassMethod $classMethod, Param $param): void + private function removeParamTypeFromMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Param $param) : void { // It already has no type => nothing to do - check original param, as it could have been removed by this rule - $originalParam = $param->getAttribute(AttributeKey::ORIGINAL_NODE); - if ($originalParam instanceof Param) { + $originalParam = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE); + if ($originalParam instanceof \PhpParser\Node\Param) { if ($originalParam->type === null) { return; } } elseif ($param->type === null) { return; } - // Add the current type in the PHPDoc $this->nativeParamToPhpDocDecorator->decorate($classMethod, $param); $param->type = null; } - - private function skipClassMethod(ClassMethod $classMethod, Scope $classScope): bool + private function skipClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Analyser\Scope $classScope) : bool { if ($classMethod->isMagic()) { - return true; + return \true; } - if ($classMethod->params === []) { - return true; + return \true; } - if ($this->paramContravariantDetector->hasChildMethod($classMethod, $classScope)) { - return false; + return \false; } - - return ! $this->paramContravariantDetector->hasParentMethod($classMethod, $classScope); + return !$this->paramContravariantDetector->hasParentMethod($classMethod, $classScope); } - - private function isEmptyClassReflection(Scope $scope): bool + private function isEmptyClassReflection(\PHPStan\Analyser\Scope $scope) : bool { $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return true; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \true; } - if ($classReflection->isInterface()) { - return false; + return \false; } - - return count($classReflection->getAncestors()) === 1; + return \count($classReflection->getAncestors()) === 1; } } diff --git a/rules/DowngradePhp72/Rector/FuncCall/DowngradePregUnmatchedAsNullConstantRector.php b/rules/DowngradePhp72/Rector/FuncCall/DowngradePregUnmatchedAsNullConstantRector.php index 77abf535968..8de6f18fc04 100644 --- a/rules/DowngradePhp72/Rector/FuncCall/DowngradePregUnmatchedAsNullConstantRector.php +++ b/rules/DowngradePhp72/Rector/FuncCall/DowngradePregUnmatchedAsNullConstantRector.php @@ -1,10 +1,9 @@ ifManipulator = $ifManipulator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class, ClassConst::class]; + return [\PhpParser\Node\Expr\FuncCall::class, \PhpParser\Node\Stmt\ClassConst::class]; } - /** * @param FuncCall|ClassConst $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof ClassConst) { + if ($node instanceof \PhpParser\Node\Stmt\ClassConst) { return $this->processsClassConst($node); } - - if (! $this->isRegexFunctionNames($node)) { + if (!$this->isRegexFunctionNames($node)) { return null; } - $args = $node->args; - if (! isset($args[3])) { + if (!isset($args[3])) { return null; } - $flags = $args[3]->value; /** @var Variable $variable */ $variable = $args[2]->value; - - if ($flags instanceof BitwiseOr) { + if ($flags instanceof \PhpParser\Node\Expr\BinaryOp\BitwiseOr) { $this->cleanBitWiseOrFlags($node, $flags); - if (! $this->nodeComparator->areNodesEqual($flags, $node->args[3]->value)) { + if (!$this->nodeComparator->areNodesEqual($flags, $node->args[3]->value)) { return $this->handleEmptyStringToNullMatch($node, $variable); } - return null; } - - if (! $flags instanceof ConstFetch) { + if (!$flags instanceof \PhpParser\Node\Expr\ConstFetch) { return null; } - - if (! $this->isName($flags, self::FLAG)) { + if (!$this->isName($flags, self::FLAG)) { return null; } - $node = $this->handleEmptyStringToNullMatch($node, $variable); unset($node->args[3]); - return $node; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove PREG_UNMATCHED_AS_NULL from preg_match and set null value on empty string matched on each match', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove PREG_UNMATCHED_AS_NULL from preg_match and set null value on empty string matched on each match', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -122,8 +101,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -137,206 +115,149 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - - private function processsClassConst(ClassConst $classConst): ClassConst + private function processsClassConst(\PhpParser\Node\Stmt\ClassConst $classConst) : \PhpParser\Node\Stmt\ClassConst { foreach ($classConst->consts as $key => $singleClassConst) { - if (! $singleClassConst->value instanceof ConstFetch) { + if (!$singleClassConst->value instanceof \PhpParser\Node\Expr\ConstFetch) { continue; } - if (! $this->isName($singleClassConst->value, self::FLAG)) { + if (!$this->isName($singleClassConst->value, self::FLAG)) { continue; } - $classConst->consts[$key]->value = new LNumber(512); + $classConst->consts[$key]->value = new \PhpParser\Node\Scalar\LNumber(512); return $classConst; } - return $classConst; } - - private function isRegexFunctionNames(FuncCall $funcCall): bool + private function isRegexFunctionNames(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { if ($this->isNames($funcCall, self::REGEX_FUNCTION_NAMES)) { - return true; + return \true; } - $variable = $funcCall->name; - if (! $variable instanceof Variable) { - return false; + if (!$variable instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - /** @var Assign|null $assignExprVariable */ - $assignExprVariable = $this->betterNodeFinder->findFirstPreviousOfNode($funcCall, function (Node $node) use ( - $variable - ): bool { - if (! $node instanceof Assign) { - return false; + $assignExprVariable = $this->betterNodeFinder->findFirstPreviousOfNode($funcCall, function (\PhpParser\Node $node) use($variable) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - return $this->nodeComparator->areNodesEqual($node->var, $variable); }); - - if (! $assignExprVariable instanceof Assign) { - return false; + if (!$assignExprVariable instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - $expr = $assignExprVariable->expr; - if (! $expr instanceof Ternary) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\Ternary) { + return \false; } - - if (! $expr->if instanceof String_) { - return false; + if (!$expr->if instanceof \PhpParser\Node\Scalar\String_) { + return \false; } - - if (! $expr->else instanceof String_) { - return false; + if (!$expr->else instanceof \PhpParser\Node\Scalar\String_) { + return \false; } - - return in_array($expr->if->value, self::REGEX_FUNCTION_NAMES, true) && in_array( - $expr->else->value, - self::REGEX_FUNCTION_NAMES, - true - ); + return \in_array($expr->if->value, self::REGEX_FUNCTION_NAMES, \true) && \in_array($expr->else->value, self::REGEX_FUNCTION_NAMES, \true); } - - private function cleanBitWiseOrFlags(FuncCall $funcCall, BitwiseOr $bitwiseOr, ?Expr $expr = null): void + private function cleanBitWiseOrFlags(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr\BinaryOp\BitwiseOr $bitwiseOr, ?\PhpParser\Node\Expr $expr = null) : void { - if ($bitwiseOr->left instanceof BitwiseOr) { + if ($bitwiseOr->left instanceof \PhpParser\Node\Expr\BinaryOp\BitwiseOr) { /** @var BitwiseOr $leftLeft */ $leftLeft = $bitwiseOr->left; - if ($leftLeft->left instanceof ConstFetch && $this->isName($leftLeft->left, self::FLAG)) { - $bitwiseOr = new BitwiseOr($leftLeft->right, $bitwiseOr->right); + if ($leftLeft->left instanceof \PhpParser\Node\Expr\ConstFetch && $this->isName($leftLeft->left, self::FLAG)) { + $bitwiseOr = new \PhpParser\Node\Expr\BinaryOp\BitwiseOr($leftLeft->right, $bitwiseOr->right); } - /** @var BitwiseOr $leftRight */ $leftRight = $bitwiseOr->left; - if ($leftRight->right instanceof ConstFetch && $this->isName($leftRight->right, self::FLAG)) { - $bitwiseOr = new BitwiseOr($leftRight->left, $bitwiseOr->right); + if ($leftRight->right instanceof \PhpParser\Node\Expr\ConstFetch && $this->isName($leftRight->right, self::FLAG)) { + $bitwiseOr = new \PhpParser\Node\Expr\BinaryOp\BitwiseOr($leftRight->left, $bitwiseOr->right); } - - if ($bitwiseOr->left instanceof BitwiseOr) { + if ($bitwiseOr->left instanceof \PhpParser\Node\Expr\BinaryOp\BitwiseOr) { $this->cleanBitWiseOrFlags($funcCall, $bitwiseOr->left, $bitwiseOr->right); return; } } - - if ($expr instanceof Expr) { - $bitwiseOr = new BitwiseOr($bitwiseOr, $expr); + if ($expr instanceof \PhpParser\Node\Expr) { + $bitwiseOr = new \PhpParser\Node\Expr\BinaryOp\BitwiseOr($bitwiseOr, $expr); } - $this->assignThirdArgsValue($funcCall, $bitwiseOr); } - - private function assignThirdArgsValue(FuncCall $funcCall, BitwiseOr $bitwiseOr): void + private function assignThirdArgsValue(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr\BinaryOp\BitwiseOr $bitwiseOr) : void { - if ($bitwiseOr instanceof BitWiseOr && $bitwiseOr->right instanceof ConstFetch && $this->isName( - $bitwiseOr->right, - self::FLAG - )) { + if ($bitwiseOr instanceof \PhpParser\Node\Expr\BinaryOp\BitwiseOr && $bitwiseOr->right instanceof \PhpParser\Node\Expr\ConstFetch && $this->isName($bitwiseOr->right, self::FLAG)) { $bitwiseOr = $bitwiseOr->left; } - - if ($bitwiseOr instanceof BitWiseOr && $bitwiseOr->left instanceof ConstFetch && $this->isName( - $bitwiseOr->left, - self::FLAG - )) { + if ($bitwiseOr instanceof \PhpParser\Node\Expr\BinaryOp\BitwiseOr && $bitwiseOr->left instanceof \PhpParser\Node\Expr\ConstFetch && $this->isName($bitwiseOr->left, self::FLAG)) { $bitwiseOr = $bitwiseOr->right; } - $funcCall->args[3]->value = $bitwiseOr; } - - private function handleEmptyStringToNullMatch(FuncCall $funcCall, Variable $variable): FuncCall + private function handleEmptyStringToNullMatch(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr\Variable $variable) : \PhpParser\Node\Expr\FuncCall { - $closure = new Closure(); - $variablePass = new Variable('value'); - $param = new Param($variablePass); - $param->byRef = true; + $closure = new \PhpParser\Node\Expr\Closure(); + $variablePass = new \PhpParser\Node\Expr\Variable('value'); + $param = new \PhpParser\Node\Param($variablePass); + $param->byRef = \true; $closure->params = [$param]; - - $assign = new Assign($variablePass, $this->nodeFactory->createNull()); - - $if = $this->ifManipulator->createIfExpr( - new Identical($variablePass, new String_('')), - new Expression($assign) - ); - + $assign = new \PhpParser\Node\Expr\Assign($variablePass, $this->nodeFactory->createNull()); + $if = $this->ifManipulator->createIfExpr(new \PhpParser\Node\Expr\BinaryOp\Identical($variablePass, new \PhpParser\Node\Scalar\String_('')), new \PhpParser\Node\Stmt\Expression($assign)); $closure->stmts[0] = $if; - $arguments = $this->nodeFactory->createArgs([$variable, $closure]); $replaceEmptystringToNull = $this->nodeFactory->createFuncCall('array_walk_recursive', $arguments); - return $this->processReplace($funcCall, $replaceEmptystringToNull); } - - private function processReplace(FuncCall $funcCall, FuncCall $replaceEmptystringToNull): FuncCall + private function processReplace(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr\FuncCall $replaceEmptystringToNull) : \PhpParser\Node\Expr\FuncCall { - $parent = $funcCall->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Expression) { + $parent = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Stmt\Expression) { $this->addNodeAfterNode($replaceEmptystringToNull, $funcCall); return $funcCall; } - - if ($parent instanceof If_ && $parent->cond === $funcCall) { + if ($parent instanceof \PhpParser\Node\Stmt\If_ && $parent->cond === $funcCall) { return $this->processInIf($parent, $funcCall, $replaceEmptystringToNull); } - - if (! $parent instanceof Node) { - throw new NotImplementedException(); + if (!$parent instanceof \PhpParser\Node) { + throw new \RectorPrefix20210509\Nette\NotImplementedException(); } - - $if = $parent->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof BooleanNot) { + $if = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Expr\BooleanNot) { return $this->processInIf($if, $funcCall, $replaceEmptystringToNull); } - - if (! $parent instanceof Identical) { - throw new NotImplementedYetException(); + if (!$parent instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { + throw new \Rector\Core\Exception\NotImplementedYetException(); } - - if (! $if instanceof If_) { - throw new NotImplementedYetException(); + if (!$if instanceof \PhpParser\Node\Stmt\If_) { + throw new \Rector\Core\Exception\NotImplementedYetException(); } - return $this->processInIf($if, $funcCall, $replaceEmptystringToNull); } - - private function processInIf(If_ $if, FuncCall $funcCall, FuncCall $replaceEmptystringToNull): FuncCall + private function processInIf(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr\FuncCall $replaceEmptystringToNull) : \PhpParser\Node\Expr\FuncCall { $cond = $if->cond; - - if (! $cond instanceof Identical && ! $cond instanceof BooleanNot) { + if (!$cond instanceof \PhpParser\Node\Expr\BinaryOp\Identical && !$cond instanceof \PhpParser\Node\Expr\BooleanNot) { $this->handleNotInIdenticalAndBooleanNot($if, $replaceEmptystringToNull); } - - if ($cond instanceof Identical) { - $valueCompare = $cond->left === $funcCall - ? $cond->right - : $cond->left; + if ($cond instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { + $valueCompare = $cond->left === $funcCall ? $cond->right : $cond->left; if ($this->valueResolver->isFalse($valueCompare)) { $this->addNodeAfterNode($replaceEmptystringToNull, $if); } } - - if ($cond instanceof BooleanNot) { + if ($cond instanceof \PhpParser\Node\Expr\BooleanNot) { $this->addNodeAfterNode($replaceEmptystringToNull, $if); } - return $funcCall; } - - private function handleNotInIdenticalAndBooleanNot(If_ $if, FuncCall $funcCall): void + private function handleNotInIdenticalAndBooleanNot(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node\Expr\FuncCall $funcCall) : void { if ($if->stmts !== []) { $firstStmt = $if->stmts[0]; $this->addNodeBeforeNode($funcCall, $firstStmt); } else { - $if->stmts[0] = new Expression($funcCall); + $if->stmts[0] = new \PhpParser\Node\Stmt\Expression($funcCall); } } } diff --git a/rules/DowngradePhp72/Rector/FuncCall/DowngradeStreamIsattyRector.php b/rules/DowngradePhp72/Rector/FuncCall/DowngradeStreamIsattyRector.php index 11761506e6a..04ad69342f1 100644 --- a/rules/DowngradePhp72/Rector/FuncCall/DowngradeStreamIsattyRector.php +++ b/rules/DowngradePhp72/Rector/FuncCall/DowngradeStreamIsattyRector.php @@ -1,7 +1,6 @@ inlineCodeParser = $inlineCodeParser; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Downgrade stream_isatty() function', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Downgrade stream_isatty() function', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($stream) @@ -46,9 +40,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($stream) @@ -64,47 +56,37 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'stream_isatty')) { + if (!$this->isName($node, 'stream_isatty')) { return null; } - $function = $this->createClosure(); - $assign = new Assign(new Variable('streamIsatty'), $function); - + $assign = new \PhpParser\Node\Expr\Assign(new \PhpParser\Node\Expr\Variable('streamIsatty'), $function); $this->addNodeBeforeNode($assign, $node); - - return new FuncCall(new Variable('streamIsatty'), $node->args); + return new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Expr\Variable('streamIsatty'), $node->args); } - - private function createClosure(): Closure + private function createClosure() : \PhpParser\Node\Expr\Closure { $stmts = $this->inlineCodeParser->parse(__DIR__ . '/../../snippet/isatty_closure.php.inc'); - /** @var Expression $expression */ $expression = $stmts[0]; - $expr = $expression->expr; - if (! $expr instanceof Closure) { - throw new ShouldNotHappenException(); + if (!$expr instanceof \PhpParser\Node\Expr\Closure) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - return $expr; } } diff --git a/rules/DowngradePhp72/Rector/FunctionLike/DowngradeObjectTypeDeclarationRector.php b/rules/DowngradePhp72/Rector/FunctionLike/DowngradeObjectTypeDeclarationRector.php index a21e24ece13..ee152a95b75 100644 --- a/rules/DowngradePhp72/Rector/FunctionLike/DowngradeObjectTypeDeclarationRector.php +++ b/rules/DowngradePhp72/Rector/FunctionLike/DowngradeObjectTypeDeclarationRector.php @@ -1,7 +1,6 @@ phpDocFromTypeDeclarationDecorator = $phpDocFromTypeDeclarationDecorator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, ClassMethod::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param Function_|ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $objectWithoutClassType = new ObjectWithoutClassType(); - + $objectWithoutClassType = new \PHPStan\Type\ObjectWithoutClassType(); foreach ($node->params as $param) { - $this->phpDocFromTypeDeclarationDecorator->decorateParamWithSpecificType( - $param, - $node, - $objectWithoutClassType - ); + $this->phpDocFromTypeDeclarationDecorator->decorateParamWithSpecificType($param, $node, $objectWithoutClassType); } - - if (! $this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType( - $node, - $objectWithoutClassType - )) { + if (!$this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $objectWithoutClassType)) { return null; } - return $node; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove the "object" param and return type, add a @param and @return tags instead', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove the "object" param and return type, add a @param and @return tags instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function someFunction(object $someObject): object @@ -75,8 +55,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -88,8 +67,6 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } } diff --git a/rules/DowngradePhp73/Rector/FuncCall/DowngradeArrayKeyFirstLastRector.php b/rules/DowngradePhp73/Rector/FuncCall/DowngradeArrayKeyFirstLastRector.php index 1f345a984a5..2a92581f0df 100644 --- a/rules/DowngradePhp73/Rector/FuncCall/DowngradeArrayKeyFirstLastRector.php +++ b/rules/DowngradePhp73/Rector/FuncCall/DowngradeArrayKeyFirstLastRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->isName($node, 'array_key_first')) { return $this->refactorArrayKeyFirst($node); } - if ($this->isName($node, 'array_key_last')) { return $this->refactorArrayKeyLast($node); } - return null; } - - private function refactorArrayKeyFirst(FuncCall $funcCall): FuncCall + private function refactorArrayKeyFirst(\PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\FuncCall { $array = $funcCall->args[0]->value; - $resetFuncCall = $this->nodeFactory->createFuncCall('reset', [$array]); $this->addNodeBeforeNode($resetFuncCall, $funcCall); - - $funcCall->name = new Name('key'); - + $funcCall->name = new \PhpParser\Node\Name('key'); return $funcCall; } - - private function refactorArrayKeyLast(FuncCall $funcCall): FuncCall + private function refactorArrayKeyLast(\PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\FuncCall { $array = $funcCall->args[0]->value; $resetFuncCall = $this->nodeFactory->createFuncCall('end', [$array]); $this->addNodeBeforeNode($resetFuncCall, $funcCall); - - $funcCall->name = new Name('key'); - + $funcCall->name = new \PhpParser\Node\Name('key'); return $funcCall; } } diff --git a/rules/DowngradePhp73/Rector/FuncCall/DowngradeTrailingCommasInFunctionCallsRector.php b/rules/DowngradePhp73/Rector/FuncCall/DowngradeTrailingCommasInFunctionCallsRector.php index 631dc9b3f1d..34b2a859ce2 100644 --- a/rules/DowngradePhp73/Rector/FuncCall/DowngradeTrailingCommasInFunctionCallsRector.php +++ b/rules/DowngradePhp73/Rector/FuncCall/DowngradeTrailingCommasInFunctionCallsRector.php @@ -1,7 +1,6 @@ followedByCommaAnalyzer = $followedByCommaAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove trailing commas in function calls', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove trailing commas in function calls', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function __construct(string $value) @@ -47,8 +39,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function __construct(string $value) @@ -60,37 +51,31 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class, MethodCall::class, StaticCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class, \PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param FuncCall|MethodCall|StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->args) { - $lastArgumentPosition = array_key_last($node->args); - + \end($node->args); + $lastArgumentPosition = \key($node->args); $last = $node->args[$lastArgumentPosition]; - if (! $this->followedByCommaAnalyzer->isFollowed($this->file, $last)) { + if (!$this->followedByCommaAnalyzer->isFollowed($this->file, $last)) { return null; } - // remove comma - $last->setAttribute(AttributeKey::FUNC_ARGS_TRAILING_COMMA, false); - $node->setAttribute(AttributeKey::ORIGINAL_NODE, null); + $last->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::FUNC_ARGS_TRAILING_COMMA, \false); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); } - return $node; } } diff --git a/rules/DowngradePhp73/Rector/FuncCall/SetCookieOptionsArrayToArgumentsRector.php b/rules/DowngradePhp73/Rector/FuncCall/SetCookieOptionsArrayToArgumentsRector.php index dcdbbfada47..0c90020b290 100644 --- a/rules/DowngradePhp73/Rector/FuncCall/SetCookieOptionsArrayToArgumentsRector.php +++ b/rules/DowngradePhp73/Rector/FuncCall/SetCookieOptionsArrayToArgumentsRector.php @@ -1,7 +1,6 @@ */ - private const ARGUMENT_ORDER = [ - 'expires' => 2, - 'path' => 3, - 'domain' => 4, - 'secure' => 5, - 'httponly' => 6, - ]; - + private const ARGUMENT_ORDER = ['expires' => 2, 'path' => 3, 'domain' => 4, 'secure' => 5, 'httponly' => 6]; /** * Conversion table from argument index to options name * @var array */ - private const ARGUMENT_DEFAULT_VALUES = [ - 2 => 0, - 3 => '', - 4 => '', - 5 => false, - 6 => false, - ]; - + private const ARGUMENT_DEFAULT_VALUES = [2 => 0, 3 => '', 4 => '', 5 => \false, 6 => \false]; /** * @var int */ private $highestIndex = 1; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Convert setcookie option array to arguments', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Convert setcookie option array to arguments', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' setcookie('name', $value, ['expires' => 360]); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' setcookie('name', $value, 360); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $node->args = $this->composeNewArgs($node); - return $node; } - - private function shouldSkip(FuncCall $funcCall): bool + private function shouldSkip(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - if (! $this->isNames($funcCall, ['setcookie', 'setrawcookie'])) { - return true; + if (!$this->isNames($funcCall, ['setcookie', 'setrawcookie'])) { + return \true; } - - $argsCount = count($funcCall->args); + $argsCount = \count($funcCall->args); if ($argsCount <= 2) { - return true; + return \true; } - return ! ($funcCall->args[2]->value instanceof Array_); + return !$funcCall->args[2]->value instanceof \PhpParser\Node\Expr\Array_; } - /** * @return Arg[] */ - private function composeNewArgs(FuncCall $funcCall): array + private function composeNewArgs(\PhpParser\Node\Expr\FuncCall $funcCall) : array { $this->highestIndex = 1; - $newArgs = [$funcCall->args[0], $funcCall->args[1]]; - /** @var Array_ $optionsArray */ $optionsArray = $funcCall->args[2]->value; /** @var ArrayItem|null $arrayItem */ @@ -119,62 +86,49 @@ CODE_SAMPLE if ($arrayItem === null) { continue; } - /** @var Arg $value */ $value = $arrayItem->value; /** @var String_ $key */ $key = $arrayItem->key; $name = $key->value; - - if (! $this->isMappableArrayKey($name)) { + if (!$this->isMappableArrayKey($name)) { continue; } - $order = self::ARGUMENT_ORDER[$name]; if ($order > $this->highestIndex) { $this->highestIndex = $order; } - $newArgs[$order] = $value; } - $newArgs = $this->fillMissingArgumentsWithDefaultValues($newArgs); - ksort($newArgs); - + \ksort($newArgs); return $newArgs; } - - private function isMappableArrayKey(string $key): bool + private function isMappableArrayKey(string $key) : bool { return isset(self::ARGUMENT_ORDER[$key]); } - /** * @param Arg[] $args * @return Arg[] */ - private function fillMissingArgumentsWithDefaultValues(array $args): array + private function fillMissingArgumentsWithDefaultValues(array $args) : array { for ($i = 1; $i < $this->highestIndex; ++$i) { if (isset($args[$i])) { continue; } - $args[$i] = $this->createDefaultValueArg($i); } - return $args; } - - private function createDefaultValueArg(int $argumentIndex): Arg + private function createDefaultValueArg(int $argumentIndex) : \PhpParser\Node\Arg { - if (! array_key_exists($argumentIndex, self::ARGUMENT_DEFAULT_VALUES)) { - throw new ShouldNotHappenException(); + if (!\array_key_exists($argumentIndex, self::ARGUMENT_DEFAULT_VALUES)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $argumentDefaultValue = self::ARGUMENT_DEFAULT_VALUES[$argumentIndex]; - $expr = BuilderHelpers::normalizeValue($argumentDefaultValue); - - return new Arg($expr); + $expr = \PhpParser\BuilderHelpers::normalizeValue($argumentDefaultValue); + return new \PhpParser\Node\Arg($expr); } } diff --git a/rules/DowngradePhp73/Rector/List_/DowngradeListReferenceAssignmentRector.php b/rules/DowngradePhp73/Rector/List_/DowngradeListReferenceAssignmentRector.php index 89be247be4a..5614a289e85 100644 --- a/rules/DowngradePhp73/Rector/List_/DowngradeListReferenceAssignmentRector.php +++ b/rules/DowngradePhp73/Rector/List_/DowngradeListReferenceAssignmentRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [List_::class, Array_::class]; + return [\PhpParser\Node\Expr\List_::class, \PhpParser\Node\Expr\Array_::class]; } - /** * @param List_|Array_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->shouldRefactor($node)) { + if (!$this->shouldRefactor($node)) { return null; } - // Get all the params passed by reference /** @var Assign $parentNode */ - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); /** @var Variable $exprVariable */ $exprVariable = $parentNode->expr; - // Count number of params by ref on the right side, to remove them later on $rightSideRemovableParamsCount = $this->countRightSideMostParamsByRefOrEmpty($node->items); - // Add new nodes to do the assignment by reference $newNodes = $this->createAssignRefArrayFromListReferences($node->items, $exprVariable, []); $this->addNodesAfterNode($newNodes, $node); - // Remove the stale params right-most-side return $this->removeStaleParams($node, $rightSideRemovableParamsCount); } - /** * Remove the right-side-most params by reference or empty from `list()`, * since they are not needed anymore. @@ -122,61 +103,59 @@ CODE_SAMPLE * @param List_|Array_ $node * @return List_|Array_|null */ - public function removeStaleParams(Node $node, int $rightSideRemovableParamsCount): ?Node + public function removeStaleParams(\PhpParser\Node $node, int $rightSideRemovableParamsCount) : ?\PhpParser\Node { - $nodeItemsCount = count($node->items); + $nodeItemsCount = \count($node->items); if ($rightSideRemovableParamsCount === $nodeItemsCount) { // Remove the parent Assign node /** @var Assign $parentNode */ - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); $this->removeNode($parentNode); return null; } if ($rightSideRemovableParamsCount > 0) { - array_splice($node->items, $nodeItemsCount - $rightSideRemovableParamsCount); + \array_splice($node->items, $nodeItemsCount - $rightSideRemovableParamsCount); } return $node; } - /** * @param List_|Array_ $node */ - private function shouldRefactor(Node $node): bool + private function shouldRefactor(\PhpParser\Node $node) : bool { - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // Check it follows `list(...) = $foo` - if (! $parentNode instanceof Assign) { - return false; + if (!$parentNode instanceof \PhpParser\Node\Expr\Assign) { + return \false; } if ($parentNode->var !== $node) { - return false; + return \false; } - if (! $parentNode->expr instanceof Variable) { - return false; + if (!$parentNode->expr instanceof \PhpParser\Node\Expr\Variable) { + return \false; } return $this->hasAnyItemByRef($node->items); } - /** * Count the number of params by reference placed at the end * These params are not needed anymore, so they can be removed * @param (ArrayItem|null)[] $listItems */ - private function countRightSideMostParamsByRefOrEmpty(array $listItems): int + private function countRightSideMostParamsByRefOrEmpty(array $listItems) : int { // Their position is kept in the array $count = 0; - $listItemsCount = count($listItems); + $listItemsCount = \count($listItems); // Start from the end => right-side-most params for ($i = $listItemsCount - 1; $i >= 0; --$i) { $listItem = $listItems[$i]; // Also include null items, since they can be removed - if (! $listItem instanceof ArrayItem || $listItem->byRef) { + if (!$listItem instanceof \PhpParser\Node\Expr\ArrayItem || $listItem->byRef) { ++$count; continue; } // If it is a nested list, check if all its items are by reference - $isNested = $listItem->value instanceof List_ || $listItem->value instanceof Array_; + $isNested = $listItem->value instanceof \PhpParser\Node\Expr\List_ || $listItem->value instanceof \PhpParser\Node\Expr\Array_; if ($isNested) { /** @var List_|Array_ $nestedList */ $nestedList = $listItem->value; @@ -190,60 +169,43 @@ CODE_SAMPLE } return $count; } - /** * @param (ArrayItem|null)[] $listItems * @param (int|string)[] $nestedArrayIndexes * @return AssignRef[] */ - private function createAssignRefArrayFromListReferences( - array $listItems, - Variable $exprVariable, - array $nestedArrayIndexes - ): array { + private function createAssignRefArrayFromListReferences(array $listItems, \PhpParser\Node\Expr\Variable $exprVariable, array $nestedArrayIndexes) : array + { // After filtering, their original position is kept in the array $newNodes = []; foreach ($listItems as $position => $listItem) { - if (! $listItem instanceof ArrayItem) { + if (!$listItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - if ($listItem->value instanceof Variable && ! $listItem->byRef) { + if ($listItem->value instanceof \PhpParser\Node\Expr\Variable && !$listItem->byRef) { continue; } // Access the key, if provided, or the position otherwise $key = $this->getArrayItemKey($listItem, $position); // Either the item is a variable, or a nested list - if ($listItem->value instanceof Variable) { + if ($listItem->value instanceof \PhpParser\Node\Expr\Variable) { /** @var Variable $itemVariable */ $itemVariable = $listItem->value; // Remove the reference in the present node - $listItem->byRef = false; + $listItem->byRef = \false; // In its place, assign the value by reference on a new node - $assignVariable = new Variable($itemVariable->name); - $newNodes[] = $this->createAssignRefWithArrayDimFetch( - $assignVariable, - $exprVariable, - $nestedArrayIndexes, - $key - ); + $assignVariable = new \PhpParser\Node\Expr\Variable($itemVariable->name); + $newNodes[] = $this->createAssignRefWithArrayDimFetch($assignVariable, $exprVariable, $nestedArrayIndexes, $key); continue; } // Nested list. Combine with the nodes from the recursive call /** @var List_ $nestedList */ $nestedList = $listItem->value; - $listNestedArrayIndexes = array_merge($nestedArrayIndexes, [$key]); - $newNodes = array_merge( - $newNodes, - $this->createAssignRefArrayFromListReferences( - $nestedList->items, - $exprVariable, - $listNestedArrayIndexes - ) - ); + $listNestedArrayIndexes = \array_merge($nestedArrayIndexes, [$key]); + $newNodes = \array_merge($newNodes, $this->createAssignRefArrayFromListReferences($nestedList->items, $exprVariable, $listNestedArrayIndexes)); } return $newNodes; } - /** * Indicates if there is at least 1 item passed by reference, as in: * - list(&$a, $b) @@ -251,11 +213,10 @@ CODE_SAMPLE * * @param (ArrayItem|null)[] $items */ - private function hasAnyItemByRef(array $items): bool + private function hasAnyItemByRef(array $items) : bool { return $this->getItemsByRef($items, self::ANY) !== []; } - /** * Indicates if there is all items are passed by reference, as in: * - list(&$a, &$b) @@ -263,79 +224,67 @@ CODE_SAMPLE * * @param (ArrayItem|null)[] $items */ - private function hasAllItemsByRef(array $items): bool + private function hasAllItemsByRef(array $items) : bool { - return count($this->getItemsByRef($items, self::ALL)) === count($items); + return \count($this->getItemsByRef($items, self::ALL)) === \count($items); } - /** * Return the key inside the ArrayItem, if provided, or the position otherwise * @param int|string $position * @return int|string */ - private function getArrayItemKey(ArrayItem $arrayItem, $position) + private function getArrayItemKey(\PhpParser\Node\Expr\ArrayItem $arrayItem, $position) { - if ($arrayItem->key instanceof String_) { + if ($arrayItem->key instanceof \PhpParser\Node\Scalar\String_) { return $arrayItem->key->value; } - if ($arrayItem->key instanceof LNumber) { + if ($arrayItem->key instanceof \PhpParser\Node\Scalar\LNumber) { return $arrayItem->key->value; } return $position; } - /** * Re-build the path to the variable with all accumulated indexes * @param (string|int)[] $nestedArrayIndexes The path to build nested lists * @param string|int $arrayIndex */ - private function createAssignRefWithArrayDimFetch( - Variable $assignVariable, - Variable $exprVariable, - array $nestedArrayIndexes, - $arrayIndex - ): AssignRef { + private function createAssignRefWithArrayDimFetch(\PhpParser\Node\Expr\Variable $assignVariable, \PhpParser\Node\Expr\Variable $exprVariable, array $nestedArrayIndexes, $arrayIndex) : \PhpParser\Node\Expr\AssignRef + { $nestedExprVariable = $exprVariable; foreach ($nestedArrayIndexes as $nestedArrayIndex) { - $nestedArrayIndexDim = BuilderHelpers::normalizeValue($nestedArrayIndex); - $nestedExprVariable = new ArrayDimFetch($nestedExprVariable, $nestedArrayIndexDim); + $nestedArrayIndexDim = \PhpParser\BuilderHelpers::normalizeValue($nestedArrayIndex); + $nestedExprVariable = new \PhpParser\Node\Expr\ArrayDimFetch($nestedExprVariable, $nestedArrayIndexDim); } - $dim = BuilderHelpers::normalizeValue($arrayIndex); - $arrayDimFetch = new ArrayDimFetch($nestedExprVariable, $dim); - return new AssignRef($assignVariable, $arrayDimFetch); + $dim = \PhpParser\BuilderHelpers::normalizeValue($arrayIndex); + $arrayDimFetch = new \PhpParser\Node\Expr\ArrayDimFetch($nestedExprVariable, $dim); + return new \PhpParser\Node\Expr\AssignRef($assignVariable, $arrayDimFetch); } - /** * @param array $arrayItems * @return ArrayItem[] */ - private function getItemsByRef(array $arrayItems, int $condition): array + private function getItemsByRef(array $arrayItems, int $condition) : array { $itemsByRef = []; - foreach ($arrayItems as $arrayItem) { if ($arrayItem === null) { continue; } - - if (! $this->isItemByRef($arrayItem, $condition)) { + if (!$this->isItemByRef($arrayItem, $condition)) { continue; } - $itemsByRef[] = $arrayItem; } - return $itemsByRef; } - /** * Indicate if the item is a variable by reference, * or a nested list containing variables by reference */ - private function isItemByRef(ArrayItem $arrayItem, int $condition): bool + private function isItemByRef(\PhpParser\Node\Expr\ArrayItem $arrayItem, int $condition) : bool { // Check if the item is a nested list/nested array destructuring - $isNested = $arrayItem->value instanceof List_ || $arrayItem->value instanceof Array_; + $isNested = $arrayItem->value instanceof \PhpParser\Node\Expr\List_ || $arrayItem->value instanceof \PhpParser\Node\Expr\Array_; if ($isNested) { // Recursive call /** @var List_|Array_ $nestedList */ @@ -346,8 +295,8 @@ CODE_SAMPLE // $condition === self::ANY return $this->hasAnyItemByRef($nestedList->items); } - if (! $arrayItem->value instanceof Variable) { - return false; + if (!$arrayItem->value instanceof \PhpParser\Node\Expr\Variable) { + return \false; } return $arrayItem->byRef; } diff --git a/rules/DowngradePhp73/Rector/String_/DowngradeFlexibleHeredocSyntaxRector.php b/rules/DowngradePhp73/Rector/String_/DowngradeFlexibleHeredocSyntaxRector.php index 899dcd01d1b..13b913a889d 100644 --- a/rules/DowngradePhp73/Rector/String_/DowngradeFlexibleHeredocSyntaxRector.php +++ b/rules/DowngradePhp73/Rector/String_/DowngradeFlexibleHeredocSyntaxRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [String_::class, Encapsed::class]; + return [\PhpParser\Node\Scalar\String_::class, \PhpParser\Node\Scalar\Encapsed::class]; } - /** * @param Encapsed|String_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $stringKind = $node->getAttribute(AttributeKey::KIND); - if (! in_array($stringKind, self::HERENOW_DOC_KINDS, true)) { + $stringKind = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND); + if (!\in_array($stringKind, self::HERENOW_DOC_KINDS, \true)) { return null; } - // skip correctly indented - $docIndentation = (string) $node->getAttribute(AttributeKey::DOC_INDENTATION); + $docIndentation = (string) $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::DOC_INDENTATION); if ($docIndentation === '') { return null; } - - $node->setAttribute(AttributeKey::DOC_INDENTATION, ''); - $node->setAttribute(AttributeKey::ORIGINAL_NODE, null); - + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::DOC_INDENTATION, ''); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); return $node; } } diff --git a/rules/DowngradePhp73/Tokenizer/FollowedByCommaAnalyzer.php b/rules/DowngradePhp73/Tokenizer/FollowedByCommaAnalyzer.php index 4c895234aa5..b12e78b7a8b 100644 --- a/rules/DowngradePhp73/Tokenizer/FollowedByCommaAnalyzer.php +++ b/rules/DowngradePhp73/Tokenizer/FollowedByCommaAnalyzer.php @@ -1,37 +1,30 @@ getOldTokens(); - $nextTokenPosition = $node->getEndTokenPos() + 1; while (isset($oldTokens[$nextTokenPosition])) { $currentToken = $oldTokens[$nextTokenPosition]; - // only space - if (is_array($currentToken) || Strings::match($currentToken, '#\s+#')) { + if (\is_array($currentToken) || \RectorPrefix20210509\Nette\Utils\Strings::match($currentToken, '#\\s+#')) { ++$nextTokenPosition; continue; } - // without comma if ($currentToken === ')') { - return false; + return \false; } - break; } - - return true; + return \true; } } diff --git a/rules/DowngradePhp74/Rector/Array_/DowngradeArraySpreadRector.php b/rules/DowngradePhp74/Rector/Array_/DowngradeArraySpreadRector.php index c69757ff7da..1fe925a1442 100644 --- a/rules/DowngradePhp74/Rector/Array_/DowngradeArraySpreadRector.php +++ b/rules/DowngradePhp74/Rector/Array_/DowngradeArraySpreadRector.php @@ -1,7 +1,6 @@ variableNaming = $variableNaming; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Replace array spread with array_merge function', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replace array spread with array_merge function', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -64,8 +56,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -81,53 +72,44 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Array_::class]; + return [\PhpParser\Node\Expr\Array_::class]; } - /** * @param Array_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->shouldRefactor($node)) { + if (!$this->shouldRefactor($node)) { return null; } return $this->refactorNode($node); } - - private function shouldRefactor(Array_ $array): bool + private function shouldRefactor(\PhpParser\Node\Expr\Array_ $array) : bool { // Check that any item in the array is the spread foreach ($array->items as $item) { - if (! $item instanceof ArrayItem) { + if (!$item instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - if ($item->unpack) { - return true; + return \true; } } - - return false; + return \false; } - - private function refactorNode(Array_ $array): FuncCall + private function refactorNode(\PhpParser\Node\Expr\Array_ $array) : \PhpParser\Node\Expr\FuncCall { $newItems = $this->createArrayItems($array); // Replace this array node with an `array_merge` return $this->createArrayMerge($array, $newItems); } - /** * Iterate all array items: * 1. If they use the spread, remove it @@ -135,14 +117,14 @@ CODE_SAMPLE * to be added once the next spread is found, or at the end * @return ArrayItem[] */ - private function createArrayItems(Array_ $array): array + private function createArrayItems(\PhpParser\Node\Expr\Array_ $array) : array { $newItems = []; $accumulatedItems = []; foreach ($array->items as $position => $item) { if ($item !== null && $item->unpack) { // Spread operator found - if (! $item->value instanceof Variable) { + if (!$item->value instanceof \PhpParser\Node\Expr\Variable) { // If it is a not variable, transform it to a variable $item->value = $this->createVariableFromNonVariable($array, $item, $position); } @@ -156,7 +138,6 @@ CODE_SAMPLE $newItems[] = $item; continue; } - // Normal item, it goes into the accumulated array $accumulatedItems[] = $item; } @@ -166,24 +147,22 @@ CODE_SAMPLE } return $newItems; } - /** * @param (ArrayItem|null)[] $items */ - private function createArrayMerge(Array_ $array, array $items): FuncCall + private function createArrayMerge(\PhpParser\Node\Expr\Array_ $array, array $items) : \PhpParser\Node\Expr\FuncCall { /** @var Scope $nodeScope */ - $nodeScope = $array->getAttribute(AttributeKey::SCOPE); - return new FuncCall(new Name('array_merge'), array_map(function (ArrayItem $item) use ($nodeScope): Arg { + $nodeScope = $array->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + return new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('array_merge'), \array_map(function (\PhpParser\Node\Expr\ArrayItem $item) use($nodeScope) : Arg { if ($item !== null && $item->unpack) { // Do not unpack anymore - $item->unpack = false; + $item->unpack = \false; return $this->createArgFromSpreadArrayItem($nodeScope, $item); } - return new Arg($item); + return new \PhpParser\Node\Arg($item); }, $items)); } - /** * If it is a variable, we add it directly * Otherwise it could be a function, method, ternary, traversable, etc @@ -192,85 +171,72 @@ CODE_SAMPLE * such as a method executing some side-effect * @param int|string $position */ - private function createVariableFromNonVariable(Array_ $array, ArrayItem $arrayItem, $position): Variable + private function createVariableFromNonVariable(\PhpParser\Node\Expr\Array_ $array, \PhpParser\Node\Expr\ArrayItem $arrayItem, $position) : \PhpParser\Node\Expr\Variable { /** @var Scope $nodeScope */ - $nodeScope = $array->getAttribute(AttributeKey::SCOPE); + $nodeScope = $array->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); // The variable name will be item0Unpacked, item1Unpacked, etc, // depending on their position. // The number can't be at the end of the var name, or it would // conflict with the counter (for if that name is already taken) - $variableName = $this->variableNaming->resolveFromNodeWithScopeCountAndFallbackName( - $array, - $nodeScope, - 'item' . $position . 'Unpacked' - ); + $variableName = $this->variableNaming->resolveFromNodeWithScopeCountAndFallbackName($array, $nodeScope, 'item' . $position . 'Unpacked'); // Assign the value to the variable, and replace the element with the variable - $newVariable = new Variable($variableName); - $this->addNodeBeforeNode(new Assign($newVariable, $arrayItem->value), $array); + $newVariable = new \PhpParser\Node\Expr\Variable($variableName); + $this->addNodeBeforeNode(new \PhpParser\Node\Expr\Assign($newVariable, $arrayItem->value), $array); return $newVariable; } - /** * @param array $items */ - private function createArrayItem(array $items): ArrayItem + private function createArrayItem(array $items) : \PhpParser\Node\Expr\ArrayItem { - return new ArrayItem(new Array_($items)); + return new \PhpParser\Node\Expr\ArrayItem(new \PhpParser\Node\Expr\Array_($items)); } - - private function createArgFromSpreadArrayItem(Scope $nodeScope, ArrayItem $arrayItem): Arg + private function createArgFromSpreadArrayItem(\PHPStan\Analyser\Scope $nodeScope, \PhpParser\Node\Expr\ArrayItem $arrayItem) : \PhpParser\Node\Arg { // By now every item is a variable /** @var Variable $variable */ $variable = $arrayItem->value; $variableName = $this->getName($variable) ?? ''; - // If the variable is not in scope, it's one we just added. // Then get the type from the attribute if ($nodeScope->hasVariableType($variableName)->yes()) { $type = $nodeScope->getVariableType($variableName); } else { - $originalNode = $arrayItem->getAttribute(AttributeKey::ORIGINAL_NODE); - if ($originalNode instanceof ArrayItem) { + $originalNode = $arrayItem->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE); + if ($originalNode instanceof \PhpParser\Node\Expr\ArrayItem) { $type = $nodeScope->getType($originalNode->value); } else { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } } - - $iteratorToArrayFuncCall = new FuncCall(new Name('iterator_to_array'), [new Arg($arrayItem)]); - + $iteratorToArrayFuncCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('iterator_to_array'), [new \PhpParser\Node\Arg($arrayItem)]); if ($type !== null) { // If we know it is an array, then print it directly // Otherwise PHPStan throws an error: // "Else branch is unreachable because ternary operator condition is always true." - if ($type instanceof ArrayType) { - return new Arg($arrayItem); + if ($type instanceof \PHPStan\Type\ArrayType) { + return new \PhpParser\Node\Arg($arrayItem); } // If it is iterable, then directly return `iterator_to_array` if ($this->isIterableType($type)) { - return new Arg($iteratorToArrayFuncCall); + return new \PhpParser\Node\Arg($iteratorToArrayFuncCall); } } - // Print a ternary, handling either an array or an iterator - $inArrayFuncCall = new FuncCall(new Name('is_array'), [new Arg($arrayItem)]); - return new Arg(new Ternary($inArrayFuncCall, $arrayItem, $iteratorToArrayFuncCall)); + $inArrayFuncCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('is_array'), [new \PhpParser\Node\Arg($arrayItem)]); + return new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\Ternary($inArrayFuncCall, $arrayItem, $iteratorToArrayFuncCall)); } - /** * Iterables: either objects declaring the interface Traversable, * or the pseudo-type iterable */ - private function isIterableType(Type $type): bool + private function isIterableType(\PHPStan\Type\Type $type) : bool { - if ($type instanceof IterableType) { - return true; + if ($type instanceof \PHPStan\Type\IterableType) { + return \true; } - - $traversableObjectType = new ObjectType('Traversable'); - return $traversableObjectType->isSuperTypeOf($type) - ->yes(); + $traversableObjectType = new \PHPStan\Type\ObjectType('Traversable'); + return $traversableObjectType->isSuperTypeOf($type)->yes(); } } diff --git a/rules/DowngradePhp74/Rector/ArrowFunction/ArrowFunctionToAnonymousFunctionRector.php b/rules/DowngradePhp74/Rector/ArrowFunction/ArrowFunctionToAnonymousFunctionRector.php index 32c3c4985d3..5531e96be86 100644 --- a/rules/DowngradePhp74/Rector/ArrowFunction/ArrowFunctionToAnonymousFunctionRector.php +++ b/rules/DowngradePhp74/Rector/ArrowFunction/ArrowFunctionToAnonymousFunctionRector.php @@ -1,7 +1,6 @@ anonymousFunctionFactory = $anonymousFunctionFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replace arrow functions with anonymous functions', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replace arrow functions with anonymous functions', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -43,8 +37,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -56,25 +49,21 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ArrowFunction::class]; + return [\PhpParser\Node\Expr\ArrowFunction::class]; } - /** * @param ArrowFunction $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $stmts = [new Return_($node->expr)]; - + $stmts = [new \PhpParser\Node\Stmt\Return_($node->expr)]; return $this->anonymousFunctionFactory->create($node->params, $stmts, $node->returnType); } } diff --git a/rules/DowngradePhp74/Rector/ClassMethod/DowngradeContravariantArgumentTypeRector.php b/rules/DowngradePhp74/Rector/ClassMethod/DowngradeContravariantArgumentTypeRector.php index 02b018254c4..b020052ecda 100644 --- a/rules/DowngradePhp74/Rector/ClassMethod/DowngradeContravariantArgumentTypeRector.php +++ b/rules/DowngradePhp74/Rector/ClassMethod/DowngradeContravariantArgumentTypeRector.php @@ -1,7 +1,6 @@ phpDocTypeChanger = $phpDocTypeChanger; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Function_::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove contravariant argument type declarations', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove contravariant argument type declarations', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class ParentType {} class ChildType extends ParentType {} @@ -70,8 +63,7 @@ class B extends A } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class ParentType {} class ChildType extends ParentType {} @@ -92,120 +84,88 @@ class B extends A } } CODE_SAMPLE - ), - ]); +)]); } - /** * @param ClassMethod|Function_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->params === []) { return null; } - foreach ($node->params as $param) { $this->refactorParam($param, $node); } - return null; } - - private function isNullableParam(Param $param, FunctionLike $functionLike): bool + private function isNullableParam(\PhpParser\Node\Param $param, \PhpParser\Node\FunctionLike $functionLike) : bool { if ($param->variadic) { - return false; + return \false; } - if ($param->type === null) { - return false; + return \false; } - // Don't consider for Union types - if ($param->type instanceof UnionType) { - return false; + if ($param->type instanceof \PhpParser\Node\UnionType) { + return \false; } - // Contravariant arguments are supported for __construct - if ($this->isName($functionLike, MethodName::CONSTRUCT)) { - return false; + if ($this->isName($functionLike, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { + return \false; } - // Check if the type is different from the one declared in some ancestor return $this->getDifferentParamTypeFromAncestorClass($param, $functionLike) !== null; } - - private function getDifferentParamTypeFromAncestorClass(Param $param, FunctionLike $functionLike): ?string + private function getDifferentParamTypeFromAncestorClass(\PhpParser\Node\Param $param, \PhpParser\Node\FunctionLike $functionLike) : ?string { - $scope = $functionLike->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $functionLike->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { // possibly trait return null; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - $paramName = $this->getName($param); - // If it is the NullableType, extract the name from its inner type /** @var Node $paramType */ $paramType = $param->type; - - if ($param->type instanceof NullableType) { + if ($param->type instanceof \PhpParser\Node\NullableType) { /** @var NullableType $nullableType */ $nullableType = $paramType; $paramTypeName = $this->getName($nullableType->type); } else { $paramTypeName = $this->getName($paramType); } - if ($paramTypeName === null) { return null; } - /** @var string $methodName */ $methodName = $this->getName($functionLike); - // parent classes or implemented interfaces /** @var ClassReflection[] $parentClassReflections */ - $parentClassReflections = array_merge($classReflection->getParents(), $classReflection->getInterfaces()); - + $parentClassReflections = \array_merge($classReflection->getParents(), $classReflection->getInterfaces()); foreach ($parentClassReflections as $parentClassReflection) { - if (! $parentClassReflection->hasMethod($methodName)) { + if (!$parentClassReflection->hasMethod($methodName)) { continue; } - $nativeClassReflection = $parentClassReflection->getNativeReflection(); - // Find the param we're looking for $parentReflectionMethod = $nativeClassReflection->getMethod($methodName); - - $differentAncestorParamTypeName = $this->getDifferentParamTypeFromReflectionMethod( - $parentReflectionMethod, - $paramName, - $paramTypeName - ); - + $differentAncestorParamTypeName = $this->getDifferentParamTypeFromReflectionMethod($parentReflectionMethod, $paramName, $paramTypeName); if ($differentAncestorParamTypeName !== null) { return $differentAncestorParamTypeName; } } - return null; } - - private function getDifferentParamTypeFromReflectionMethod( - ReflectionMethod $reflectionMethod, - string $paramName, - string $paramTypeName - ): ?string { + private function getDifferentParamTypeFromReflectionMethod(\ReflectionMethod $reflectionMethod, string $paramName, string $paramTypeName) : ?string + { /** @var ReflectionParameter[] $parentReflectionMethodParams */ $parentReflectionMethodParams = $reflectionMethod->getParameters(); - foreach ($parentReflectionMethodParams as $parentReflectionMethodParam) { if ($parentReflectionMethodParam->getName() === $paramName) { /** @@ -213,50 +173,42 @@ CODE_SAMPLE * @see https://www.php.net/manual/en/reflectionparameter.gettype.php#125334 */ $reflectionParamType = $parentReflectionMethodParam->getType(); - /** * If the type is null, we don't have enough information * to check if they are different. Then do nothing */ - if (! $reflectionParamType instanceof ReflectionNamedType) { + if (!$reflectionParamType instanceof \ReflectionNamedType) { continue; } - if ($reflectionParamType->getName() !== $paramTypeName) { // We found it: a different param type in some ancestor return $reflectionParamType->getName(); } } } - return null; } - /** * @param ClassMethod|Function_ $functionLike */ - private function refactorParam(Param $param, FunctionLike $functionLike): void + private function refactorParam(\PhpParser\Node\Param $param, \PhpParser\Node\FunctionLike $functionLike) : void { - if (! $this->isNullableParam($param, $functionLike)) { + if (!$this->isNullableParam($param, $functionLike)) { return; } - $this->decorateWithDocBlock($functionLike, $param); $param->type = null; } - /** * @param ClassMethod|Function_ $functionLike */ - private function decorateWithDocBlock(FunctionLike $functionLike, Param $param): void + private function decorateWithDocBlock(\PhpParser\Node\FunctionLike $functionLike, \PhpParser\Node\Param $param) : void { if ($param->type === null) { return; } - $type = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); $paramName = $this->getName($param->var) ?? ''; - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($functionLike); $this->phpDocTypeChanger->changeParamType($phpDocInfo, $type, $param, $paramName); } diff --git a/rules/DowngradePhp74/Rector/ClassMethod/DowngradeCovariantReturnTypeRector.php b/rules/DowngradePhp74/Rector/ClassMethod/DowngradeCovariantReturnTypeRector.php index fdaca2f024c..053fc28735b 100644 --- a/rules/DowngradePhp74/Rector/ClassMethod/DowngradeCovariantReturnTypeRector.php +++ b/rules/DowngradePhp74/Rector/ClassMethod/DowngradeCovariantReturnTypeRector.php @@ -1,7 +1,6 @@ phpDocTypeChanger = $phpDocTypeChanger; $this->privatesCaller = $privatesCaller; $this->returnTagRemover = $returnTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Make method return same type as parent', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Make method return same type as parent', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class ParentType {} class ChildType extends ParentType {} @@ -76,8 +65,7 @@ class B extends A } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class ParentType {} class ChildType extends ParentType {} @@ -98,129 +86,99 @@ class B extends A } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->returnType === null) { return null; } - $parentReturnType = $this->resolveDifferentAncestorReturnType($node, $node->returnType); - if ($parentReturnType instanceof MixedType) { + if ($parentReturnType instanceof \PHPStan\Type\MixedType) { return null; } - // The return type name could either be a classname, without the leading "\", // or one among the reserved identifiers ("static", "self", "iterable", etc) // To find out which is the case, check if this name exists as a class $parentReturnTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($parentReturnType); - if (! $parentReturnTypeNode instanceof Node) { + if (!$parentReturnTypeNode instanceof \PhpParser\Node) { return null; } - // Make it nullable? - if ($node->returnType instanceof NullableType && ! $parentReturnTypeNode instanceof NullableType && ! $parentReturnTypeNode instanceof UnionType) { - $parentReturnTypeNode = new NullableType($parentReturnTypeNode); + if ($node->returnType instanceof \PhpParser\Node\NullableType && !$parentReturnTypeNode instanceof \PhpParser\Node\NullableType && !$parentReturnTypeNode instanceof \PhpParser\Node\UnionType) { + $parentReturnTypeNode = new \PhpParser\Node\NullableType($parentReturnTypeNode); } - // skip if type is already set if ($this->nodeComparator->areNodesEqual($parentReturnTypeNode, $node->returnType)) { return null; } - // Add the docblock before changing the type $this->addDocBlockReturn($node); $node->returnType = $parentReturnTypeNode; - return $node; } - /** * @param UnionType|NullableType|Name|Node\Identifier $returnTypeNode */ - private function resolveDifferentAncestorReturnType(ClassMethod $classMethod, Node $returnTypeNode): Type + private function resolveDifferentAncestorReturnType(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node $returnTypeNode) : \PHPStan\Type\Type { - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { // possibly trait - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return new MixedType(); + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return new \PHPStan\Type\MixedType(); } - - if ($returnTypeNode instanceof UnionType) { - return new MixedType(); + if ($returnTypeNode instanceof \PhpParser\Node\UnionType) { + return new \PHPStan\Type\MixedType(); } - - $bareReturnType = $returnTypeNode instanceof NullableType ? $returnTypeNode->type : $returnTypeNode; - + $bareReturnType = $returnTypeNode instanceof \PhpParser\Node\NullableType ? $returnTypeNode->type : $returnTypeNode; $returnType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($bareReturnType); $methodName = $this->getName($classMethod); - /** @var ClassReflection[] $parentClassesAndInterfaces */ - $parentClassesAndInterfaces = array_merge($classReflection->getParents(), $classReflection->getInterfaces()); - + $parentClassesAndInterfaces = \array_merge($classReflection->getParents(), $classReflection->getInterfaces()); foreach ($parentClassesAndInterfaces as $parentClassAndInterface) { $parentClassAndInterfaceHasMethod = $parentClassAndInterface->hasMethod($methodName); - if (! $parentClassAndInterfaceHasMethod) { + if (!$parentClassAndInterfaceHasMethod) { continue; } - - $classMethodScope = $classMethod->getAttribute(AttributeKey::SCOPE); + $classMethodScope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); $parameterMethodReflection = $parentClassAndInterface->getMethod($methodName, $classMethodScope); - - if (! $parameterMethodReflection instanceof PhpMethodReflection) { + if (!$parameterMethodReflection instanceof \PHPStan\Reflection\Php\PhpMethodReflection) { continue; } - /** @var Type $parentReturnType */ - $parentReturnType = $this->privatesCaller->callPrivateMethod( - $parameterMethodReflection, - 'getReturnType', - [] - ); - + $parentReturnType = $this->privatesCaller->callPrivateMethod($parameterMethodReflection, 'getReturnType', []); if ($parentReturnType->equals($returnType)) { continue; } - // This is an ancestor class with a different return type return $parentReturnType; } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - private function addDocBlockReturn(ClassMethod $classMethod): void + private function addDocBlockReturn(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); - // keep return type if already set one - if (! $phpDocInfo->getReturnType() instanceof MixedType) { + if (!$phpDocInfo->getReturnType() instanceof \PHPStan\Type\MixedType) { return; } - /** @var Node $returnType */ $returnType = $classMethod->returnType; $type = $this->staticTypeMapper->mapPhpParserNodePHPStanType($returnType); - $this->phpDocTypeChanger->changeReturnType($phpDocInfo, $type); $this->returnTagRemover->removeReturnTagIfUseless($phpDocInfo, $classMethod); } diff --git a/rules/DowngradePhp74/Rector/ClassMethod/DowngradeSelfTypeDeclarationRector.php b/rules/DowngradePhp74/Rector/ClassMethod/DowngradeSelfTypeDeclarationRector.php index f1f95f354eb..375ba5dffcb 100644 --- a/rules/DowngradePhp74/Rector/ClassMethod/DowngradeSelfTypeDeclarationRector.php +++ b/rules/DowngradePhp74/Rector/ClassMethod/DowngradeSelfTypeDeclarationRector.php @@ -1,7 +1,6 @@ phpDocFromTypeDeclarationDecorator = $phpDocFromTypeDeclarationDecorator; $this->reflectionProvider = $reflectionProvider; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove "self" return type, add a "@return self" tag instead', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove "self" return type, add a "@return self" tag instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function foo(): self @@ -61,8 +49,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function foo() @@ -71,35 +58,28 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $scope = $node->getAttribute(AttributeKey::SCOPE); + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); if ($scope === null) { // in a trait - $className = $node->getAttribute(AttributeKey::CLASS_NAME); + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); $classReflection = $this->reflectionProvider->getClass($className); } else { $classReflection = $scope->getClassReflection(); } - - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - - $thisType = new ThisType($classReflection); - - if (! $this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $thisType)) { + $thisType = new \PHPStan\Type\ThisType($classReflection); + if (!$this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $thisType)) { return null; } - return $node; } } diff --git a/rules/DowngradePhp74/Rector/Coalesce/DowngradeNullCoalescingOperatorRector.php b/rules/DowngradePhp74/Rector/Coalesce/DowngradeNullCoalescingOperatorRector.php index ff606405ef4..f6fae7186ac 100644 --- a/rules/DowngradePhp74/Rector/Coalesce/DowngradeNullCoalescingOperatorRector.php +++ b/rules/DowngradePhp74/Rector/Coalesce/DowngradeNullCoalescingOperatorRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [AssignCoalesce::class]; + return [\PhpParser\Node\Expr\AssignOp\Coalesce::class]; } - /** * @param AssignCoalesce $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - return new Assign($node->var, new Coalesce($node->var, $node->expr)); + return new \PhpParser\Node\Expr\Assign($node->var, new \PhpParser\Node\Expr\BinaryOp\Coalesce($node->var, $node->expr)); } } diff --git a/rules/DowngradePhp74/Rector/FuncCall/DowngradeArrayMergeCallWithoutArgumentsRector.php b/rules/DowngradePhp74/Rector/FuncCall/DowngradeArrayMergeCallWithoutArgumentsRector.php index ecaa6672adf..8261b463e03 100644 --- a/rules/DowngradePhp74/Rector/FuncCall/DowngradeArrayMergeCallWithoutArgumentsRector.php +++ b/rules/DowngradePhp74/Rector/FuncCall/DowngradeArrayMergeCallWithoutArgumentsRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->shouldRefactor($node)) { + if (!$this->shouldRefactor($node)) { return null; } - - $node->args = [new Arg(new Array_())]; - + $node->args = [new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\Array_())]; return $node; } - - private function shouldRefactor(FuncCall $funcCall): bool + private function shouldRefactor(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - if (! $this->isNames($funcCall, ['array_merge', 'array_merge_recursive'])) { - return false; + if (!$this->isNames($funcCall, ['array_merge', 'array_merge_recursive'])) { + return \false; } - // If param is provided, do nothing if ($funcCall->args !== []) { - return false; + return \false; } - - return true; + return \true; } } diff --git a/rules/DowngradePhp74/Rector/FuncCall/DowngradeStripTagsCallWithArrayRector.php b/rules/DowngradePhp74/Rector/FuncCall/DowngradeStripTagsCallWithArrayRector.php index 95554751532..45027b2cca1 100644 --- a/rules/DowngradePhp74/Rector/FuncCall/DowngradeStripTagsCallWithArrayRector.php +++ b/rules/DowngradePhp74/Rector/FuncCall/DowngradeStripTagsCallWithArrayRector.php @@ -1,7 +1,6 @@ variableNaming = $variableNaming; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Convert 2nd param to `strip_tags` from array to string', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Convert 2nd param to `strip_tags` from array to string', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($string) @@ -64,8 +56,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($string) @@ -83,103 +74,82 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->shouldRefactor($node)) { + if (!$this->shouldRefactor($node)) { return null; } - $allowableTagsParam = $node->args[1]->value; - - if ($allowableTagsParam instanceof Array_) { + if ($allowableTagsParam instanceof \PhpParser\Node\Expr\Array_) { // If it is an array, convert it to string $newExpr = $this->createArrayFromString($allowableTagsParam); - } elseif ($allowableTagsParam instanceof Variable || $allowableTagsParam instanceof PropertyFetch || $allowableTagsParam instanceof ConstFetch || $allowableTagsParam instanceof ClassConstFetch) { + } elseif ($allowableTagsParam instanceof \PhpParser\Node\Expr\Variable || $allowableTagsParam instanceof \PhpParser\Node\Expr\PropertyFetch || $allowableTagsParam instanceof \PhpParser\Node\Expr\ConstFetch || $allowableTagsParam instanceof \PhpParser\Node\Expr\ClassConstFetch) { // If it is a variable or a const (other than null), add logic to maybe convert to string $newExpr = $this->createIsArrayTernaryFromExpression($allowableTagsParam); } else { // It is a function or method call, ternary or coalesce, or any other: // Assign the value to a variable // First obtain a variable name that does not exist in the node (to not override its value) - $variableName = $this->variableNaming->resolveFromFuncCallFirstArgumentWithSuffix( - $node, - 'AllowableTags', - 'allowableTags', - $node->getAttribute(AttributeKey::SCOPE) - ); + $variableName = $this->variableNaming->resolveFromFuncCallFirstArgumentWithSuffix($node, 'AllowableTags', 'allowableTags', $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE)); // Assign the value to the variable - $newVariable = new Variable($variableName); - $this->addNodeBeforeNode(new Assign($newVariable, $allowableTagsParam), $node); - + $newVariable = new \PhpParser\Node\Expr\Variable($variableName); + $this->addNodeBeforeNode(new \PhpParser\Node\Expr\Assign($newVariable, $allowableTagsParam), $node); // Apply refactor on the variable $newExpr = $this->createIsArrayTernaryFromExpression($newVariable); } - // Replace the arg with a new one - array_splice($node->args, 1, 1, [new Arg($newExpr)]); + \array_splice($node->args, 1, 1, [new \PhpParser\Node\Arg($newExpr)]); return $node; } - - private function shouldRefactor(FuncCall $funcCall): bool + private function shouldRefactor(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - if (! $this->isName($funcCall, 'strip_tags')) { - return false; + if (!$this->isName($funcCall, 'strip_tags')) { + return \false; } - // If param not provided, do nothing - if (count($funcCall->args) < 2) { - return false; + if (\count($funcCall->args) < 2) { + return \false; } - // Process anything other than String and null (eg: variables, function calls) $allowableTagsParam = $funcCall->args[1]->value; - // Skip for string - if ($allowableTagsParam instanceof String_) { - return false; + if ($allowableTagsParam instanceof \PhpParser\Node\Scalar\String_) { + return \false; } // Skip for null // Allow for everything else (Array_, Variable, PropertyFetch, ConstFetch, ClassConstFetch, FuncCall, MethodCall, Coalesce, Ternary, others?) - return ! $this->valueResolver->isNull($allowableTagsParam); + return !$this->valueResolver->isNull($allowableTagsParam); } - /** * @param Array_|Variable|PropertyFetch|ConstFetch|ClassConstFetch $expr */ - private function createArrayFromString(Expr $expr): Concat + private function createArrayFromString(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\BinaryOp\Concat { - $args = [new Arg(new String_('><')), new Arg($expr)]; - $implodeFuncCall = new FuncCall(new Name('implode'), $args); - - $concat = new Concat(new String_('<'), $implodeFuncCall); - return new Concat($concat, new String_('>')); + $args = [new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_('><')), new \PhpParser\Node\Arg($expr)]; + $implodeFuncCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('implode'), $args); + $concat = new \PhpParser\Node\Expr\BinaryOp\Concat(new \PhpParser\Node\Scalar\String_('<'), $implodeFuncCall); + return new \PhpParser\Node\Expr\BinaryOp\Concat($concat, new \PhpParser\Node\Scalar\String_('>')); } - /** * @param Variable|PropertyFetch|ConstFetch|ClassConstFetch $expr */ - private function createIsArrayTernaryFromExpression(Expr $expr): Ternary + private function createIsArrayTernaryFromExpression(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\Ternary { - $isArrayFuncCall = new FuncCall(new Name('is_array'), [new Arg($expr)]); - $nullNotIdentical = new NotIdentical($expr, $this->nodeFactory->createNull()); - $booleanAnd = new BooleanAnd($nullNotIdentical, $isArrayFuncCall); - - return new Ternary($booleanAnd, $this->createArrayFromString($expr), $expr); + $isArrayFuncCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('is_array'), [new \PhpParser\Node\Arg($expr)]); + $nullNotIdentical = new \PhpParser\Node\Expr\BinaryOp\NotIdentical($expr, $this->nodeFactory->createNull()); + $booleanAnd = new \PhpParser\Node\Expr\BinaryOp\BooleanAnd($nullNotIdentical, $isArrayFuncCall); + return new \PhpParser\Node\Expr\Ternary($booleanAnd, $this->createArrayFromString($expr), $expr); } } diff --git a/rules/DowngradePhp74/Rector/Identical/DowngradeFreadFwriteFalsyToNegationRector.php b/rules/DowngradePhp74/Rector/Identical/DowngradeFreadFwriteFalsyToNegationRector.php index 2d9e42d060c..c25b633d828 100644 --- a/rules/DowngradePhp74/Rector/Identical/DowngradeFreadFwriteFalsyToNegationRector.php +++ b/rules/DowngradePhp74/Rector/Identical/DowngradeFreadFwriteFalsyToNegationRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identical::class]; + return [\PhpParser\Node\Expr\BinaryOp\Identical::class]; } - /** * @param Identical $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $compareValue = $this->getCompareValue($node); - if (! $compareValue instanceof Expr) { + if (!$compareValue instanceof \PhpParser\Node\Expr) { return null; } - - if (! $this->valueResolver->isFalse($compareValue)) { + if (!$this->valueResolver->isFalse($compareValue)) { return null; } - - return new BooleanNot($this->getFunction($node)); + return new \PhpParser\Node\Expr\BooleanNot($this->getFunction($node)); } - - private function getCompareValue(Identical $identical): ?Expr + private function getCompareValue(\PhpParser\Node\Expr\BinaryOp\Identical $identical) : ?\PhpParser\Node\Expr { - if ($identical->left instanceof FuncCall && $this->isNames($identical->left, self::FUNC_FREAD_FWRITE)) { + if ($identical->left instanceof \PhpParser\Node\Expr\FuncCall && $this->isNames($identical->left, self::FUNC_FREAD_FWRITE)) { return $identical->right; } - if (! $identical->right instanceof FuncCall) { + if (!$identical->right instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - if (! $this->isNames($identical->right, self::FUNC_FREAD_FWRITE)) { + if (!$this->isNames($identical->right, self::FUNC_FREAD_FWRITE)) { return null; } return $identical->left; } - - private function getFunction(Identical $identical): FuncCall + private function getFunction(\PhpParser\Node\Expr\BinaryOp\Identical $identical) : \PhpParser\Node\Expr\FuncCall { /** @var FuncCall $funcCall */ - $funcCall = $identical->left instanceof FuncCall - ? $identical->left - : $identical->right; - + $funcCall = $identical->left instanceof \PhpParser\Node\Expr\FuncCall ? $identical->left : $identical->right; return $funcCall; } } diff --git a/rules/DowngradePhp74/Rector/LNumber/DowngradeNumericLiteralSeparatorRector.php b/rules/DowngradePhp74/Rector/LNumber/DowngradeNumericLiteralSeparatorRector.php index fa3268b1b4e..a0f774c408c 100644 --- a/rules/DowngradePhp74/Rector/LNumber/DowngradeNumericLiteralSeparatorRector.php +++ b/rules/DowngradePhp74/Rector/LNumber/DowngradeNumericLiteralSeparatorRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [LNumber::class, DNumber::class]; + return [\PhpParser\Node\Scalar\LNumber::class, \PhpParser\Node\Scalar\DNumber::class]; } - /** * @param LNumber|DNumber $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->shouldRefactor($node)) { + if (!$this->shouldRefactor($node)) { return null; } - $numberNode = clone $node; $numberNodeValue = (string) $numberNode->value; - if (Strings::contains($numberNodeValue, '+')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($numberNodeValue, '+')) { return null; } - $node->value = (string) $node->value; - /** * This code follows a guess, to avoid modifying floats needlessly. * If the node is a float, but it doesn't contain ".", @@ -84,21 +70,20 @@ CODE_SAMPLE * by adding ".0" at the end (eg: 0.0). * Then, add it again. */ - if ($node instanceof DNumber && ! Strings::contains($node->value, '.')) { + if ($node instanceof \PhpParser\Node\Scalar\DNumber && !\RectorPrefix20210509\Nette\Utils\Strings::contains($node->value, '.')) { $node->value .= '.0'; } return $node; } - /** * @param LNumber|DNumber $node */ - public function shouldRefactor(Node $node): bool + public function shouldRefactor(\PhpParser\Node $node) : bool { // "_" notation can be applied to decimal numbers only - if ($node instanceof LNumber) { - return $node->getAttribute(AttributeKey::KIND) === LNumber::KIND_DEC; + if ($node instanceof \PhpParser\Node\Scalar\LNumber) { + return $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND) === \PhpParser\Node\Scalar\LNumber::KIND_DEC; } - return true; + return \true; } } diff --git a/rules/DowngradePhp74/Rector/Property/DowngradeTypedPropertyRector.php b/rules/DowngradePhp74/Rector/Property/DowngradeTypedPropertyRector.php index f4ebadb258b..e544b9bbf20 100644 --- a/rules/DowngradePhp74/Rector/Property/DowngradeTypedPropertyRector.php +++ b/rules/DowngradePhp74/Rector/Property/DowngradeTypedPropertyRector.php @@ -1,7 +1,6 @@ phpDocTypeChanger = $phpDocTypeChanger; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes property type definition from type definitions to `@var` annotations.', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes property type definition from type definitions to `@var` annotations.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private string $property; } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -54,32 +46,26 @@ class SomeClass private $property; } CODE_SAMPLE - ), - ]); +)]); } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->type === null) { return null; } - $this->decoratePropertyWithDocBlock($node, $node->type); $node->type = null; - return $node; } - - private function decoratePropertyWithDocBlock(Property $property, Node $typeNode): void + private function decoratePropertyWithDocBlock(\PhpParser\Node\Stmt\Property $property, \PhpParser\Node $typeNode) : void { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); if ($phpDocInfo->getVarTagValueNode() !== null) { return; } - $newType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($typeNode); $this->phpDocTypeChanger->changeVarType($phpDocInfo, $newType); } diff --git a/rules/DowngradePhp80/Rector/Catch_/DowngradeNonCapturingCatchesRector.php b/rules/DowngradePhp80/Rector/Catch_/DowngradeNonCapturingCatchesRector.php index c0cdb1e4073..fc1e2bcea91 100644 --- a/rules/DowngradePhp80/Rector/Catch_/DowngradeNonCapturingCatchesRector.php +++ b/rules/DowngradePhp80/Rector/Catch_/DowngradeNonCapturingCatchesRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Catch_::class]; + return [\PhpParser\Node\Stmt\Catch_::class]; } - /** * @param Catch_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->var !== null) { return null; } - - $node->var = new Variable('exception'); - + $node->var = new \PhpParser\Node\Expr\Variable('exception'); return $node; } } diff --git a/rules/DowngradePhp80/Rector/ClassConstFetch/DowngradeClassOnObjectToGetClassRector.php b/rules/DowngradePhp80/Rector/ClassConstFetch/DowngradeClassOnObjectToGetClassRector.php index d75d3941493..3e343fa8153 100644 --- a/rules/DowngradePhp80/Rector/ClassConstFetch/DowngradeClassOnObjectToGetClassRector.php +++ b/rules/DowngradePhp80/Rector/ClassConstFetch/DowngradeClassOnObjectToGetClassRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassConstFetch::class]; + return [\PhpParser\Node\Expr\ClassConstFetch::class]; } - /** * @param ClassConstFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node->name, 'class')) { + if (!$this->isName($node->name, 'class')) { return null; } - - if (! $node->class instanceof Variable) { + if (!$node->class instanceof \PhpParser\Node\Expr\Variable) { return null; } - - return new FuncCall(new Name('get_class'), [new Arg($node->class)]); + return new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('get_class'), [new \PhpParser\Node\Arg($node->class)]); } } diff --git a/rules/DowngradePhp80/Rector/ClassMethod/DowngradeStaticTypeDeclarationRector.php b/rules/DowngradePhp80/Rector/ClassMethod/DowngradeStaticTypeDeclarationRector.php index 1d96d16916d..568e528a9ad 100644 --- a/rules/DowngradePhp80/Rector/ClassMethod/DowngradeStaticTypeDeclarationRector.php +++ b/rules/DowngradePhp80/Rector/ClassMethod/DowngradeStaticTypeDeclarationRector.php @@ -1,7 +1,6 @@ phpDocFromTypeDeclarationDecorator = $phpDocFromTypeDeclarationDecorator; $this->reflectionProvider = $reflectionProvider; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove "static" return and param type, add a "@param $this" and "@return $this" tag instead', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove "static" return and param type, add a "@param $this" and "@return $this" tag instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function getStatic(): static @@ -61,8 +49,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -74,38 +61,30 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $scope = $node->getAttribute(AttributeKey::SCOPE); + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); if ($scope === null) { - $className = $node->getAttribute(AttributeKey::CLASS_NAME); + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); $classReflection = $this->reflectionProvider->getClass($className); } else { $classReflection = $scope->getClassReflection(); } - - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - - $staticType = new StaticType($classReflection->getName()); - + $staticType = new \PHPStan\Type\StaticType($classReflection->getName()); foreach ($node->getParams() as $param) { $this->phpDocFromTypeDeclarationDecorator->decorateParamWithSpecificType($param, $node, $staticType); } - - if (! $this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $staticType)) { + if (!$this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $staticType)) { return null; } - return $node; } } diff --git a/rules/DowngradePhp80/Rector/ClassMethod/DowngradeTrailingCommasInParamUseRector.php b/rules/DowngradePhp80/Rector/ClassMethod/DowngradeTrailingCommasInParamUseRector.php index 364458751ff..d4e2b4ab5cc 100644 --- a/rules/DowngradePhp80/Rector/ClassMethod/DowngradeTrailingCommasInParamUseRector.php +++ b/rules/DowngradePhp80/Rector/ClassMethod/DowngradeTrailingCommasInParamUseRector.php @@ -1,7 +1,6 @@ followedByCommaAnalyzer = $followedByCommaAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove trailing commas in param or use list', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove trailing commas in param or use list', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function __construct(string $value1, string $value2,) @@ -59,8 +51,7 @@ function inFunction(string $value1, string $value2,) { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function __construct(string $value1, string $value2) @@ -77,97 +68,70 @@ function inFunction(string $value1, string $value2) { } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ - ClassMethod::class, - Function_::class, - Closure::class, - StaticCall::class, - FuncCall::class, - MethodCall::class, - New_::class, - ]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Expr\Closure::class, \PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Expr\FuncCall::class, \PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\New_::class]; } - /** * @param ClassMethod|Function_|Closure|FuncCall|MethodCall|StaticCall|New_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof MethodCall || - $node instanceof FuncCall || - $node instanceof StaticCall || - $node instanceof New_ - ) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall || $node instanceof \PhpParser\Node\Expr\FuncCall || $node instanceof \PhpParser\Node\Expr\StaticCall || $node instanceof \PhpParser\Node\Expr\New_) { /** @var MethodCall|FuncCall|StaticCall|New_ $node */ return $this->processArgs($node); } - - if ($node instanceof Closure) { + if ($node instanceof \PhpParser\Node\Expr\Closure) { $this->processUses($node); } - /** @var ClassMethod|Function_ $node */ return $this->processParams($node); } - /** * @param FuncCall|MethodCall|StaticCall|New_ $node */ - private function processArgs(Node $node): ?Node + private function processArgs(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->args === []) { return null; } - return $this->cleanTrailingComma($node, $node->args); } - - private function processUses(Closure $node): void + private function processUses(\PhpParser\Node\Expr\Closure $node) : void { if ($node->uses === []) { return; } - $this->cleanTrailingComma($node, $node->uses); } - /** * @param ClassMethod|Function_|Closure $node */ - private function processParams(Node $node): ?Node + private function processParams(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->params === []) { return null; } - return $this->cleanTrailingComma($node, $node->params); } - /** * @param ClosureUse[]|Param[]|Arg[] $array */ - private function cleanTrailingComma(Node $node, array $array): ?Node + private function cleanTrailingComma(\PhpParser\Node $node, array $array) : ?\PhpParser\Node { - $lastPosition = array_key_last($array); - + \end($array); + $lastPosition = \key($array); $last = $array[$lastPosition]; - if (! $this->followedByCommaAnalyzer->isFollowed($this->file, $last)) { + if (!$this->followedByCommaAnalyzer->isFollowed($this->file, $last)) { return null; } - - $node->setAttribute(AttributeKey::ORIGINAL_NODE, null); - $last->setAttribute(AttributeKey::FUNC_ARGS_TRAILING_COMMA, false); - + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); + $last->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::FUNC_ARGS_TRAILING_COMMA, \false); return $node; } } diff --git a/rules/DowngradePhp80/Rector/Class_/DowngradePropertyPromotionRector.php b/rules/DowngradePhp80/Rector/Class_/DowngradePropertyPromotionRector.php index 50886e7ebbf..185293993bf 100644 --- a/rules/DowngradePhp80/Rector/Class_/DowngradePropertyPromotionRector.php +++ b/rules/DowngradePhp80/Rector/Class_/DowngradePropertyPromotionRector.php @@ -1,7 +1,6 @@ classInsertManipulator = $classInsertManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change constructor property promotion to property asssign', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change constructor property promotion to property asssign', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function __construct(public float $value = 0.0) @@ -45,9 +39,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public float $value; @@ -58,111 +50,89 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $promotedParams = $this->resolvePromotedParams($node); if ($promotedParams === []) { return null; } - $properties = $this->addPropertiesFromParams($promotedParams, $node); - $this->addPropertyAssignsToConstructorClassMethod($properties, $node); - foreach ($promotedParams as $promotedParam) { $promotedParam->flags = 0; } - return $node; } - /** * @return Param[] */ - private function resolvePromotedParams(Class_ $class): array + private function resolvePromotedParams(\PhpParser\Node\Stmt\Class_ $class) : array { - $constructorClassMethod = $class->getMethod(MethodName::CONSTRUCT); - if (! $constructorClassMethod instanceof ClassMethod) { + $constructorClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructorClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return []; } - $promotedParams = []; - foreach ($constructorClassMethod->params as $param) { if ($param->flags === 0) { continue; } - $promotedParams[] = $param; } - return $promotedParams; } - /** * @param Param[] $promotedParams * @return Property[] */ - private function addPropertiesFromParams(array $promotedParams, Class_ $class): array + private function addPropertiesFromParams(array $promotedParams, \PhpParser\Node\Stmt\Class_ $class) : array { $properties = $this->createPropertiesFromParams($promotedParams); $this->classInsertManipulator->addPropertiesToClass($class, $properties); - return $properties; } - /** * @param Property[] $properties */ - private function addPropertyAssignsToConstructorClassMethod(array $properties, Class_ $class): void + private function addPropertyAssignsToConstructorClassMethod(array $properties, \PhpParser\Node\Stmt\Class_ $class) : void { $assigns = []; - foreach ($properties as $property) { $propertyName = $this->getName($property); $assign = $this->nodeFactory->createPropertyAssignment($propertyName); - $assigns[] = new Expression($assign); + $assigns[] = new \PhpParser\Node\Stmt\Expression($assign); } - /** @var ClassMethod $constructorClassMethod */ - $constructorClassMethod = $class->getMethod(MethodName::CONSTRUCT); - $constructorClassMethod->stmts = array_merge($assigns, (array) $constructorClassMethod->stmts); + $constructorClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + $constructorClassMethod->stmts = \array_merge($assigns, (array) $constructorClassMethod->stmts); } - /** * @param Param[] $params * @return Property[] */ - private function createPropertiesFromParams(array $params): array + private function createPropertiesFromParams(array $params) : array { $properties = []; - foreach ($params as $param) { /** @var string $name */ $name = $this->getName($param->var); - $property = $this->nodeFactory->createProperty($name); $property->flags = $param->flags; $property->type = $param->type; - $properties[] = $property; } - return $properties; } } diff --git a/rules/DowngradePhp80/Rector/Expression/DowngradeMatchToSwitchRector.php b/rules/DowngradePhp80/Rector/Expression/DowngradeMatchToSwitchRector.php index 1625b6952af..17cbd341b3d 100644 --- a/rules/DowngradePhp80/Rector/Expression/DowngradeMatchToSwitchRector.php +++ b/rules/DowngradePhp80/Rector/Expression/DowngradeMatchToSwitchRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Expression::class]; + return [\PhpParser\Node\Stmt\Expression::class]; } - /** * @param Expression $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof Assign) { + if (!$node->expr instanceof \PhpParser\Node\Expr\Assign) { return null; } - $assign = $node->expr; - if (! $assign->expr instanceof Match_) { + if (!$assign->expr instanceof \PhpParser\Node\Expr\Match_) { return null; } - /** @var Match_ $match */ $match = $assign->expr; - $switchCases = $this->createSwitchCasesFromMatchArms($match->arms, $assign->var); - return new Switch_($match->cond, $switchCases); + return new \PhpParser\Node\Stmt\Switch_($match->cond, $switchCases); } - /** * @param MatchArm[] $matchArms * @return Case_[] */ - private function createSwitchCasesFromMatchArms(array $matchArms, Expr $assignVarExpr): array + private function createSwitchCasesFromMatchArms(array $matchArms, \PhpParser\Node\Expr $assignVarExpr) : array { $switchCases = []; - foreach ($matchArms as $matchArm) { - if (count((array) $matchArm->conds) > 1) { + if (\count((array) $matchArm->conds) > 1) { $lastCase = null; - foreach ((array) $matchArm->conds as $matchArmCond) { - $lastCase = new Case_($matchArmCond); + $lastCase = new \PhpParser\Node\Stmt\Case_($matchArmCond); $switchCases[] = $lastCase; } - - if (! $lastCase instanceof Case_) { - throw new ShouldNotHappenException(); + if (!$lastCase instanceof \PhpParser\Node\Stmt\Case_) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $lastCase->stmts = $this->createSwitchStmts($matchArm, $assignVarExpr); } else { $stmts = $this->createSwitchStmts($matchArm, $assignVarExpr); - $switchCases[] = new Case_($matchArm->conds[0] ?? null, $stmts); + $switchCases[] = new \PhpParser\Node\Stmt\Case_($matchArm->conds[0] ?? null, $stmts); } } return $switchCases; } - /** * @return Stmt[] */ - private function createSwitchStmts(MatchArm $matchArm, Expr $assignVarExpr): array + private function createSwitchStmts(\PhpParser\Node\MatchArm $matchArm, \PhpParser\Node\Expr $assignVarExpr) : array { $stmts = []; - - $stmts[] = new Expression(new Assign($assignVarExpr, $matchArm->body)); - $stmts[] = new Break_(); - + $stmts[] = new \PhpParser\Node\Stmt\Expression(new \PhpParser\Node\Expr\Assign($assignVarExpr, $matchArm->body)); + $stmts[] = new \PhpParser\Node\Stmt\Break_(); return $stmts; } } diff --git a/rules/DowngradePhp80/Rector/FunctionLike/DowngradeMixedTypeDeclarationRector.php b/rules/DowngradePhp80/Rector/FunctionLike/DowngradeMixedTypeDeclarationRector.php index 1028e52c771..4bbaef90269 100644 --- a/rules/DowngradePhp80/Rector/FunctionLike/DowngradeMixedTypeDeclarationRector.php +++ b/rules/DowngradePhp80/Rector/FunctionLike/DowngradeMixedTypeDeclarationRector.php @@ -1,7 +1,6 @@ phpDocFromTypeDeclarationDecorator = $phpDocFromTypeDeclarationDecorator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, ClassMethod::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove the "mixed" param and return type, add a @param and @return tag instead', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove the "mixed" param and return type, add a @param and @return tag instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function someFunction(mixed $anything): mixed @@ -50,8 +41,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -63,26 +53,20 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param ClassMethod|Function_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $mixedType = new MixedType(); - + $mixedType = new \PHPStan\Type\MixedType(); foreach ($node->getParams() as $param) { $this->phpDocFromTypeDeclarationDecorator->decorateParamWithSpecificType($param, $node, $mixedType); } - - if (! $this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $mixedType)) { + if (!$this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, $mixedType)) { return null; } - return $node; } } diff --git a/rules/DowngradePhp80/Rector/FunctionLike/DowngradeUnionTypeDeclarationRector.php b/rules/DowngradePhp80/Rector/FunctionLike/DowngradeUnionTypeDeclarationRector.php index b39b51cac07..ea5be08d9be 100644 --- a/rules/DowngradePhp80/Rector/FunctionLike/DowngradeUnionTypeDeclarationRector.php +++ b/rules/DowngradePhp80/Rector/FunctionLike/DowngradeUnionTypeDeclarationRector.php @@ -1,7 +1,6 @@ phpDocFromTypeDeclarationDecorator = $phpDocFromTypeDeclarationDecorator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, ClassMethod::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Remove the union type params and returns, add @param/@return tags instead', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove the union type params and returns, add @param/@return tags instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function echoInput(string|int $input): int|bool @@ -53,8 +44,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -67,32 +57,25 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param ClassMethod|Function_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($node->getParams() as $param) { - if (! $param->type instanceof UnionType) { + if (!$param->type instanceof \PhpParser\Node\UnionType) { continue; } - $this->phpDocFromTypeDeclarationDecorator->decorateParam($param, $node, [\PHPStan\Type\UnionType::class]); } - - if (! $node->returnType instanceof UnionType) { + if (!$node->returnType instanceof \PhpParser\Node\UnionType) { return null; } - - if (! $this->phpDocFromTypeDeclarationDecorator->decorate($node)) { + if (!$this->phpDocFromTypeDeclarationDecorator->decorate($node)) { return null; } - return $node; } } diff --git a/rules/DowngradePhp80/Rector/NullsafeMethodCall/DowngradeNullsafeToTernaryOperatorRector.php b/rules/DowngradePhp80/Rector/NullsafeMethodCall/DowngradeNullsafeToTernaryOperatorRector.php index 63570336359..f3ba7a534fa 100644 --- a/rules/DowngradePhp80/Rector/NullsafeMethodCall/DowngradeNullsafeToTernaryOperatorRector.php +++ b/rules/DowngradePhp80/Rector/NullsafeMethodCall/DowngradeNullsafeToTernaryOperatorRector.php @@ -1,7 +1,6 @@ variableNaming = $variableNaming; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change nullsafe operator to ternary operator rector', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change nullsafe operator to ternary operator rector', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $dateAsString = $booking->getStartDate()?->asDateTimeString(); $dateAsString = $booking->startDate?->dateTimeString; CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $dateAsString = ($bookingGetStartDate = $booking->getStartDate()) ? $bookingGetStartDate->asDateTimeString() : null; $dateAsString = ($bookingGetStartDate = $booking->startDate) ? $bookingGetStartDate->dateTimeString : null; CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [NullsafeMethodCall::class, NullsafePropertyFetch::class]; + return [\PhpParser\Node\Expr\NullsafeMethodCall::class, \PhpParser\Node\Expr\NullsafePropertyFetch::class]; } - /** * @param NullsafeMethodCall|NullsafePropertyFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $tempVarName = $this->variableNaming->resolveFromNodeWithScopeCountAndFallbackName( - $node->var, - $node->getAttribute(AttributeKey::SCOPE), - '_' - ); - - $variable = new Variable($tempVarName); - $called = $node instanceof NullsafeMethodCall - ? new MethodCall($variable, $node->name, $node->args) - : new PropertyFetch($variable, $node->name); - - return new Ternary(new Assign($variable, $node->var), $called, $this->nodeFactory->createNull()); + $tempVarName = $this->variableNaming->resolveFromNodeWithScopeCountAndFallbackName($node->var, $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE), '_'); + $variable = new \PhpParser\Node\Expr\Variable($tempVarName); + $called = $node instanceof \PhpParser\Node\Expr\NullsafeMethodCall ? new \PhpParser\Node\Expr\MethodCall($variable, $node->name, $node->args) : new \PhpParser\Node\Expr\PropertyFetch($variable, $node->name); + return new \PhpParser\Node\Expr\Ternary(new \PhpParser\Node\Expr\Assign($variable, $node->var), $called, $this->nodeFactory->createNull()); } } diff --git a/rules/DowngradePhp80/Rector/Property/DowngradeUnionTypeTypedPropertyRector.php b/rules/DowngradePhp80/Rector/Property/DowngradeUnionTypeTypedPropertyRector.php index b0f35519556..916c22756a0 100644 --- a/rules/DowngradePhp80/Rector/Property/DowngradeUnionTypeTypedPropertyRector.php +++ b/rules/DowngradePhp80/Rector/Property/DowngradeUnionTypeTypedPropertyRector.php @@ -1,7 +1,6 @@ phpDocTypeChanger = $phpDocTypeChanger; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Removes union type property type definition, adding `@var` annotations instead.', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removes union type property type definition, adding `@var` annotations instead.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private string|int $property; } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -55,47 +47,38 @@ class SomeClass private $property; } CODE_SAMPLE - ), - ]); +)]); } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->type === null) { return null; } - - if (! $this->shouldRemoveProperty($node)) { + if (!$this->shouldRemoveProperty($node)) { return null; } - $this->decoratePropertyWithDocBlock($node, $node->type); $node->type = null; - return $node; } - - private function decoratePropertyWithDocBlock(Property $property, Node $typeNode): void + private function decoratePropertyWithDocBlock(\PhpParser\Node\Stmt\Property $property, \PhpParser\Node $typeNode) : void { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); if ($phpDocInfo->getVarTagValueNode() !== null) { return; } - $newType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($typeNode); $this->phpDocTypeChanger->changeVarType($phpDocInfo, $newType); } - - private function shouldRemoveProperty(Property $property): bool + private function shouldRemoveProperty(\PhpParser\Node\Stmt\Property $property) : bool { if ($property->type === null) { - return false; + return \false; } - // Check it is the union type - return $property->type instanceof UnionType; + return $property->type instanceof \PhpParser\Node\UnionType; } } diff --git a/rules/EarlyReturn/NodeFactory/InvertedIfFactory.php b/rules/EarlyReturn/NodeFactory/InvertedIfFactory.php index 3b61a0b6508..648ee4c8fa8 100644 --- a/rules/EarlyReturn/NodeFactory/InvertedIfFactory.php +++ b/rules/EarlyReturn/NodeFactory/InvertedIfFactory.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->conditionInverter = $conditionInverter; $this->contextAnalyzer = $contextAnalyzer; } - /** * @param Expr[] $conditions * @return If_[] */ - public function createFromConditions(If_ $if, array $conditions, Return_ $return): array + public function createFromConditions(\PhpParser\Node\Stmt\If_ $if, array $conditions, \PhpParser\Node\Stmt\Return_ $return) : array { $ifs = []; - $stmt = $this->contextAnalyzer->isInLoop($if) && ! $this->getIfNextReturn($if) - ? [new Continue_()] - : [$return]; - + $stmt = $this->contextAnalyzer->isInLoop($if) && !$this->getIfNextReturn($if) ? [new \PhpParser\Node\Stmt\Continue_()] : [$return]; $getNextReturnExpr = $this->getNextReturnExpr($if); - if ($getNextReturnExpr instanceof Return_) { + if ($getNextReturnExpr instanceof \PhpParser\Node\Stmt\Return_) { $return->expr = $getNextReturnExpr->expr; } - foreach ($conditions as $condition) { $invertedCondition = $this->conditionInverter->createInvertedCondition($condition); - $if = new If_($invertedCondition); + $if = new \PhpParser\Node\Stmt\If_($invertedCondition); $if->stmts = $stmt; $ifs[] = $if; } - return $ifs; } - - private function getNextReturnExpr(If_ $if): ?Node + private function getNextReturnExpr(\PhpParser\Node\Stmt\If_ $if) : ?\PhpParser\Node { - $closure = $this->betterNodeFinder->findParentType($if, Closure::class); - if ($closure instanceof Closure) { + $closure = $this->betterNodeFinder->findParentType($if, \PhpParser\Node\Expr\Closure::class); + if ($closure instanceof \PhpParser\Node\Expr\Closure) { return null; } - - return $this->betterNodeFinder->findFirstNext($if, function (Node $node): bool { - return $node instanceof Return_ && $node->expr instanceof Expr; + return $this->betterNodeFinder->findFirstNext($if, function (\PhpParser\Node $node) : bool { + return $node instanceof \PhpParser\Node\Stmt\Return_ && $node->expr instanceof \PhpParser\Node\Expr; }); } - - private function getIfNextReturn(If_ $if): ?Return_ + private function getIfNextReturn(\PhpParser\Node\Stmt\If_ $if) : ?\PhpParser\Node\Stmt\Return_ { - $nextNode = $if->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextNode instanceof Return_) { + $nextNode = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextNode instanceof \PhpParser\Node\Stmt\Return_) { return null; } - return $nextNode; } } diff --git a/rules/EarlyReturn/NodeTransformer/ConditionInverter.php b/rules/EarlyReturn/NodeTransformer/ConditionInverter.php index b080bf92010..a21114e14b8 100644 --- a/rules/EarlyReturn/NodeTransformer/ConditionInverter.php +++ b/rules/EarlyReturn/NodeTransformer/ConditionInverter.php @@ -1,7 +1,6 @@ binaryOpManipulator = $binaryOpManipulator; } - - public function createInvertedCondition(Expr $expr): Expr + public function createInvertedCondition(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { // inverse condition - if ($expr instanceof BinaryOp) { + if ($expr instanceof \PhpParser\Node\Expr\BinaryOp) { $inversedCondition = $this->binaryOpManipulator->invertCondition($expr); - if (! $inversedCondition instanceof BinaryOp) { - return new BooleanNot($expr); + if (!$inversedCondition instanceof \PhpParser\Node\Expr\BinaryOp) { + return new \PhpParser\Node\Expr\BooleanNot($expr); } - if ($inversedCondition instanceof BooleanAnd) { - return new BooleanNot($expr); + if ($inversedCondition instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { + return new \PhpParser\Node\Expr\BooleanNot($expr); } return $inversedCondition; } - - if ($expr instanceof BooleanNot) { + if ($expr instanceof \PhpParser\Node\Expr\BooleanNot) { return $expr->expr; } - - return new BooleanNot($expr); + return new \PhpParser\Node\Expr\BooleanNot($expr); } } diff --git a/rules/EarlyReturn/Rector/Foreach_/ChangeNestedForeachIfsToEarlyContinueRector.php b/rules/EarlyReturn/Rector/Foreach_/ChangeNestedForeachIfsToEarlyContinueRector.php index 86f4372b6f1..2d9cd747f0e 100644 --- a/rules/EarlyReturn/Rector/Foreach_/ChangeNestedForeachIfsToEarlyContinueRector.php +++ b/rules/EarlyReturn/Rector/Foreach_/ChangeNestedForeachIfsToEarlyContinueRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->conditionInverter = $conditionInverter; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change nested ifs to foreach with continue', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change nested ifs to foreach with continue', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -63,8 +56,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -84,97 +76,76 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Foreach_::class]; + return [\PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $nestedIfsWithOnlyNonReturn = $this->ifManipulator->collectNestedIfsWithNonBreaking($node); - if (count($nestedIfsWithOnlyNonReturn) < 2) { + if (\count($nestedIfsWithOnlyNonReturn) < 2) { return null; } - return $this->processNestedIfsWithNonBreaking($node, $nestedIfsWithOnlyNonReturn); } - /** * @param If_[] $nestedIfsWithOnlyReturn */ - private function processNestedIfsWithNonBreaking(Foreach_ $foreach, array $nestedIfsWithOnlyReturn): Foreach_ + private function processNestedIfsWithNonBreaking(\PhpParser\Node\Stmt\Foreach_ $foreach, array $nestedIfsWithOnlyReturn) : \PhpParser\Node\Stmt\Foreach_ { // add nested if openly after this - $nestedIfsWithOnlyReturnCount = count($nestedIfsWithOnlyReturn); - + $nestedIfsWithOnlyReturnCount = \count($nestedIfsWithOnlyReturn); // clear $foreach->stmts = []; - foreach ($nestedIfsWithOnlyReturn as $key => $nestedIfWithOnlyReturn) { // last item → the return node if ($nestedIfsWithOnlyReturnCount === $key + 1) { $finalReturn = clone $nestedIfWithOnlyReturn; - $this->addInvertedIfStmtWithContinue($nestedIfWithOnlyReturn, $foreach); - // should skip for weak inversion if ($this->isBooleanOrWithWeakComparison($nestedIfWithOnlyReturn->cond)) { continue; } - - $foreach->stmts = array_merge($foreach->stmts, $finalReturn->stmts); + $foreach->stmts = \array_merge($foreach->stmts, $finalReturn->stmts); } else { $this->addInvertedIfStmtWithContinue($nestedIfWithOnlyReturn, $foreach); } } - return $foreach; } - - private function addInvertedIfStmtWithContinue(If_ $nestedIfWithOnlyReturn, Foreach_ $foreach): void + private function addInvertedIfStmtWithContinue(\PhpParser\Node\Stmt\If_ $nestedIfWithOnlyReturn, \PhpParser\Node\Stmt\Foreach_ $foreach) : void { $invertedCondition = $this->conditionInverter->createInvertedCondition($nestedIfWithOnlyReturn->cond); - // special case - if ($invertedCondition instanceof BooleanNot && $invertedCondition->expr instanceof BooleanAnd) { + if ($invertedCondition instanceof \PhpParser\Node\Expr\BooleanNot && $invertedCondition->expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { $leftExpr = $this->negateOrDeNegate($invertedCondition->expr->left); - $if = new If_($leftExpr); - $if->stmts[] = new Continue_(); + $if = new \PhpParser\Node\Stmt\If_($leftExpr); + $if->stmts[] = new \PhpParser\Node\Stmt\Continue_(); $foreach->stmts[] = $if; - $rightExpr = $this->negateOrDeNegate($invertedCondition->expr->right); - $if = new If_($rightExpr); - $if->stmts[] = new Continue_(); + $if = new \PhpParser\Node\Stmt\If_($rightExpr); + $if->stmts[] = new \PhpParser\Node\Stmt\Continue_(); $foreach->stmts[] = $if; - return; } - // should skip for weak inversion if ($this->isBooleanOrWithWeakComparison($nestedIfWithOnlyReturn->cond)) { $foreach->stmts[] = $nestedIfWithOnlyReturn; - return; } - - $nestedIfWithOnlyReturn->setAttribute(AttributeKey::ORIGINAL_NODE, null); - + $nestedIfWithOnlyReturn->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); $nestedIfWithOnlyReturn->cond = $invertedCondition; - $nestedIfWithOnlyReturn->stmts = [new Continue_()]; - + $nestedIfWithOnlyReturn->stmts = [new \PhpParser\Node\Stmt\Continue_()]; $foreach->stmts[] = $nestedIfWithOnlyReturn; } - /** * Matches: * $a == 1 || $b == 1 @@ -182,33 +153,27 @@ CODE_SAMPLE * Skips: * $a === 1 || $b === 2 */ - private function isBooleanOrWithWeakComparison(Expr $expr): bool + private function isBooleanOrWithWeakComparison(\PhpParser\Node\Expr $expr) : bool { - if (! $expr instanceof BooleanOr) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { + return \false; } - - if ($expr->left instanceof Equal) { - return true; + if ($expr->left instanceof \PhpParser\Node\Expr\BinaryOp\Equal) { + return \true; } - - if ($expr->left instanceof NotEqual) { - return true; + if ($expr->left instanceof \PhpParser\Node\Expr\BinaryOp\NotEqual) { + return \true; } - - if ($expr->right instanceof Equal) { - return true; + if ($expr->right instanceof \PhpParser\Node\Expr\BinaryOp\Equal) { + return \true; } - - return $expr->right instanceof NotEqual; + return $expr->right instanceof \PhpParser\Node\Expr\BinaryOp\NotEqual; } - - private function negateOrDeNegate(Expr $expr): Expr + private function negateOrDeNegate(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { - if ($expr instanceof BooleanNot) { + if ($expr instanceof \PhpParser\Node\Expr\BooleanNot) { return $expr->expr; } - - return new BooleanNot($expr); + return new \PhpParser\Node\Expr\BooleanNot($expr); } } diff --git a/rules/EarlyReturn/Rector/Foreach_/ReturnAfterToEarlyOnBreakRector.php b/rules/EarlyReturn/Rector/Foreach_/ReturnAfterToEarlyOnBreakRector.php index 016eb4efa56..1a3519a5fbd 100644 --- a/rules/EarlyReturn/Rector/Foreach_/ReturnAfterToEarlyOnBreakRector.php +++ b/rules/EarlyReturn/Rector/Foreach_/ReturnAfterToEarlyOnBreakRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Foreach_::class]; + return [\PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { /** @var Break_[] $breaks */ - $breaks = $this->betterNodeFinder->findInstanceOf($node->stmts, Break_::class); - if (count($breaks) !== 1) { + $breaks = $this->betterNodeFinder->findInstanceOf($node->stmts, \PhpParser\Node\Stmt\Break_::class); + if (\count($breaks) !== 1) { return null; } - - $beforeBreak = $breaks[0]->getAttribute(AttributeKey::PREVIOUS_NODE); - if (! $beforeBreak instanceof Expression) { + $beforeBreak = $breaks[0]->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if (!$beforeBreak instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $assign = $beforeBreak->expr; - if (! $assign instanceof Assign) { + if (!$assign instanceof \PhpParser\Node\Expr\Assign) { return null; } - - $nextForeach = $node->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextForeach instanceof Return_) { + $nextForeach = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextForeach instanceof \PhpParser\Node\Stmt\Return_) { return null; } - $assignVariable = $assign->var; /** @var Expr $variablePrevious */ - $variablePrevious = $this->betterNodeFinder->findFirstPreviousOfNode($node, function (Node $node) use ( - $assignVariable - ): bool { - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Assign) { - return false; + $variablePrevious = $this->betterNodeFinder->findFirstPreviousOfNode($node, function (\PhpParser\Node $node) use($assignVariable) : bool { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Expr\Assign) { + return \false; } return $this->nodeComparator->areNodesEqual($node, $assignVariable); }); - if ($this->shouldSkip($nextForeach, $variablePrevious, $node, $assignVariable)) { return null; } - /** @var Assign $assignPreviousVariable */ - $assignPreviousVariable = $variablePrevious->getAttribute(AttributeKey::PARENT_NODE); - $parent = $assignPreviousVariable->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Expression) { + $assignPreviousVariable = $variablePrevious->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + $parent = $assignPreviousVariable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - $nextParent = $parent->getAttribute(AttributeKey::NEXT_NODE); + $nextParent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); if ($nextParent !== $node) { return null; } - return $this->processEarlyReturn($beforeBreak, $assign, $breaks, $nextForeach, $assignPreviousVariable, $node); } - /** * @param Break_[] $breaks */ - private function processEarlyReturn( - Expression $expression, - Assign $assign, - array $breaks, - Return_ $return, - Assign $assignPreviousVariable, - Foreach_ $foreach - ): Foreach_ { + private function processEarlyReturn(\PhpParser\Node\Stmt\Expression $expression, \PhpParser\Node\Expr\Assign $assign, array $breaks, \PhpParser\Node\Stmt\Return_ $return, \PhpParser\Node\Expr\Assign $assignPreviousVariable, \PhpParser\Node\Stmt\Foreach_ $foreach) : \PhpParser\Node\Stmt\Foreach_ + { $this->removeNode($expression); - $this->addNodeBeforeNode(new Return_($assign->expr), $breaks[0]); + $this->addNodeBeforeNode(new \PhpParser\Node\Stmt\Return_($assign->expr), $breaks[0]); $this->removeNode($breaks[0]); - $return->expr = $assignPreviousVariable->expr; $this->removeNode($assignPreviousVariable); - return $foreach; } - - private function shouldSkip(Return_ $return, ?Expr $expr = null, Foreach_ $foreach, Expr $assignVariable): bool + private function shouldSkip(\PhpParser\Node\Stmt\Return_ $return, ?\PhpParser\Node\Expr $expr = null, \PhpParser\Node\Stmt\Foreach_ $foreach, \PhpParser\Node\Expr $assignVariable) : bool { - if (! $expr instanceof Expr) { - return true; + if (!$expr instanceof \PhpParser\Node\Expr) { + return \true; } - - if (! $this->nodeComparator->areNodesEqual($return->expr, $expr)) { - return true; + if (!$this->nodeComparator->areNodesEqual($return->expr, $expr)) { + return \true; } - // ensure the variable only used once in foreach - $usedVariable = $this->betterNodeFinder->find($foreach->stmts, function (Node $node) use ( - $assignVariable - ): bool { + $usedVariable = $this->betterNodeFinder->find($foreach->stmts, function (\PhpParser\Node $node) use($assignVariable) : bool { return $this->nodeComparator->areNodesEqual($node, $assignVariable); }); - return count($usedVariable) > 1; + return \count($usedVariable) > 1; } } diff --git a/rules/EarlyReturn/Rector/If_/ChangeAndIfToEarlyReturnRector.php b/rules/EarlyReturn/Rector/If_/ChangeAndIfToEarlyReturnRector.php index 261df61a77e..054ca79d770 100644 --- a/rules/EarlyReturn/Rector/If_/ChangeAndIfToEarlyReturnRector.php +++ b/rules/EarlyReturn/Rector/If_/ChangeAndIfToEarlyReturnRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->invertedIfFactory = $invertedIfFactory; $this->contextAnalyzer = $contextAnalyzer; $this->booleanAndAnalyzer = $booleanAndAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes if && to early return', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes if && to early return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function canDrive(Car $car) @@ -75,9 +62,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function canDrive(Car $car) @@ -94,174 +79,137 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node * @return Node|Node[]|null */ - public function refactor(Node $node) + public function refactor(\PhpParser\Node $node) { if ($this->shouldSkip($node)) { return null; } - $ifNextReturn = $this->getIfNextReturn($node); - if ($ifNextReturn instanceof Return_ && $this->isIfStmtExprUsedInNextReturn($node, $ifNextReturn)) { + if ($ifNextReturn instanceof \PhpParser\Node\Stmt\Return_ && $this->isIfStmtExprUsedInNextReturn($node, $ifNextReturn)) { return null; } - /** @var BooleanAnd $expr */ $expr = $node->cond; $booleanAndConditions = $this->booleanAndAnalyzer->findBooleanAndConditions($expr); - - if (! $ifNextReturn instanceof Return_) { + if (!$ifNextReturn instanceof \PhpParser\Node\Stmt\Return_) { $this->addNodeAfterNode($node->stmts[0], $node); - return $this->processReplaceIfs($node, $booleanAndConditions, new Return_()); + return $this->processReplaceIfs($node, $booleanAndConditions, new \PhpParser\Node\Stmt\Return_()); } - - if ($ifNextReturn instanceof Return_ && $ifNextReturn->expr instanceof BooleanAnd) { + if ($ifNextReturn instanceof \PhpParser\Node\Stmt\Return_ && $ifNextReturn->expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { return null; } - $this->removeNode($ifNextReturn); $ifNextReturn = $node->stmts[0]; $this->addNodeAfterNode($ifNextReturn, $node); - - $ifNextReturnClone = $ifNextReturn instanceof Return_ - ? clone $ifNextReturn - : new Return_(); - - if (! $this->contextAnalyzer->isInLoop($node)) { + $ifNextReturnClone = $ifNextReturn instanceof \PhpParser\Node\Stmt\Return_ ? clone $ifNextReturn : new \PhpParser\Node\Stmt\Return_(); + if (!$this->contextAnalyzer->isInLoop($node)) { return $this->processReplaceIfs($node, $booleanAndConditions, $ifNextReturnClone); } - - if (! $ifNextReturn instanceof Expression) { + if (!$ifNextReturn instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - $this->addNodeAfterNode(new Return_(), $node); + $this->addNodeAfterNode(new \PhpParser\Node\Stmt\Return_(), $node); return $this->processReplaceIfs($node, $booleanAndConditions, $ifNextReturnClone); } - /** * @param Expr[] $conditions * @return If_|Node[] */ - private function processReplaceIfs(If_ $node, array $conditions, Return_ $ifNextReturnClone) + private function processReplaceIfs(\PhpParser\Node\Stmt\If_ $node, array $conditions, \PhpParser\Node\Stmt\Return_ $ifNextReturnClone) { $ifs = $this->invertedIfFactory->createFromConditions($node, $conditions, $ifNextReturnClone); $this->mirrorComments($ifs[0], $node); - foreach ($ifs as $if) { $this->addNodeBeforeNode($if, $node); } - $this->removeNode($node); - - if (! $node->stmts[0] instanceof Return_ && $ifNextReturnClone->expr instanceof Expr) { + if (!$node->stmts[0] instanceof \PhpParser\Node\Stmt\Return_ && $ifNextReturnClone->expr instanceof \PhpParser\Node\Expr) { return [$node, $ifNextReturnClone]; } - return $node; } - - private function shouldSkip(If_ $if): bool + private function shouldSkip(\PhpParser\Node\Stmt\If_ $if) : bool { - if (! $this->ifManipulator->isIfWithOnlyOneStmt($if)) { - return true; + if (!$this->ifManipulator->isIfWithOnlyOneStmt($if)) { + return \true; } - if (! $if->cond instanceof BooleanAnd) { - return true; + if (!$if->cond instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { + return \true; } - if (! $this->ifManipulator->isIfWithoutElseAndElseIfs($if)) { - return true; + if (!$this->ifManipulator->isIfWithoutElseAndElseIfs($if)) { + return \true; } - if ($this->isParentIfReturnsVoidOrParentIfHasNextNode($if)) { - return true; + return \true; } - if ($this->isNestedIfInLoop($if)) { - return true; + return \true; } - - return ! $this->isLastIfOrBeforeLastReturn($if); + return !$this->isLastIfOrBeforeLastReturn($if); } - - private function isIfStmtExprUsedInNextReturn(If_ $if, Return_ $return): bool + private function isIfStmtExprUsedInNextReturn(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node\Stmt\Return_ $return) : bool { - if (! $return->expr instanceof Expr) { - return false; + if (!$return->expr instanceof \PhpParser\Node\Expr) { + return \false; } - - $ifExprs = $this->betterNodeFinder->findInstanceOf($if->stmts, Expr::class); + $ifExprs = $this->betterNodeFinder->findInstanceOf($if->stmts, \PhpParser\Node\Expr::class); foreach ($ifExprs as $ifExpr) { - $isExprFoundInReturn = (bool) $this->betterNodeFinder->findFirst($return->expr, function (Node $node) use ( - $ifExpr - ): bool { + $isExprFoundInReturn = (bool) $this->betterNodeFinder->findFirst($return->expr, function (\PhpParser\Node $node) use($ifExpr) : bool { return $this->nodeComparator->areNodesEqual($node, $ifExpr); }); if ($isExprFoundInReturn) { - return true; + return \true; } } - - return false; + return \false; } - - private function getIfNextReturn(If_ $if): ?Return_ + private function getIfNextReturn(\PhpParser\Node\Stmt\If_ $if) : ?\PhpParser\Node\Stmt\Return_ { - $nextNode = $if->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextNode instanceof Return_) { + $nextNode = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextNode instanceof \PhpParser\Node\Stmt\Return_) { return null; } - return $nextNode; } - - private function isParentIfReturnsVoidOrParentIfHasNextNode(If_ $if): bool + private function isParentIfReturnsVoidOrParentIfHasNextNode(\PhpParser\Node\Stmt\If_ $if) : bool { - $parentNode = $if->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof If_) { - return false; + $parentNode = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Stmt\If_) { + return \false; } - - $nextParent = $parentNode->getAttribute(AttributeKey::NEXT_NODE); - return $nextParent instanceof Node; + $nextParent = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + return $nextParent instanceof \PhpParser\Node; } - - private function isNestedIfInLoop(If_ $if): bool + private function isNestedIfInLoop(\PhpParser\Node\Stmt\If_ $if) : bool { - if (! $this->contextAnalyzer->isInLoop($if)) { - return false; + if (!$this->contextAnalyzer->isInLoop($if)) { + return \false; } - - return (bool) $this->betterNodeFinder->findParentTypes($if, [If_::class, Else_::class, ElseIf_::class]); + return (bool) $this->betterNodeFinder->findParentTypes($if, [\PhpParser\Node\Stmt\If_::class, \PhpParser\Node\Stmt\Else_::class, \PhpParser\Node\Stmt\ElseIf_::class]); } - - private function isLastIfOrBeforeLastReturn(If_ $if): bool + private function isLastIfOrBeforeLastReturn(\PhpParser\Node\Stmt\If_ $if) : bool { - $nextNode = $if->getAttribute(AttributeKey::NEXT_NODE); - if ($nextNode instanceof Node) { - return $nextNode instanceof Return_; + $nextNode = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if ($nextNode instanceof \PhpParser\Node) { + return $nextNode instanceof \PhpParser\Node\Stmt\Return_; } - - $parent = $if->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof If_) { + $parent = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Stmt\If_) { return $this->isLastIfOrBeforeLastReturn($parent); } - - return ! $this->contextAnalyzer->isHasAssignWithIndirectReturn($parent, $if); + return !$this->contextAnalyzer->isHasAssignWithIndirectReturn($parent, $if); } } diff --git a/rules/EarlyReturn/Rector/If_/ChangeIfElseValueAssignToEarlyReturnRector.php b/rules/EarlyReturn/Rector/If_/ChangeIfElseValueAssignToEarlyReturnRector.php index 18e3213b02a..535d3183600 100644 --- a/rules/EarlyReturn/Rector/If_/ChangeIfElseValueAssignToEarlyReturnRector.php +++ b/rules/EarlyReturn/Rector/If_/ChangeIfElseValueAssignToEarlyReturnRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->stmtsManipulator = $stmtsManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change if/else value to early return', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change if/else value to early return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -60,8 +53,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -73,65 +65,52 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node * @return Stmt[]|Node|null */ - public function refactor(Node $node) + public function refactor(\PhpParser\Node $node) { - $nextNode = $node->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextNode instanceof Return_) { + $nextNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextNode instanceof \PhpParser\Node\Stmt\Return_) { return null; } - if ($nextNode->expr === null) { return null; } - - if (! $this->ifManipulator->isIfAndElseWithSameVariableAssignAsLastStmts($node, $nextNode->expr)) { + if (!$this->ifManipulator->isIfAndElseWithSameVariableAssignAsLastStmts($node, $nextNode->expr)) { return null; } - - $lastIfStmtKey = array_key_last($node->stmts); - + \end($node->stmts); + $lastIfStmtKey = \key($node->stmts); /** @var Assign $assign */ $assign = $this->stmtsManipulator->getUnwrappedLastStmt($node->stmts); - - $return = new Return_($assign->expr); + $return = new \PhpParser\Node\Stmt\Return_($assign->expr); $this->mirrorComments($return, $assign); $node->stmts[$lastIfStmtKey] = $return; - $else = $node->else; - if (! $else instanceof Else_) { - throw new ShouldNotHappenException(); + if (!$else instanceof \PhpParser\Node\Stmt\Else_) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $elseStmts = $else->stmts; - /** @var Assign $assign */ $assign = $this->stmtsManipulator->getUnwrappedLastStmt($elseStmts); - - $lastElseStmtKey = array_key_last($elseStmts); - - $return = new Return_($assign->expr); + \end($elseStmts); + $lastElseStmtKey = \key($elseStmts); + $return = new \PhpParser\Node\Stmt\Return_($assign->expr); $this->mirrorComments($return, $assign); $elseStmts[$lastElseStmtKey] = $return; - $node->else = null; $this->removeNode($nextNode); - - return array_merge([$node], $elseStmts); + return \array_merge([$node], $elseStmts); } } diff --git a/rules/EarlyReturn/Rector/If_/ChangeNestedIfsToEarlyReturnRector.php b/rules/EarlyReturn/Rector/If_/ChangeNestedIfsToEarlyReturnRector.php index bc7cb788563..f077d307919 100644 --- a/rules/EarlyReturn/Rector/If_/ChangeNestedIfsToEarlyReturnRector.php +++ b/rules/EarlyReturn/Rector/If_/ChangeNestedIfsToEarlyReturnRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->conditionInverter = $conditionInverter; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change nested ifs to early return', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change nested ifs to early return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -56,8 +49,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -74,48 +66,40 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { // A. next node is return - $nextNode = $node->getAttribute(AttributeKey::NEXT_NODE); - if (! $nextNode instanceof Return_) { + $nextNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$nextNode instanceof \PhpParser\Node\Stmt\Return_) { return null; } - $nestedIfsWithOnlyReturn = $this->ifManipulator->collectNestedIfsWithOnlyReturn($node); if ($nestedIfsWithOnlyReturn === []) { return null; } - $this->processNestedIfsWithOnlyReturn($node, $nestedIfsWithOnlyReturn, $nextNode); $this->removeNode($node); - return null; } - /** * @param If_[] $nestedIfsWithOnlyReturn */ - private function processNestedIfsWithOnlyReturn(If_ $if, array $nestedIfsWithOnlyReturn, Return_ $nextReturn): void + private function processNestedIfsWithOnlyReturn(\PhpParser\Node\Stmt\If_ $if, array $nestedIfsWithOnlyReturn, \PhpParser\Node\Stmt\Return_ $nextReturn) : void { // add nested if openly after this - $nestedIfsWithOnlyReturnCount = count($nestedIfsWithOnlyReturn); - + $nestedIfsWithOnlyReturnCount = \count($nestedIfsWithOnlyReturn); /** @var int $key */ foreach ($nestedIfsWithOnlyReturn as $key => $nestedIfWithOnlyReturn) { // last item → the return node @@ -126,28 +110,22 @@ CODE_SAMPLE } } } - - private function addStandaloneIfsWithReturn(If_ $nestedIfWithOnlyReturn, If_ $if, Return_ $return): void + private function addStandaloneIfsWithReturn(\PhpParser\Node\Stmt\If_ $nestedIfWithOnlyReturn, \PhpParser\Node\Stmt\If_ $if, \PhpParser\Node\Stmt\Return_ $return) : void { $return = clone $return; - $invertedCondition = $this->conditionInverter->createInvertedCondition($nestedIfWithOnlyReturn->cond); - // special case - if ($invertedCondition instanceof BooleanNot && $invertedCondition->expr instanceof BooleanAnd) { - $booleanNotPartIf = new If_(new BooleanNot($invertedCondition->expr->left)); + if ($invertedCondition instanceof \PhpParser\Node\Expr\BooleanNot && $invertedCondition->expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { + $booleanNotPartIf = new \PhpParser\Node\Stmt\If_(new \PhpParser\Node\Expr\BooleanNot($invertedCondition->expr->left)); $booleanNotPartIf->stmts = [clone $return]; $this->addNodeAfterNode($booleanNotPartIf, $if); - - $booleanNotPartIf = new If_(new BooleanNot($invertedCondition->expr->right)); + $booleanNotPartIf = new \PhpParser\Node\Stmt\If_(new \PhpParser\Node\Expr\BooleanNot($invertedCondition->expr->right)); $booleanNotPartIf->stmts = [clone $return]; $this->addNodeAfterNode($booleanNotPartIf, $if); return; } - $nestedIfWithOnlyReturn->cond = $invertedCondition; $nestedIfWithOnlyReturn->stmts = [clone $return]; - $this->addNodeAfterNode($nestedIfWithOnlyReturn, $if); } } diff --git a/rules/EarlyReturn/Rector/If_/ChangeOrIfContinueToMultiContinueRector.php b/rules/EarlyReturn/Rector/If_/ChangeOrIfContinueToMultiContinueRector.php index ea3444d75fc..3503efc0bd9 100644 --- a/rules/EarlyReturn/Rector/If_/ChangeOrIfContinueToMultiContinueRector.php +++ b/rules/EarlyReturn/Rector/If_/ChangeOrIfContinueToMultiContinueRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes if && to early return', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes if && to early return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function canDrive(Car $newCar) @@ -49,9 +43,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function canDrive(Car $newCar) @@ -70,35 +62,29 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->ifManipulator->isIfWithOnly($node, Continue_::class)) { + if (!$this->ifManipulator->isIfWithOnly($node, \PhpParser\Node\Stmt\Continue_::class)) { return null; } - - if (! $node->cond instanceof BooleanOr) { + if (!$node->cond instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return null; } - return $this->processMultiIfContinue($node); } - - private function processMultiIfContinue(If_ $if): If_ + private function processMultiIfContinue(\PhpParser\Node\Stmt\If_ $if) : \PhpParser\Node\Stmt\If_ { $node = clone $if; /** @var Continue_ $continue */ @@ -108,41 +94,34 @@ CODE_SAMPLE if ($key === 0) { $this->mirrorComments($if, $node); } - $this->addNodeBeforeNode($if, $node); } - $this->removeNode($node); return $node; } - /** * @param If_[] $ifs * @return If_[] */ - private function createMultipleIfs(Expr $expr, Continue_ $continue, array $ifs): array + private function createMultipleIfs(\PhpParser\Node\Expr $expr, \PhpParser\Node\Stmt\Continue_ $continue, array $ifs) : array { - while ($expr instanceof BooleanOr) { - $ifs = array_merge($ifs, $this->collectLeftbooleanOrToIfs($expr, $continue, $ifs)); + while ($expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { + $ifs = \array_merge($ifs, $this->collectLeftbooleanOrToIfs($expr, $continue, $ifs)); $ifs[] = $this->ifManipulator->createIfExpr($expr->right, $continue); - $expr = $expr->right; } - return $ifs + [$this->ifManipulator->createIfExpr($expr, $continue)]; } - /** * @param If_[] $ifs * @return If_[] */ - private function collectLeftbooleanOrToIfs(BooleanOr $booleanOr, Continue_ $continue, array $ifs): array + private function collectLeftbooleanOrToIfs(\PhpParser\Node\Expr\BinaryOp\BooleanOr $booleanOr, \PhpParser\Node\Stmt\Continue_ $continue, array $ifs) : array { $left = $booleanOr->left; - if (! $left instanceof BooleanOr) { + if (!$left instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return [$this->ifManipulator->createIfExpr($left, $continue)]; } - return $this->createMultipleIfs($left, $continue, $ifs); } } diff --git a/rules/EarlyReturn/Rector/If_/ChangeOrIfReturnToEarlyReturnRector.php b/rules/EarlyReturn/Rector/If_/ChangeOrIfReturnToEarlyReturnRector.php index f3b4004b186..4bd20e7da9f 100644 --- a/rules/EarlyReturn/Rector/If_/ChangeOrIfReturnToEarlyReturnRector.php +++ b/rules/EarlyReturn/Rector/If_/ChangeOrIfReturnToEarlyReturnRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes if || with return to early return', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes if || with return to early return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($a, $b) @@ -47,9 +41,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($a, $b) @@ -65,106 +57,82 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->ifManipulator->isIfWithOnly($node, Return_::class)) { + if (!$this->ifManipulator->isIfWithOnly($node, \PhpParser\Node\Stmt\Return_::class)) { return null; } - - if (! $node->cond instanceof BooleanOr) { + if (!$node->cond instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return null; } - if ($this->isInstanceofCondOnly($node->cond)) { return null; } - /** @var Return_ $return */ $return = $node->stmts[0]; $ifs = $this->createMultipleIfs($node->cond, $return, []); - foreach ($ifs as $key => $if) { if ($key === 0) { $this->mirrorComments($if, $node); } - $this->addNodeBeforeNode($if, $node); } - $this->removeNode($node); return $node; } - /** * @param If_[] $ifs * @return If_[] */ - private function createMultipleIfs(Expr $expr, Return_ $return, array $ifs): array + private function createMultipleIfs(\PhpParser\Node\Expr $expr, \PhpParser\Node\Stmt\Return_ $return, array $ifs) : array { - while ($expr instanceof BooleanOr) { - $ifs = array_merge($ifs, $this->collectLeftBooleanOrToIfs($expr, $return, $ifs)); + while ($expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { + $ifs = \array_merge($ifs, $this->collectLeftBooleanOrToIfs($expr, $return, $ifs)); $ifs[] = $this->createIf($expr->right, $return); - $expr = $expr->right; } return $ifs + [$this->createIf($expr, $return)]; } - /** * @param If_[] $ifs * @return If_[] */ - private function collectLeftBooleanOrToIfs(BooleanOr $booleanOr, Return_ $return, array $ifs): array + private function collectLeftBooleanOrToIfs(\PhpParser\Node\Expr\BinaryOp\BooleanOr $booleanOr, \PhpParser\Node\Stmt\Return_ $return, array $ifs) : array { $left = $booleanOr->left; - if (! $left instanceof BooleanOr) { + if (!$left instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return [$this->createIf($left, $return)]; } - return $this->createMultipleIfs($left, $return, $ifs); } - - private function createIf(Expr $expr, Return_ $return): If_ + private function createIf(\PhpParser\Node\Expr $expr, \PhpParser\Node\Stmt\Return_ $return) : \PhpParser\Node\Stmt\If_ { - return new If_( - $expr, - [ - 'stmts' => [$return], - ] - ); + return new \PhpParser\Node\Stmt\If_($expr, ['stmts' => [$return]]); } - - private function isInstanceofCondOnly(BooleanOr $booleanOr): bool + private function isInstanceofCondOnly(\PhpParser\Node\Expr\BinaryOp\BooleanOr $booleanOr) : bool { $currentNode = $booleanOr; - - if ($currentNode->left instanceof BooleanOr) { + if ($currentNode->left instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return $this->isInstanceofCondOnly($currentNode->left); } - - if ($currentNode->right instanceof BooleanOr) { + if ($currentNode->right instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return $this->isInstanceofCondOnly($currentNode->right); } - - if (! $currentNode->right instanceof Instanceof_) { - return false; + if (!$currentNode->right instanceof \PhpParser\Node\Expr\Instanceof_) { + return \false; } - - return $currentNode->left instanceof Instanceof_; + return $currentNode->left instanceof \PhpParser\Node\Expr\Instanceof_; } } diff --git a/rules/EarlyReturn/Rector/If_/RemoveAlwaysElseRector.php b/rules/EarlyReturn/Rector/If_/RemoveAlwaysElseRector.php index f921e407e77..1993c51ff2c 100644 --- a/rules/EarlyReturn/Rector/If_/RemoveAlwaysElseRector.php +++ b/rules/EarlyReturn/Rector/If_/RemoveAlwaysElseRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->doesLastStatementBreakFlow($node)) { return null; } - if ($node->elseifs !== []) { - $if = new If_($node->cond); + $if = new \PhpParser\Node\Stmt\If_($node->cond); $if->stmts = $node->stmts; - $this->addNodeBeforeNode($if, $node); - /** @var ElseIf_ $firstElseIf */ - $firstElseIf = array_shift($node->elseifs); + $firstElseIf = \array_shift($node->elseifs); $node->cond = $firstElseIf->cond; $node->stmts = $firstElseIf->stmts; $this->mirrorComments($node, $firstElseIf); - return $node; } - if ($node->else !== null) { $this->addNodesAfterNode($node->else->stmts, $node); $node->else = null; return $node; } - return null; } - - private function doesLastStatementBreakFlow(If_ $if): bool + private function doesLastStatementBreakFlow(\PhpParser\Node\Stmt\If_ $if) : bool { - $lastStmt = end($if->stmts); - - return ! ($lastStmt instanceof Return_ - || $lastStmt instanceof Throw_ - || $lastStmt instanceof Continue_ - || ($lastStmt instanceof Expression && $lastStmt->expr instanceof Exit_)); + $lastStmt = \end($if->stmts); + return !($lastStmt instanceof \PhpParser\Node\Stmt\Return_ || $lastStmt instanceof \PhpParser\Node\Stmt\Throw_ || $lastStmt instanceof \PhpParser\Node\Stmt\Continue_ || $lastStmt instanceof \PhpParser\Node\Stmt\Expression && $lastStmt->expr instanceof \PhpParser\Node\Expr\Exit_); } } diff --git a/rules/EarlyReturn/Rector/Return_/PreparedValueToEarlyReturnRector.php b/rules/EarlyReturn/Rector/Return_/PreparedValueToEarlyReturnRector.php index 4261aab1f38..2747c45199b 100644 --- a/rules/EarlyReturn/Rector/Return_/PreparedValueToEarlyReturnRector.php +++ b/rules/EarlyReturn/Rector/Return_/PreparedValueToEarlyReturnRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Return early prepared value in ifs', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Return early prepared value in ifs', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -55,9 +49,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -74,204 +66,162 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Return_::class]; + return [\PhpParser\Node\Stmt\Return_::class]; } - /** * @param Return_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $ifsBefore = $this->getIfsBefore($node); - if ($this->shouldSkip($ifsBefore, $node->expr)) { return null; } - if ($this->isAssignVarUsedInIfCond($ifsBefore, $node->expr)) { return null; } - /** @var Expr $returnExpr */ $returnExpr = $node->expr; - /** @var Expression $previousFirstExpression */ $previousFirstExpression = $this->getPreviousIfLinearEquals($ifsBefore[0], $returnExpr); - /** @var Assign $previousAssign */ $previousAssign = $previousFirstExpression->expr; - if ($this->isPreviousVarUsedInAssignExpr($ifsBefore, $previousAssign->var)) { return null; } - foreach ($ifsBefore as $ifBefore) { /** @var Expression $expressionIf */ $expressionIf = $ifBefore->stmts[0]; /** @var Assign $assignIf */ $assignIf = $expressionIf->expr; - - $ifBefore->stmts[0] = new Return_($assignIf->expr); + $ifBefore->stmts[0] = new \PhpParser\Node\Stmt\Return_($assignIf->expr); } - /** @var Assign $assignPrevious */ $assignPrevious = $previousFirstExpression->expr; $node->expr = $assignPrevious->expr; $this->removeNode($previousFirstExpression); - return $node; } - /** * @param If_[] $ifsBefore */ - private function isAssignVarUsedInIfCond(array $ifsBefore, ?Expr $expr): bool + private function isAssignVarUsedInIfCond(array $ifsBefore, ?\PhpParser\Node\Expr $expr) : bool { foreach ($ifsBefore as $ifBefore) { - $isUsedInIfCond = (bool) $this->betterNodeFinder->findFirst($ifBefore->cond, function (Node $node) use ( - $expr - ): bool { + $isUsedInIfCond = (bool) $this->betterNodeFinder->findFirst($ifBefore->cond, function (\PhpParser\Node $node) use($expr) : bool { return $this->nodeComparator->areNodesEqual($node, $expr); }); - if ($isUsedInIfCond) { - return true; + return \true; } } - - return false; + return \false; } - /** * @param If_[] $ifsBefore */ - private function isPreviousVarUsedInAssignExpr(array $ifsBefore, Expr $expr): bool + private function isPreviousVarUsedInAssignExpr(array $ifsBefore, \PhpParser\Node\Expr $expr) : bool { foreach ($ifsBefore as $ifBefore) { /** @var Expression $expression */ $expression = $ifBefore->stmts[0]; /** @var Assign $assign */ $assign = $expression->expr; - - $isUsedInAssignExpr = (bool) $this->betterNodeFinder->findFirst($assign->expr, function (Node $node) use ( - $expr - ): bool { + $isUsedInAssignExpr = (bool) $this->betterNodeFinder->findFirst($assign->expr, function (\PhpParser\Node $node) use($expr) : bool { return $this->nodeComparator->areNodesEqual($node, $expr); }); - if ($isUsedInAssignExpr) { - return true; + return \true; } } - - return false; + return \false; } - /** * @param If_[] $ifsBefore */ - private function shouldSkip(array $ifsBefore, ?Expr $returnExpr): bool + private function shouldSkip(array $ifsBefore, ?\PhpParser\Node\Expr $returnExpr) : bool { if ($ifsBefore === []) { - return true; + return \true; } - - return ! (bool) $this->getPreviousIfLinearEquals($ifsBefore[0], $returnExpr); + return !(bool) $this->getPreviousIfLinearEquals($ifsBefore[0], $returnExpr); } - - private function getPreviousIfLinearEquals(?Node $node, ?Expr $expr): ?Expression + private function getPreviousIfLinearEquals(?\PhpParser\Node $node, ?\PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Stmt\Expression { - if (! $node instanceof Node) { + if (!$node instanceof \PhpParser\Node) { return null; } - - if (! $expr instanceof Expr) { + if (!$expr instanceof \PhpParser\Node\Expr) { return null; } - - $previous = $node->getAttribute(AttributeKey::PREVIOUS_NODE); - if (! $previous instanceof Expression) { + $previous = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if (!$previous instanceof \PhpParser\Node\Stmt\Expression) { return $this->getPreviousIfLinearEquals($previous, $expr); } - - if (! $previous->expr instanceof Assign) { + if (!$previous->expr instanceof \PhpParser\Node\Expr\Assign) { return null; } - if ($this->nodeComparator->areNodesEqual($previous->expr->var, $expr)) { return $previous; } - return null; } - /** * @return If_[] */ - private function getIfsBefore(Return_ $return): array + private function getIfsBefore(\PhpParser\Node\Stmt\Return_ $return) : array { - $parent = $return->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof FunctionLike && ! $parent instanceof If_) { + $parent = $return->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\FunctionLike && !$parent instanceof \PhpParser\Node\Stmt\If_) { return []; } - if ($parent->stmts === []) { return []; } - - $firstItemPosition = array_key_last($parent->stmts); + \end($parent->stmts); + $firstItemPosition = \key($parent->stmts); if ($parent->stmts[$firstItemPosition] !== $return) { return []; } - return $this->collectIfs($parent->stmts, $return); } - /** * @param If_[] $stmts * @return If_[] */ - private function collectIfs(array $stmts, Return_ $return): array + private function collectIfs(array $stmts, \PhpParser\Node\Stmt\Return_ $return) : array { /** @va If_[] $ifs */ - $ifs = $this->betterNodeFinder->findInstanceOf($stmts, If_::class); - + $ifs = $this->betterNodeFinder->findInstanceOf($stmts, \PhpParser\Node\Stmt\If_::class); /** Skip entirely if found skipped ifs */ foreach ($ifs as $if) { /** @var If_ $if */ - if (! $this->ifManipulator->isIfWithoutElseAndElseIfs($if)) { + if (!$this->ifManipulator->isIfWithoutElseAndElseIfs($if)) { return []; } - $stmts = $if->stmts; - if (count($stmts) !== 1) { + if (\count($stmts) !== 1) { return []; } - $expression = $stmts[0]; - if (! $expression instanceof Expression) { + if (!$expression instanceof \PhpParser\Node\Stmt\Expression) { return []; } - - if (! $expression->expr instanceof Assign) { + if (!$expression->expr instanceof \PhpParser\Node\Expr\Assign) { return []; } - $assign = $expression->expr; - if (! $this->nodeComparator->areNodesEqual($assign->var, $return->expr)) { + if (!$this->nodeComparator->areNodesEqual($assign->var, $return->expr)) { return []; } } - return $ifs; } } diff --git a/rules/EarlyReturn/Rector/Return_/ReturnBinaryAndToEarlyReturnRector.php b/rules/EarlyReturn/Rector/Return_/ReturnBinaryAndToEarlyReturnRector.php index 6c5c7a34ef9..660dc7f35bd 100644 --- a/rules/EarlyReturn/Rector/Return_/ReturnBinaryAndToEarlyReturnRector.php +++ b/rules/EarlyReturn/Rector/Return_/ReturnBinaryAndToEarlyReturnRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->assignAndBinaryMap = $assignAndBinaryMap; $this->callAnalyzer = $callAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes Single return of && to early returns', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes Single return of && to early returns', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function accept() @@ -59,9 +48,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function accept() @@ -73,80 +60,62 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Return_::class]; + return [\PhpParser\Node\Stmt\Return_::class]; } - /** * @param Return_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof BooleanAnd) { + if (!$node->expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { return null; } - $left = $node->expr->left; $ifNegations = $this->createMultipleIfsNegation($left, $node, []); - $this->mirrorComments($ifNegations[0], $node); foreach ($ifNegations as $ifNegation) { - if (! $this->callAnalyzer->isObjectCall($ifNegation->cond)) { + if (!$this->callAnalyzer->isObjectCall($ifNegation->cond)) { return null; } - $this->addNodeBeforeNode($ifNegation, $node); } - /** @var BooleanAnd $booleanAnd */ $booleanAnd = $node->expr; - $lastReturnExpr = $this->assignAndBinaryMap->getTruthyExpr($booleanAnd->right); - $this->addNodeBeforeNode(new Return_($lastReturnExpr), $node); + $this->addNodeBeforeNode(new \PhpParser\Node\Stmt\Return_($lastReturnExpr), $node); $this->removeNode($node); - return $node; } - /** * @param If_[] $ifNegations * @return If_[] */ - private function createMultipleIfsNegation(Expr $expr, Return_ $return, array $ifNegations): array + private function createMultipleIfsNegation(\PhpParser\Node\Expr $expr, \PhpParser\Node\Stmt\Return_ $return, array $ifNegations) : array { - while ($expr instanceof BooleanAnd) { - $ifNegations = array_merge($ifNegations, $this->collectLeftBooleanAndToIfs($expr, $return, $ifNegations)); - $ifNegations[] = $this->ifManipulator->createIfNegation( - $expr->right, - new Return_($this->nodeFactory->createFalse()) - ); - + while ($expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { + $ifNegations = \array_merge($ifNegations, $this->collectLeftBooleanAndToIfs($expr, $return, $ifNegations)); + $ifNegations[] = $this->ifManipulator->createIfNegation($expr->right, new \PhpParser\Node\Stmt\Return_($this->nodeFactory->createFalse())); $expr = $expr->right; } - return $ifNegations + [ - $this->ifManipulator->createIfNegation($expr, new Return_($this->nodeFactory->createFalse())), - ]; + return $ifNegations + [$this->ifManipulator->createIfNegation($expr, new \PhpParser\Node\Stmt\Return_($this->nodeFactory->createFalse()))]; } - /** * @param If_[] $ifNegations * @return If_[] */ - private function collectLeftBooleanAndToIfs(BooleanAnd $booleanAnd, Return_ $return, array $ifNegations): array + private function collectLeftBooleanAndToIfs(\PhpParser\Node\Expr\BinaryOp\BooleanAnd $booleanAnd, \PhpParser\Node\Stmt\Return_ $return, array $ifNegations) : array { $left = $booleanAnd->left; - if (! $left instanceof BooleanAnd) { - return [$this->ifManipulator->createIfNegation($left, new Return_($this->nodeFactory->createFalse()))]; + if (!$left instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { + return [$this->ifManipulator->createIfNegation($left, new \PhpParser\Node\Stmt\Return_($this->nodeFactory->createFalse()))]; } - return $this->createMultipleIfsNegation($left, $return, $ifNegations); } } diff --git a/rules/EarlyReturn/Rector/Return_/ReturnBinaryOrToEarlyReturnRector.php b/rules/EarlyReturn/Rector/Return_/ReturnBinaryOrToEarlyReturnRector.php index 44cd3e43a7c..f8bcd168637 100644 --- a/rules/EarlyReturn/Rector/Return_/ReturnBinaryOrToEarlyReturnRector.php +++ b/rules/EarlyReturn/Rector/Return_/ReturnBinaryOrToEarlyReturnRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->assignAndBinaryMap = $assignAndBinaryMap; $this->callAnalyzer = $callAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Changes Single return of || to early returns', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes Single return of || to early returns', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function accept() @@ -60,9 +49,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function accept() @@ -74,90 +61,72 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Return_::class]; + return [\PhpParser\Node\Stmt\Return_::class]; } - /** * @param Return_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof BooleanOr) { + if (!$node->expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return null; } - /** @var BooleanOr $booleanOr */ $booleanOr = $node->expr; - $left = $booleanOr->left; $ifs = $this->createMultipleIfs($left, $node, []); - if ($ifs === []) { return null; } - $this->mirrorComments($ifs[0], $node); foreach ($ifs as $if) { - if (! $this->callAnalyzer->isObjectCall($if->cond)) { + if (!$this->callAnalyzer->isObjectCall($if->cond)) { return null; } - $this->addNodeBeforeNode($if, $node); } - $lastReturnExpr = $this->assignAndBinaryMap->getTruthyExpr($booleanOr->right); - $this->addNodeBeforeNode(new Return_($lastReturnExpr), $node); + $this->addNodeBeforeNode(new \PhpParser\Node\Stmt\Return_($lastReturnExpr), $node); $this->removeNode($node); - return $node; } - /** * @param If_[] $ifs * @return If_[] */ - private function createMultipleIfs(Expr $expr, Return_ $return, array $ifs): array + private function createMultipleIfs(\PhpParser\Node\Expr $expr, \PhpParser\Node\Stmt\Return_ $return, array $ifs) : array { - while ($expr instanceof BooleanOr) { - $ifs = array_merge($ifs, $this->collectLeftBooleanOrToIfs($expr, $return, $ifs)); - $ifs[] = $this->ifManipulator->createIfExpr( - $expr->right, - new Return_($this->nodeFactory->createTrue()) - ); - + while ($expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { + $ifs = \array_merge($ifs, $this->collectLeftBooleanOrToIfs($expr, $return, $ifs)); + $ifs[] = $this->ifManipulator->createIfExpr($expr->right, new \PhpParser\Node\Stmt\Return_($this->nodeFactory->createTrue())); $expr = $expr->right; - if ($expr instanceof BooleanAnd) { + if ($expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanAnd) { return []; } - if (! $expr instanceof BooleanOr) { + if (!$expr instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { continue; } return []; } - - return $ifs + [$this->ifManipulator->createIfExpr($expr, new Return_($this->nodeFactory->createTrue()))]; + return $ifs + [$this->ifManipulator->createIfExpr($expr, new \PhpParser\Node\Stmt\Return_($this->nodeFactory->createTrue()))]; } - /** * @param If_[] $ifs * @return If_[] */ - private function collectLeftBooleanOrToIfs(BooleanOr $BooleanOr, Return_ $return, array $ifs): array + private function collectLeftBooleanOrToIfs(\PhpParser\Node\Expr\BinaryOp\BooleanOr $BooleanOr, \PhpParser\Node\Stmt\Return_ $return, array $ifs) : array { $left = $BooleanOr->left; - if (! $left instanceof BooleanOr) { - return [$this->ifManipulator->createIfExpr($left, new Return_($this->nodeFactory->createTrue()))]; + if (!$left instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { + return [$this->ifManipulator->createIfExpr($left, new \PhpParser\Node\Stmt\Return_($this->nodeFactory->createTrue()))]; } - return $this->createMultipleIfs($left, $return, $ifs); } } diff --git a/rules/Generics/Filter/UnnededMethodTagValueNodeFilter.php b/rules/Generics/Filter/UnnededMethodTagValueNodeFilter.php index 5a0c1e70334..98308ab8032 100644 --- a/rules/Generics/Filter/UnnededMethodTagValueNodeFilter.php +++ b/rules/Generics/Filter/UnnededMethodTagValueNodeFilter.php @@ -1,7 +1,6 @@ classMethodAnalyzer = $classMethodAnalyzer; } - /** * @param MethodTagValueNode[] $methodTagValueNodes * @return MethodTagValueNode[] */ - public function filter( - array $methodTagValueNodes, - PhpDocInfo $phpDocInfo, - ChildParentClassReflections $genericChildParentClassReflections, - Scope $scope - ): array { + public function filter(array $methodTagValueNodes, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo, \Rector\Generics\ValueObject\ChildParentClassReflections $genericChildParentClassReflections, \PHPStan\Analyser\Scope $scope) : array + { $methodTagValueNodes = $this->filterOutExistingMethodTagValuesNodes($methodTagValueNodes, $phpDocInfo); - - return $this->filterOutImplementedClassMethods( - $methodTagValueNodes, - $genericChildParentClassReflections->getChildClassReflection(), - $scope - ); + return $this->filterOutImplementedClassMethods($methodTagValueNodes, $genericChildParentClassReflections->getChildClassReflection(), $scope); } - /** * @param MethodTagValueNode[] $methodTagValueNodes * @return MethodTagValueNode[] */ - private function filterOutExistingMethodTagValuesNodes( - array $methodTagValueNodes, - PhpDocInfo $phpDocInfo - ): array { + private function filterOutExistingMethodTagValuesNodes(array $methodTagValueNodes, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : array + { $methodTagNames = $phpDocInfo->getMethodTagNames(); if ($methodTagNames === []) { return $methodTagValueNodes; } - $filteredMethodTagValueNodes = []; foreach ($methodTagValueNodes as $methodTagValueNode) { - if (in_array($methodTagValueNode->methodName, $methodTagNames, true)) { + if (\in_array($methodTagValueNode->methodName, $methodTagNames, \true)) { continue; } - $filteredMethodTagValueNodes[] = $methodTagValueNode; } - return $filteredMethodTagValueNodes; } - /** * @param MethodTagValueNode[] $methodTagValueNodes * @return MethodTagValueNode[] */ - private function filterOutImplementedClassMethods( - array $methodTagValueNodes, - ClassReflection $classReflection, - Scope $scope - ): array { + private function filterOutImplementedClassMethods(array $methodTagValueNodes, \PHPStan\Reflection\ClassReflection $classReflection, \PHPStan\Analyser\Scope $scope) : array + { $filteredMethodTagValueNodes = []; foreach ($methodTagValueNodes as $methodTagValueNode) { - if ($this->classMethodAnalyzer->hasClassMethodDirectly( - $classReflection, - $methodTagValueNode->methodName, - $scope - )) { + if ($this->classMethodAnalyzer->hasClassMethodDirectly($classReflection, $methodTagValueNode->methodName, $scope)) { continue; } - $filteredMethodTagValueNodes[] = $methodTagValueNode; } - return $filteredMethodTagValueNodes; } } diff --git a/rules/Generics/NodeType/ExtendsTemplateTypeMapFallbackFactory.php b/rules/Generics/NodeType/ExtendsTemplateTypeMapFallbackFactory.php index 573884317c9..c9f85701026 100644 --- a/rules/Generics/NodeType/ExtendsTemplateTypeMapFallbackFactory.php +++ b/rules/Generics/NodeType/ExtendsTemplateTypeMapFallbackFactory.php @@ -1,7 +1,6 @@ resolveExtendsTags($classReflection); if ($extendsTags === []) { return null; } - $parentGenericTypeNames = $this->resolveParentGenericTypeNames($classReflection); - foreach ($extendsTags as $extendTag) { $extendsTagType = $extendTag->getType(); - if (! $extendsTagType instanceof GenericObjectType) { + if (!$extendsTagType instanceof \PHPStan\Type\Generic\GenericObjectType) { continue; } - $templateTypeMap = []; foreach ($extendsTagType->getTypes() as $key => $genericExtendType) { - if (! isset($parentGenericTypeNames[$key])) { + if (!isset($parentGenericTypeNames[$key])) { continue; } - $parentGenericTypeName = $parentGenericTypeNames[$key]; - - if ($genericExtendType instanceof TypeWithClassName) { + if ($genericExtendType instanceof \PHPStan\Type\TypeWithClassName) { // this plac ewill need more work - $templateTypeScope = TemplateTypeScope::createWithClass($classReflection->getName()); - $genericExtendType = $this->createTemplateObjectType( - $templateTypeScope, - $parentGenericTypeName, - $genericExtendType - ); + $templateTypeScope = \PHPStan\Type\Generic\TemplateTypeScope::createWithClass($classReflection->getName()); + $genericExtendType = $this->createTemplateObjectType($templateTypeScope, $parentGenericTypeName, $genericExtendType); } - $templateTypeMap[$parentGenericTypeName] = $genericExtendType; } - - return new TemplateTypeMap($templateTypeMap); + return new \PHPStan\Type\Generic\TemplateTypeMap($templateTypeMap); } - return null; } - /** * @return ExtendsTag[] */ - private function resolveExtendsTags(ClassReflection $classReflection): array + private function resolveExtendsTags(\PHPStan\Reflection\ClassReflection $classReflection) : array { $parentClassReflection = $classReflection->getParentClass(); - if (! $parentClassReflection instanceof ClassReflection) { + if (!$parentClassReflection instanceof \PHPStan\Reflection\ClassReflection) { return []; } - $resolvedPhpDocBlock = $classReflection->getResolvedPhpDoc(); - if (! $resolvedPhpDocBlock instanceof ResolvedPhpDocBlock) { + if (!$resolvedPhpDocBlock instanceof \PHPStan\PhpDoc\ResolvedPhpDocBlock) { return []; } - return $resolvedPhpDocBlock->getExtendsTags(); } - /** * @return string[] */ - private function resolveParentGenericTypeNames(ClassReflection $classReflection): array + private function resolveParentGenericTypeNames(\PHPStan\Reflection\ClassReflection $classReflection) : array { $parentClassReflection = $classReflection->getParentClass(); - if (! $parentClassReflection instanceof ClassReflection) { + if (!$parentClassReflection instanceof \PHPStan\Reflection\ClassReflection) { return []; } - $templateTypeMap = $parentClassReflection->getTemplateTypeMap(); - return array_keys($templateTypeMap->getTypes()); + return \array_keys($templateTypeMap->getTypes()); } - - private function createTemplateObjectType( - TemplateTypeScope $templateTypeScope, - string $parentGenericTypeName, - TypeWithClassName $typeWithClassName - ): TemplateObjectType { - return new TemplateObjectType( - $templateTypeScope, - new TemplateTypeParameterStrategy(), - TemplateTypeVariance::createInvariant(), - $parentGenericTypeName, - new ObjectType($typeWithClassName->getClassName()) - ); + private function createTemplateObjectType(\PHPStan\Type\Generic\TemplateTypeScope $templateTypeScope, string $parentGenericTypeName, \PHPStan\Type\TypeWithClassName $typeWithClassName) : \PHPStan\Type\Generic\TemplateObjectType + { + return new \PHPStan\Type\Generic\TemplateObjectType($templateTypeScope, new \PHPStan\Type\Generic\TemplateTypeParameterStrategy(), \PHPStan\Type\Generic\TemplateTypeVariance::createInvariant(), $parentGenericTypeName, new \PHPStan\Type\ObjectType($typeWithClassName->getClassName())); } } diff --git a/rules/Generics/NodeType/GenericTypeSpecifier.php b/rules/Generics/NodeType/GenericTypeSpecifier.php index 892e3442c63..ebddef28bc2 100644 --- a/rules/Generics/NodeType/GenericTypeSpecifier.php +++ b/rules/Generics/NodeType/GenericTypeSpecifier.php @@ -1,7 +1,6 @@ staticTypeMapper = $staticTypeMapper; $this->extendsTemplateTypeMapFallbackFactory = $extendsTemplateTypeMapFallbackFactory; } - /** * @param MethodTagValueNode[] $methodTagValueNodes */ - public function replaceGenericTypesWithSpecificTypes( - array $methodTagValueNodes, - Node $node, - ClassReflection $classReflection - ): void { + public function replaceGenericTypesWithSpecificTypes(array $methodTagValueNodes, \PhpParser\Node $node, \PHPStan\Reflection\ClassReflection $classReflection) : void + { $templateTypeMap = $this->resolveAvailableTemplateTypeMap($classReflection); foreach ($methodTagValueNodes as $methodTagValueNode) { if ($methodTagValueNode->returnType === null) { continue; } - - $returnType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanTypeWithTemplateTypeMap( - $methodTagValueNode->returnType, - $node, - $templateTypeMap - ); - - $resolvedType = TemplateTypeHelper::resolveTemplateTypes($returnType, $templateTypeMap); + $returnType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanTypeWithTemplateTypeMap($methodTagValueNode->returnType, $node, $templateTypeMap); + $resolvedType = \PHPStan\Type\Generic\TemplateTypeHelper::resolveTemplateTypes($returnType, $templateTypeMap); $resolvedTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPHPStanPhpDocTypeNode($resolvedType); $methodTagValueNode->returnType = $resolvedTypeNode; } } - - private function resolveAvailableTemplateTypeMap(ClassReflection $classReflection): TemplateTypeMap + private function resolveAvailableTemplateTypeMap(\PHPStan\Reflection\ClassReflection $classReflection) : \PHPStan\Type\Generic\TemplateTypeMap { $templateTypeMap = $classReflection->getTemplateTypeMap(); - // add template map from extends if ($templateTypeMap->getTypes() !== []) { return $templateTypeMap; } - $fallbackTemplateTypeMap = $this->extendsTemplateTypeMapFallbackFactory->createFromClassReflection( - $classReflection - ); - - if ($fallbackTemplateTypeMap instanceof TemplateTypeMap) { + $fallbackTemplateTypeMap = $this->extendsTemplateTypeMapFallbackFactory->createFromClassReflection($classReflection); + if ($fallbackTemplateTypeMap instanceof \PHPStan\Type\Generic\TemplateTypeMap) { return $fallbackTemplateTypeMap; } - return $templateTypeMap; } } diff --git a/rules/Generics/Rector/Class_/GenericsPHPStormMethodAnnotationRector.php b/rules/Generics/Rector/Class_/GenericsPHPStormMethodAnnotationRector.php index 37c4163b29d..d69b7397ffa 100644 --- a/rules/Generics/Rector/Class_/GenericsPHPStormMethodAnnotationRector.php +++ b/rules/Generics/Rector/Class_/GenericsPHPStormMethodAnnotationRector.php @@ -1,7 +1,6 @@ classGenericMethodResolver = $classGenericMethodResolver; $this->genericTypeSpecifier = $genericTypeSpecifier; $this->genericClassReflectionAnalyzer = $genericClassReflectionAnalyzer; $this->unnededMethodTagValueNodeFilter = $unnededMethodTagValueNodeFilter; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Complete PHPStorm @method annotations, to make it understand the PHPStan/Psalm generics', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Complete PHPStorm @method annotations, to make it understand the PHPStan/Psalm generics', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' /** * @template TEntity as object */ @@ -84,9 +69,7 @@ final class AndroidDeviceRepository extends AbstractRepository { } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' /** * @template TEntity as object */ @@ -109,56 +92,36 @@ final class AndroidDeviceRepository extends AbstractRepository { } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $childParentClassReflections = $this->genericClassReflectionAnalyzer->resolveChildParent($node); - if (! $childParentClassReflections instanceof ChildParentClassReflections) { + if (!$childParentClassReflections instanceof \Rector\Generics\ValueObject\ChildParentClassReflections) { return null; } - // resolve generic method from parent $methodTagValueNodes = $this->classGenericMethodResolver->resolveFromClass($childParentClassReflections); - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - - $methodTagValueNodes = $this->unnededMethodTagValueNodeFilter->filter( - $methodTagValueNodes, - $phpDocInfo, - $childParentClassReflections, - $scope - ); - - $this->genericTypeSpecifier->replaceGenericTypesWithSpecificTypes( - $methodTagValueNodes, - $node, - $childParentClassReflections->getChildClassReflection() - ); - + $methodTagValueNodes = $this->unnededMethodTagValueNodeFilter->filter($methodTagValueNodes, $phpDocInfo, $childParentClassReflections, $scope); + $this->genericTypeSpecifier->replaceGenericTypesWithSpecificTypes($methodTagValueNodes, $node, $childParentClassReflections->getChildClassReflection()); foreach ($methodTagValueNodes as $methodTagValueNode) { $phpDocInfo->addTagValueNode($methodTagValueNode); } - return $node; } } diff --git a/rules/Generics/Reflection/ClassGenericMethodResolver.php b/rules/Generics/Reflection/ClassGenericMethodResolver.php index 9f2266ed006..3cc4dad9292 100644 --- a/rules/Generics/Reflection/ClassGenericMethodResolver.php +++ b/rules/Generics/Reflection/ClassGenericMethodResolver.php @@ -1,95 +1,67 @@ simplePhpDocParser = $simplePhpDocParser; $this->methodTagValueNodeFactory = $methodTagValueNodeFactory; } - /** * @return MethodTagValueNode[] */ - public function resolveFromClass(ChildParentClassReflections $genericChildParentClassReflections): array + public function resolveFromClass(\Rector\Generics\ValueObject\ChildParentClassReflections $genericChildParentClassReflections) : array { $methodTagValueNodes = []; - $classReflection = $genericChildParentClassReflections->getParentClassReflection(); - $templateNames = array_keys($classReflection->getTemplateTags()); - + $templateNames = \array_keys($classReflection->getTemplateTags()); foreach ($classReflection->getNativeMethods() as $methodReflection) { $parentMethodDocComment = $methodReflection->getDocComment(); if ($parentMethodDocComment === null) { continue; } - // how to parse? $parentMethodSimplePhpDocNode = $this->simplePhpDocParser->parseDocBlock($parentMethodDocComment); - $methodTagValueNode = $this->resolveMethodTagValueNode( - $parentMethodSimplePhpDocNode, - $templateNames, - $methodReflection, - $genericChildParentClassReflections - ); - if (! $methodTagValueNode instanceof MethodTagValueNode) { + $methodTagValueNode = $this->resolveMethodTagValueNode($parentMethodSimplePhpDocNode, $templateNames, $methodReflection, $genericChildParentClassReflections); + if (!$methodTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueNode) { continue; } - $methodTagValueNodes[] = $methodTagValueNode; } - return $methodTagValueNodes; } - /** * @param string[] $templateNames */ - private function resolveMethodTagValueNode( - SimplePhpDocNode $simplePhpDocNode, - array $templateNames, - MethodReflection $methodReflection, - ChildParentClassReflections $genericChildParentClassReflections - ): ?MethodTagValueNode { + private function resolveMethodTagValueNode(\RectorPrefix20210509\Symplify\SimplePhpDocParser\ValueObject\Ast\PhpDoc\SimplePhpDocNode $simplePhpDocNode, array $templateNames, \PHPStan\Reflection\MethodReflection $methodReflection, \Rector\Generics\ValueObject\ChildParentClassReflections $genericChildParentClassReflections) : ?\PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueNode + { foreach ($simplePhpDocNode->getReturnTagValues() as $returnTagValueNode) { foreach ($templateNames as $templateName) { $typeAsString = (string) $returnTagValueNode->type; - if (! Strings::match($typeAsString, '#\b' . preg_quote($templateName, '#') . '\b#')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($typeAsString, '#\\b' . \preg_quote($templateName, '#') . '\\b#')) { continue; } - - return $this->methodTagValueNodeFactory->createFromMethodReflectionAndReturnTagValueNode( - $methodReflection, - $returnTagValueNode, - $genericChildParentClassReflections - ); + return $this->methodTagValueNodeFactory->createFromMethodReflectionAndReturnTagValueNode($methodReflection, $returnTagValueNode, $genericChildParentClassReflections); } } - return null; } } diff --git a/rules/Generics/Reflection/ClassMethodAnalyzer.php b/rules/Generics/Reflection/ClassMethodAnalyzer.php index 8c678c2e4f4..7eee6c98fc5 100644 --- a/rules/Generics/Reflection/ClassMethodAnalyzer.php +++ b/rules/Generics/Reflection/ClassMethodAnalyzer.php @@ -1,26 +1,19 @@ hasMethod($methodName)) { - return false; + public function hasClassMethodDirectly(\PHPStan\Reflection\ClassReflection $classReflection, string $methodName, \PHPStan\Analyser\Scope $scope) : bool + { + if (!$classReflection->hasMethod($methodName)) { + return \false; } - $classMethodReflection = $classReflection->getMethod($methodName, $scope); $declaringClassReflection = $classMethodReflection->getDeclaringClass(); - return $declaringClassReflection->getName() === $classReflection->getName(); } } diff --git a/rules/Generics/Reflection/GenericClassReflectionAnalyzer.php b/rules/Generics/Reflection/GenericClassReflectionAnalyzer.php index 16583f6fa07..0fdc3ae5b4d 100644 --- a/rules/Generics/Reflection/GenericClassReflectionAnalyzer.php +++ b/rules/Generics/Reflection/GenericClassReflectionAnalyzer.php @@ -1,7 +1,6 @@ extends === null) { return null; } - - $scope = $class->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $class->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - - if (! $this->isGeneric($classReflection)) { + if (!$this->isGeneric($classReflection)) { return null; } - $parentClassReflection = $classReflection->getParentClass(); - if (! $parentClassReflection instanceof ClassReflection) { + if (!$parentClassReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - - if (! $this->isGeneric($parentClassReflection)) { + if (!$this->isGeneric($parentClassReflection)) { return null; } - - return new ChildParentClassReflections($classReflection, $parentClassReflection); + return new \Rector\Generics\ValueObject\ChildParentClassReflections($classReflection, $parentClassReflection); } - /** * Solve isGeneric() ignores extends and similar tags, * so it has to be extended with "@extends" and "@implements" */ - private function isGeneric(ClassReflection $classReflection): bool + private function isGeneric(\PHPStan\Reflection\ClassReflection $classReflection) : bool { if ($classReflection->isGeneric()) { - return true; + return \true; } - $resolvedPhpDocBlock = $classReflection->getResolvedPhpDoc(); - if (! $resolvedPhpDocBlock instanceof ResolvedPhpDocBlock) { - return false; + if (!$resolvedPhpDocBlock instanceof \PHPStan\PhpDoc\ResolvedPhpDocBlock) { + return \false; } - if ($resolvedPhpDocBlock->getExtendsTags() !== []) { - return true; + return \true; } - return $resolvedPhpDocBlock->getImplementsTags() !== []; } } diff --git a/rules/Generics/TagValueNodeFactory/MethodTagValueNodeFactory.php b/rules/Generics/TagValueNodeFactory/MethodTagValueNodeFactory.php index 383b8084bbd..1bc0ba9cbda 100644 --- a/rules/Generics/TagValueNodeFactory/MethodTagValueNodeFactory.php +++ b/rules/Generics/TagValueNodeFactory/MethodTagValueNodeFactory.php @@ -1,7 +1,6 @@ methodTagValueParameterNodeFactory = $methodTagValueParameterNodeFactory; $this->staticTypeMapper = $staticTypeMapper; } - - public function createFromMethodReflectionAndReturnTagValueNode( - MethodReflection $methodReflection, - ReturnTagValueNode $returnTagValueNode, - ChildParentClassReflections $childParentClassReflections - ): MethodTagValueNode { + public function createFromMethodReflectionAndReturnTagValueNode(\PHPStan\Reflection\MethodReflection $methodReflection, \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode $returnTagValueNode, \Rector\Generics\ValueObject\ChildParentClassReflections $childParentClassReflections) : \PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueNode + { $templateTypeMap = $childParentClassReflections->getTemplateTypeMap(); $returnTagTypeNode = $this->resolveReturnTagTypeNode($returnTagValueNode, $templateTypeMap); - - $parameterReflections = $methodReflection->getVariants()[0] - ->getParameters(); + $parameterReflections = $methodReflection->getVariants()[0]->getParameters(); $stringParameters = $this->resolveStringParameters($parameterReflections); - - return new MethodTagValueNode( - false, - $returnTagTypeNode, - $methodReflection->getName(), - $stringParameters, - '' - ); + return new \PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueNode(\false, $returnTagTypeNode, $methodReflection->getName(), $stringParameters, ''); } - /** * @param ParameterReflection[] $parameterReflections * @return MethodTagValueParameterNode[] */ - private function resolveStringParameters(array $parameterReflections): array + private function resolveStringParameters(array $parameterReflections) : array { $stringParameters = []; - foreach ($parameterReflections as $parameterReflection) { - $stringParameters[] = $this->methodTagValueParameterNodeFactory->createFromParamReflection( - $parameterReflection - ); + $stringParameters[] = $this->methodTagValueParameterNodeFactory->createFromParamReflection($parameterReflection); } - return $stringParameters; } - - private function resolveReturnTagTypeNode( - ReturnTagValueNode $returnTagValueNode, - TemplateTypeMap $templateTypeMap - ): TypeNode { + private function resolveReturnTagTypeNode(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode $returnTagValueNode, \PHPStan\Type\Generic\TemplateTypeMap $templateTypeMap) : \PHPStan\PhpDocParser\Ast\Type\TypeNode + { $returnTagTypeNode = $returnTagValueNode->type; - if ($returnTagValueNode->type instanceof UnionTypeNode) { + if ($returnTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\UnionTypeNode) { return $this->resolveUnionTypeNode($returnTagValueNode->type, $templateTypeMap); } - - if ($returnTagValueNode->type instanceof IdentifierTypeNode) { - return $this->resolveIdentifierTypeNode( - $returnTagValueNode->type, - $templateTypeMap, - $returnTagTypeNode - ); + if ($returnTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode) { + return $this->resolveIdentifierTypeNode($returnTagValueNode->type, $templateTypeMap, $returnTagTypeNode); } - return $returnTagTypeNode; } - - private function resolveUnionTypeNode(UnionTypeNode $unionTypeNode, TemplateTypeMap $templateTypeMap): UnionTypeNode + private function resolveUnionTypeNode(\PHPStan\PhpDocParser\Ast\Type\UnionTypeNode $unionTypeNode, \PHPStan\Type\Generic\TemplateTypeMap $templateTypeMap) : \PHPStan\PhpDocParser\Ast\Type\UnionTypeNode { $resolvedTypes = []; foreach ($unionTypeNode->types as $unionedTypeNode) { - if ($unionedTypeNode instanceof ArrayTypeNode) { - if (! $unionedTypeNode->type instanceof IdentifierTypeNode) { - throw new ShouldNotHappenException(); + if ($unionedTypeNode instanceof \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode) { + if (!$unionedTypeNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $resolvedType = $this->resolveIdentifierTypeNode( - $unionedTypeNode->type, - $templateTypeMap, - $unionedTypeNode - ); - - $resolvedTypes[] = new ArrayTypeNode($resolvedType); - } elseif ($unionedTypeNode instanceof IdentifierTypeNode) { - $resolvedTypes[] = $this->resolveIdentifierTypeNode( - $unionedTypeNode, - $templateTypeMap, - $unionedTypeNode - ); + $resolvedType = $this->resolveIdentifierTypeNode($unionedTypeNode->type, $templateTypeMap, $unionedTypeNode); + $resolvedTypes[] = new \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode($resolvedType); + } elseif ($unionedTypeNode instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode) { + $resolvedTypes[] = $this->resolveIdentifierTypeNode($unionedTypeNode, $templateTypeMap, $unionedTypeNode); } } - - return new UnionTypeNode($resolvedTypes); + return new \PHPStan\PhpDocParser\Ast\Type\UnionTypeNode($resolvedTypes); } - - private function resolveIdentifierTypeNode( - IdentifierTypeNode $identifierTypeNode, - TemplateTypeMap $templateTypeMap, - TypeNode $fallbackTypeNode - ): TypeNode { + private function resolveIdentifierTypeNode(\PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode $identifierTypeNode, \PHPStan\Type\Generic\TemplateTypeMap $templateTypeMap, \PHPStan\PhpDocParser\Ast\Type\TypeNode $fallbackTypeNode) : \PHPStan\PhpDocParser\Ast\Type\TypeNode + { $typeName = $identifierTypeNode->name; $genericType = $templateTypeMap->getType($typeName); - - if ($genericType instanceof Type) { + if ($genericType instanceof \PHPStan\Type\Type) { return $this->staticTypeMapper->mapPHPStanTypeToPHPStanPhpDocTypeNode($genericType); } - return $fallbackTypeNode; } } diff --git a/rules/Generics/TagValueNodeFactory/MethodTagValueParameterNodeFactory.php b/rules/Generics/TagValueNodeFactory/MethodTagValueParameterNodeFactory.php index 2383ee6e0e2..4a80593922f 100644 --- a/rules/Generics/TagValueNodeFactory/MethodTagValueParameterNodeFactory.php +++ b/rules/Generics/TagValueNodeFactory/MethodTagValueParameterNodeFactory.php @@ -1,39 +1,33 @@ staticTypeMapper = $staticTypeMapper; } - - public function createFromParamReflection(ParameterReflection $parameterReflection): MethodTagValueParameterNode + public function createFromParamReflection(\PHPStan\Reflection\ParameterReflection $parameterReflection) : \PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueParameterNode { $parameterType = $parameterReflection->getType(); - if ($parameterType instanceof MixedType && ! $parameterType->isExplicitMixed()) { + if ($parameterType instanceof \PHPStan\Type\MixedType && !$parameterType->isExplicitMixed()) { $parameterTypeNode = null; } else { $parameterTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPHPStanPhpDocTypeNode($parameterType); } - - return new MethodTagValueParameterNode( + return new \PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueParameterNode( $parameterTypeNode, - $parameterReflection->passedByReference() - ->yes(), + $parameterReflection->passedByReference()->yes(), $parameterReflection->isVariadic(), '$' . $parameterReflection->getName(), // @todo resolve diff --git a/rules/Generics/ValueObject/ChildParentClassReflections.php b/rules/Generics/ValueObject/ChildParentClassReflections.php index 0cdb11993e3..5e876d8087d 100644 --- a/rules/Generics/ValueObject/ChildParentClassReflections.php +++ b/rules/Generics/ValueObject/ChildParentClassReflections.php @@ -1,48 +1,40 @@ childClassReflection = $childClassReflection; $this->parentClassReflection = $parentClassReflection; } - - public function getChildClassReflection(): ClassReflection + public function getChildClassReflection() : \PHPStan\Reflection\ClassReflection { return $this->childClassReflection; } - - public function getParentClassReflection(): ClassReflection + public function getParentClassReflection() : \PHPStan\Reflection\ClassReflection { return $this->parentClassReflection; } - /** * Child class has priority with template map */ - public function getTemplateTypeMap(): TemplateTypeMap + public function getTemplateTypeMap() : \PHPStan\Type\Generic\TemplateTypeMap { $parentClassTemplateTypeMap = $this->parentClassReflection->getTemplateTypeMap(); $childClassTemplateTypeMap = $this->childClassReflection->getTemplateTypeMap(); - return $childClassTemplateTypeMap->intersect($parentClassTemplateTypeMap); } } diff --git a/rules/LeagueEvent/Rector/MethodCall/DispatchStringToObjectRector.php b/rules/LeagueEvent/Rector/MethodCall/DispatchStringToObjectRector.php index 626b075c941..03ccb01b442 100644 --- a/rules/LeagueEvent/Rector/MethodCall/DispatchStringToObjectRector.php +++ b/rules/LeagueEvent/Rector/MethodCall/DispatchStringToObjectRector.php @@ -23,29 +23,22 @@ use PHPStan\Type\StringType; use Rector\Core\Rector\AbstractRector; use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; - /** * @see \Rector\Tests\LeagueEvent\Rector\MethodCall\DispatchStringToObjectRector\DispatchStringToObjectRectorTest */ -final class DispatchStringToObjectRector extends AbstractRector +final class DispatchStringToObjectRector extends \Rector\Core\Rector\AbstractRector { /** * @var string */ private const STMTS = 'stmts'; - /** * @var string */ private const NAME = 'name'; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change string events to anonymous class which implement \League\Event\HasEventName', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change string events to anonymous class which implement \\League\\Event\\HasEventName', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { /** @var \League\Event\EventDispatcher */ @@ -57,8 +50,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { /** @var \League\Event\EventDispatcher */ @@ -76,94 +68,61 @@ final class SomeClass } } CODE_SAMPLE - ), - - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - return $this->updateNode($node); } - - private function shouldSkip(MethodCall $methodCall): bool + private function shouldSkip(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { - if (! $this->isNames($methodCall->name, ['dispatch', 'emit'])) { - return true; + if (!$this->isNames($methodCall->name, ['dispatch', 'emit'])) { + return \true; } - - if (! $this->nodeTypeResolver->isObjectTypes($methodCall->var, [ - new ObjectType('League\Event\EventDispatcher'), - new ObjectType('League\Event\Emitter'), - ])) { - return true; + if (!$this->nodeTypeResolver->isObjectTypes($methodCall->var, [new \PHPStan\Type\ObjectType('League\\Event\\EventDispatcher'), new \PHPStan\Type\ObjectType('League\\Event\\Emitter')])) { + return \true; } - - return ! $this->getStaticType($methodCall->args[0]->value) instanceof StringType; + return !$this->getStaticType($methodCall->args[0]->value) instanceof \PHPStan\Type\StringType; } - - private function updateNode(MethodCall $methodCall): MethodCall + private function updateNode(\PhpParser\Node\Expr\MethodCall $methodCall) : \PhpParser\Node\Expr\MethodCall { - $methodCall->args[0] = new Arg($this->createNewAnonymousEventClass($methodCall->args[0]->value)); + $methodCall->args[0] = new \PhpParser\Node\Arg($this->createNewAnonymousEventClass($methodCall->args[0]->value)); return $methodCall; } - - private function createNewAnonymousEventClass(Expr $expr): New_ + private function createNewAnonymousEventClass(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\New_ { - $implements = [new FullyQualified('League\Event\HasEventName')]; - - return new New_(new Class_(null, [ - 'implements' => $implements, - self::STMTS => $this->createAnonymousEventClassBody(), - ]), [new Arg($expr)]); + $implements = [new \PhpParser\Node\Name\FullyQualified('League\\Event\\HasEventName')]; + return new \PhpParser\Node\Expr\New_(new \PhpParser\Node\Stmt\Class_(null, ['implements' => $implements, self::STMTS => $this->createAnonymousEventClassBody()]), [new \PhpParser\Node\Arg($expr)]); } - /** * @return Stmt[] */ - private function createAnonymousEventClassBody(): array + private function createAnonymousEventClassBody() : array { - return [ - new Property(Class_::MODIFIER_PRIVATE, [new PropertyProperty(self::NAME)]), - new ClassMethod('__construct', [ - 'flags' => Class_::MODIFIER_PUBLIC, - 'params' => $this->createConstructParams(), - self::STMTS => [new Expression($this->createConstructAssign())], - ]), - new ClassMethod('eventName', [ - 'flags' => Class_::MODIFIER_PUBLIC, - 'returnType' => 'string', - self::STMTS => [new Return_(new Variable('this->name'))], - ]), - ]; + return [new \PhpParser\Node\Stmt\Property(\PhpParser\Node\Stmt\Class_::MODIFIER_PRIVATE, [new \PhpParser\Node\Stmt\PropertyProperty(self::NAME)]), new \PhpParser\Node\Stmt\ClassMethod('__construct', ['flags' => \PhpParser\Node\Stmt\Class_::MODIFIER_PUBLIC, 'params' => $this->createConstructParams(), self::STMTS => [new \PhpParser\Node\Stmt\Expression($this->createConstructAssign())]]), new \PhpParser\Node\Stmt\ClassMethod('eventName', ['flags' => \PhpParser\Node\Stmt\Class_::MODIFIER_PUBLIC, 'returnType' => 'string', self::STMTS => [new \PhpParser\Node\Stmt\Return_(new \PhpParser\Node\Expr\Variable('this->name'))]])]; } - /** * @return Param[] */ - private function createConstructParams(): array + private function createConstructParams() : array { - return [new Param(new Variable(self::NAME), null, 'string')]; + return [new \PhpParser\Node\Param(new \PhpParser\Node\Expr\Variable(self::NAME), null, 'string')]; } - - private function createConstructAssign(): Assign + private function createConstructAssign() : \PhpParser\Node\Expr\Assign { - return new Assign(new Variable('this->name'), new Variable(self::NAME)); + return new \PhpParser\Node\Expr\Assign(new \PhpParser\Node\Expr\Variable('this->name'), new \PhpParser\Node\Expr\Variable(self::NAME)); } } diff --git a/rules/MockeryToProphecy/Collector/MockVariableCollector.php b/rules/MockeryToProphecy/Collector/MockVariableCollector.php index 9f2e79063ad..9a9de4b6a9c 100644 --- a/rules/MockeryToProphecy/Collector/MockVariableCollector.php +++ b/rules/MockeryToProphecy/Collector/MockVariableCollector.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->valueResolver = $valueResolver; } - /** * @param FuncCall|StaticCall $node * @return array */ - public function collectMockVariableName(Node $node): array + public function collectMockVariableName(\PhpParser\Node $node) : array { $mockVariableTypesByNames = []; - - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Assign) { + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Expr\Assign) { return []; } - - if (! $parentNode->var instanceof Variable) { + if (!$parentNode->var instanceof \PhpParser\Node\Expr\Variable) { return []; } - /** @var Variable $variable */ $variable = $parentNode->var; - /** @var string $variableName */ $variableName = $this->nodeNameResolver->getName($variable); - $type = $node->args[0]->value; - $mockedType = $this->valueResolver->getValue($type); $mockVariableTypesByNames[$variableName] = $mockedType; - return $mockVariableTypesByNames; } } diff --git a/rules/MockeryToProphecy/Rector/ClassMethod/MockeryCreateMockToProphizeRector.php b/rules/MockeryToProphecy/Rector/ClassMethod/MockeryCreateMockToProphizeRector.php index ac782ae563b..3a638ac9463 100644 --- a/rules/MockeryToProphecy/Rector/ClassMethod/MockeryCreateMockToProphizeRector.php +++ b/rules/MockeryToProphecy/Rector/ClassMethod/MockeryCreateMockToProphizeRector.php @@ -1,7 +1,6 @@ */ private $mockVariableTypesByNames = []; - /** * @var MockVariableCollector */ private $mockVariableCollector; - /** * @var TestsNodeAnalyzer */ private $testsNodeAnalyzer; - - public function __construct(MockVariableCollector $mockVariableCollector, TestsNodeAnalyzer $testsNodeAnalyzer) + public function __construct(\Rector\MockeryToProphecy\Collector\MockVariableCollector $mockVariableCollector, \Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer $testsNodeAnalyzer) { $this->mockVariableCollector = $mockVariableCollector; $this->testsNodeAnalyzer = $testsNodeAnalyzer; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->testsNodeAnalyzer->isInTestClass($node)) { + if (!$this->testsNodeAnalyzer->isInTestClass($node)) { return null; } - $this->replaceMockCreationsAndCollectVariableNames($node); $this->revealMockArguments($node); - return $node; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes mockery mock creation to Prophesize', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes mockery mock creation to Prophesize', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $mock = \Mockery::mock('MyClass'); $service = new Service(); $service->injectDependency($mock); CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $mock = $this->prophesize('MyClass'); $service = new Service(); $service->injectDependency($mock->reveal()); CODE_SAMPLE - ), - ] - ); +)]); } - - private function replaceMockCreationsAndCollectVariableNames(ClassMethod $classMethod): void + private function replaceMockCreationsAndCollectVariableNames(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { if ($classMethod->stmts === null) { return; } - - $this->traverseNodesWithCallable($classMethod->stmts, function (Node $node): ?MethodCall { - if (! $node instanceof StaticCall) { + $this->traverseNodesWithCallable($classMethod->stmts, function (\PhpParser\Node $node) : ?MethodCall { + if (!$node instanceof \PhpParser\Node\Expr\StaticCall) { return null; } - $callerType = $this->nodeTypeResolver->resolve($node->class); - if (! $callerType->isSuperTypeOf(new ObjectType('Mockery'))->yes()) { + if (!$callerType->isSuperTypeOf(new \PHPStan\Type\ObjectType('Mockery'))->yes()) { return null; } - - if (! $this->isName($node->name, 'mock')) { + if (!$this->isName($node->name, 'mock')) { return null; } - $collectedVariableTypesByNames = $this->mockVariableCollector->collectMockVariableName($node); - - $this->mockVariableTypesByNames = array_merge( - $this->mockVariableTypesByNames, - $collectedVariableTypesByNames - ); - - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Arg) { + $this->mockVariableTypesByNames = \array_merge($this->mockVariableTypesByNames, $collectedVariableTypesByNames); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Arg) { $prophesizeMethodCall = $this->createProphesizeMethodCall($node); return $this->nodeFactory->createMethodCall($prophesizeMethodCall, 'reveal'); } - return $this->createProphesizeMethodCall($node); }); } - - private function revealMockArguments(ClassMethod $classMethod): void + private function revealMockArguments(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { if ($classMethod->stmts === null) { return; } - - $this->traverseNodesWithCallable($classMethod->stmts, function (Node $node): ?MethodCall { - if (! $node instanceof Arg) { + $this->traverseNodesWithCallable($classMethod->stmts, function (\PhpParser\Node $node) : ?MethodCall { + if (!$node instanceof \PhpParser\Node\Arg) { return null; } - - if (! $node->value instanceof Variable) { + if (!$node->value instanceof \PhpParser\Node\Expr\Variable) { return null; } - /** @var string $variableName */ $variableName = $this->getName($node->value); - - if (! isset($this->mockVariableTypesByNames[$variableName])) { + if (!isset($this->mockVariableTypesByNames[$variableName])) { return null; } - return $this->nodeFactory->createMethodCall($node->value, 'reveal'); }); } - - private function createProphesizeMethodCall(StaticCall $staticCall): MethodCall + private function createProphesizeMethodCall(\PhpParser\Node\Expr\StaticCall $staticCall) : \PhpParser\Node\Expr\MethodCall { return $this->nodeFactory->createLocalMethodCall('prophesize', [$staticCall->args[0]]); } diff --git a/rules/MockeryToProphecy/Rector/StaticCall/MockeryCloseRemoveRector.php b/rules/MockeryToProphecy/Rector/StaticCall/MockeryCloseRemoveRector.php index ffa58184c70..ef839026520 100644 --- a/rules/MockeryToProphecy/Rector/StaticCall/MockeryCloseRemoveRector.php +++ b/rules/MockeryToProphecy/Rector/StaticCall/MockeryCloseRemoveRector.php @@ -1,7 +1,6 @@ testsNodeAnalyzer = $testsNodeAnalyzer; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->testsNodeAnalyzer->isInTestClass($node)) { + if (!$this->testsNodeAnalyzer->isInTestClass($node)) { return null; } - $callerType = $this->nodeTypeResolver->resolve($node->class); - if (! $callerType->isSuperTypeOf(new ObjectType('Mockery'))->yes()) { + if (!$callerType->isSuperTypeOf(new \PHPStan\Type\ObjectType('Mockery'))->yes()) { return null; } - - if (! $this->isName($node->name, 'close')) { + if (!$this->isName($node->name, 'close')) { return null; } - $this->removeNode($node); - return null; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Removes mockery close from test classes', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removes mockery close from test classes', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' public function tearDown() : void { \Mockery::close(); } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' public function tearDown() : void { } CODE_SAMPLE - ), - ] - ); +)]); } } diff --git a/rules/MysqlToMysqli/Rector/Assign/MysqlAssignToMysqliRector.php b/rules/MysqlToMysqli/Rector/Assign/MysqlAssignToMysqliRector.php index 6ab3b6fde6c..63ef930dcec 100644 --- a/rules/MysqlToMysqli/Rector/Assign/MysqlAssignToMysqliRector.php +++ b/rules/MysqlToMysqli/Rector/Assign/MysqlAssignToMysqliRector.php @@ -1,7 +1,6 @@ */ - private const FIELD_TO_FIELD_DIRECT = [ - 'mysql_field_len' => 'length', - 'mysql_field_name' => 'name', - 'mysql_field_table' => 'table', - ]; - + private const FIELD_TO_FIELD_DIRECT = ['mysql_field_len' => 'length', 'mysql_field_name' => 'name', 'mysql_field_table' => 'table']; /** * @var string */ private const MYSQLI_DATA_SEEK = 'mysqli_data_seek'; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Converts more complex mysql functions to mysqli', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Converts more complex mysql functions to mysqli', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $data = mysql_db_name($result, $row); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' mysqli_data_seek($result, $row); $fetch = mysql_fetch_row($result); $data = $fetch[0]; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof FuncCall) { + if (!$node->expr instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - /** @var FuncCall $funcCallNode */ $funcCallNode = $node->expr; - if ($this->isName($funcCallNode, 'mysql_tablename')) { return $this->processMysqlTableName($node, $funcCallNode); } - if ($this->isName($funcCallNode, 'mysql_db_name')) { return $this->processMysqlDbName($node, $funcCallNode); } - if ($this->isName($funcCallNode, 'mysql_db_query')) { return $this->processMysqliSelectDb($node, $funcCallNode); } - if ($this->isName($funcCallNode, 'mysql_fetch_field')) { return $this->processMysqlFetchField($node, $funcCallNode); } - if ($this->isName($funcCallNode, 'mysql_result')) { return $this->processMysqlResult($node, $funcCallNode); } - return $this->processFieldToFieldDirect($node, $funcCallNode); } - - private function processMysqlTableName(Assign $assign, FuncCall $funcCall): FuncCall + private function processMysqlTableName(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\FuncCall { - $funcCall->name = new Name(self::MYSQLI_DATA_SEEK); - - $newFuncCall = new FuncCall(new Name('mysql_fetch_array'), [$funcCall->args[0]]); - $newAssignNode = new Assign($assign->var, new ArrayDimFetch($newFuncCall, new LNumber(0))); - + $funcCall->name = new \PhpParser\Node\Name(self::MYSQLI_DATA_SEEK); + $newFuncCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('mysql_fetch_array'), [$funcCall->args[0]]); + $newAssignNode = new \PhpParser\Node\Expr\Assign($assign->var, new \PhpParser\Node\Expr\ArrayDimFetch($newFuncCall, new \PhpParser\Node\Scalar\LNumber(0))); $this->addNodeAfterNode($newAssignNode, $assign); - return $funcCall; } - - private function processMysqlDbName(Assign $assign, FuncCall $funcCall): FuncCall + private function processMysqlDbName(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\FuncCall { - $funcCall->name = new Name(self::MYSQLI_DATA_SEEK); - - $mysqlFetchRowFuncCall = new FuncCall(new Name('mysqli_fetch_row'), [$funcCall->args[0]]); - $fetchVariable = new Variable('fetch'); - $newAssignNode = new Assign($fetchVariable, $mysqlFetchRowFuncCall); + $funcCall->name = new \PhpParser\Node\Name(self::MYSQLI_DATA_SEEK); + $mysqlFetchRowFuncCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('mysqli_fetch_row'), [$funcCall->args[0]]); + $fetchVariable = new \PhpParser\Node\Expr\Variable('fetch'); + $newAssignNode = new \PhpParser\Node\Expr\Assign($fetchVariable, $mysqlFetchRowFuncCall); $this->addNodeAfterNode($newAssignNode, $assign); - - $newAssignNode = new Assign($assign->var, new ArrayDimFetch($fetchVariable, new LNumber(0))); + $newAssignNode = new \PhpParser\Node\Expr\Assign($assign->var, new \PhpParser\Node\Expr\ArrayDimFetch($fetchVariable, new \PhpParser\Node\Scalar\LNumber(0))); $this->addNodeAfterNode($newAssignNode, $assign); - return $funcCall; } - - private function processMysqliSelectDb(Assign $assign, FuncCall $funcCall): FuncCall + private function processMysqliSelectDb(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\FuncCall { - $funcCall->name = new Name('mysqli_select_db'); - - $newAssignNode = new Assign($assign->var, new FuncCall(new Name('mysqli_query'), [$funcCall->args[1]])); + $funcCall->name = new \PhpParser\Node\Name('mysqli_select_db'); + $newAssignNode = new \PhpParser\Node\Expr\Assign($assign->var, new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('mysqli_query'), [$funcCall->args[1]])); $this->addNodeAfterNode($newAssignNode, $assign); - unset($funcCall->args[1]); - return $funcCall; } - - private function processMysqlFetchField(Assign $assign, FuncCall $funcCall): Assign + private function processMysqlFetchField(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\Assign { if (isset($funcCall->args[1])) { - $funcCall->name = new Name('mysqli_fetch_field_direct'); + $funcCall->name = new \PhpParser\Node\Name('mysqli_fetch_field_direct'); } else { - $funcCall->name = new Name('mysqli_fetch_field'); + $funcCall->name = new \PhpParser\Node\Name('mysqli_fetch_field'); } - return $assign; } - - private function processMysqlResult(Assign $assign, FuncCall $funcCall): FuncCall + private function processMysqlResult(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\FuncCall { $fetchField = null; if (isset($funcCall->args[2])) { $fetchField = $funcCall->args[2]->value; unset($funcCall->args[2]); } - - $funcCall->name = new Name(self::MYSQLI_DATA_SEEK); - - $mysqlFetchArrayFuncCall = new FuncCall(new Name('mysqli_fetch_array'), [$funcCall->args[0]]); - $fetchVariable = new Variable('fetch'); - $newAssignNode = new Assign($fetchVariable, $mysqlFetchArrayFuncCall); + $funcCall->name = new \PhpParser\Node\Name(self::MYSQLI_DATA_SEEK); + $mysqlFetchArrayFuncCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('mysqli_fetch_array'), [$funcCall->args[0]]); + $fetchVariable = new \PhpParser\Node\Expr\Variable('fetch'); + $newAssignNode = new \PhpParser\Node\Expr\Assign($fetchVariable, $mysqlFetchArrayFuncCall); $this->addNodeAfterNode($newAssignNode, $assign); - - $newAssignNode = new Assign($assign->var, new ArrayDimFetch($fetchVariable, $fetchField ?? new LNumber(0))); + $newAssignNode = new \PhpParser\Node\Expr\Assign($assign->var, new \PhpParser\Node\Expr\ArrayDimFetch($fetchVariable, $fetchField ?? new \PhpParser\Node\Scalar\LNumber(0))); $this->addNodeAfterNode($newAssignNode, $assign); - return $funcCall; } - - private function processFieldToFieldDirect(Assign $assign, FuncCall $funcCall): ?Assign + private function processFieldToFieldDirect(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr\Assign { foreach (self::FIELD_TO_FIELD_DIRECT as $funcName => $property) { if ($this->isName($funcCall, $funcName)) { - $parentNode = $funcCall->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof PropertyFetch) { + $parentNode = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\PropertyFetch) { continue; } - if ($parentNode instanceof StaticPropertyFetch) { + if ($parentNode instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { continue; } - - $funcCall->name = new Name('mysqli_fetch_field_direct'); - $assign->expr = new PropertyFetch($funcCall, $property); - + $funcCall->name = new \PhpParser\Node\Name('mysqli_fetch_field_direct'); + $assign->expr = new \PhpParser\Node\Expr\PropertyFetch($funcCall, $property); return $assign; } } - return null; } } diff --git a/rules/MysqlToMysqli/Rector/FuncCall/MysqlFuncCallToMysqliRector.php b/rules/MysqlToMysqli/Rector/FuncCall/MysqlFuncCallToMysqliRector.php index b8c89bf225e..bef34532140 100644 --- a/rules/MysqlToMysqli/Rector/FuncCall/MysqlFuncCallToMysqliRector.php +++ b/rules/MysqlToMysqli/Rector/FuncCall/MysqlFuncCallToMysqliRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->isName($node, 'mysql_create_db')) { return $this->processMysqlCreateDb($node); } - if ($this->isName($node, 'mysql_drop_db')) { return $this->processMysqlDropDb($node); } - if ($this->isName($node, 'mysql_list_dbs')) { - $node->name = new Name(self::MYSQLI_QUERY); - $node->args[0] = new Arg(new String_('SHOW DATABASES')); + $node->name = new \PhpParser\Node\Name(self::MYSQLI_QUERY); + $node->args[0] = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_('SHOW DATABASES')); } - if ($this->isName($node, 'mysql_list_fields')) { - $node->name = new Name(self::MYSQLI_QUERY); + $node->name = new \PhpParser\Node\Name(self::MYSQLI_QUERY); $node->args[0]->value = $this->joinStringWithNode('SHOW COLUMNS FROM', $node->args[1]->value); - unset($node->args[1]); } - if ($this->isName($node, 'mysql_list_tables')) { - $node->name = new Name(self::MYSQLI_QUERY); + $node->name = new \PhpParser\Node\Name(self::MYSQLI_QUERY); $node->args[0]->value = $this->joinStringWithNode('SHOW TABLES FROM', $node->args[0]->value); } - return $node; } - - private function processMysqlCreateDb(FuncCall $funcCall): FuncCall + private function processMysqlCreateDb(\PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\FuncCall { - $funcCall->name = new Name(self::MYSQLI_QUERY); + $funcCall->name = new \PhpParser\Node\Name(self::MYSQLI_QUERY); $funcCall->args[0]->value = $this->joinStringWithNode('CREATE DATABASE', $funcCall->args[0]->value); - return $funcCall; } - - private function processMysqlDropDb(FuncCall $funcCall): FuncCall + private function processMysqlDropDb(\PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\FuncCall { - $funcCall->name = new Name(self::MYSQLI_QUERY); + $funcCall->name = new \PhpParser\Node\Name(self::MYSQLI_QUERY); $funcCall->args[0]->value = $this->joinStringWithNode('DROP DATABASE', $funcCall->args[0]->value); - return $funcCall; } - - private function joinStringWithNode(string $string, Expr $expr): Expr + private function joinStringWithNode(string $string, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { - if ($expr instanceof String_) { - return new String_($string . ' ' . $expr->value); + if ($expr instanceof \PhpParser\Node\Scalar\String_) { + return new \PhpParser\Node\Scalar\String_($string . ' ' . $expr->value); } - - return new Concat(new String_($string . ' '), $expr); + return new \PhpParser\Node\Expr\BinaryOp\Concat(new \PhpParser\Node\Scalar\String_($string . ' '), $expr); } } diff --git a/rules/MysqlToMysqli/Rector/FuncCall/MysqlPConnectToMysqliConnectRector.php b/rules/MysqlToMysqli/Rector/FuncCall/MysqlPConnectToMysqliConnectRector.php index c2963edc4a5..2caecff24c5 100644 --- a/rules/MysqlToMysqli/Rector/FuncCall/MysqlPConnectToMysqliConnectRector.php +++ b/rules/MysqlToMysqli/Rector/FuncCall/MysqlPConnectToMysqliConnectRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'mysql_pconnect')) { + if (!$this->isName($node, 'mysql_pconnect')) { return null; } - - $node->name = new Name('mysqli_connect'); - + $node->name = new \PhpParser\Node\Name('mysqli_connect'); $node->args[0]->value = $this->joinStringWithNode('p:', $node->args[0]->value); - return $node; } - - private function joinStringWithNode(string $string, Expr $expr): Expr + private function joinStringWithNode(string $string, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { - if ($expr instanceof String_) { - return new String_($string . $expr->value); + if ($expr instanceof \PhpParser\Node\Scalar\String_) { + return new \PhpParser\Node\Scalar\String_($string . $expr->value); } - - return new Concat(new String_($string), $expr); + return new \PhpParser\Node\Expr\BinaryOp\Concat(new \PhpParser\Node\Scalar\String_($string), $expr); } } diff --git a/rules/MysqlToMysqli/Rector/FuncCall/MysqlQueryMysqlErrorWithLinkRector.php b/rules/MysqlToMysqli/Rector/FuncCall/MysqlQueryMysqlErrorWithLinkRector.php index 104e01cd5f7..7654556184e 100644 --- a/rules/MysqlToMysqli/Rector/FuncCall/MysqlQueryMysqlErrorWithLinkRector.php +++ b/rules/MysqlToMysqli/Rector/FuncCall/MysqlQueryMysqlErrorWithLinkRector.php @@ -1,7 +1,6 @@ */ - private const FUNCTION_RENAME_MAP = [ - 'mysql_affected_rows' => 'mysqli_affected_rows', - 'mysql_client_encoding' => 'mysqli_character_set_name', - 'mysql_close' => 'mysqli_close', - 'mysql_errno' => 'mysqli_errno', - 'mysql_error' => 'mysqli_error', - 'mysql_escape_string' => 'mysqli_real_escape_string', - 'mysql_get_host_info' => 'mysqli_get_host_info', - 'mysql_get_proto_info' => 'mysqli_get_proto_info', - 'mysql_get_server_info' => 'mysqli_get_server_info', - 'mysql_info' => 'mysqli_info', - 'mysql_insert_id' => 'mysqli_insert_id', - 'mysql_ping' => 'mysqli_ping', - 'mysql_query' => 'mysqli_query', - 'mysql_real_escape_string' => 'mysqli_real_escape_string', - 'mysql_select_db' => 'mysqli_select_db', - 'mysql_set_charset' => 'mysqli_set_charset', - 'mysql_stat' => 'mysqli_stat', - 'mysql_thread_id' => 'mysqli_thread_id', - ]; - + private const FUNCTION_RENAME_MAP = ['mysql_affected_rows' => 'mysqli_affected_rows', 'mysql_client_encoding' => 'mysqli_character_set_name', 'mysql_close' => 'mysqli_close', 'mysql_errno' => 'mysqli_errno', 'mysql_error' => 'mysqli_error', 'mysql_escape_string' => 'mysqli_real_escape_string', 'mysql_get_host_info' => 'mysqli_get_host_info', 'mysql_get_proto_info' => 'mysqli_get_proto_info', 'mysql_get_server_info' => 'mysqli_get_server_info', 'mysql_info' => 'mysqli_info', 'mysql_insert_id' => 'mysqli_insert_id', 'mysql_ping' => 'mysqli_ping', 'mysql_query' => 'mysqli_query', 'mysql_real_escape_string' => 'mysqli_real_escape_string', 'mysql_select_db' => 'mysqli_select_db', 'mysql_set_charset' => 'mysqli_set_charset', 'mysql_stat' => 'mysqli_stat', 'mysql_thread_id' => 'mysqli_thread_id']; /** * @var array */ - private const FUNCTION_CONNECTION_PARAMETER_POSITION_MAP = [ - 'mysql_affected_rows' => 0, - 'mysql_client_encoding' => 0, - 'mysql_close' => 0, - 'mysql_errno' => 0, - 'mysql_error' => 0, - 'mysql_get_host_info' => 0, - 'mysql_get_proto_info' => 0, - 'mysql_get_server_info' => 0, - 'mysql_info' => 0, - 'mysql_insert_id' => 0, - 'mysql_ping' => 0, - 'mysql_query' => 1, - 'mysql_real_escape_string' => 1, - 'mysql_select_db' => 1, - 'mysql_set_charset' => 1, - 'mysql_stat' => 0, - 'mysql_thread_id' => 0, - ]; - - public function getRuleDefinition(): RuleDefinition + private const FUNCTION_CONNECTION_PARAMETER_POSITION_MAP = ['mysql_affected_rows' => 0, 'mysql_client_encoding' => 0, 'mysql_close' => 0, 'mysql_errno' => 0, 'mysql_error' => 0, 'mysql_get_host_info' => 0, 'mysql_get_proto_info' => 0, 'mysql_get_server_info' => 0, 'mysql_info' => 0, 'mysql_insert_id' => 0, 'mysql_ping' => 0, 'mysql_query' => 1, 'mysql_real_escape_string' => 1, 'mysql_select_db' => 1, 'mysql_set_charset' => 1, 'mysql_stat' => 0, 'mysql_thread_id' => 0]; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Add mysql_query and mysql_error with connection', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add mysql_query and mysql_error with connection', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -93,8 +48,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -108,134 +62,101 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach (self::FUNCTION_RENAME_MAP as $oldFunction => $newFunction) { - if (! $this->isName($node, $oldFunction)) { + if (!$this->isName($node, $oldFunction)) { continue; } - - if ( - $node->args === [] - || ! $this->isProbablyMysql($node->args[0]->value) - ) { + if ($node->args === [] || !$this->isProbablyMysql($node->args[0]->value)) { $connectionVariable = $this->findConnectionVariable($node); - $this->removeExistingConnectionParameter($node); - - if (! $connectionVariable instanceof Expr) { + if (!$connectionVariable instanceof \PhpParser\Node\Expr) { return null; } - - $node->args = array_merge([new Arg($connectionVariable)], $node->args); + $node->args = \array_merge([new \PhpParser\Node\Arg($connectionVariable)], $node->args); } - - $node->name = new Name($newFunction); - + $node->name = new \PhpParser\Node\Name($newFunction); return $node; } - return null; } - - private function isProbablyMysql(Expr $expr): bool + private function isProbablyMysql(\PhpParser\Node\Expr $expr) : bool { - if ($this->isObjectType($expr, new ObjectType('mysqli'))) { - return true; + if ($this->isObjectType($expr, new \PHPStan\Type\ObjectType('mysqli'))) { + return \true; } - $staticType = $this->getStaticType($expr); - $resourceType = new ResourceType(); - + $resourceType = new \PHPStan\Type\ResourceType(); if ($staticType->equals($resourceType)) { - return true; + return \true; } - if ($this->isUnionTypeWithResourceSubType($staticType, $resourceType)) { - return true; + return \true; } - if (! $expr instanceof Variable) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->isMysqliConnect($expr); } - - private function findConnectionVariable(FuncCall $funcCall): ?Expr + private function findConnectionVariable(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr { - $connectionAssign = $this->betterNodeFinder->findFirstPrevious($funcCall, function (Node $node): ?bool { - if (! $node instanceof Assign) { + $connectionAssign = $this->betterNodeFinder->findFirstPrevious($funcCall, function (\PhpParser\Node $node) : ?bool { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - - return $this->isObjectType($node->expr, new ObjectType('mysqli')); + return $this->isObjectType($node->expr, new \PHPStan\Type\ObjectType('mysqli')); }); - - if (! $connectionAssign instanceof Assign) { + if (!$connectionAssign instanceof \PhpParser\Node\Expr\Assign) { return null; } - return $connectionAssign->var; } - - private function removeExistingConnectionParameter(FuncCall $funcCall): void + private function removeExistingConnectionParameter(\PhpParser\Node\Expr\FuncCall $funcCall) : void { /** @var string $functionName */ $functionName = $this->getName($funcCall); - if (! isset(self::FUNCTION_CONNECTION_PARAMETER_POSITION_MAP[$functionName])) { + if (!isset(self::FUNCTION_CONNECTION_PARAMETER_POSITION_MAP[$functionName])) { return; } - $connectionPosition = self::FUNCTION_CONNECTION_PARAMETER_POSITION_MAP[$functionName]; unset($funcCall->args[$connectionPosition]); } - - private function isUnionTypeWithResourceSubType(Type $staticType, ResourceType $resourceType): bool + private function isUnionTypeWithResourceSubType(\PHPStan\Type\Type $staticType, \PHPStan\Type\ResourceType $resourceType) : bool { - if ($staticType instanceof UnionType) { + if ($staticType instanceof \PHPStan\Type\UnionType) { foreach ($staticType->getTypes() as $type) { if ($type->equals($resourceType)) { - return true; + return \true; } } } - - return false; + return \false; } - - private function isMysqliConnect(Variable $variable): bool + private function isMysqliConnect(\PhpParser\Node\Expr\Variable $variable) : bool { - return (bool) $this->betterNodeFinder->findFirstPrevious($variable, function (Node $node) use ( - $variable - ): bool { - if (! $node instanceof Assign) { - return false; + return (bool) $this->betterNodeFinder->findFirstPrevious($variable, function (\PhpParser\Node $node) use($variable) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - if (! $node->expr instanceof FuncCall) { - return false; + if (!$node->expr instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - - if (! $this->nodeComparator->areNodesEqual($node->var, $variable)) { - return false; + if (!$this->nodeComparator->areNodesEqual($node->var, $variable)) { + return \false; } - return $this->isName($node->expr, 'mysqli_connect'); }); } diff --git a/rules/Naming/ArrayDimFetchRenamer.php b/rules/Naming/ArrayDimFetchRenamer.php index 1fdb1a2a1a8..a34c8b4b789 100644 --- a/rules/Naming/ArrayDimFetchRenamer.php +++ b/rules/Naming/ArrayDimFetchRenamer.php @@ -1,7 +1,6 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeComparator = $nodeComparator; } - /** * @see \Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector::renameVariableInClassMethod */ - public function renameToVariable( - ClassMethod $classMethod, - ArrayDimFetch $arrayDimFetch, - string $variableName - ): void { - $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->stmts, function ( - Node $node - ) use ($arrayDimFetch, $variableName) { + public function renameToVariable(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch, string $variableName) : void + { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->stmts, function (\PhpParser\Node $node) use($arrayDimFetch, $variableName) { // do not rename element above if ($node->getLine() <= $arrayDimFetch->getLine()) { return null; } - if ($this->isScopeNesting($node)) { - return NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; } - - if (! $this->nodeComparator->areNodesEqual($node, $arrayDimFetch)) { + if (!$this->nodeComparator->areNodesEqual($node, $arrayDimFetch)) { return null; } - - return new Variable($variableName); + return new \PhpParser\Node\Expr\Variable($variableName); }); } - - private function isScopeNesting(Node $node): bool + private function isScopeNesting(\PhpParser\Node $node) : bool { - return $node instanceof Closure || $node instanceof Function_ || $node instanceof ArrowFunction; + return $node instanceof \PhpParser\Node\Expr\Closure || $node instanceof \PhpParser\Node\Stmt\Function_ || $node instanceof \PhpParser\Node\Expr\ArrowFunction; } } diff --git a/rules/Naming/Contract/Guard/ConflictingNameGuardInterface.php b/rules/Naming/Contract/Guard/ConflictingNameGuardInterface.php index f15ee551451..0867bc3e6ff 100644 --- a/rules/Naming/Contract/Guard/ConflictingNameGuardInterface.php +++ b/rules/Naming/Contract/Guard/ConflictingNameGuardInterface.php @@ -1,12 +1,10 @@ propertyNaming = $propertyNaming; $this->nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; } - - public function resolve(Property $property): ?string + public function resolve(\PhpParser\Node\Stmt\Property $property) : ?string { - if (! $this->nodeTypeResolver->isPropertyBoolean($property)) { + if (!$this->nodeTypeResolver->isPropertyBoolean($property)) { return null; } - $expectedName = $this->propertyNaming->getExpectedNameFromBooleanPropertyType($property); if ($expectedName === null) { return null; } - // skip if already has suffix $currentName = $this->nodeNameResolver->getName($property); if ($this->nodeNameResolver->endsWith($currentName, $expectedName)) { return null; } - return $expectedName; } } diff --git a/rules/Naming/ExpectedNameResolver/InflectorSingularResolver.php b/rules/Naming/ExpectedNameResolver/InflectorSingularResolver.php index 59021ac5bd7..12176279024 100644 --- a/rules/Naming/ExpectedNameResolver/InflectorSingularResolver.php +++ b/rules/Naming/ExpectedNameResolver/InflectorSingularResolver.php @@ -1,80 +1,63 @@ */ - private const SINGULAR_VERB = [ - 'news' => 'new', - ]; - + private const SINGULAR_VERB = ['news' => 'new']; /** * @var string * @see https://regex101.com/r/lbQaGC/1 */ private const CAMELCASE_REGEX = '#(?([a-z]+|[A-Z]{1,}[a-z]+))#'; - /** * @var string * @see https://regex101.com/r/2aGdkZ/2 */ private const BY_MIDDLE_REGEX = '#(?By[A-Z][a-zA-Z]+)#'; - /** * @var string */ private const SINGLE = 'single'; - /** * @var Inflector */ private $inflector; - - public function __construct(Inflector $inflector) + public function __construct(\RectorPrefix20210509\Doctrine\Inflector\Inflector $inflector) { $this->inflector = $inflector; } - - public function resolve(string $currentName): string + public function resolve(string $currentName) : string { - $matchBy = Strings::match($currentName, self::BY_MIDDLE_REGEX); + $matchBy = \RectorPrefix20210509\Nette\Utils\Strings::match($currentName, self::BY_MIDDLE_REGEX); if ($matchBy) { - return Strings::substring($currentName, 0, - strlen($matchBy['by'])); + return \RectorPrefix20210509\Nette\Utils\Strings::substring($currentName, 0, -\strlen($matchBy['by'])); } - - if (array_key_exists($currentName, self::SINGULAR_VERB)) { + if (\array_key_exists($currentName, self::SINGULAR_VERB)) { return self::SINGULAR_VERB[$currentName]; } - - if (strpos($currentName, self::SINGLE) === 0) { + if (\strpos($currentName, self::SINGLE) === 0) { return $currentName; } - - $camelCases = Strings::matchAll($currentName, self::CAMELCASE_REGEX); + $camelCases = \RectorPrefix20210509\Nette\Utils\Strings::matchAll($currentName, self::CAMELCASE_REGEX); $singularValueVarName = ''; foreach ($camelCases as $camelCase) { $singularValueVarName .= $this->inflector->singularize($camelCase['camelcase']); } - if ($singularValueVarName === '') { return $currentName; } - - $singularValueVarName = $singularValueVarName === $currentName - ? self::SINGLE . ucfirst($singularValueVarName) - : $singularValueVarName; - if (strpos($singularValueVarName, self::SINGLE) !== 0) { + $singularValueVarName = $singularValueVarName === $currentName ? self::SINGLE . \ucfirst($singularValueVarName) : $singularValueVarName; + if (\strpos($singularValueVarName, self::SINGLE) !== 0) { return $singularValueVarName; } - $length = strlen($singularValueVarName); + $length = \strlen($singularValueVarName); if ($length < 40) { return $singularValueVarName; } diff --git a/rules/Naming/ExpectedNameResolver/MatchParamTypeExpectedNameResolver.php b/rules/Naming/ExpectedNameResolver/MatchParamTypeExpectedNameResolver.php index 078b7c6fc43..6e69ef59854 100644 --- a/rules/Naming/ExpectedNameResolver/MatchParamTypeExpectedNameResolver.php +++ b/rules/Naming/ExpectedNameResolver/MatchParamTypeExpectedNameResolver.php @@ -1,45 +1,38 @@ staticTypeMapper = $staticTypeMapper; $this->propertyNaming = $propertyNaming; } - - public function resolve(Param $param): ?string + public function resolve(\PhpParser\Node\Param $param) : ?string { // nothing to verify if ($param->type === null) { return null; } - $staticType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); $expectedName = $this->propertyNaming->getExpectedNameFromType($staticType); - if (! $expectedName instanceof ExpectedName) { + if (!$expectedName instanceof \Rector\Naming\ValueObject\ExpectedName) { return null; } - return $expectedName->getName(); } } diff --git a/rules/Naming/ExpectedNameResolver/MatchPropertyTypeExpectedNameResolver.php b/rules/Naming/ExpectedNameResolver/MatchPropertyTypeExpectedNameResolver.php index efa93b000ab..b38dc821b7a 100644 --- a/rules/Naming/ExpectedNameResolver/MatchPropertyTypeExpectedNameResolver.php +++ b/rules/Naming/ExpectedNameResolver/MatchPropertyTypeExpectedNameResolver.php @@ -1,7 +1,6 @@ propertyNaming = $propertyNaming; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->nodeNameResolver = $nodeNameResolver; } - - public function resolve(Property $property): ?string + public function resolve(\PhpParser\Node\Stmt\Property $property) : ?string { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); - $expectedName = $this->propertyNaming->getExpectedNameFromType($phpDocInfo->getVarType()); - if (! $expectedName instanceof ExpectedName) { + if (!$expectedName instanceof \Rector\Naming\ValueObject\ExpectedName) { return null; } - // skip if already has suffix $currentName = $this->nodeNameResolver->getName($property); if ($this->nodeNameResolver->endsWith($currentName, $expectedName->getName())) { return null; } - return $expectedName->getName(); } } diff --git a/rules/Naming/Guard/BreakingVariableRenameGuard.php b/rules/Naming/Guard/BreakingVariableRenameGuard.php index 573fe2261e7..294d0149416 100644 --- a/rules/Naming/Guard/BreakingVariableRenameGuard.php +++ b/rules/Naming/Guard/BreakingVariableRenameGuard.php @@ -1,11 +1,10 @@ betterNodeFinder = $betterNodeFinder; $this->conflictingNameResolver = $conflictingNameResolver; $this->overridenExistingNamesResolver = $overridenExistingNamesResolver; @@ -82,205 +67,157 @@ final class BreakingVariableRenameGuard $this->typeUnwrapper = $typeUnwrapper; $this->nodeNameResolver = $nodeNameResolver; } - /** * @param ClassMethod|Function_|Closure $functionLike */ - public function shouldSkipVariable( - string $currentName, - string $expectedName, - FunctionLike $functionLike, - Variable $variable - ): bool { + public function shouldSkipVariable(string $currentName, string $expectedName, \PhpParser\Node\FunctionLike $functionLike, \PhpParser\Node\Expr\Variable $variable) : bool + { // is the suffix? → also accepted - if (Strings::endsWith($currentName, ucfirst($expectedName))) { - return true; + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($currentName, \ucfirst($expectedName))) { + return \true; } - if ($this->conflictingNameResolver->checkNameIsInFunctionLike($expectedName, $functionLike)) { - return true; + return \true; } - if ($this->overridenExistingNamesResolver->checkNameInClassMethodForNew($currentName, $functionLike)) { - return true; + return \true; } - if ($this->isVariableAlreadyDefined($variable, $currentName)) { - return true; + return \true; } - if ($this->skipOnConflictOtherVariable($functionLike, $expectedName)) { - return true; + return \true; } - if ($this->isUsedInClosureUsesName($expectedName, $functionLike)) { - return true; + return \true; } - if ($this->isUsedInForeachKeyValueVar($variable, $currentName)) { - return true; + return \true; } - return $this->isUsedInIfAndOtherBranches($variable, $currentName); } - - public function shouldSkipParam( - string $currentName, - string $expectedName, - ClassMethod $classMethod, - Param $param - ): bool { + public function shouldSkipParam(string $currentName, string $expectedName, \PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Param $param) : bool + { // is the suffix? → also accepted - if (Strings::endsWith($currentName, ucfirst($expectedName))) { - return true; + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($currentName, \ucfirst($expectedName))) { + return \true; } - $conflictingNames = $this->conflictingNameResolver->resolveConflictingVariableNamesForParam($classMethod); - if (in_array($expectedName, $conflictingNames, true)) { - return true; + if (\in_array($expectedName, $conflictingNames, \true)) { + return \true; } - if ($this->conflictingNameResolver->checkNameIsInFunctionLike($expectedName, $classMethod)) { - return true; + return \true; } - if ($this->overridenExistingNamesResolver->checkNameInClassMethodForParam($expectedName, $classMethod)) { - return true; + return \true; } - if ($this->isVariableAlreadyDefined($param->var, $currentName)) { - return true; + return \true; } - if ($this->isRamseyUuidInterface($param)) { - return true; + return \true; } - if ($this->isDateTimeAtNamingConvention($param)) { - return true; + return \true; } - - return (bool) $this->betterNodeFinder->find((array) $classMethod->stmts, function (Node $node) use ( - $expectedName - ): bool { - if (! $node instanceof Variable) { - return false; + return (bool) $this->betterNodeFinder->find((array) $classMethod->stmts, function (\PhpParser\Node $node) use($expectedName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeNameResolver->isName($node, $expectedName); }); } - - private function isVariableAlreadyDefined(Variable $variable, string $currentVariableName): bool + private function isVariableAlreadyDefined(\PhpParser\Node\Expr\Variable $variable, string $currentVariableName) : bool { - $scope = $variable->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - $trinaryLogic = $scope->hasVariableType($currentVariableName); if ($trinaryLogic->yes()) { - return true; + return \true; } - return $trinaryLogic->maybe(); } - /** * @param ClassMethod|Function_|Closure $functionLike */ - private function skipOnConflictOtherVariable(FunctionLike $functionLike, string $newName): bool + private function skipOnConflictOtherVariable(\PhpParser\Node\FunctionLike $functionLike, string $newName) : bool { - return $this->betterNodeFinder->hasInstanceOfName((array) $functionLike->stmts, Variable::class, $newName); + return $this->betterNodeFinder->hasInstanceOfName((array) $functionLike->stmts, \PhpParser\Node\Expr\Variable::class, $newName); } - /** * @param ClassMethod|Function_|Closure $functionLike */ - private function isUsedInClosureUsesName(string $expectedName, FunctionLike $functionLike): bool + private function isUsedInClosureUsesName(string $expectedName, \PhpParser\Node\FunctionLike $functionLike) : bool { - if (! $functionLike instanceof Closure) { - return false; + if (!$functionLike instanceof \PhpParser\Node\Expr\Closure) { + return \false; } - return $this->betterNodeFinder->hasVariableOfName($functionLike->uses, $expectedName); } - - private function isUsedInForeachKeyValueVar(Variable $variable, string $currentName): bool + private function isUsedInForeachKeyValueVar(\PhpParser\Node\Expr\Variable $variable, string $currentName) : bool { - $previousForeach = $this->betterNodeFinder->findFirstPreviousOfTypes($variable, [Foreach_::class]); - if ($previousForeach instanceof Foreach_) { + $previousForeach = $this->betterNodeFinder->findFirstPreviousOfTypes($variable, [\PhpParser\Node\Stmt\Foreach_::class]); + if ($previousForeach instanceof \PhpParser\Node\Stmt\Foreach_) { if ($previousForeach->keyVar === $variable) { - return false; + return \false; } - if ($previousForeach->valueVar === $variable) { - return false; + return \false; } - if ($this->nodeNameResolver->isName($previousForeach->valueVar, $currentName)) { - return true; + return \true; } - if ($previousForeach->keyVar === null) { - return false; + return \false; } - if ($this->nodeNameResolver->isName($previousForeach->keyVar, $currentName)) { - return true; + return \true; } } - - return false; + return \false; } - - private function isUsedInIfAndOtherBranches(Variable $variable, string $currentVariableName): bool + private function isUsedInIfAndOtherBranches(\PhpParser\Node\Expr\Variable $variable, string $currentVariableName) : bool { // is in if branches? - $previousIf = $this->betterNodeFinder->findFirstPreviousOfTypes($variable, [If_::class]); - if ($previousIf instanceof If_) { + $previousIf = $this->betterNodeFinder->findFirstPreviousOfTypes($variable, [\PhpParser\Node\Stmt\If_::class]); + if ($previousIf instanceof \PhpParser\Node\Stmt\If_) { $variableUses = []; - $variableUses[] = $this->betterNodeFinder->findVariableOfName($previousIf->stmts, $currentVariableName); - $previousStmts = $previousIf->else !== null ? $previousIf->else->stmts : []; $variableUses[] = $this->betterNodeFinder->findVariableOfName($previousStmts, $currentVariableName); $variableUses[] = $this->betterNodeFinder->findVariableOfName($previousIf->elseifs, $currentVariableName); - - $variableUses = array_filter($variableUses); - if (count($variableUses) > 1) { - return true; + $variableUses = \array_filter($variableUses); + if (\count($variableUses) > 1) { + return \true; } } - - return false; + return \false; } - /** * @TODO Remove once ParamRenamer created */ - private function isRamseyUuidInterface(Param $param): bool + private function isRamseyUuidInterface(\PhpParser\Node\Param $param) : bool { - return $this->nodeTypeResolver->isObjectType($param, new ObjectType('Ramsey\Uuid\UuidInterface')); + return $this->nodeTypeResolver->isObjectType($param, new \PHPStan\Type\ObjectType('Ramsey\\Uuid\\UuidInterface')); } - /** * @TODO Remove once ParamRenamer created */ - private function isDateTimeAtNamingConvention(Param $param): bool + private function isDateTimeAtNamingConvention(\PhpParser\Node\Param $param) : bool { $type = $this->nodeTypeResolver->resolve($param); $type = $this->typeUnwrapper->unwrapFirstObjectTypeFromUnionType($type); - if (! $type instanceof TypeWithClassName) { - return false; + if (!$type instanceof \PHPStan\Type\TypeWithClassName) { + return \false; } - - if (! is_a($type->getClassName(), DateTimeInterface::class, true)) { - return false; + if (!\is_a($type->getClassName(), \DateTimeInterface::class, \true)) { + return \false; } - /** @var string $currentName */ $currentName = $this->nodeNameResolver->getName($param); - return (bool) Strings::match($currentName, self::AT_NAMING_REGEX . ''); + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($currentName, self::AT_NAMING_REGEX . ''); } } diff --git a/rules/Naming/Guard/DateTimeAtNamingConventionGuard.php b/rules/Naming/Guard/DateTimeAtNamingConventionGuard.php index 2f2f1be5a6c..859165404e7 100644 --- a/rules/Naming/Guard/DateTimeAtNamingConventionGuard.php +++ b/rules/Naming/Guard/DateTimeAtNamingConventionGuard.php @@ -1,63 +1,53 @@ nodeTypeResolver = $nodeTypeResolver; $this->typeUnwrapper = $typeUnwrapper; } - /** * @param PropertyRename $renameValueObject */ - public function isConflicting(RenameValueObjectInterface $renameValueObject): bool + public function isConflicting(\Rector\Naming\Contract\RenameValueObjectInterface $renameValueObject) : bool { return $this->isDateTimeAtNamingConvention($renameValueObject); } - - private function isDateTimeAtNamingConvention(PropertyRename $propertyRename): bool + private function isDateTimeAtNamingConvention(\Rector\Naming\ValueObject\PropertyRename $propertyRename) : bool { $type = $this->nodeTypeResolver->resolve($propertyRename->getProperty()); $type = $this->typeUnwrapper->unwrapFirstObjectTypeFromUnionType($type); - - if (! $type instanceof TypeWithClassName) { - return false; + if (!$type instanceof \PHPStan\Type\TypeWithClassName) { + return \false; } - - if (! is_a($type->getClassName(), DateTimeInterface::class, true)) { - return false; + if (!\is_a($type->getClassName(), \DateTimeInterface::class, \true)) { + return \false; } - - return (bool) Strings::match($propertyRename->getCurrentName(), self::AT_NAMING_REGEX . ''); + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($propertyRename->getCurrentName(), self::AT_NAMING_REGEX . ''); } } diff --git a/rules/Naming/Guard/HasMagicGetSetGuard.php b/rules/Naming/Guard/HasMagicGetSetGuard.php index f038432f8f2..d35503ddfed 100644 --- a/rules/Naming/Guard/HasMagicGetSetGuard.php +++ b/rules/Naming/Guard/HasMagicGetSetGuard.php @@ -1,40 +1,34 @@ reflectionProvider = $reflectionProvider; } - /** * @param PropertyRename $renameValueObject */ - public function isConflicting(RenameValueObjectInterface $renameValueObject): bool + public function isConflicting(\Rector\Naming\Contract\RenameValueObjectInterface $renameValueObject) : bool { - if (! $this->reflectionProvider->hasClass($renameValueObject->getClassLikeName())) { - return false; + if (!$this->reflectionProvider->hasClass($renameValueObject->getClassLikeName())) { + return \false; } - $classReflection = $this->reflectionProvider->getClass($renameValueObject->getClassLikeName()); if ($classReflection->hasMethod('__set')) { - return true; + return \true; } - return $classReflection->hasMethod('__get'); } } diff --git a/rules/Naming/Guard/NotPrivatePropertyGuard.php b/rules/Naming/Guard/NotPrivatePropertyGuard.php index 7420a6148ff..ed6cc74fde4 100644 --- a/rules/Naming/Guard/NotPrivatePropertyGuard.php +++ b/rules/Naming/Guard/NotPrivatePropertyGuard.php @@ -1,20 +1,18 @@ isPrivateProperty(); + return !$renameValueObject->isPrivateProperty(); } } diff --git a/rules/Naming/Guard/PropertyConflictingNameGuard/BoolPropertyConflictingNameGuard.php b/rules/Naming/Guard/PropertyConflictingNameGuard/BoolPropertyConflictingNameGuard.php index 817b9b24a56..0878c1d8c9e 100644 --- a/rules/Naming/Guard/PropertyConflictingNameGuard/BoolPropertyConflictingNameGuard.php +++ b/rules/Naming/Guard/PropertyConflictingNameGuard/BoolPropertyConflictingNameGuard.php @@ -1,7 +1,6 @@ boolPropertyExpectedNameResolver = $boolPropertyExpectedNameResolver; $this->nodeNameResolver = $nodeNameResolver; $this->arrayFilter = $arrayFilter; } - - public function isConflicting(PropertyRename $propertyRename): bool + public function isConflicting(\Rector\Naming\ValueObject\PropertyRename $propertyRename) : bool { $conflictingPropertyNames = $this->resolve($propertyRename->getClassLike()); - return in_array($propertyRename->getExpectedName(), $conflictingPropertyNames, true); + return \in_array($propertyRename->getExpectedName(), $conflictingPropertyNames, \true); } - /** * @return string[] */ - public function resolve(ClassLike $classLike): array + public function resolve(\PhpParser\Node\Stmt\ClassLike $classLike) : array { $expectedNames = []; foreach ($classLike->getProperties() as $property) { @@ -55,10 +45,8 @@ final class BoolPropertyConflictingNameGuard // fallback to existing name $expectedName = $this->nodeNameResolver->getName($property); } - $expectedNames[] = $expectedName; } - return $this->arrayFilter->filterWithAtLeastTwoOccurences($expectedNames); } } diff --git a/rules/Naming/Guard/PropertyConflictingNameGuard/MatchPropertyTypeConflictingNameGuard.php b/rules/Naming/Guard/PropertyConflictingNameGuard/MatchPropertyTypeConflictingNameGuard.php index 3d81461432c..d43e616ef33 100644 --- a/rules/Naming/Guard/PropertyConflictingNameGuard/MatchPropertyTypeConflictingNameGuard.php +++ b/rules/Naming/Guard/PropertyConflictingNameGuard/MatchPropertyTypeConflictingNameGuard.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->arrayFilter = $arrayFilter; $this->matchPropertyTypeExpectedNameResolver = $matchPropertyTypeExpectedNameResolver; } - /** * @param PropertyRename $renameValueObject */ - public function isConflicting(RenameValueObjectInterface $renameValueObject): bool + public function isConflicting(\Rector\Naming\Contract\RenameValueObjectInterface $renameValueObject) : bool { $conflictingPropertyNames = $this->resolve($renameValueObject->getClassLike()); - return in_array($renameValueObject->getExpectedName(), $conflictingPropertyNames, true); + return \in_array($renameValueObject->getExpectedName(), $conflictingPropertyNames, \true); } - /** * @return string[] */ - public function resolve(ClassLike $classLike): array + public function resolve(\PhpParser\Node\Stmt\ClassLike $classLike) : array { $expectedNames = []; foreach ($classLike->getProperties() as $property) { @@ -59,10 +49,8 @@ final class MatchPropertyTypeConflictingNameGuard // fallback to existing name $expectedName = $this->nodeNameResolver->getName($property); } - $expectedNames[] = $expectedName; } - return $this->arrayFilter->filterWithAtLeastTwoOccurences($expectedNames); } } diff --git a/rules/Naming/Guard/RamseyUuidInterfaceGuard.php b/rules/Naming/Guard/RamseyUuidInterfaceGuard.php index 30da9b16332..60e3b63762b 100644 --- a/rules/Naming/Guard/RamseyUuidInterfaceGuard.php +++ b/rules/Naming/Guard/RamseyUuidInterfaceGuard.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; } - /** * @param PropertyRename $renameValueObject */ - public function isConflicting(RenameValueObjectInterface $renameValueObject): bool + public function isConflicting(\Rector\Naming\Contract\RenameValueObjectInterface $renameValueObject) : bool { - return $this->nodeTypeResolver->isObjectType( - $renameValueObject->getProperty(), - new ObjectType('Ramsey\Uuid\UuidInterface') - ); + return $this->nodeTypeResolver->isObjectType($renameValueObject->getProperty(), new \PHPStan\Type\ObjectType('Ramsey\\Uuid\\UuidInterface')); } } diff --git a/rules/Naming/Matcher/CallMatcher.php b/rules/Naming/Matcher/CallMatcher.php index 06891879d23..ebdc6ce49ff 100644 --- a/rules/Naming/Matcher/CallMatcher.php +++ b/rules/Naming/Matcher/CallMatcher.php @@ -1,7 +1,6 @@ expr instanceof MethodCall) { + if ($node->expr instanceof \PhpParser\Node\Expr\MethodCall) { return $node->expr; } - - if ($node->expr instanceof StaticCall) { + if ($node->expr instanceof \PhpParser\Node\Expr\StaticCall) { return $node->expr; } - - if ($node->expr instanceof FuncCall) { + if ($node->expr instanceof \PhpParser\Node\Expr\FuncCall) { return $node->expr; } - return null; } } diff --git a/rules/Naming/Matcher/ForeachMatcher.php b/rules/Naming/Matcher/ForeachMatcher.php index 0bd01b2cc9d..48a44d0afde 100644 --- a/rules/Naming/Matcher/ForeachMatcher.php +++ b/rules/Naming/Matcher/ForeachMatcher.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->callMatcher = $callMatcher; $this->betterNodeFinder = $betterNodeFinder; } - - public function match(Foreach_ $foreach): ?VariableAndCallForeach + public function match(\PhpParser\Node\Stmt\Foreach_ $foreach) : ?\Rector\Naming\ValueObject\VariableAndCallForeach { $call = $this->callMatcher->matchCall($foreach); if ($call === null) { return null; } - - if (! $foreach->valueVar instanceof Variable) { + if (!$foreach->valueVar instanceof \PhpParser\Node\Expr\Variable) { return null; } - $functionLike = $this->getFunctionLike($foreach); if ($functionLike === null) { return null; } - $variableName = $this->nodeNameResolver->getName($foreach->valueVar); if ($variableName === null) { return null; } - - return new VariableAndCallForeach($foreach->valueVar, $call, $variableName, $functionLike); + return new \Rector\Naming\ValueObject\VariableAndCallForeach($foreach->valueVar, $call, $variableName, $functionLike); } - /** * @return ClassMethod|Function_|Closure|null */ - private function getFunctionLike(Foreach_ $foreach): ?Node + private function getFunctionLike(\PhpParser\Node\Stmt\Foreach_ $foreach) : ?\PhpParser\Node { - return $this->betterNodeFinder->findParentTypes( - $foreach, - [Closure::class, ClassMethod::class, Function_::class] - ); + return $this->betterNodeFinder->findParentTypes($foreach, [\PhpParser\Node\Expr\Closure::class, \PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class]); } } diff --git a/rules/Naming/Matcher/VariableAndCallAssignMatcher.php b/rules/Naming/Matcher/VariableAndCallAssignMatcher.php index 5e346a3ca28..bf84c50c331 100644 --- a/rules/Naming/Matcher/VariableAndCallAssignMatcher.php +++ b/rules/Naming/Matcher/VariableAndCallAssignMatcher.php @@ -1,7 +1,6 @@ callMatcher = $callMatcher; $this->nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; } - - public function match(Assign $assign): ?VariableAndCallAssign + public function match(\PhpParser\Node\Expr\Assign $assign) : ?\Rector\Naming\ValueObject\VariableAndCallAssign { $call = $this->callMatcher->matchCall($assign); if ($call === null) { return null; } - - if (! $assign->var instanceof Variable) { + if (!$assign->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - $variableName = $this->nodeNameResolver->getName($assign->var); if ($variableName === null) { return null; } - $functionLike = $this->getFunctionLike($assign); - if (! $functionLike instanceof FunctionLike) { + if (!$functionLike instanceof \PhpParser\Node\FunctionLike) { return null; } - - return new VariableAndCallAssign($assign->var, $call, $assign, $variableName, $functionLike); + return new \Rector\Naming\ValueObject\VariableAndCallAssign($assign->var, $call, $assign, $variableName, $functionLike); } - /** * @return ClassMethod|Function_|Closure|null */ - private function getFunctionLike(Assign $assign): ?Node + private function getFunctionLike(\PhpParser\Node\Expr\Assign $assign) : ?\PhpParser\Node { - return $this->betterNodeFinder->findParentTypes( - $assign, - [Closure::class, ClassMethod::class, Function_::class] - ); + return $this->betterNodeFinder->findParentTypes($assign, [\PhpParser\Node\Expr\Closure::class, \PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class]); } } diff --git a/rules/Naming/NamespaceMatcher.php b/rules/Naming/NamespaceMatcher.php index 57b7ad08054..d183a17fdf7 100644 --- a/rules/Naming/NamespaceMatcher.php +++ b/rules/Naming/NamespaceMatcher.php @@ -1,28 +1,24 @@ $newNamespace) { - if (Strings::startsWith($name, $oldNamespace)) { - return new RenamedNamespace($name, $oldNamespace, $newNamespace); + if (\RectorPrefix20210509\Nette\Utils\Strings::startsWith($name, $oldNamespace)) { + return new \Rector\Renaming\ValueObject\RenamedNamespace($name, $oldNamespace, $newNamespace); } } - return null; } } diff --git a/rules/Naming/Naming/ConflictingNameResolver.php b/rules/Naming/Naming/ConflictingNameResolver.php index f2906cedee4..c43f32423dc 100644 --- a/rules/Naming/Naming/ConflictingNameResolver.php +++ b/rules/Naming/Naming/ConflictingNameResolver.php @@ -1,7 +1,6 @@ expectedNameResolver = $expectedNameResolver; $this->nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; $this->arrayFilter = $arrayFilter; $this->matchParamTypeExpectedNameResolver = $matchParamTypeExpectedNameResolver; } - /** * @return string[] */ - public function resolveConflictingVariableNamesForParam(ClassMethod $classMethod): array + public function resolveConflictingVariableNamesForParam(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $expectedNames = []; foreach ($classMethod->params as $param) { @@ -71,104 +57,84 @@ final class ConflictingNameResolver if ($expectedName === null) { continue; } - $expectedNames[] = $expectedName; } - return $this->arrayFilter->filterWithAtLeastTwoOccurences($expectedNames); } - /** * @param ClassMethod|Function_|Closure $functionLike */ - public function checkNameIsInFunctionLike(string $variableName, FunctionLike $functionLike): bool + public function checkNameIsInFunctionLike(string $variableName, \PhpParser\Node\FunctionLike $functionLike) : bool { $conflictingVariableNames = $this->resolveConflictingVariableNamesForNew($functionLike); - return in_array($variableName, $conflictingVariableNames, true); + return \in_array($variableName, $conflictingVariableNames, \true); } - /** * @param ClassMethod|Function_|Closure $functionLike * @return string[] */ - private function resolveConflictingVariableNamesForNew(FunctionLike $functionLike): array + private function resolveConflictingVariableNamesForNew(\PhpParser\Node\FunctionLike $functionLike) : array { // cache it! - $classMethodHash = spl_object_hash($functionLike); - + $classMethodHash = \spl_object_hash($functionLike); if (isset($this->conflictingVariableNamesByClassMethod[$classMethodHash])) { return $this->conflictingVariableNamesByClassMethod[$classMethodHash]; } - $paramNames = $this->collectParamNames($functionLike); $newAssignNames = $this->resolveForNewAssigns($functionLike); $nonNewAssignNames = $this->resolveForNonNewAssigns($functionLike); - - $protectedNames = array_merge($paramNames, $newAssignNames, $nonNewAssignNames); - + $protectedNames = \array_merge($paramNames, $newAssignNames, $nonNewAssignNames); $protectedNames = $this->arrayFilter->filterWithAtLeastTwoOccurences($protectedNames); $this->conflictingVariableNamesByClassMethod[$classMethodHash] = $protectedNames; - return $protectedNames; } - /** * @param ClassMethod|Function_|Closure $functionLike * @return string[] */ - private function collectParamNames(FunctionLike $functionLike): array + private function collectParamNames(\PhpParser\Node\FunctionLike $functionLike) : array { $paramNames = []; - // params foreach ($functionLike->params as $param) { $paramNames[] = $this->nodeNameResolver->getName($param); } - return $paramNames; } - /** * @param ClassMethod|Function_|Closure $functionLike * @return string[] */ - private function resolveForNewAssigns(FunctionLike $functionLike): array + private function resolveForNewAssigns(\PhpParser\Node\FunctionLike $functionLike) : array { $names = []; - /** @var Assign[] $assigns */ - $assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, Assign::class); + $assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, \PhpParser\Node\Expr\Assign::class); foreach ($assigns as $assign) { $name = $this->expectedNameResolver->resolveForAssignNew($assign); if ($name === null) { continue; } - $names[] = $name; } - return $names; } - /** * @param ClassMethod|Function_|Closure $functionLike * @return string[] */ - private function resolveForNonNewAssigns(FunctionLike $functionLike): array + private function resolveForNonNewAssigns(\PhpParser\Node\FunctionLike $functionLike) : array { $names = []; - /** @var Assign[] $assigns */ - $assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, Assign::class); + $assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, \PhpParser\Node\Expr\Assign::class); foreach ($assigns as $assign) { $name = $this->expectedNameResolver->resolveForAssignNonNew($assign); if ($name === null) { continue; } - $names[] = $name; } - return $names; } } diff --git a/rules/Naming/Naming/ExpectedNameResolver.php b/rules/Naming/Naming/ExpectedNameResolver.php index 7ee0200e8f6..a3b7c0faa0f 100644 --- a/rules/Naming/Naming/ExpectedNameResolver.php +++ b/rules/Naming/Naming/ExpectedNameResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->propertyNaming = $propertyNaming; $this->nodeTypeResolver = $nodeTypeResolver; $this->matchParamTypeExpectedNameResolver = $matchParamTypeExpectedNameResolver; } - - public function resolveForParamIfNotYet(Param $param): ?string + public function resolveForParamIfNotYet(\PhpParser\Node\Param $param) : ?string { - if ($param->type instanceof UnionType) { + if ($param->type instanceof \PhpParser\Node\UnionType) { return null; } - $expectedName = $this->matchParamTypeExpectedNameResolver->resolve($param); if ($expectedName === null) { return null; } - /** @var string $currentName */ $currentName = $this->nodeNameResolver->getName($param->var); if ($currentName === $expectedName) { return null; } - if ($this->nodeNameResolver->endsWith($currentName, $expectedName)) { return null; } - return $expectedName; } - - public function resolveForAssignNonNew(Assign $assign): ?string + public function resolveForAssignNonNew(\PhpParser\Node\Expr\Assign $assign) : ?string { - if ($assign->expr instanceof New_) { + if ($assign->expr instanceof \PhpParser\Node\Expr\New_) { return null; } - - if (! $assign->var instanceof Variable) { + if (!$assign->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - /** @var Variable $variable */ $variable = $assign->var; - return $this->nodeNameResolver->getName($variable); } - - public function resolveForAssignNew(Assign $assign): ?string + public function resolveForAssignNew(\PhpParser\Node\Expr\Assign $assign) : ?string { - if (! $assign->expr instanceof New_) { + if (!$assign->expr instanceof \PhpParser\Node\Expr\New_) { return null; } - - if (! $assign->var instanceof Variable) { + if (!$assign->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - /** @var New_ $new */ $new = $assign->expr; - if (! $new->class instanceof Name) { + if (!$new->class instanceof \PhpParser\Node\Name) { return null; } - $className = $this->nodeNameResolver->getName($new->class); - $fullyQualifiedObjectType = new FullyQualifiedObjectType($className); - + $fullyQualifiedObjectType = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($className); $expectedName = $this->propertyNaming->getExpectedNameFromType($fullyQualifiedObjectType); - if (! $expectedName instanceof ExpectedName) { + if (!$expectedName instanceof \Rector\Naming\ValueObject\ExpectedName) { return null; } - return $expectedName->getName(); } - /** * @param MethodCall|StaticCall|FuncCall $expr */ - public function resolveForCall(Expr $expr): ?string + public function resolveForCall(\PhpParser\Node\Expr $expr) : ?string { if ($this->isDynamicNameCall($expr)) { return null; } - $name = $this->nodeNameResolver->getName($expr->name); if ($name === null) { return null; } - $returnedType = $this->nodeTypeResolver->getStaticType($expr); - - if ($returnedType instanceof ArrayType) { + if ($returnedType instanceof \PHPStan\Type\ArrayType) { return null; } - - if ($returnedType instanceof MixedType) { + if ($returnedType instanceof \PHPStan\Type\MixedType) { return null; } - $expectedName = $this->propertyNaming->getExpectedNameFromType($returnedType); - if ($expectedName !== null) { return $expectedName->getName(); } - // call with args can return different value, so skip there if not sure about the type if ($expr->args !== []) { return null; } - $expectedNameFromMethodName = $this->propertyNaming->getExpectedNameFromMethodName($name); if ($expectedNameFromMethodName !== null) { return $expectedNameFromMethodName->getName(); } - return null; } - /** * @param MethodCall|StaticCall|FuncCall $expr */ - public function resolveForForeach(Expr $expr): ?string + public function resolveForForeach(\PhpParser\Node\Expr $expr) : ?string { if ($this->isDynamicNameCall($expr)) { return null; } - $name = $this->nodeNameResolver->getName($expr->name); if ($name === null) { return null; } - $returnedType = $this->nodeTypeResolver->getStaticType($expr); if ($returnedType->isIterable()->no()) { return null; } - - if ($returnedType instanceof ArrayType) { + if ($returnedType instanceof \PHPStan\Type\ArrayType) { $returnedType = $this->resolveReturnTypeFromArrayType($expr, $returnedType); - if (! $returnedType instanceof Type) { + if (!$returnedType instanceof \PHPStan\Type\Type) { return null; } } - $expectedNameFromType = $this->propertyNaming->getExpectedNameFromType($returnedType); - if ($expectedNameFromType !== null) { return $expectedNameFromType->getSingularized(); } - $expectedNameFromMethodName = $this->propertyNaming->getExpectedNameFromMethodName($name); - if (! $expectedNameFromMethodName instanceof ExpectedName) { + if (!$expectedNameFromMethodName instanceof \Rector\Naming\ValueObject\ExpectedName) { return null; } - if ($expectedNameFromMethodName->isSingular()) { return null; } - return $expectedNameFromMethodName->getSingularized(); } - /** * @param MethodCall|StaticCall|FuncCall $expr */ - private function isDynamicNameCall(Expr $expr): bool + private function isDynamicNameCall(\PhpParser\Node\Expr $expr) : bool { - if ($expr->name instanceof StaticCall) { - return true; + if ($expr->name instanceof \PhpParser\Node\Expr\StaticCall) { + return \true; } - - if ($expr->name instanceof MethodCall) { - return true; + if ($expr->name instanceof \PhpParser\Node\Expr\MethodCall) { + return \true; } - - return $expr->name instanceof FuncCall; + return $expr->name instanceof \PhpParser\Node\Expr\FuncCall; } - - private function resolveReturnTypeFromArrayType(Expr $expr, ArrayType $arrayType): ?Type + private function resolveReturnTypeFromArrayType(\PhpParser\Node\Expr $expr, \PHPStan\Type\ArrayType $arrayType) : ?\PHPStan\Type\Type { - $parentNode = $expr->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Foreach_) { + $parentNode = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Stmt\Foreach_) { return null; } - - if (! $arrayType->getItemType() instanceof ObjectType) { + if (!$arrayType->getItemType() instanceof \PHPStan\Type\ObjectType) { return null; } - return $arrayType->getItemType(); } } diff --git a/rules/Naming/Naming/MethodNameResolver.php b/rules/Naming/Naming/MethodNameResolver.php index 1d1c37221d7..50196935a63 100644 --- a/rules/Naming/Naming/MethodNameResolver.php +++ b/rules/Naming/Naming/MethodNameResolver.php @@ -1,45 +1,37 @@ variableNaming = $variableNaming; } - - public function resolveGetterFromReturnedExpr(Expr $expr): ?string + public function resolveGetterFromReturnedExpr(\PhpParser\Node\Expr $expr) : ?string { $variableName = $this->variableNaming->resolveFromNode($expr); if ($variableName === null) { return null; } - - return 'get' . ucfirst($variableName); + return 'get' . \ucfirst($variableName); } - - public function resolveIsserFromReturnedExpr(Expr $expr): ?string + public function resolveIsserFromReturnedExpr(\PhpParser\Node\Expr $expr) : ?string { $variableName = $this->variableNaming->resolveFromNode($expr); if ($variableName === null) { return null; } - - if (Strings::match($variableName, '#^(is)#')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($variableName, '#^(is)#')) { return $variableName; } - - return 'is' . ucfirst($variableName); + return 'is' . \ucfirst($variableName); } } diff --git a/rules/Naming/Naming/OverridenExistingNamesResolver.php b/rules/Naming/Naming/OverridenExistingNamesResolver.php index 43ca8eb0a6b..3dc2fbd119c 100644 --- a/rules/Naming/Naming/OverridenExistingNamesResolver.php +++ b/rules/Naming/Naming/OverridenExistingNamesResolver.php @@ -1,7 +1,6 @@ > */ private $overridenExistingVariableNamesByClassMethod = []; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var BetterNodeFinder */ private $betterNodeFinder; - /** * @var ArrayFilter */ private $arrayFilter; - - public function __construct( - ArrayFilter $arrayFilter, - BetterNodeFinder $betterNodeFinder, - NodeNameResolver $nodeNameResolver - ) { + public function __construct(\Rector\Naming\PhpArray\ArrayFilter $arrayFilter, \Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder, \Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver) + { $this->nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; $this->arrayFilter = $arrayFilter; } - /** * @param ClassMethod|Function_|Closure $functionLike */ - public function checkNameInClassMethodForNew(string $variableName, FunctionLike $functionLike): bool + public function checkNameInClassMethodForNew(string $variableName, \PhpParser\Node\FunctionLike $functionLike) : bool { $overridenVariableNames = $this->resolveOveriddenNamesForNew($functionLike); - return in_array($variableName, $overridenVariableNames, true); + return \in_array($variableName, $overridenVariableNames, \true); } - - public function checkNameInClassMethodForParam(string $expectedName, ClassMethod $classMethod): bool + public function checkNameInClassMethodForParam(string $expectedName, \PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { /** @var Assign[] $assigns */ - $assigns = $this->betterNodeFinder->findInstanceOf((array) $classMethod->stmts, Assign::class); + $assigns = $this->betterNodeFinder->findInstanceOf((array) $classMethod->stmts, \PhpParser\Node\Expr\Assign::class); $usedVariableNames = []; foreach ($assigns as $assign) { - if (! $assign->var instanceof Variable) { + if (!$assign->var instanceof \PhpParser\Node\Expr\Variable) { continue; } - $variableName = $this->nodeNameResolver->getName($assign->var); if ($variableName === null) { continue; } - $usedVariableNames[] = $variableName; } - - return in_array($expectedName, $usedVariableNames, true); + return \in_array($expectedName, $usedVariableNames, \true); } - /** * @param ClassMethod|Function_|Closure $functionLike * @return string[] */ - private function resolveOveriddenNamesForNew(FunctionLike $functionLike): array + private function resolveOveriddenNamesForNew(\PhpParser\Node\FunctionLike $functionLike) : array { - $classMethodHash = spl_object_hash($functionLike); - + $classMethodHash = \spl_object_hash($functionLike); if (isset($this->overridenExistingVariableNamesByClassMethod[$classMethodHash])) { return $this->overridenExistingVariableNamesByClassMethod[$classMethodHash]; } - $currentlyUsedNames = []; - /** @var Assign[] $assigns */ - $assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, Assign::class); - + $assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, \PhpParser\Node\Expr\Assign::class); foreach ($assigns as $assign) { /** @var Variable $assignVariable */ $assignVariable = $assign->var; @@ -100,15 +81,11 @@ final class OverridenExistingNamesResolver if ($currentVariableName === null) { continue; } - $currentlyUsedNames[] = $currentVariableName; } - - $currentlyUsedNames = array_values($currentlyUsedNames); + $currentlyUsedNames = \array_values($currentlyUsedNames); $currentlyUsedNames = $this->arrayFilter->filterWithAtLeastTwoOccurences($currentlyUsedNames); - $this->overridenExistingVariableNamesByClassMethod[$classMethodHash] = $currentlyUsedNames; - return $currentlyUsedNames; } } diff --git a/rules/Naming/Naming/PropertyNaming.php b/rules/Naming/Naming/PropertyNaming.php index f74514aeece..dac65c024cb 100644 --- a/rules/Naming/Naming/PropertyNaming.php +++ b/rules/Naming/Naming/PropertyNaming.php @@ -1,10 +1,9 @@ [A-Z].+)#'; - /** * @var TypeUnwrapper */ private $typeUnwrapper; - /** * @var RectorNamingInflector */ private $rectorNamingInflector; - /** * @var BetterNodeFinder */ private $betterNodeFinder; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var NodeTypeResolver */ private $nodeTypeResolver; - /** * @var ReflectionProvider */ private $reflectionProvider; - - public function __construct( - TypeUnwrapper $typeUnwrapper, - RectorNamingInflector $rectorNamingInflector, - BetterNodeFinder $betterNodeFinder, - NodeNameResolver $nodeNameResolver, - NodeTypeResolver $nodeTypeResolver, - ReflectionProvider $reflectionProvider - ) { + public function __construct(\Rector\PHPStanStaticTypeMapper\Utils\TypeUnwrapper $typeUnwrapper, \Rector\Naming\RectorNamingInflector $rectorNamingInflector, \Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder, \Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver, \PHPStan\Reflection\ReflectionProvider $reflectionProvider) + { $this->typeUnwrapper = $typeUnwrapper; $this->rectorNamingInflector = $rectorNamingInflector; $this->betterNodeFinder = $betterNodeFinder; @@ -105,276 +86,220 @@ final class PropertyNaming $this->nodeTypeResolver = $nodeTypeResolver; $this->reflectionProvider = $reflectionProvider; } - - public function getExpectedNameFromMethodName(string $methodName): ?ExpectedName + public function getExpectedNameFromMethodName(string $methodName) : ?\Rector\Naming\ValueObject\ExpectedName { - $matches = Strings::match($methodName, self::GET_PREFIX_REGEX); + $matches = \RectorPrefix20210509\Nette\Utils\Strings::match($methodName, self::GET_PREFIX_REGEX); if ($matches === null) { return null; } - - $originalName = lcfirst($matches['root_name']); - - return new ExpectedName($originalName, $this->rectorNamingInflector->singularize($originalName)); + $originalName = \lcfirst($matches['root_name']); + return new \Rector\Naming\ValueObject\ExpectedName($originalName, $this->rectorNamingInflector->singularize($originalName)); } - - public function getExpectedNameFromType(Type $type): ?ExpectedName + public function getExpectedNameFromType(\PHPStan\Type\Type $type) : ?\Rector\Naming\ValueObject\ExpectedName { $type = $this->typeUnwrapper->unwrapNullableType($type); - if (! $type instanceof TypeWithClassName) { + if (!$type instanceof \PHPStan\Type\TypeWithClassName) { return null; } - - if ($type instanceof SelfObjectType) { + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\SelfObjectType) { return null; } - - if ($type instanceof StaticType) { + if ($type instanceof \PHPStan\Type\StaticType) { return null; } - $className = $this->nodeTypeResolver->getFullyQualifiedClassName($type); - foreach (self::EXCLUDED_CLASSES as $excludedClass) { - if (Strings::match($className, $excludedClass)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($className, $excludedClass)) { return null; } } - $shortClassName = $this->resolveShortClassName($className); $shortClassName = $this->removePrefixesAndSuffixes($shortClassName); - // if all is upper-cased, it should be lower-cased - if ($shortClassName === strtoupper($shortClassName)) { - $shortClassName = strtolower($shortClassName); + if ($shortClassName === \strtoupper($shortClassName)) { + $shortClassName = \strtolower($shortClassName); } - // remove "_" - $shortClassName = Strings::replace($shortClassName, '#_#', ''); + $shortClassName = \RectorPrefix20210509\Nette\Utils\Strings::replace($shortClassName, '#_#', ''); $shortClassName = $this->normalizeUpperCase($shortClassName); - // prolong too short generic names with one namespace up $originalName = $this->prolongIfTooShort($shortClassName, $className); - return new ExpectedName($originalName, $this->rectorNamingInflector->singularize($originalName)); + return new \Rector\Naming\ValueObject\ExpectedName($originalName, $this->rectorNamingInflector->singularize($originalName)); } - /** * @param ObjectType|string $objectType */ - public function fqnToVariableName($objectType): string + public function fqnToVariableName($objectType) : string { $className = $this->resolveClassName($objectType); - $shortName = $this->fqnToShortName($className); $shortName = $this->removeInterfaceSuffixPrefix($className, $shortName); - // prolong too short generic names with one namespace up return $this->prolongIfTooShort($shortName, $className); } - /** * @changelog https://stackoverflow.com/a/2792045/1348344 */ - public function underscoreToName(string $underscoreName): string + public function underscoreToName(string $underscoreName) : string { - $uppercaseWords = ucwords($underscoreName, '_'); - $pascalCaseName = str_replace('_', '', $uppercaseWords); - - return lcfirst($pascalCaseName); + $uppercaseWords = \ucwords($underscoreName, '_'); + $pascalCaseName = \str_replace('_', '', $uppercaseWords); + return \lcfirst($pascalCaseName); } - - public function getExpectedNameFromBooleanPropertyType(Property $property): ?string + public function getExpectedNameFromBooleanPropertyType(\PhpParser\Node\Stmt\Property $property) : ?string { $prefixedClassMethods = $this->getPrefixedClassMethods($property); if ($prefixedClassMethods === []) { return null; } - $classMethods = $this->filterClassMethodsWithPropertyFetchReturnOnly($prefixedClassMethods, $property); - if (count($classMethods) !== 1) { + if (\count($classMethods) !== 1) { return null; } - - $classMethod = reset($classMethods); + $classMethod = \reset($classMethods); return $this->nodeNameResolver->getName($classMethod); } - - private function resolveShortClassName(string $className): string + private function resolveShortClassName(string $className) : string { - if (Strings::contains($className, '\\')) { - return (string) Strings::after($className, '\\', -1); + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($className, '\\')) { + return (string) \RectorPrefix20210509\Nette\Utils\Strings::after($className, '\\', -1); } - return $className; } - - private function removePrefixesAndSuffixes(string $shortClassName): string + private function removePrefixesAndSuffixes(string $shortClassName) : string { // is SomeInterface - if (Strings::endsWith($shortClassName, self::INTERFACE)) { - $shortClassName = Strings::substring($shortClassName, 0, -strlen(self::INTERFACE)); + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($shortClassName, self::INTERFACE)) { + $shortClassName = \RectorPrefix20210509\Nette\Utils\Strings::substring($shortClassName, 0, -\strlen(self::INTERFACE)); } - // is ISomeClass if ($this->isPrefixedInterface($shortClassName)) { - $shortClassName = Strings::substring($shortClassName, 1); + $shortClassName = \RectorPrefix20210509\Nette\Utils\Strings::substring($shortClassName, 1); } - // is AbstractClass - if (Strings::startsWith($shortClassName, 'Abstract')) { - $shortClassName = Strings::substring($shortClassName, strlen('Abstract')); + if (\RectorPrefix20210509\Nette\Utils\Strings::startsWith($shortClassName, 'Abstract')) { + $shortClassName = \RectorPrefix20210509\Nette\Utils\Strings::substring($shortClassName, \strlen('Abstract')); } - return $shortClassName; } - - private function normalizeUpperCase(string $shortClassName): string + private function normalizeUpperCase(string $shortClassName) : string { // turns $SOMEUppercase => $someUppercase - for ($i = 0; $i <= strlen($shortClassName); ++$i) { - if (ctype_upper($shortClassName[$i]) && $this->isNumberOrUpper($shortClassName[$i + 1])) { - $shortClassName[$i] = strtolower($shortClassName[$i]); + for ($i = 0; $i <= \strlen($shortClassName); ++$i) { + if (\ctype_upper($shortClassName[$i]) && $this->isNumberOrUpper($shortClassName[$i + 1])) { + $shortClassName[$i] = \strtolower($shortClassName[$i]); } else { break; } } - return $shortClassName; } - - private function prolongIfTooShort(string $shortClassName, string $className): string + private function prolongIfTooShort(string $shortClassName, string $className) : string { - if (in_array($shortClassName, ['Factory', 'Repository'], true)) { - $namespaceAbove = (string) Strings::after($className, '\\', -2); - $namespaceAbove = (string) Strings::before($namespaceAbove, '\\'); - - return lcfirst($namespaceAbove) . $shortClassName; + if (\in_array($shortClassName, ['Factory', 'Repository'], \true)) { + $namespaceAbove = (string) \RectorPrefix20210509\Nette\Utils\Strings::after($className, '\\', -2); + $namespaceAbove = (string) \RectorPrefix20210509\Nette\Utils\Strings::before($namespaceAbove, '\\'); + return \lcfirst($namespaceAbove) . $shortClassName; } - - return lcfirst($shortClassName); + return \lcfirst($shortClassName); } - /** * @param ObjectType|string $objectType */ - private function resolveClassName($objectType): string + private function resolveClassName($objectType) : string { - if ($objectType instanceof ObjectType) { + if ($objectType instanceof \PHPStan\Type\ObjectType) { return $objectType->getClassName(); } - return $objectType; } - - private function fqnToShortName(string $fqn): string + private function fqnToShortName(string $fqn) : string { - if (! Strings::contains($fqn, '\\')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($fqn, '\\')) { return $fqn; } - /** @var string $lastNamePart */ - $lastNamePart = Strings::after($fqn, '\\', - 1); - if (Strings::endsWith($lastNamePart, self::INTERFACE)) { - return Strings::substring($lastNamePart, 0, - strlen(self::INTERFACE)); + $lastNamePart = \RectorPrefix20210509\Nette\Utils\Strings::after($fqn, '\\', -1); + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($lastNamePart, self::INTERFACE)) { + return \RectorPrefix20210509\Nette\Utils\Strings::substring($lastNamePart, 0, -\strlen(self::INTERFACE)); } - return $lastNamePart; } - - private function removeInterfaceSuffixPrefix(string $className, string $shortName): string + private function removeInterfaceSuffixPrefix(string $className, string $shortName) : string { // remove interface prefix/suffix - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return $shortName; } - // starts with "I\W+"? - if (Strings::match($shortName, self::I_PREFIX_REGEX)) { - return Strings::substring($shortName, 1); + if (\RectorPrefix20210509\Nette\Utils\Strings::match($shortName, self::I_PREFIX_REGEX)) { + return \RectorPrefix20210509\Nette\Utils\Strings::substring($shortName, 1); } - - if (Strings::endsWith($shortName, self::INTERFACE)) { - return Strings::substring($shortName, -strlen(self::INTERFACE)); + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($shortName, self::INTERFACE)) { + return \RectorPrefix20210509\Nette\Utils\Strings::substring($shortName, -\strlen(self::INTERFACE)); } - return $shortName; } - /** * @return ClassMethod[] */ - private function getPrefixedClassMethods(Property $property): array + private function getPrefixedClassMethods(\PhpParser\Node\Stmt\Property $property) : array { - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { return []; } - - $classMethods = $this->betterNodeFinder->findInstanceOf($classLike, ClassMethod::class); - return array_filter($classMethods, function (ClassMethod $classMethod): bool { + $classMethods = $this->betterNodeFinder->findInstanceOf($classLike, \PhpParser\Node\Stmt\ClassMethod::class); + return \array_filter($classMethods, function (\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { return $this->isBoolishMethodName($classMethod); }); } - /** * @param ClassMethod[] $prefixedClassMethods * @return ClassMethod[] */ - private function filterClassMethodsWithPropertyFetchReturnOnly( - array $prefixedClassMethods, - Property $property - ): array { + private function filterClassMethodsWithPropertyFetchReturnOnly(array $prefixedClassMethods, \PhpParser\Node\Stmt\Property $property) : array + { $classMethodName = $this->nodeNameResolver->getName($property); - - return array_filter($prefixedClassMethods, function (ClassMethod $classMethod) use ($classMethodName): bool { + return \array_filter($prefixedClassMethods, function (\PhpParser\Node\Stmt\ClassMethod $classMethod) use($classMethodName) : bool { return $this->doesClassMethodMatchReturnPropertyFetch($classMethod, $classMethodName); }); } - - private function isPrefixedInterface(string $shortClassName): bool + private function isPrefixedInterface(string $shortClassName) : bool { - if (strlen($shortClassName) <= 3) { - return false; + if (\strlen($shortClassName) <= 3) { + return \false; } - - if (! Strings::startsWith($shortClassName, 'I')) { - return false; + if (!\RectorPrefix20210509\Nette\Utils\Strings::startsWith($shortClassName, 'I')) { + return \false; } - if (! ctype_upper($shortClassName[1])) { - return false; + if (!\ctype_upper($shortClassName[1])) { + return \false; } - return ctype_lower($shortClassName[2]); + return \ctype_lower($shortClassName[2]); } - - private function isNumberOrUpper(string $char): bool + private function isNumberOrUpper(string $char) : bool { - if (ctype_upper($char)) { - return true; + if (\ctype_upper($char)) { + return \true; } - - return ctype_digit($char); + return \ctype_digit($char); } - - private function isBoolishMethodName(ClassMethod $classMethod): bool + private function isBoolishMethodName(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { $classMethodName = $this->nodeNameResolver->getName($classMethod); - return (bool) Strings::match($classMethodName, self::PREFIXED_CLASS_METHODS_REGEX); + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($classMethodName, self::PREFIXED_CLASS_METHODS_REGEX); } - - private function doesClassMethodMatchReturnPropertyFetch( - ClassMethod $classMethod, - string $currentClassMethodName - ): bool { + private function doesClassMethodMatchReturnPropertyFetch(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $currentClassMethodName) : bool + { $possibleReturn = $classMethod->stmts[0] ?? null; - if (! $possibleReturn instanceof Return_) { - return false; + if (!$possibleReturn instanceof \PhpParser\Node\Stmt\Return_) { + return \false; } - $node = $possibleReturn->expr; - if (! $node instanceof PropertyFetch) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - return $this->nodeNameResolver->isName($node->name, $currentClassMethodName); } } diff --git a/rules/Naming/Naming/VariableNaming.php b/rules/Naming/Naming/VariableNaming.php index 2eb0b7adcee..aefb53e446f 100644 --- a/rules/Naming/Naming/VariableNaming.php +++ b/rules/Naming/Naming/VariableNaming.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->valueResolver = $valueResolver; $this->nodeTypeResolver = $nodeTypeResolver; } - - public function resolveFromNode(Node $node): ?string + public function resolveFromNode(\PhpParser\Node $node) : ?string { $nodeType = $this->nodeTypeResolver->getStaticType($node); return $this->resolveFromNodeAndType($node, $nodeType); } - - public function resolveFromNodeAndType(Node $node, Type $type): ?string + public function resolveFromNodeAndType(\PhpParser\Node $node, \PHPStan\Type\Type $type) : ?string { $variableName = $this->resolveBareFromNode($node); if ($variableName === null) { return null; } - // adjust static to specific class - if ($variableName === 'this' && $type instanceof ThisType) { + if ($variableName === 'this' && $type instanceof \PHPStan\Type\ThisType) { $shortClassName = $this->nodeNameResolver->getShortName($type->getClassName()); - $variableName = lcfirst($shortClassName); + $variableName = \lcfirst($shortClassName); } - - $stringy = new Stringy($variableName); + $stringy = new \RectorPrefix20210509\Stringy\Stringy($variableName); return (string) $stringy->camelize(); } - - private function resolveBareFromNode(Node $node): ?string + private function resolveBareFromNode(\PhpParser\Node $node) : ?string { $node = $this->unwrapNode($node); - - if ($node instanceof ArrayDimFetch) { + if ($node instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return $this->resolveParamNameFromArrayDimFetch($node); } - - if ($node instanceof PropertyFetch) { + if ($node instanceof \PhpParser\Node\Expr\PropertyFetch) { return $this->resolveFromPropertyFetch($node); } - - if ($node !== null && ($node instanceof MethodCall || $node instanceof NullsafeMethodCall || $node instanceof StaticCall)) { + if ($node !== null && ($node instanceof \PhpParser\Node\Expr\MethodCall || $node instanceof \PhpParser\Node\Expr\NullsafeMethodCall || $node instanceof \PhpParser\Node\Expr\StaticCall)) { return $this->resolveFromMethodCall($node); } - - if ($node instanceof New_) { + if ($node instanceof \PhpParser\Node\Expr\New_) { return $this->resolveFromNew($node); } - - if ($node instanceof FuncCall) { + if ($node instanceof \PhpParser\Node\Expr\FuncCall) { return $this->resolveFromNode($node->name); } - - if (! $node instanceof Node) { - throw new NotImplementedYetException(); + if (!$node instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\NotImplementedYetException(); } - $paramName = $this->nodeNameResolver->getName($node); if ($paramName !== null) { return $paramName; } - - if ($node instanceof String_) { + if ($node instanceof \PhpParser\Node\Scalar\String_) { return $node->value; } - return null; } - - private function unwrapNode(Node $node): ?Node + private function unwrapNode(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof Arg) { + if ($node instanceof \PhpParser\Node\Arg) { return $node->value; } - - if ($node instanceof Cast) { + if ($node instanceof \PhpParser\Node\Expr\Cast) { return $node->expr; } - - if ($node instanceof Ternary) { + if ($node instanceof \PhpParser\Node\Expr\Ternary) { return $node->if; } - return $node; } - - private function resolveParamNameFromArrayDimFetch(ArrayDimFetch $arrayDimFetch): ?string + private function resolveParamNameFromArrayDimFetch(\PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : ?string { - while ($arrayDimFetch instanceof ArrayDimFetch) { - if ($arrayDimFetch->dim instanceof Scalar) { + while ($arrayDimFetch instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + if ($arrayDimFetch->dim instanceof \PhpParser\Node\Scalar) { $valueName = $this->nodeNameResolver->getName($arrayDimFetch->var); $dimName = $this->valueResolver->getValue($arrayDimFetch->dim); - - $stringy = new Stringy($dimName); + $stringy = new \RectorPrefix20210509\Stringy\Stringy($dimName); $dimName = (string) $stringy->upperCamelize(); - return $valueName . $dimName; } - $arrayDimFetch = $arrayDimFetch->var; } - return $this->resolveBareFromNode($arrayDimFetch); } - - private function resolveFromPropertyFetch(PropertyFetch $propertyFetch): string + private function resolveFromPropertyFetch(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : string { $varName = $this->nodeNameResolver->getName($propertyFetch->var); - if (! is_string($varName)) { - throw new NotImplementedYetException(); + if (!\is_string($varName)) { + throw new \Rector\Core\Exception\NotImplementedYetException(); } - $propertyName = $this->nodeNameResolver->getName($propertyFetch->name); - if (! is_string($propertyName)) { - throw new NotImplementedYetException(); + if (!\is_string($propertyName)) { + throw new \Rector\Core\Exception\NotImplementedYetException(); } - if ($varName === 'this') { return $propertyName; } - - return $varName . ucfirst($propertyName); + return $varName . \ucfirst($propertyName); } - /** * @param MethodCall|NullsafeMethodCall|StaticCall $node */ - private function resolveFromMethodCall(Node $node): ?string + private function resolveFromMethodCall(\PhpParser\Node $node) : ?string { - if ($node->name instanceof MethodCall) { + if ($node->name instanceof \PhpParser\Node\Expr\MethodCall) { return $this->resolveFromMethodCall($node->name); } - $methodName = $this->nodeNameResolver->getName($node->name); - if (! is_string($methodName)) { + if (!\is_string($methodName)) { return null; } - return $methodName; } - - private function resolveFromNew(New_ $new): string + private function resolveFromNew(\PhpParser\Node\Expr\New_ $new) : string { - if ($new->class instanceof Name) { + if ($new->class instanceof \PhpParser\Node\Name) { $className = $this->nodeNameResolver->getName($new->class); return $this->nodeNameResolver->getShortName($className); } - - throw new NotImplementedYetException(); + throw new \Rector\Core\Exception\NotImplementedYetException(); } } diff --git a/rules/Naming/NamingConvention/NamingConventionAnalyzer.php b/rules/Naming/NamingConvention/NamingConventionAnalyzer.php index c31ed0cdc47..c395cd955ca 100644 --- a/rules/Naming/NamingConvention/NamingConventionAnalyzer.php +++ b/rules/Naming/NamingConvention/NamingConventionAnalyzer.php @@ -1,28 +1,24 @@ nodeNameResolver = $nodeNameResolver; } - /** * Matches cases: * @@ -32,15 +28,14 @@ final class NamingConventionAnalyzer * * @param FuncCall|StaticCall|MethodCall $expr */ - public function isCallMatchingVariableName(Expr $expr, string $currentName, string $expectedName): bool + public function isCallMatchingVariableName(\PhpParser\Node\Expr $expr, string $currentName, string $expectedName) : bool { // skip "$call = $method->call();" based conventions $callName = $this->nodeNameResolver->getName($expr->name); if ($currentName === $callName) { - return true; + return \true; } - // starts with or ends with - return (bool) Strings::match($currentName, '#^(' . $expectedName . '|' . $expectedName . '$)#i'); + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($currentName, '#^(' . $expectedName . '|' . $expectedName . '$)#i'); } } diff --git a/rules/Naming/NodeRenamer/MethodCallRenamer.php b/rules/Naming/NodeRenamer/MethodCallRenamer.php index b6c0608a2a7..324ec81368b 100644 --- a/rules/Naming/NodeRenamer/MethodCallRenamer.php +++ b/rules/Naming/NodeRenamer/MethodCallRenamer.php @@ -1,33 +1,28 @@ nodeRepository = $nodeRepository; } - - public function updateClassMethodCalls(ClassMethod $classMethod, string $desiredMethodName): void + public function updateClassMethodCalls(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $desiredMethodName) : void { /** @var MethodCall[] $methodCalls */ $methodCalls = $this->nodeRepository->findCallsByClassMethod($classMethod); - foreach ($methodCalls as $methodCall) { - $methodCall->name = new Identifier($desiredMethodName); + $methodCall->name = new \PhpParser\Node\Identifier($desiredMethodName); } } } diff --git a/rules/Naming/ParamRenamer/ParamRenamer.php b/rules/Naming/ParamRenamer/ParamRenamer.php index 84c83a8592b..7086835a268 100644 --- a/rules/Naming/ParamRenamer/ParamRenamer.php +++ b/rules/Naming/ParamRenamer/ParamRenamer.php @@ -1,48 +1,33 @@ variableRenamer = $variableRenamer; $this->propertyDocBlockManipulator = $propertyDocBlockManipulator; } - - public function rename(ParamRename $paramRename): void + public function rename(\Rector\Naming\ValueObject\ParamRename $paramRename) : void { // 1. rename param - $paramRename->getVariable() - ->name = $paramRename->getExpectedName(); - + $paramRename->getVariable()->name = $paramRename->getExpectedName(); // 2. rename param in the rest of the method - $this->variableRenamer->renameVariableInFunctionLike( - $paramRename->getFunctionLike(), - null, - $paramRename->getCurrentName(), - $paramRename->getExpectedName() - ); - + $this->variableRenamer->renameVariableInFunctionLike($paramRename->getFunctionLike(), null, $paramRename->getCurrentName(), $paramRename->getExpectedName()); // 3. rename @param variable in docblock too $this->propertyDocBlockManipulator->renameParameterNameInDocBlock($paramRename); } diff --git a/rules/Naming/PhpArray/ArrayFilter.php b/rules/Naming/PhpArray/ArrayFilter.php index a7105e5bce0..48c5631df6c 100644 --- a/rules/Naming/PhpArray/ArrayFilter.php +++ b/rules/Naming/PhpArray/ArrayFilter.php @@ -1,7 +1,6 @@ $valueToCount */ - $valueToCount = array_count_values($values); - + $valueToCount = \array_count_values($values); $duplicatedValues = []; - foreach ($valueToCount as $value => $count) { /** @var int $count */ if ($count < 2) { continue; } - /** @var string $value */ $duplicatedValues[] = $value; } - return $duplicatedValues; } } diff --git a/rules/Naming/PhpDoc/VarTagValueNodeRenamer.php b/rules/Naming/PhpDoc/VarTagValueNodeRenamer.php index 6615964de26..804c5590608 100644 --- a/rules/Naming/PhpDoc/VarTagValueNodeRenamer.php +++ b/rules/Naming/PhpDoc/VarTagValueNodeRenamer.php @@ -1,32 +1,24 @@ getVarTagValueNode(); - if (! $varTagValueNode instanceof VarTagValueNode) { + if (!$varTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode) { return; } - if ($varTagValueNode->variableName !== '$' . $originalName) { return; } - $varTagValueNode->variableName = '$' . $expectedName; - // invoke node reprint - same as in php-parser - $varTagValueNode->setAttribute(PhpDocAttributeKey::ORIG_NODE, null); + $varTagValueNode->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::ORIG_NODE, null); } } diff --git a/rules/Naming/PropertyRenamer/BoolPropertyRenamer.php b/rules/Naming/PropertyRenamer/BoolPropertyRenamer.php index b0877bd947e..bfcf9f2ed9e 100644 --- a/rules/Naming/PropertyRenamer/BoolPropertyRenamer.php +++ b/rules/Naming/PropertyRenamer/BoolPropertyRenamer.php @@ -1,39 +1,31 @@ boolPropertyConflictingNameGuard = $boolPropertyConflictingNameGuard; $this->propertyRenamer = $propertyRenamer; } - - public function rename(PropertyRename $propertyRename): ?Property + public function rename(\Rector\Naming\ValueObject\PropertyRename $propertyRename) : ?\PhpParser\Node\Stmt\Property { if ($this->boolPropertyConflictingNameGuard->isConflicting($propertyRename)) { return null; } - return $this->propertyRenamer->rename($propertyRename); } } diff --git a/rules/Naming/PropertyRenamer/MatchTypePropertyRenamer.php b/rules/Naming/PropertyRenamer/MatchTypePropertyRenamer.php index 3d037abcc7b..57a5fa6bba0 100644 --- a/rules/Naming/PropertyRenamer/MatchTypePropertyRenamer.php +++ b/rules/Naming/PropertyRenamer/MatchTypePropertyRenamer.php @@ -1,39 +1,31 @@ matchPropertyTypeConflictingNameGuard = $matchPropertyTypeConflictingNameGuard; $this->propertyRenamer = $propertyRenamer; } - - public function rename(PropertyRename $propertyRename): ?Property + public function rename(\Rector\Naming\ValueObject\PropertyRename $propertyRename) : ?\PhpParser\Node\Stmt\Property { if ($this->matchPropertyTypeConflictingNameGuard->isConflicting($propertyRename)) { return null; } - return $this->propertyRenamer->rename($propertyRename); } } diff --git a/rules/Naming/PropertyRenamer/PropertyFetchRenamer.php b/rules/Naming/PropertyRenamer/PropertyFetchRenamer.php index 5602a059da2..f5a3f442bd1 100644 --- a/rules/Naming/PropertyRenamer/PropertyFetchRenamer.php +++ b/rules/Naming/PropertyRenamer/PropertyFetchRenamer.php @@ -1,7 +1,6 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeNameResolver = $nodeNameResolver; } - - public function renamePropertyFetchesInClass(ClassLike $classLike, string $currentName, string $expectedName): void + public function renamePropertyFetchesInClass(\PhpParser\Node\Stmt\ClassLike $classLike, string $currentName, string $expectedName) : void { // 1. replace property fetch rename in whole class - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - $classLike, - function (Node $node) use ($currentName, $expectedName): ?Node { - if ($node instanceof PropertyFetch && $this->nodeNameResolver->isLocalPropertyFetchNamed( - $node, - $currentName - )) { - $node->name = new Identifier($expectedName); - return $node; - } - - if (! $node instanceof StaticPropertyFetch) { - return null; - } - - if (! $this->nodeNameResolver->isName($node->name, $currentName)) { - return null; - } - - $node->name = new VarLikeIdentifier($expectedName); + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classLike, function (\PhpParser\Node $node) use($currentName, $expectedName) : ?Node { + if ($node instanceof \PhpParser\Node\Expr\PropertyFetch && $this->nodeNameResolver->isLocalPropertyFetchNamed($node, $currentName)) { + $node->name = new \PhpParser\Node\Identifier($expectedName); return $node; } - ); + if (!$node instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { + return null; + } + if (!$this->nodeNameResolver->isName($node->name, $currentName)) { + return null; + } + $node->name = new \PhpParser\Node\VarLikeIdentifier($expectedName); + return $node; + }); } } diff --git a/rules/Naming/PropertyRenamer/PropertyRenamer.php b/rules/Naming/PropertyRenamer/PropertyRenamer.php index 834ca436084..2cfedddbf4d 100644 --- a/rules/Naming/PropertyRenamer/PropertyRenamer.php +++ b/rules/Naming/PropertyRenamer/PropertyRenamer.php @@ -1,57 +1,42 @@ propertyRenameGuard = $propertyRenameGuard; $this->propertyFetchRenamer = $propertyFetchRenamer; } - - public function rename(PropertyRename $propertyRename): ?Property + public function rename(\Rector\Naming\ValueObject\PropertyRename $propertyRename) : ?\PhpParser\Node\Stmt\Property { if ($propertyRename->isAlreadyExpectedName()) { return null; } - if ($this->propertyRenameGuard->shouldSkip($propertyRename)) { return null; } - $onlyPropertyProperty = $propertyRename->getPropertyProperty(); - $onlyPropertyProperty->name = new VarLikeIdentifier($propertyRename->getExpectedName()); + $onlyPropertyProperty->name = new \PhpParser\Node\VarLikeIdentifier($propertyRename->getExpectedName()); $this->renamePropertyFetchesInClass($propertyRename); - return $propertyRename->getProperty(); } - - private function renamePropertyFetchesInClass(PropertyRename $propertyRename): void + private function renamePropertyFetchesInClass(\Rector\Naming\ValueObject\PropertyRename $propertyRename) : void { - $this->propertyFetchRenamer->renamePropertyFetchesInClass( - $propertyRename->getClassLike(), - $propertyRename->getCurrentName(), - $propertyRename->getExpectedName() - ); + $this->propertyFetchRenamer->renamePropertyFetchesInClass($propertyRename->getClassLike(), $propertyRename->getCurrentName(), $propertyRename->getExpectedName()); } } diff --git a/rules/Naming/Rector/Assign/RenameVariableToMatchMethodCallReturnTypeRector.php b/rules/Naming/Rector/Assign/RenameVariableToMatchMethodCallReturnTypeRector.php index 27723a1aa67..8eba98f921d 100644 --- a/rules/Naming/Rector/Assign/RenameVariableToMatchMethodCallReturnTypeRector.php +++ b/rules/Naming/Rector/Assign/RenameVariableToMatchMethodCallReturnTypeRector.php @@ -1,7 +1,6 @@ expectedNameResolver = $expectedNameResolver; $this->variableRenamer = $variableRenamer; $this->breakingVariableRenameGuard = $breakingVariableRenameGuard; @@ -98,12 +78,9 @@ final class RenameVariableToMatchMethodCallReturnTypeRector extends AbstractRect $this->reflectionProvider = $reflectionProvider; $this->familyRelationsAnalyzer = $familyRelationsAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Rename variable to match method return type', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Rename variable to match method return type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -117,8 +94,7 @@ public function getRunner(): Runner } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -132,33 +108,28 @@ public function getRunner(): Runner } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $variableAndCallAssign = $this->variableAndCallAssignMatcher->match($node); - if (! $variableAndCallAssign instanceof VariableAndCallAssign) { + if (!$variableAndCallAssign instanceof \Rector\Naming\ValueObject\VariableAndCallAssign) { return null; } - $call = $variableAndCallAssign->getCall(); if ($this->isMultipleCall($call)) { return null; } - $expectedName = $this->expectedNameResolver->resolveForCall($call); if ($expectedName === null) { return null; @@ -166,124 +137,77 @@ CODE_SAMPLE if ($this->isName($node->var, $expectedName)) { return null; } - if ($this->shouldSkip($variableAndCallAssign, $expectedName)) { return null; } - $this->renameVariable($variableAndCallAssign, $expectedName); - return $node; } - /** * @param FuncCall|StaticCall|MethodCall $callNode */ - private function isMultipleCall(Node $callNode): bool + private function isMultipleCall(\PhpParser\Node $callNode) : bool { - $parentNode = $callNode->getAttribute(AttributeKey::PARENT_NODE); - - $callNodeClass = get_class($callNode); - + $parentNode = $callNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + $callNodeClass = \get_class($callNode); while ($parentNode) { - $usedNodes = $this->betterNodeFinder->find($parentNode, function (Node $node) use ( - $callNodeClass, - $callNode - ): bool { - $nodeClass = get_class($node); + $usedNodes = $this->betterNodeFinder->find($parentNode, function (\PhpParser\Node $node) use($callNodeClass, $callNode) : bool { + $nodeClass = \get_class($node); if ($callNodeClass !== $nodeClass) { - return false; + return \false; } - /** @var FuncCall|StaticCall|MethodCall $node */ $passedNode = clone $node; - /** @var FuncCall|StaticCall|MethodCall $callNode */ $usedNode = clone $callNode; - /** @var FuncCall|StaticCall|MethodCall $passedNode */ $passedNode->args = []; - /** @var FuncCall|StaticCall|MethodCall $usedNode */ $usedNode->args = []; - return $this->nodeComparator->areNodesEqual($passedNode, $usedNode); }); - - if (count($usedNodes) > 1) { - return true; + if (\count($usedNodes) > 1) { + return \true; } - - $parentNode = $parentNode->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); } - - return false; + return \false; } - - private function shouldSkip(VariableAndCallAssign $variableAndCallAssign, string $expectedName): bool + private function shouldSkip(\Rector\Naming\ValueObject\VariableAndCallAssign $variableAndCallAssign, string $expectedName) : bool { - if ($this->namingConventionAnalyzer->isCallMatchingVariableName( - $variableAndCallAssign->getCall(), - $variableAndCallAssign->getVariableName(), - $expectedName - )) { - return true; + if ($this->namingConventionAnalyzer->isCallMatchingVariableName($variableAndCallAssign->getCall(), $variableAndCallAssign->getVariableName(), $expectedName)) { + return \true; } - if ($this->isClassTypeWithChildren($variableAndCallAssign->getCall())) { - return true; + return \true; } - - return $this->breakingVariableRenameGuard->shouldSkipVariable( - $variableAndCallAssign->getVariableName(), - $expectedName, - $variableAndCallAssign->getFunctionLike(), - $variableAndCallAssign->getVariable() - ); + return $this->breakingVariableRenameGuard->shouldSkipVariable($variableAndCallAssign->getVariableName(), $expectedName, $variableAndCallAssign->getFunctionLike(), $variableAndCallAssign->getVariable()); } - - private function renameVariable(VariableAndCallAssign $variableAndCallAssign, string $expectedName): void + private function renameVariable(\Rector\Naming\ValueObject\VariableAndCallAssign $variableAndCallAssign, string $expectedName) : void { $assign = $variableAndCallAssign->getAssign(); $assignPhpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($assign); - - $this->varTagValueNodeRenamer->renameAssignVarTagVariableName( - $assignPhpDocInfo, - $variableAndCallAssign->getVariableName(), - $expectedName - ); - - $this->variableRenamer->renameVariableInFunctionLike( - $variableAndCallAssign->getFunctionLike(), - $variableAndCallAssign->getAssign(), - $variableAndCallAssign->getVariableName(), - $expectedName - ); + $this->varTagValueNodeRenamer->renameAssignVarTagVariableName($assignPhpDocInfo, $variableAndCallAssign->getVariableName(), $expectedName); + $this->variableRenamer->renameVariableInFunctionLike($variableAndCallAssign->getFunctionLike(), $variableAndCallAssign->getAssign(), $variableAndCallAssign->getVariableName(), $expectedName); } - /** * @param StaticCall|MethodCall|FuncCall $expr */ - private function isClassTypeWithChildren(Expr $expr): bool + private function isClassTypeWithChildren(\PhpParser\Node\Expr $expr) : bool { $callStaticType = $this->getStaticType($expr); $callStaticType = $this->typeUnwrapper->unwrapNullableType($callStaticType); - - if (! $callStaticType instanceof ObjectType) { - return false; + if (!$callStaticType instanceof \PHPStan\Type\ObjectType) { + return \false; } - - if (is_a($callStaticType->getClassName(), ClassLike::class, true)) { - return false; + if (\is_a($callStaticType->getClassName(), \PhpParser\Node\Stmt\ClassLike::class, \true)) { + return \false; } - - if (! $this->reflectionProvider->hasClass($callStaticType->getClassName())) { - return false; + if (!$this->reflectionProvider->hasClass($callStaticType->getClassName())) { + return \false; } - $classReflection = $this->reflectionProvider->getClass($callStaticType->getClassName()); $childrenClassReflections = $this->familyRelationsAnalyzer->getChildrenOfClassReflection($classReflection); - return $childrenClassReflections !== []; } } diff --git a/rules/Naming/Rector/ClassMethod/MakeGetterClassMethodNameStartWithGetRector.php b/rules/Naming/Rector/ClassMethod/MakeGetterClassMethodNameStartWithGetRector.php index 7a2df74bb8f..226c5785f5e 100644 --- a/rules/Naming/Rector/ClassMethod/MakeGetterClassMethodNameStartWithGetRector.php +++ b/rules/Naming/Rector/ClassMethod/MakeGetterClassMethodNameStartWithGetRector.php @@ -1,7 +1,6 @@ methodNameResolver = $methodNameResolver; $this->methodCallRenamer = $methodCallRenamer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change getter method names to start with get/provide', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change getter method names to start with get/provide', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -63,9 +53,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -79,75 +67,60 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->isAlreadyGetterNamedClassMethod($node)) { return null; } - $getterClassMethodReturnedExpr = $this->matchGetterClassMethodReturnedExpr($node); - if (! $getterClassMethodReturnedExpr instanceof Expr) { + if (!$getterClassMethodReturnedExpr instanceof \PhpParser\Node\Expr) { return null; } - $getterMethodName = $this->methodNameResolver->resolveGetterFromReturnedExpr($getterClassMethodReturnedExpr); if ($getterMethodName === null) { return null; } - if ($this->isName($node->name, $getterMethodName)) { return null; } - $this->methodCallRenamer->updateClassMethodCalls($node, $getterMethodName); - $node->name = new Identifier($getterMethodName); - + $node->name = new \PhpParser\Node\Identifier($getterMethodName); return $node; } - - private function isAlreadyGetterNamedClassMethod(ClassMethod $classMethod): bool + private function isAlreadyGetterNamedClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { return $this->isName($classMethod, self::GETTER_NAME_PATTERN); } - - private function matchGetterClassMethodReturnedExpr(ClassMethod $classMethod): ?Expr + private function matchGetterClassMethodReturnedExpr(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PhpParser\Node\Expr { $stmts = (array) $classMethod->stmts; - if (count($stmts) !== 1) { + if (\count($stmts) !== 1) { return null; } - $onlyStmt = $stmts[0] ?? null; - if (! $onlyStmt instanceof Return_) { + if (!$onlyStmt instanceof \PhpParser\Node\Stmt\Return_) { return null; } - - if (! $onlyStmt->expr instanceof PropertyFetch) { + if (!$onlyStmt->expr instanceof \PhpParser\Node\Expr\PropertyFetch) { return null; } - $propertyStaticType = $this->getStaticType($onlyStmt->expr); // is handled by boolish Rector → skip here - if ($propertyStaticType instanceof BooleanType) { + if ($propertyStaticType instanceof \PHPStan\Type\BooleanType) { return null; } - return $onlyStmt->expr; } } diff --git a/rules/Naming/Rector/ClassMethod/MakeIsserClassMethodNameStartWithIsRector.php b/rules/Naming/Rector/ClassMethod/MakeIsserClassMethodNameStartWithIsRector.php index f8670be1765..bdd32dca0ff 100644 --- a/rules/Naming/Rector/ClassMethod/MakeIsserClassMethodNameStartWithIsRector.php +++ b/rules/Naming/Rector/ClassMethod/MakeIsserClassMethodNameStartWithIsRector.php @@ -1,7 +1,6 @@ methodNameResolver = $methodNameResolver; $this->methodCallRenamer = $methodCallRenamer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change is method names to start with is/has/was', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change is method names to start with is/has/was', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -64,9 +54,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -80,75 +68,59 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->isAlreadyIsserNamedClassMethod($node)) { return null; } - $getterClassMethodReturnedExpr = $this->matchIsserClassMethodReturnedExpr($node); - if (! $getterClassMethodReturnedExpr instanceof Expr) { + if (!$getterClassMethodReturnedExpr instanceof \PhpParser\Node\Expr) { return null; } - $isserMethodName = $this->methodNameResolver->resolveIsserFromReturnedExpr($getterClassMethodReturnedExpr); if ($isserMethodName === null) { return null; } - if ($this->isName($node->name, $isserMethodName)) { return null; } - - $node->name = new Identifier($isserMethodName); - + $node->name = new \PhpParser\Node\Identifier($isserMethodName); $this->methodCallRenamer->updateClassMethodCalls($node, $isserMethodName); - return $node; } - - private function isAlreadyIsserNamedClassMethod(ClassMethod $classMethod): bool + private function isAlreadyIsserNamedClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { return $this->isName($classMethod, self::ISSER_NAME_REGEX); } - - private function matchIsserClassMethodReturnedExpr(ClassMethod $classMethod): ?Expr + private function matchIsserClassMethodReturnedExpr(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PhpParser\Node\Expr { $stmts = (array) $classMethod->stmts; - if (count($stmts) !== 1) { + if (\count($stmts) !== 1) { return null; } - $onlyStmt = $stmts[0] ?? null; - if (! $onlyStmt instanceof Return_) { + if (!$onlyStmt instanceof \PhpParser\Node\Stmt\Return_) { return null; } - - if (! $onlyStmt->expr instanceof PropertyFetch) { + if (!$onlyStmt->expr instanceof \PhpParser\Node\Expr\PropertyFetch) { return null; } - $propertyStaticType = $this->getStaticType($onlyStmt->expr); - if (! $propertyStaticType instanceof BooleanType) { + if (!$propertyStaticType instanceof \PHPStan\Type\BooleanType) { return null; } - return $onlyStmt->expr; } } diff --git a/rules/Naming/Rector/ClassMethod/RenameParamToMatchTypeRector.php b/rules/Naming/Rector/ClassMethod/RenameParamToMatchTypeRector.php index b47e7ee4f75..b7c40b18950 100644 --- a/rules/Naming/Rector/ClassMethod/RenameParamToMatchTypeRector.php +++ b/rules/Naming/Rector/ClassMethod/RenameParamToMatchTypeRector.php @@ -1,7 +1,6 @@ expectedNameResolver = $expectedNameResolver; $this->breakingVariableRenameGuard = $breakingVariableRenameGuard; $this->paramRenameFactory = $paramRenameFactory; $this->paramRenamer = $paramRenamer; $this->matchParamTypeExpectedNameResolver = $matchParamTypeExpectedNameResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Rename variable to match new ClassType', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Rename variable to match new ClassType', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run(Apple $pie) @@ -80,8 +64,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run(Apple $apple) @@ -90,70 +73,56 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $this->hasChanged = false; - + $this->hasChanged = \false; foreach ($node->params as $param) { $expectedName = $this->expectedNameResolver->resolveForParamIfNotYet($param); if ($expectedName === null) { continue; } - if ($this->shouldSkipParam($param, $expectedName, $node)) { continue; } - $expectedName = $this->matchParamTypeExpectedNameResolver->resolve($param); if ($expectedName === null) { continue; } - $paramRename = $this->paramRenameFactory->createFromResolvedExpectedName($param, $expectedName); - if (! $paramRename instanceof ParamRename) { + if (!$paramRename instanceof \Rector\Naming\ValueObject\ParamRename) { continue; } - $this->paramRenamer->rename($paramRename); - $this->hasChanged = true; + $this->hasChanged = \true; } - - if (! $this->hasChanged) { + if (!$this->hasChanged) { return null; } - return $node; } - - private function shouldSkipParam(Param $param, string $expectedName, ClassMethod $classMethod): bool + private function shouldSkipParam(\PhpParser\Node\Param $param, string $expectedName, \PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { /** @var string $paramName */ $paramName = $this->getName($param); - if ($this->breakingVariableRenameGuard->shouldSkipParam($paramName, $expectedName, $classMethod, $param)) { - return true; + return \true; } - // promoted property - if (! $this->isName($classMethod, MethodName::CONSTRUCT)) { - return false; + if (!$this->isName($classMethod, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { + return \false; } - return $param->flags !== 0; } } diff --git a/rules/Naming/Rector/ClassMethod/RenameVariableToMatchNewTypeRector.php b/rules/Naming/Rector/ClassMethod/RenameVariableToMatchNewTypeRector.php index b06a3a2fd7f..58fcad681bb 100644 --- a/rules/Naming/Rector/ClassMethod/RenameVariableToMatchNewTypeRector.php +++ b/rules/Naming/Rector/ClassMethod/RenameVariableToMatchNewTypeRector.php @@ -1,7 +1,6 @@ expectedNameResolver = $expectedNameResolver; $this->breakingVariableRenameGuard = $breakingVariableRenameGuard; $this->variableRenamer = $variableRenamer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Rename variable to match new ClassType', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Rename variable to match new ClassType', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -60,8 +49,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -71,29 +59,24 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $hasChanged = false; - + $hasChanged = \false; $assignsOfNew = $this->getAssignsOfNew($node); foreach ($assignsOfNew as $assignOfNew) { $expectedName = $this->expectedNameResolver->resolveForAssignNew($assignOfNew); - /** @var Variable $variable */ $variable = $assignOfNew->var; if ($expectedName === null) { @@ -102,42 +85,33 @@ CODE_SAMPLE if ($this->isName($variable, $expectedName)) { continue; } - $currentName = $this->getName($variable); if ($currentName === null) { continue; } - if ($this->breakingVariableRenameGuard->shouldSkipVariable($currentName, $expectedName, $node, $variable)) { continue; } - - $hasChanged = true; - + $hasChanged = \true; // 1. rename assigned variable - $assignOfNew->var = new Variable($expectedName); - + $assignOfNew->var = new \PhpParser\Node\Expr\Variable($expectedName); // 2. rename variable in the $this->variableRenamer->renameVariableInFunctionLike($node, $assignOfNew, $currentName, $expectedName); } - - if (! $hasChanged) { + if (!$hasChanged) { return null; } - return $node; } - /** * @return Assign[] */ - private function getAssignsOfNew(ClassMethod $classMethod): array + private function getAssignsOfNew(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { /** @var Assign[] $assigns */ - $assigns = $this->betterNodeFinder->findInstanceOf((array) $classMethod->stmts, Assign::class); - - return array_filter($assigns, function (Assign $assign): bool { - return $assign->expr instanceof New_; + $assigns = $this->betterNodeFinder->findInstanceOf((array) $classMethod->stmts, \PhpParser\Node\Expr\Assign::class); + return \array_filter($assigns, function (\PhpParser\Node\Expr\Assign $assign) : bool { + return $assign->expr instanceof \PhpParser\Node\Expr\New_; }); } } diff --git a/rules/Naming/Rector/Class_/RenamePropertyToMatchTypeRector.php b/rules/Naming/Rector/Class_/RenamePropertyToMatchTypeRector.php index 1bde9378413..85010e4ea49 100644 --- a/rules/Naming/Rector/Class_/RenamePropertyToMatchTypeRector.php +++ b/rules/Naming/Rector/Class_/RenamePropertyToMatchTypeRector.php @@ -1,7 +1,6 @@ propertyRenameFactory = $propertyRenameFactory; $this->matchTypePropertyRenamer = $matchTypePropertyRenamer; $this->matchPropertyTypeExpectedNameResolver = $matchPropertyTypeExpectedNameResolver; $this->matchParamTypeExpectedNameResolver = $matchParamTypeExpectedNameResolver; $this->propertyFetchRenamer = $propertyFetchRenamer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Rename property and method param to match its type', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Rename property and method param to match its type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -91,8 +73,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -106,81 +87,65 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class, Interface_::class]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Stmt\Interface_::class]; } - /** * @param Class_|Interface_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $this->refactorClassProperties($node); $this->renamePropertyPromotion($node); - - if (! $this->hasChanged) { + if (!$this->hasChanged) { return null; } - return $node; } - - private function refactorClassProperties(ClassLike $classLike): void + private function refactorClassProperties(\PhpParser\Node\Stmt\ClassLike $classLike) : void { foreach ($classLike->getProperties() as $property) { $expectedPropertyName = $this->matchPropertyTypeExpectedNameResolver->resolve($property); if ($expectedPropertyName === null) { continue; } - $propertyRename = $this->propertyRenameFactory->createFromExpectedName($property, $expectedPropertyName); - if (! $propertyRename instanceof PropertyRename) { + if (!$propertyRename instanceof \Rector\Naming\ValueObject\PropertyRename) { continue; } - $renameProperty = $this->matchTypePropertyRenamer->rename($propertyRename); - if (! $renameProperty instanceof Property) { + if (!$renameProperty instanceof \PhpParser\Node\Stmt\Property) { continue; } - - $this->hasChanged = true; + $this->hasChanged = \true; } } - - private function renamePropertyPromotion(ClassLike $classLike): void + private function renamePropertyPromotion(\PhpParser\Node\Stmt\ClassLike $classLike) : void { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::PROPERTY_PROMOTION)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::PROPERTY_PROMOTION)) { return; } - - $constructClassMethod = $classLike->getMethod(MethodName::CONSTRUCT); - if (! $constructClassMethod instanceof ClassMethod) { + $constructClassMethod = $classLike->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - foreach ($constructClassMethod->params as $param) { if ($param->flags === 0) { continue; } - // promoted property $desiredPropertyName = $this->matchParamTypeExpectedNameResolver->resolve($param); if ($desiredPropertyName === null) { continue; } - $currentName = $this->getName($param); $this->propertyFetchRenamer->renamePropertyFetchesInClass($classLike, $currentName, $desiredPropertyName); - $param->var->name = $desiredPropertyName; } } diff --git a/rules/Naming/Rector/Foreach_/RenameForeachValueVariableToMatchExprVariableRector.php b/rules/Naming/Rector/Foreach_/RenameForeachValueVariableToMatchExprVariableRector.php index ecac4dd9345..9dba15f6451 100644 --- a/rules/Naming/Rector/Foreach_/RenameForeachValueVariableToMatchExprVariableRector.php +++ b/rules/Naming/Rector/Foreach_/RenameForeachValueVariableToMatchExprVariableRector.php @@ -1,7 +1,6 @@ inflectorSingularResolver = $inflectorSingularResolver; $this->foreachAnalyzer = $foreachAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Renames value variable name in foreach loop to match expression variable', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Renames value variable name in foreach loop to match expression variable', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -53,9 +46,7 @@ public function run() } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -67,45 +58,37 @@ public function run() } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Foreach_::class]; + return [\PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof Variable && ! $node->expr instanceof PropertyFetch) { + if (!$node->expr instanceof \PhpParser\Node\Expr\Variable && !$node->expr instanceof \PhpParser\Node\Expr\PropertyFetch) { return null; } - if ($this->isNotThisTypePropertyFetch($node->expr)) { return null; } - $exprName = $this->getName($node->expr); if ($exprName === null) { return null; } - - if ($node->keyVar instanceof Node) { + if ($node->keyVar instanceof \PhpParser\Node) { return null; } - $valueVarName = $this->getName($node->valueVar); if ($valueVarName === null) { return null; } - $singularValueVarName = $this->inflectorSingularResolver->resolve($exprName); if ($singularValueVarName === $exprName) { return null; @@ -113,41 +96,31 @@ CODE_SAMPLE if ($singularValueVarName === $valueVarName) { return null; } - if ($this->foreachAnalyzer->isValueVarUsed($node, $singularValueVarName)) { return null; } - return $this->processRename($node, $valueVarName, $singularValueVarName); } - - private function isNotThisTypePropertyFetch(Expr $expr): bool + private function isNotThisTypePropertyFetch(\PhpParser\Node\Expr $expr) : bool { - if ($expr instanceof PropertyFetch) { + if ($expr instanceof \PhpParser\Node\Expr\PropertyFetch) { $variableType = $this->getStaticType($expr->var); - return ! $variableType instanceof ThisType; + return !$variableType instanceof \PHPStan\Type\ThisType; } - - return false; + return \false; } - - private function processRename(Foreach_ $foreach, string $valueVarName, string $singularValueVarName): Foreach_ + private function processRename(\PhpParser\Node\Stmt\Foreach_ $foreach, string $valueVarName, string $singularValueVarName) : \PhpParser\Node\Stmt\Foreach_ { - $foreach->valueVar = new Variable($singularValueVarName); - $this->traverseNodesWithCallable($foreach->stmts, function (Node $node) use ( - $singularValueVarName, - $valueVarName - ): ?Variable { - if (! $node instanceof Variable) { + $foreach->valueVar = new \PhpParser\Node\Expr\Variable($singularValueVarName); + $this->traverseNodesWithCallable($foreach->stmts, function (\PhpParser\Node $node) use($singularValueVarName, $valueVarName) : ?Variable { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { return null; } - - if (! $this->isName($node, $valueVarName)) { + if (!$this->isName($node, $valueVarName)) { return null; } - return new Variable($singularValueVarName); + return new \PhpParser\Node\Expr\Variable($singularValueVarName); }); - return $foreach; } } diff --git a/rules/Naming/Rector/Foreach_/RenameForeachValueVariableToMatchMethodCallReturnTypeRector.php b/rules/Naming/Rector/Foreach_/RenameForeachValueVariableToMatchMethodCallReturnTypeRector.php index 023063a99c4..e491b4a4c39 100644 --- a/rules/Naming/Rector/Foreach_/RenameForeachValueVariableToMatchMethodCallReturnTypeRector.php +++ b/rules/Naming/Rector/Foreach_/RenameForeachValueVariableToMatchMethodCallReturnTypeRector.php @@ -1,7 +1,6 @@ expectedNameResolver = $expectedNameResolver; $this->variableRenamer = $variableRenamer; $this->breakingVariableRenameGuard = $breakingVariableRenameGuard; $this->namingConventionAnalyzer = $namingConventionAnalyzer; $this->varValueAndCallForeachMatcher = $foreachMatcher; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Renames value variable name in foreach loop to match method type', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Renames value variable name in foreach loop to match method type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -78,9 +61,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -92,29 +73,24 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Foreach_::class]; + return [\PhpParser\Node\Stmt\Foreach_::class]; } - /** * @param Foreach_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $variableAndCallForeach = $this->varValueAndCallForeachMatcher->match($node); - if (! $variableAndCallForeach instanceof VariableAndCallForeach) { + if (!$variableAndCallForeach instanceof \Rector\Naming\ValueObject\VariableAndCallForeach) { return null; } - $expectedName = $this->expectedNameResolver->resolveForForeach($variableAndCallForeach->getCall()); if ($expectedName === null) { return null; @@ -122,41 +98,21 @@ CODE_SAMPLE if ($this->isName($variableAndCallForeach->getVariable(), $expectedName)) { return null; } - if ($this->shouldSkip($variableAndCallForeach, $expectedName)) { return null; } - $this->renameVariable($variableAndCallForeach, $expectedName); - return $node; } - - private function shouldSkip(VariableAndCallForeach $variableAndCallForeach, string $expectedName): bool + private function shouldSkip(\Rector\Naming\ValueObject\VariableAndCallForeach $variableAndCallForeach, string $expectedName) : bool { - if ($this->namingConventionAnalyzer->isCallMatchingVariableName( - $variableAndCallForeach->getCall(), - $variableAndCallForeach->getVariableName(), - $expectedName - )) { - return true; + if ($this->namingConventionAnalyzer->isCallMatchingVariableName($variableAndCallForeach->getCall(), $variableAndCallForeach->getVariableName(), $expectedName)) { + return \true; } - - return $this->breakingVariableRenameGuard->shouldSkipVariable( - $variableAndCallForeach->getVariableName(), - $expectedName, - $variableAndCallForeach->getFunctionLike(), - $variableAndCallForeach->getVariable() - ); + return $this->breakingVariableRenameGuard->shouldSkipVariable($variableAndCallForeach->getVariableName(), $expectedName, $variableAndCallForeach->getFunctionLike(), $variableAndCallForeach->getVariable()); } - - private function renameVariable(VariableAndCallForeach $variableAndCallForeach, string $expectedName): void + private function renameVariable(\Rector\Naming\ValueObject\VariableAndCallForeach $variableAndCallForeach, string $expectedName) : void { - $this->variableRenamer->renameVariableInFunctionLike( - $variableAndCallForeach->getFunctionLike(), - null, - $variableAndCallForeach->getVariableName(), - $expectedName - ); + $this->variableRenamer->renameVariableInFunctionLike($variableAndCallForeach->getFunctionLike(), null, $variableAndCallForeach->getVariableName(), $expectedName); } } diff --git a/rules/Naming/Rector/Property/MakeBoolPropertyRespectIsHasWasMethodNamingRector.php b/rules/Naming/Rector/Property/MakeBoolPropertyRespectIsHasWasMethodNamingRector.php index 9da54594b3d..fb6e7c868ae 100644 --- a/rules/Naming/Rector/Property/MakeBoolPropertyRespectIsHasWasMethodNamingRector.php +++ b/rules/Naming/Rector/Property/MakeBoolPropertyRespectIsHasWasMethodNamingRector.php @@ -1,7 +1,6 @@ propertyRenameFactory = $propertyRenameFactory; $this->boolPropertyRenamer = $boolPropertyRenamer; $this->boolPropertyExpectedNameResolver = $boolPropertyExpectedNameResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Renames property to respect is/has/was method naming', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Renames property to respect is/has/was method naming', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private $full = false; @@ -60,8 +49,7 @@ public function isFull() } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { private $isFull = false; @@ -73,42 +61,35 @@ public function isFull() } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->nodeTypeResolver->isPropertyBoolean($node)) { + if (!$this->nodeTypeResolver->isPropertyBoolean($node)) { return null; } - $expectedBoolName = $this->boolPropertyExpectedNameResolver->resolve($node); if ($expectedBoolName === null) { return null; } - $propertyRename = $this->propertyRenameFactory->createFromExpectedName($node, $expectedBoolName); - if (! $propertyRename instanceof PropertyRename) { + if (!$propertyRename instanceof \Rector\Naming\ValueObject\PropertyRename) { return null; } - $property = $this->boolPropertyRenamer->rename($propertyRename); - if (! $property instanceof Property) { + if (!$property instanceof \PhpParser\Node\Stmt\Property) { return null; } - return $node; } } diff --git a/rules/Naming/RectorNamingInflector.php b/rules/Naming/RectorNamingInflector.php index 8be27ca38d2..f709c535914 100644 --- a/rules/Naming/RectorNamingInflector.php +++ b/rules/Naming/RectorNamingInflector.php @@ -1,12 +1,10 @@ .+)(?Data|Info)$#'; - /** * @var Inflector */ private $inflector; - - public function __construct(Inflector $inflector) + public function __construct(\RectorPrefix20210509\Doctrine\Inflector\Inflector $inflector) { $this->inflector = $inflector; } - - public function singularize(string $name): string + public function singularize(string $name) : string { - $matches = Strings::match($name, self::DATA_INFO_SUFFIX_REGEX); + $matches = \RectorPrefix20210509\Nette\Utils\Strings::match($name, self::DATA_INFO_SUFFIX_REGEX); if ($matches === null) { return $this->inflector->singularize($name); } - $singularized = $this->inflector->singularize($matches['prefix']); $uninflectable = $matches['suffix']; - return $singularized . $uninflectable; } } diff --git a/rules/Naming/RenameGuard/PropertyRenameGuard.php b/rules/Naming/RenameGuard/PropertyRenameGuard.php index 6b534780667..6bddd0cd6be 100644 --- a/rules/Naming/RenameGuard/PropertyRenameGuard.php +++ b/rules/Naming/RenameGuard/PropertyRenameGuard.php @@ -1,19 +1,16 @@ conflictingNameGuards = $conflictingNameGuards; } - - public function shouldSkip(RenameValueObjectInterface $renameValueObject): bool + public function shouldSkip(\Rector\Naming\Contract\RenameValueObjectInterface $renameValueObject) : bool { foreach ($this->conflictingNameGuards as $conflictingNameGuard) { if ($conflictingNameGuard->isConflicting($renameValueObject)) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/Naming/ValueObject/ExpectedName.php b/rules/Naming/ValueObject/ExpectedName.php index 911326629a4..d9b4ef1a532 100644 --- a/rules/Naming/ValueObject/ExpectedName.php +++ b/rules/Naming/ValueObject/ExpectedName.php @@ -1,7 +1,6 @@ name = $name; $this->singularized = $singularized; } - - public function getName(): string + public function getName() : string { return $this->name; } - - public function getSingularized(): string + public function getSingularized() : string { return $this->singularized; } - - public function isSingular(): bool + public function isSingular() : bool { return $this->name === $this->singularized; } diff --git a/rules/Naming/ValueObject/ParamRename.php b/rules/Naming/ValueObject/ParamRename.php index 400c18799d5..bff573db908 100644 --- a/rules/Naming/ValueObject/ParamRename.php +++ b/rules/Naming/ValueObject/ParamRename.php @@ -1,7 +1,6 @@ param = $param; $this->variable = $variable; $this->expectedName = $expectedName; $this->currentName = $currentName; $this->functionLike = $functionLike; } - - public function getCurrentName(): string + public function getCurrentName() : string { return $this->currentName; } - - public function getExpectedName(): string + public function getExpectedName() : string { return $this->expectedName; } - /** * @return ClassMethod|Function_|Closure */ - public function getFunctionLike(): FunctionLike + public function getFunctionLike() : \PhpParser\Node\FunctionLike { return $this->functionLike; } - - public function getParam(): Param + public function getParam() : \PhpParser\Node\Param { return $this->param; } - - public function getVariable(): Variable + public function getVariable() : \PhpParser\Node\Expr\Variable { return $this->variable; } diff --git a/rules/Naming/ValueObject/PropertyRename.php b/rules/Naming/ValueObject/PropertyRename.php index 393cf11aa0e..74d02a62cbe 100644 --- a/rules/Naming/ValueObject/PropertyRename.php +++ b/rules/Naming/ValueObject/PropertyRename.php @@ -1,54 +1,40 @@ property = $property; $this->expectedName = $expectedName; $this->currentName = $currentName; @@ -56,43 +42,35 @@ final class PropertyRename implements RenamePropertyValueObjectInterface $this->classLikeName = $classLikeName; $this->propertyProperty = $propertyProperty; } - - public function getProperty(): Property + public function getProperty() : \PhpParser\Node\Stmt\Property { return $this->property; } - - public function isPrivateProperty(): bool + public function isPrivateProperty() : bool { return $this->property->isPrivate(); } - - public function getExpectedName(): string + public function getExpectedName() : string { return $this->expectedName; } - - public function getCurrentName(): string + public function getCurrentName() : string { return $this->currentName; } - - public function isAlreadyExpectedName(): bool + public function isAlreadyExpectedName() : bool { return $this->currentName === $this->expectedName; } - - public function getClassLike(): ClassLike + public function getClassLike() : \PhpParser\Node\Stmt\ClassLike { return $this->classLike; } - - public function getClassLikeName(): string + public function getClassLikeName() : string { return $this->classLikeName; } - - public function getPropertyProperty(): PropertyProperty + public function getPropertyProperty() : \PhpParser\Node\Stmt\PropertyProperty { return $this->propertyProperty; } diff --git a/rules/Naming/ValueObject/VariableAndCallAssign.php b/rules/Naming/ValueObject/VariableAndCallAssign.php index 73e2f9ef194..910cb2f183a 100644 --- a/rules/Naming/ValueObject/VariableAndCallAssign.php +++ b/rules/Naming/ValueObject/VariableAndCallAssign.php @@ -1,7 +1,6 @@ variable = $variable; $this->call = $expr; $this->variableName = $variableName; $this->functionLike = $functionLike; $this->assign = $assign; } - - public function getVariable(): Variable + public function getVariable() : \PhpParser\Node\Expr\Variable { return $this->variable; } - /** * @return FuncCall|StaticCall|MethodCall */ - public function getCall(): Expr + public function getCall() : \PhpParser\Node\Expr { return $this->call; } - - public function getVariableName(): string + public function getVariableName() : string { return $this->variableName; } - /** * @return ClassMethod|Function_|Closure */ - public function getFunctionLike(): FunctionLike + public function getFunctionLike() : \PhpParser\Node\FunctionLike { return $this->functionLike; } - - public function getAssign(): Assign + public function getAssign() : \PhpParser\Node\Expr\Assign { return $this->assign; } diff --git a/rules/Naming/ValueObject/VariableAndCallForeach.php b/rules/Naming/ValueObject/VariableAndCallForeach.php index cd87cd8758b..6478a14f01f 100644 --- a/rules/Naming/ValueObject/VariableAndCallForeach.php +++ b/rules/Naming/ValueObject/VariableAndCallForeach.php @@ -1,7 +1,6 @@ variable = $variable; $this->call = $expr; $this->variableName = $variableName; $this->functionLike = $functionLike; } - - public function getVariable(): Variable + public function getVariable() : \PhpParser\Node\Expr\Variable { return $this->variable; } - /** * @return FuncCall|StaticCall|MethodCall */ - public function getCall(): Expr + public function getCall() : \PhpParser\Node\Expr { return $this->call; } - - public function getVariableName(): string + public function getVariableName() : string { return $this->variableName; } - /** * @return ClassMethod|Function_|Closure */ - public function getFunctionLike(): FunctionLike + public function getFunctionLike() : \PhpParser\Node\FunctionLike { return $this->functionLike; } diff --git a/rules/Naming/ValueObjectFactory/ParamRenameFactory.php b/rules/Naming/ValueObjectFactory/ParamRenameFactory.php index ff4fe77ee4e..321e84b1b0f 100644 --- a/rules/Naming/ValueObjectFactory/ParamRenameFactory.php +++ b/rules/Naming/ValueObjectFactory/ParamRenameFactory.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; } - - public function createFromResolvedExpectedName(Param $param, string $expectedName): ?ParamRename + public function createFromResolvedExpectedName(\PhpParser\Node\Param $param, string $expectedName) : ?\Rector\Naming\ValueObject\ParamRename { /** @var ClassMethod|Function_|Closure|ArrowFunction|null $functionLike */ - $functionLike = $this->betterNodeFinder->findParentType($param, FunctionLike::class); + $functionLike = $this->betterNodeFinder->findParentType($param, \PhpParser\Node\FunctionLike::class); if ($functionLike === null) { - throw new ShouldNotHappenException("There shouldn't be a param outside of FunctionLike"); + throw new \Rector\Core\Exception\ShouldNotHappenException("There shouldn't be a param outside of FunctionLike"); } - - if ($functionLike instanceof ArrowFunction) { + if ($functionLike instanceof \PhpParser\Node\Expr\ArrowFunction) { return null; } - $currentName = $this->nodeNameResolver->getName($param->var); if ($currentName === null) { return null; } - return new ParamRename($currentName, $expectedName, $param, $param->var, $functionLike); + return new \Rector\Naming\ValueObject\ParamRename($currentName, $expectedName, $param, $param->var, $functionLike); } } diff --git a/rules/Naming/ValueObjectFactory/PropertyRenameFactory.php b/rules/Naming/ValueObjectFactory/PropertyRenameFactory.php index 1bbb935365c..62f9d4b4f62 100644 --- a/rules/Naming/ValueObjectFactory/PropertyRenameFactory.php +++ b/rules/Naming/ValueObjectFactory/PropertyRenameFactory.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; } - - public function createFromExpectedName(Property $property, string $expectedName): ?PropertyRename + public function createFromExpectedName(\PhpParser\Node\Stmt\Property $property, string $expectedName) : ?\Rector\Naming\ValueObject\PropertyRename { $currentName = $this->nodeNameResolver->getName($property); - - $propertyClassLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $propertyClassLike instanceof ClassLike) { + $propertyClassLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$propertyClassLike instanceof \PhpParser\Node\Stmt\ClassLike) { return null; } - - $propertyClassLikeName = $property->getAttribute(AttributeKey::CLASS_NAME); + $propertyClassLikeName = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($propertyClassLikeName === null) { return null; } - - return new PropertyRename( - $property, - $expectedName, - $currentName, - $propertyClassLike, - $propertyClassLikeName, - $property->props[0] - ); + return new \Rector\Naming\ValueObject\PropertyRename($property, $expectedName, $currentName, $propertyClassLike, $propertyClassLikeName, $property->props[0]); } } diff --git a/rules/Naming/VariableRenamer.php b/rules/Naming/VariableRenamer.php index ab48beb050a..0ad2528bd19 100644 --- a/rules/Naming/VariableRenamer.php +++ b/rules/Naming/VariableRenamer.php @@ -1,7 +1,6 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeNameResolver = $nodeNameResolver; $this->varTagValueNodeRenamer = $varTagValueNodeRenamer; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->betterNodeFinder = $betterNodeFinder; } - /** * @param ClassMethod|Function_|Closure $functionLike */ - public function renameVariableInFunctionLike( - FunctionLike $functionLike, - ?Assign $assign = null, - string $oldName, - string $expectedName - ): void { - $isRenamingActive = false; - - if ($assign === null) { - $isRenamingActive = true; - } - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $functionLike->stmts, - function (Node $node) use ($oldName, $expectedName, $assign, &$isRenamingActive): ?Variable { - if ($assign !== null && $node === $assign) { - $isRenamingActive = true; - return null; - } - - if (! $node instanceof Variable) { - return null; - } - - // skip param names - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Param) { - return null; - } - - // TODO: Remove in next PR (with above param check?), - // TODO: Should be implemented in BreakingVariableRenameGuard::shouldSkipParam() - if ($this->isParamInParentFunction($node)) { - return null; - } - - if (! $isRenamingActive) { - return null; - } - - return $this->renameVariableIfMatchesName($node, $oldName, $expectedName); - } - ); - } - - private function isParamInParentFunction(Variable $variable): bool + public function renameVariableInFunctionLike(\PhpParser\Node\FunctionLike $functionLike, ?\PhpParser\Node\Expr\Assign $assign = null, string $oldName, string $expectedName) : void { - $closure = $this->betterNodeFinder->findParentType($variable, Closure::class); - if (! $closure instanceof Closure) { - return false; + $isRenamingActive = \false; + if ($assign === null) { + $isRenamingActive = \true; + } + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $functionLike->stmts, function (\PhpParser\Node $node) use($oldName, $expectedName, $assign, &$isRenamingActive) : ?Variable { + if ($assign !== null && $node === $assign) { + $isRenamingActive = \true; + return null; + } + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return null; + } + // skip param names + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Param) { + return null; + } + // TODO: Remove in next PR (with above param check?), + // TODO: Should be implemented in BreakingVariableRenameGuard::shouldSkipParam() + if ($this->isParamInParentFunction($node)) { + return null; + } + if (!$isRenamingActive) { + return null; + } + return $this->renameVariableIfMatchesName($node, $oldName, $expectedName); + }); + } + private function isParamInParentFunction(\PhpParser\Node\Expr\Variable $variable) : bool + { + $closure = $this->betterNodeFinder->findParentType($variable, \PhpParser\Node\Expr\Closure::class); + if (!$closure instanceof \PhpParser\Node\Expr\Closure) { + return \false; } - $variableName = $this->nodeNameResolver->getName($variable); if ($variableName === null) { - return false; + return \false; } - foreach ($closure->params as $param) { if ($this->nodeNameResolver->isName($param, $variableName)) { - return true; + return \true; } } - - return false; + return \false; } - - private function renameVariableIfMatchesName(Variable $variable, string $oldName, string $expectedName): ?Variable + private function renameVariableIfMatchesName(\PhpParser\Node\Expr\Variable $variable, string $oldName, string $expectedName) : ?\PhpParser\Node\Expr\Variable { - if (! $this->nodeNameResolver->isName($variable, $oldName)) { + if (!$this->nodeNameResolver->isName($variable, $oldName)) { return null; } - $variable->name = $expectedName; - $variablePhpDocInfo = $this->resolvePhpDocInfo($variable); $this->varTagValueNodeRenamer->renameAssignVarTagVariableName($variablePhpDocInfo, $oldName, $expectedName); - return $variable; } - /** * Expression doc block has higher priority */ - private function resolvePhpDocInfo(Variable $variable): PhpDocInfo + private function resolvePhpDocInfo(\PhpParser\Node\Expr\Variable $variable) : \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo { - $expression = $variable->getAttribute(AttributeKey::CURRENT_STATEMENT); - if ($expression instanceof Node) { + $expression = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); + if ($expression instanceof \PhpParser\Node) { return $this->phpDocInfoFactory->createFromNodeOrEmpty($expression); } - return $this->phpDocInfoFactory->createFromNodeOrEmpty($variable); } } diff --git a/rules/Order/Contract/RankeableInterface.php b/rules/Order/Contract/RankeableInterface.php index 194adf1b22f..695548fc202 100644 --- a/rules/Order/Contract/RankeableInterface.php +++ b/rules/Order/Contract/RankeableInterface.php @@ -1,15 +1,13 @@ $oldToNewKeys */ - public function hasOrderChanged(array $oldToNewKeys): bool + public function hasOrderChanged(array $oldToNewKeys) : bool { - $keys = array_keys($oldToNewKeys); - $values = array_values($oldToNewKeys); - + $keys = \array_keys($oldToNewKeys); + $values = \array_values($oldToNewKeys); return $keys !== $values; } } diff --git a/rules/Order/Rector/Class_/OrderClassConstantsByIntegerValueRector.php b/rules/Order/Rector/Class_/OrderClassConstantsByIntegerValueRector.php index 56ede2ea49e..816b22eaad4 100644 --- a/rules/Order/Rector/Class_/OrderClassConstantsByIntegerValueRector.php +++ b/rules/Order/Rector/Class_/OrderClassConstantsByIntegerValueRector.php @@ -1,7 +1,6 @@ orderChangeAnalyzer = $orderChangeAnalyzer; $this->stmtOrder = $stmtOrder; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Order class constant order by their integer value', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Order class constant order by their integer value', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { const MODE_ON = 0; @@ -51,8 +42,7 @@ class SomeClass const MODE_MAYBE = 1; } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { const MODE_ON = 0; @@ -62,84 +52,67 @@ class SomeClass const MODE_OFF = 2; } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $numericClassConstsByKey = $this->resolveClassConstByPosition($node); if ($numericClassConstsByKey === []) { return null; } - $classConstConstsByValue = $this->resolveClassConstConstByUniqueValue($numericClassConstsByKey); - $sortedClassConstConstsByValue = $classConstConstsByValue; - asort($sortedClassConstConstsByValue); - + \asort($sortedClassConstConstsByValue); $oldToNewKeys = $this->stmtOrder->createOldToNewKeys($sortedClassConstConstsByValue, $classConstConstsByValue); - if (! $this->orderChangeAnalyzer->hasOrderChanged($oldToNewKeys)) { + if (!$this->orderChangeAnalyzer->hasOrderChanged($oldToNewKeys)) { return null; } - $this->stmtOrder->reorderClassStmtsByOldToNewKeys($node, $oldToNewKeys); - return $node; } - /** * @return ClassConst[] */ - private function resolveClassConstByPosition(Class_ $class): array + private function resolveClassConstByPosition(\PhpParser\Node\Stmt\Class_ $class) : array { $classConstConstsByValue = []; foreach ($class->stmts as $key => $classStmt) { - if (! $classStmt instanceof ClassConst) { + if (!$classStmt instanceof \PhpParser\Node\Stmt\ClassConst) { continue; } - - if (count($classStmt->consts) !== 1) { + if (\count($classStmt->consts) !== 1) { continue; } - $classConstConst = $classStmt->consts[0]; - if (! $classConstConst->value instanceof LNumber) { + if (!$classConstConst->value instanceof \PhpParser\Node\Scalar\LNumber) { continue; } - $classConstConstsByValue[$key] = $classStmt; } - return $classConstConstsByValue; } - /** * @param array $numericClassConstsByKey * @return array */ - private function resolveClassConstConstByUniqueValue(array $numericClassConstsByKey): array + private function resolveClassConstConstByUniqueValue(array $numericClassConstsByKey) : array { $classConstConstsByValue = []; foreach ($numericClassConstsByKey as $position => $numericClassConst) { $constantValue = $this->valueResolver->getValue($numericClassConst->consts[0]->value); $classConstConstsByValue[$position] = $constantValue; } - - $arrayCountValue = array_count_values($classConstConstsByValue); - + $arrayCountValue = \array_count_values($classConstConstsByValue); // work only with unique constants foreach ($classConstConstsByValue as $position => $constantValue) { if ($arrayCountValue[$constantValue] > 1) { diff --git a/rules/Order/Rector/Class_/OrderConstantsByVisibilityRector.php b/rules/Order/Rector/Class_/OrderConstantsByVisibilityRector.php index 9df29d0b675..d045495f79f 100644 --- a/rules/Order/Rector/Class_/OrderConstantsByVisibilityRector.php +++ b/rules/Order/Rector/Class_/OrderConstantsByVisibilityRector.php @@ -1,7 +1,6 @@ orderChangeAnalyzer = $orderChangeAnalyzer; $this->stmtOrder = $stmtOrder; $this->stmtVisibilitySorter = $stmtVisibilitySorter; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Orders constants by visibility', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Orders constants by visibility', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { private const PRIVATE_CONST = 'private'; @@ -56,9 +45,7 @@ final class SomeClass public const PUBLIC_CONST = 'public'; } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public const PUBLIC_CONST = 'public'; @@ -66,32 +53,26 @@ final class SomeClass private const PRIVATE_CONST = 'private'; } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $currentClassConstsOrder = $this->stmtOrder->getStmtsOfTypeOrder($node, ClassConst::class); + $currentClassConstsOrder = $this->stmtOrder->getStmtsOfTypeOrder($node, \PhpParser\Node\Stmt\ClassConst::class); $classConstsInDesiredOrder = $this->stmtVisibilitySorter->sortConstants($node); - $oldToNewKeys = $this->stmtOrder->createOldToNewKeys($classConstsInDesiredOrder, $currentClassConstsOrder); - - if (! $this->orderChangeAnalyzer->hasOrderChanged($oldToNewKeys)) { + if (!$this->orderChangeAnalyzer->hasOrderChanged($oldToNewKeys)) { return null; } - $this->stmtOrder->reorderClassStmtsByOldToNewKeys($node, $oldToNewKeys); return $node; } diff --git a/rules/Order/Rector/Class_/OrderFirstLevelClassStatementsRector.php b/rules/Order/Rector/Class_/OrderFirstLevelClassStatementsRector.php index 2dcfb73de88..ba622146503 100644 --- a/rules/Order/Rector/Class_/OrderFirstLevelClassStatementsRector.php +++ b/rules/Order/Rector/Class_/OrderFirstLevelClassStatementsRector.php @@ -1,7 +1,6 @@ */ - private const TYPE_TO_RANK = [ - ClassMethod::class => 3, - Property::class => 2, - ClassConst::class => 1, - ]; - - public function getRuleDefinition(): RuleDefinition + private const TYPE_TO_RANK = [\PhpParser\Node\Stmt\ClassMethod::class => 3, \PhpParser\Node\Stmt\Property::class => 2, \PhpParser\Node\Stmt\ClassConst::class => 1]; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Orders first level Class statements', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Orders first level Class statements', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function functionName(); @@ -42,9 +33,7 @@ final class SomeClass use TraitName; } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { use TraitName; @@ -53,53 +42,41 @@ final class SomeClass public function functionName(); } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class, Trait_::class]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Stmt\Trait_::class]; } - /** * @param Class_|Trait_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $node->stmts = $this->getStmtsInDesiredPosition($node->stmts); - return $node; } - /** * @param Stmt[] $stmts * @return Stmt[] */ - private function getStmtsInDesiredPosition(array $stmts): array + private function getStmtsInDesiredPosition(array $stmts) : array { - uasort( - $stmts, - function (Stmt $firstStmt, Stmt $secondStmt): int { - return [$this->resolveClassElementRank($firstStmt), $firstStmt->getLine()] - <=> [$this->resolveClassElementRank($secondStmt), $secondStmt->getLine()]; - } - ); - + \uasort($stmts, function (\PhpParser\Node\Stmt $firstStmt, \PhpParser\Node\Stmt $secondStmt) : int { + return [$this->resolveClassElementRank($firstStmt), $firstStmt->getLine()] <=> [$this->resolveClassElementRank($secondStmt), $secondStmt->getLine()]; + }); return $stmts; } - - private function resolveClassElementRank(Stmt $stmt): int + private function resolveClassElementRank(\PhpParser\Node\Stmt $stmt) : int { foreach (self::TYPE_TO_RANK as $type => $rank) { - if (is_a($stmt, $type, true)) { + if (\is_a($stmt, $type, \true)) { return $rank; } } - // TraitUse return 0; } diff --git a/rules/Order/Rector/Class_/OrderMethodsByVisibilityRector.php b/rules/Order/Rector/Class_/OrderMethodsByVisibilityRector.php index 80fecce7dc5..f00662aa708 100644 --- a/rules/Order/Rector/Class_/OrderMethodsByVisibilityRector.php +++ b/rules/Order/Rector/Class_/OrderMethodsByVisibilityRector.php @@ -1,7 +1,6 @@ orderChangeAnalyzer = $orderChangeAnalyzer; $this->stmtOrder = $stmtOrder; $this->stmtVisibilitySorter = $stmtVisibilitySorter; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Orders method by visibility', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Orders method by visibility', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { protected function protectedFunctionName(); @@ -85,9 +52,7 @@ class SomeClass public function publicFunctionName(); } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function publicFunctionName(); @@ -95,53 +60,45 @@ class SomeClass private function privateFunctionName(); } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class, Trait_::class]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Stmt\Trait_::class]; } - /** * @param Class_|Trait_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $currentMethodsOrder = $this->stmtOrder->getStmtsOfTypeOrder($node, ClassMethod::class); + $currentMethodsOrder = $this->stmtOrder->getStmtsOfTypeOrder($node, \PhpParser\Node\Stmt\ClassMethod::class); $methodsInDesiredOrder = $this->getMethodsInDesiredOrder($node); - $oldToNewKeys = $this->stmtOrder->createOldToNewKeys($methodsInDesiredOrder, $currentMethodsOrder); - // nothing to re-order - if (! $this->orderChangeAnalyzer->hasOrderChanged($oldToNewKeys)) { + if (!$this->orderChangeAnalyzer->hasOrderChanged($oldToNewKeys)) { return null; } - $this->stmtOrder->reorderClassStmtsByOldToNewKeys($node, $oldToNewKeys); return $node; } - /** * @return string[] */ - private function getMethodsInDesiredOrder(ClassLike $classLike): array + private function getMethodsInDesiredOrder(\PhpParser\Node\Stmt\ClassLike $classLike) : array { $classMethodNames = $this->stmtVisibilitySorter->sortMethods($classLike); return $this->applyPreferredPosition($classMethodNames); } - /** * @param string[] $classMethods * @return string[] */ - private function applyPreferredPosition(array $classMethods): array + private function applyPreferredPosition(array $classMethods) : array { - $mergedMethods = array_merge(self::PREFERRED_ORDER, $classMethods); - return array_unique($mergedMethods); + $mergedMethods = \array_merge(self::PREFERRED_ORDER, $classMethods); + return \array_unique($mergedMethods); } } diff --git a/rules/Order/Rector/Class_/OrderPrivateMethodsByUseRector.php b/rules/Order/Rector/Class_/OrderPrivateMethodsByUseRector.php index c5442ab7955..e73c6faca57 100644 --- a/rules/Order/Rector/Class_/OrderPrivateMethodsByUseRector.php +++ b/rules/Order/Rector/Class_/OrderPrivateMethodsByUseRector.php @@ -1,7 +1,6 @@ stmtOrder = $stmtOrder; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Order private methods in order of their use', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Order private methods in order of their use', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -61,8 +52,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -80,127 +70,93 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class, Trait_::class]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Stmt\Trait_::class]; } - /** * @param Class_|Trait_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $sortedAndOriginalClassMethods = $this->getSortedAndOriginalClassMethods($node); - // order is correct, nothing to change - if (! $sortedAndOriginalClassMethods->hasOrderChanged()) { + if (!$sortedAndOriginalClassMethods->hasOrderChanged()) { return null; } - // different private method count, one of them is dead probably $attempt = 0; - while (! $sortedAndOriginalClassMethods->hasOrderSame()) { + while (!$sortedAndOriginalClassMethods->hasOrderSame()) { ++$attempt; if ($attempt >= self::MAX_ATTEMPTS) { break; } - - $oldToNewKeys = $this->stmtOrder->createOldToNewKeys( - $sortedAndOriginalClassMethods->getSortedClassMethods(), - $sortedAndOriginalClassMethods->getOriginalClassMethods() - ); - + $oldToNewKeys = $this->stmtOrder->createOldToNewKeys($sortedAndOriginalClassMethods->getSortedClassMethods(), $sortedAndOriginalClassMethods->getOriginalClassMethods()); $this->stmtOrder->reorderClassStmtsByOldToNewKeys($node, $oldToNewKeys); $sortedAndOriginalClassMethods = $this->getSortedAndOriginalClassMethods($node); } - return $node; } - /** * @param Class_|Trait_ $classLike */ - private function getSortedAndOriginalClassMethods( - ClassLike $classLike - ): SortedClassMethodsAndOriginalClassMethods { - return new SortedClassMethodsAndOriginalClassMethods( - $this->getLocalPrivateMethodCallOrder($classLike), - $this->resolvePrivateClassMethods($classLike) - ); + private function getSortedAndOriginalClassMethods(\PhpParser\Node\Stmt\ClassLike $classLike) : \Rector\Order\ValueObject\SortedClassMethodsAndOriginalClassMethods + { + return new \Rector\Order\ValueObject\SortedClassMethodsAndOriginalClassMethods($this->getLocalPrivateMethodCallOrder($classLike), $this->resolvePrivateClassMethods($classLike)); } - /** * @return array */ - private function getLocalPrivateMethodCallOrder(ClassLike $classLike): array + private function getLocalPrivateMethodCallOrder(\PhpParser\Node\Stmt\ClassLike $classLike) : array { $localPrivateMethodCallInOrder = []; - - $this->traverseNodesWithCallable($classLike->getMethods(), function (Node $node) use ( - &$localPrivateMethodCallInOrder, - $classLike - ) { - if (! $node instanceof MethodCall) { + $this->traverseNodesWithCallable($classLike->getMethods(), function (\PhpParser\Node $node) use(&$localPrivateMethodCallInOrder, $classLike) { + if (!$node instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - - if (! $node->var instanceof Variable) { + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - - if (! $this->nodeNameResolver->isName($node->var, 'this')) { + if (!$this->nodeNameResolver->isName($node->var, 'this')) { return null; } - $methodName = $this->getName($node->name); if ($methodName === null) { return null; } - $classMethod = $classLike->getMethod($methodName); - if (! $classMethod instanceof ClassMethod) { + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - if ($classMethod->isPrivate()) { $localPrivateMethodCallInOrder[] = $methodName; } - return null; }); - - return array_unique($localPrivateMethodCallInOrder); + return \array_unique($localPrivateMethodCallInOrder); } - /** * @return array */ - private function resolvePrivateClassMethods(ClassLike $classLike): array + private function resolvePrivateClassMethods(\PhpParser\Node\Stmt\ClassLike $classLike) : array { $privateClassMethods = []; - foreach ($classLike->stmts as $key => $classStmt) { - if (! $classStmt instanceof ClassMethod) { + if (!$classStmt instanceof \PhpParser\Node\Stmt\ClassMethod) { continue; } - - if (! $classStmt->isPrivate()) { + if (!$classStmt->isPrivate()) { continue; } - /** @var string $classMethodName */ $classMethodName = $this->getName($classStmt); $privateClassMethods[$key] = $classMethodName; } - return $privateClassMethods; } } diff --git a/rules/Order/Rector/Class_/OrderPropertiesByVisibilityRector.php b/rules/Order/Rector/Class_/OrderPropertiesByVisibilityRector.php index 5ac7c66b261..ab8dcf61913 100644 --- a/rules/Order/Rector/Class_/OrderPropertiesByVisibilityRector.php +++ b/rules/Order/Rector/Class_/OrderPropertiesByVisibilityRector.php @@ -1,7 +1,6 @@ orderChangeAnalyzer = $orderChangeAnalyzer; $this->stmtOrder = $stmtOrder; $this->stmtVisibilitySorter = $stmtVisibilitySorter; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Orders properties by visibility', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Orders properties by visibility', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { protected $protectedProperty; @@ -57,9 +46,7 @@ final class SomeClass public $publicProperty; } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public $publicProperty; @@ -67,33 +54,27 @@ final class SomeClass private $privateProperty; } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class, Trait_::class]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Stmt\Trait_::class]; } - /** * @param Class_|Trait_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $currentPropertiesOrder = $this->stmtOrder->getStmtsOfTypeOrder($node, Property::class); + $currentPropertiesOrder = $this->stmtOrder->getStmtsOfTypeOrder($node, \PhpParser\Node\Stmt\Property::class); $propertiesInDesiredOrder = $this->stmtVisibilitySorter->sortProperties($node); - $oldToNewKeys = $this->stmtOrder->createOldToNewKeys($propertiesInDesiredOrder, $currentPropertiesOrder); - // nothing to re-order - if (! $this->orderChangeAnalyzer->hasOrderChanged($oldToNewKeys)) { + if (!$this->orderChangeAnalyzer->hasOrderChanged($oldToNewKeys)) { return null; } - $this->stmtOrder->reorderClassStmtsByOldToNewKeys($node, $oldToNewKeys); return $node; } diff --git a/rules/Order/StmtOrder.php b/rules/Order/StmtOrder.php index 4c63aa6032f..ac93f9b404d 100644 --- a/rules/Order/StmtOrder.php +++ b/rules/Order/StmtOrder.php @@ -1,13 +1,11 @@ nodeNameResolver = $nodeNameResolver; } - /** * @param array $desiredStmtOrder * @param array $currentStmtOrder * @return array */ - public function createOldToNewKeys(array $desiredStmtOrder, array $currentStmtOrder): array + public function createOldToNewKeys(array $desiredStmtOrder, array $currentStmtOrder) : array { $newKeys = []; foreach ($desiredStmtOrder as $singleDesiredStmtOrder) { @@ -38,66 +34,52 @@ final class StmtOrder } } } - - $oldKeys = array_values($newKeys); - sort($oldKeys); - + $oldKeys = \array_values($newKeys); + \sort($oldKeys); /** @var array $oldToNewKeys */ - $oldToNewKeys = array_combine($oldKeys, $newKeys); - + $oldToNewKeys = \array_combine($oldKeys, $newKeys); return $oldToNewKeys; } - /** * @param array $oldToNewKeys */ - public function reorderClassStmtsByOldToNewKeys(ClassLike $classLike, array $oldToNewKeys): void + public function reorderClassStmtsByOldToNewKeys(\PhpParser\Node\Stmt\ClassLike $classLike, array $oldToNewKeys) : void { $reorderedStmts = []; - - $stmtCount = count($classLike->stmts); - + $stmtCount = \count($classLike->stmts); foreach ($classLike->stmts as $key => $stmt) { - if (! array_key_exists($key, $oldToNewKeys)) { + if (!\array_key_exists($key, $oldToNewKeys)) { $reorderedStmts[$key] = $stmt; continue; } - // reorder here $newKey = $oldToNewKeys[$key]; - $reorderedStmts[$key] = $classLike->stmts[$newKey]; } - for ($i = 0; $i < $stmtCount; ++$i) { - if (! array_key_exists($i, $reorderedStmts)) { + if (!\array_key_exists($i, $reorderedStmts)) { continue; } - $classLike->stmts[$i] = $reorderedStmts[$i]; } } - /** * @param class-string $type * @return array */ - public function getStmtsOfTypeOrder(ClassLike $classLike, string $type): array + public function getStmtsOfTypeOrder(\PhpParser\Node\Stmt\ClassLike $classLike, string $type) : array { $stmtsByPosition = []; foreach ($classLike->stmts as $position => $classStmt) { - if (! is_a($classStmt, $type)) { + if (!\is_a($classStmt, $type)) { continue; } - $name = $this->nodeNameResolver->getName($classStmt); if ($name === null) { continue; } - $stmtsByPosition[$position] = $name; } - return $stmtsByPosition; } } diff --git a/rules/Order/StmtVisibilitySorter.php b/rules/Order/StmtVisibilitySorter.php index a59cdeac5da..0685a70021e 100644 --- a/rules/Order/StmtVisibilitySorter.php +++ b/rules/Order/StmtVisibilitySorter.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; } - /** * @param Class_|Trait_ $classLike * @return string[] */ - public function sortProperties(ClassLike $classLike): array + public function sortProperties(\PhpParser\Node\Stmt\ClassLike $classLike) : array { $propertyRankeables = []; - foreach ($classLike->stmts as $position => $propertyStmt) { - if (! $propertyStmt instanceof Property) { + if (!$propertyStmt instanceof \PhpParser\Node\Stmt\Property) { continue; } - /** @var string $propertyName */ $propertyName = $this->nodeNameResolver->getName($propertyStmt); - - $propertyRankeables[] = new PropertyRankeable( - $propertyName, - $this->getVisibilityLevelOrder($propertyStmt), - $propertyStmt, - $position - ); + $propertyRankeables[] = new \Rector\Order\ValueObject\PropertyRankeable($propertyName, $this->getVisibilityLevelOrder($propertyStmt), $propertyStmt, $position); } - return $this->sortByRanksAndGetNames($propertyRankeables); } - /** * @return string[] */ - public function sortMethods(ClassLike $classLike): array + public function sortMethods(\PhpParser\Node\Stmt\ClassLike $classLike) : array { $classMethodsRankeables = []; - foreach ($classLike->stmts as $position => $classStmt) { - if (! $classStmt instanceof ClassMethod) { + if (!$classStmt instanceof \PhpParser\Node\Stmt\ClassMethod) { continue; } - /** @var string $classMethodName */ $classMethodName = $this->nodeNameResolver->getName($classStmt); - - $classMethodsRankeables[] = new ClassMethodRankeable( - $classMethodName, - $this->getVisibilityLevelOrder($classStmt), - $position, - $classStmt - ); + $classMethodsRankeables[] = new \Rector\Order\ValueObject\ClassMethodRankeable($classMethodName, $this->getVisibilityLevelOrder($classStmt), $position, $classStmt); } - return $this->sortByRanksAndGetNames($classMethodsRankeables); } - /** * @param Class_|Interface_ $classLike * @return string[] */ - public function sortConstants(ClassLike $classLike): array + public function sortConstants(\PhpParser\Node\Stmt\ClassLike $classLike) : array { $classConstsRankeables = []; foreach ($classLike->stmts as $position => $constantStmt) { - if (! $constantStmt instanceof ClassConst) { + if (!$constantStmt instanceof \PhpParser\Node\Stmt\ClassConst) { continue; } - /** @var string $constantName */ $constantName = $this->nodeNameResolver->getName($constantStmt); - - $classConstsRankeables[] = new ClassConstRankeable( - $constantName, - $this->getVisibilityLevelOrder($constantStmt), - $position - ); + $classConstsRankeables[] = new \Rector\Order\ValueObject\ClassConstRankeable($constantName, $this->getVisibilityLevelOrder($constantStmt), $position); } - return $this->sortByRanksAndGetNames($classConstsRankeables); } - /** * @param ClassMethod|Property|ClassConst $stmt */ - private function getVisibilityLevelOrder(Stmt $stmt): int + private function getVisibilityLevelOrder(\PhpParser\Node\Stmt $stmt) : int { if ($stmt->isPrivate()) { return 2; } - if ($stmt->isProtected()) { return 1; } - return 0; } - /** * @param RankeableInterface[] $rankeables * @return string[] */ - private function sortByRanksAndGetNames(array $rankeables): array + private function sortByRanksAndGetNames(array $rankeables) : array { - uasort( - $rankeables, - function (RankeableInterface $firstRankeable, RankeableInterface $secondRankeable): int { - return $firstRankeable->getRanks() <=> $secondRankeable->getRanks(); - } - ); - + \uasort($rankeables, function (\Rector\Order\Contract\RankeableInterface $firstRankeable, \Rector\Order\Contract\RankeableInterface $secondRankeable) : int { + return $firstRankeable->getRanks() <=> $secondRankeable->getRanks(); + }); $names = []; foreach ($rankeables as $rankeable) { $names[] = $rankeable->getName(); } - return $names; } } diff --git a/rules/Order/ValueObject/ClassConstRankeable.php b/rules/Order/ValueObject/ClassConstRankeable.php index 5892e381333..1b9844cac33 100644 --- a/rules/Order/ValueObject/ClassConstRankeable.php +++ b/rules/Order/ValueObject/ClassConstRankeable.php @@ -1,45 +1,38 @@ name = $name; $this->visibility = $visibility; $this->position = $position; } - - public function getName(): string + public function getName() : string { return $this->name; } - /** * An array to sort the element order by * @return int[] */ - public function getRanks(): array + public function getRanks() : array { return [$this->visibility, $this->position]; } diff --git a/rules/Order/ValueObject/ClassMethodRankeable.php b/rules/Order/ValueObject/ClassMethodRankeable.php index b184e6c232f..8269ce38edd 100644 --- a/rules/Order/ValueObject/ClassMethodRankeable.php +++ b/rules/Order/ValueObject/ClassMethodRankeable.php @@ -1,58 +1,50 @@ name = $name; $this->visibility = $visibility; $this->position = $position; $this->classMethod = $classMethod; } - - public function getName(): string + public function getName() : string { return $this->name; } - /** * An array to sort the element order by * @return bool[]|int[] */ - public function getRanks(): array + public function getRanks() : array { return [ $this->visibility, $this->classMethod->isStatic(), // negated on purpose, to put abstract later - ! $this->classMethod->isAbstract(), + !$this->classMethod->isAbstract(), $this->classMethod->isFinal(), $this->position, ]; diff --git a/rules/Order/ValueObject/PropertyRankeable.php b/rules/Order/ValueObject/PropertyRankeable.php index b572d27dcff..54c2c003906 100644 --- a/rules/Order/ValueObject/PropertyRankeable.php +++ b/rules/Order/ValueObject/PropertyRankeable.php @@ -1,51 +1,43 @@ name = $name; $this->visibility = $visibility; $this->property = $property; $this->position = $position; } - - public function getName(): string + public function getName() : string { return $this->name; } - /** * @return bool[]|int[] */ - public function getRanks(): array + public function getRanks() : array { return [$this->visibility, $this->property->isStatic(), $this->position]; } diff --git a/rules/Order/ValueObject/SortedClassMethodsAndOriginalClassMethods.php b/rules/Order/ValueObject/SortedClassMethodsAndOriginalClassMethods.php index 14014eb6dcd..189d9e2493b 100644 --- a/rules/Order/ValueObject/SortedClassMethodsAndOriginalClassMethods.php +++ b/rules/Order/ValueObject/SortedClassMethodsAndOriginalClassMethods.php @@ -1,7 +1,6 @@ */ private $sortedClassMethods = []; - /** * @var array */ private $originalClassMethods = []; - /** * @param array $sortedClassMethods * @param array $originalClassMethods @@ -25,33 +22,28 @@ final class SortedClassMethodsAndOriginalClassMethods $this->sortedClassMethods = $sortedClassMethods; $this->originalClassMethods = $originalClassMethods; } - /** * @return array */ - public function getSortedClassMethods(): array + public function getSortedClassMethods() : array { return $this->sortedClassMethods; } - /** * @return array */ - public function getOriginalClassMethods(): array + public function getOriginalClassMethods() : array { return $this->originalClassMethods; } - - public function hasOrderChanged(): bool + public function hasOrderChanged() : bool { return $this->sortedClassMethods !== $this->originalClassMethods; } - - public function hasOrderSame(): bool + public function hasOrderSame() : bool { - $sortedClassMethodValues = array_values($this->sortedClassMethods); - $originalClassMethodValues = array_values($this->originalClassMethods); - + $sortedClassMethodValues = \array_values($this->sortedClassMethods); + $originalClassMethodValues = \array_values($this->originalClassMethods); return $sortedClassMethodValues === $originalClassMethodValues; } } diff --git a/rules/PHPOffice/Rector/MethodCall/ChangeConditionalGetConditionRector.php b/rules/PHPOffice/Rector/MethodCall/ChangeConditionalGetConditionRector.php index 2b1c6e6a14e..3fbc56435c3 100644 --- a/rules/PHPOffice/Rector/MethodCall/ChangeConditionalGetConditionRector.php +++ b/rules/PHPOffice/Rector/MethodCall/ChangeConditionalGetConditionRector.php @@ -1,7 +1,6 @@ getCondition() to getConditions()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change argument PHPExcel_Style_Conditional->getCondition() to getConditions()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run(): void @@ -39,8 +33,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run(): void @@ -50,35 +43,28 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isObjectType($node->var, new ObjectType('PHPExcel_Style_Conditional'))) { + if (!$this->isObjectType($node->var, new \PHPStan\Type\ObjectType('PHPExcel_Style_Conditional'))) { return null; } - - if (! $this->isName($node->name, 'getCondition')) { + if (!$this->isName($node->name, 'getCondition')) { return null; } - - $node->name = new Identifier('getConditions'); - $arrayDimFetch = new ArrayDimFetch($node, new LNumber(0)); - - return new Coalesce($arrayDimFetch, new String_('')); + $node->name = new \PhpParser\Node\Identifier('getConditions'); + $arrayDimFetch = new \PhpParser\Node\Expr\ArrayDimFetch($node, new \PhpParser\Node\Scalar\LNumber(0)); + return new \PhpParser\Node\Expr\BinaryOp\Coalesce($arrayDimFetch, new \PhpParser\Node\Scalar\String_('')); } } diff --git a/rules/PHPOffice/Rector/MethodCall/ChangeConditionalReturnedCellRector.php b/rules/PHPOffice/Rector/MethodCall/ChangeConditionalReturnedCellRector.php index 2f1ff905dcd..ea029e8514c 100644 --- a/rules/PHPOffice/Rector/MethodCall/ChangeConditionalReturnedCellRector.php +++ b/rules/PHPOffice/Rector/MethodCall/ChangeConditionalReturnedCellRector.php @@ -1,7 +1,6 @@ conditionalSetValues[] = new ConditionalSetValue('setCellValue', 'getCell', 'setValue', 2, false); - - $this->conditionalSetValues[] = new ConditionalSetValue( - 'setCellValueByColumnAndRow', - 'getCellByColumnAndRow', - 'setValue', - 3, - true - ); - $this->conditionalSetValues[] = new ConditionalSetValue( - 'setCellValueExplicit', - 'getCell', - 'setValueExplicit', - 3, - false - ); - $this->conditionalSetValues[] = new ConditionalSetValue( - 'setCellValueExplicitByColumnAndRow', - 'getCellByColumnAndRow', - 'setValueExplicit', - 4, - true - ); + $this->conditionalSetValues[] = new \Rector\PHPOffice\ValueObject\ConditionalSetValue('setCellValue', 'getCell', 'setValue', 2, \false); + $this->conditionalSetValues[] = new \Rector\PHPOffice\ValueObject\ConditionalSetValue('setCellValueByColumnAndRow', 'getCellByColumnAndRow', 'setValue', 3, \true); + $this->conditionalSetValues[] = new \Rector\PHPOffice\ValueObject\ConditionalSetValue('setCellValueExplicit', 'getCell', 'setValueExplicit', 3, \false); + $this->conditionalSetValues[] = new \Rector\PHPOffice\ValueObject\ConditionalSetValue('setCellValueExplicitByColumnAndRow', 'getCellByColumnAndRow', 'setValueExplicit', 4, \true); } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change conditional call to getCell()', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change conditional call to getCell()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run(): void @@ -66,8 +41,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run(): void @@ -77,58 +51,46 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isObjectType($node->var, new ObjectType('PHPExcel_Worksheet'))) { + if (!$this->isObjectType($node->var, new \PHPStan\Type\ObjectType('PHPExcel_Worksheet'))) { return null; } - foreach ($this->conditionalSetValues as $conditionalSetValue) { - if (! $this->isName($node->name, $conditionalSetValue->getOldMethod())) { + if (!$this->isName($node->name, $conditionalSetValue->getOldMethod())) { continue; } - - if (! isset($node->args[$conditionalSetValue->getArgPosition()])) { + if (!isset($node->args[$conditionalSetValue->getArgPosition()])) { continue; } - $args = $node->args; unset($args[$conditionalSetValue->getArgPosition()]); - $locationArgs = []; $locationArgs[] = $args[0]; unset($args[0]); - if ($conditionalSetValue->hasRow()) { $locationArgs[] = $args[1]; unset($args[1]); } - $variable = clone $node->var; - - $getCellMethodCall = new MethodCall($variable, $conditionalSetValue->getNewGetMethod(), $locationArgs); + $getCellMethodCall = new \PhpParser\Node\Expr\MethodCall($variable, $conditionalSetValue->getNewGetMethod(), $locationArgs); $node->var = $getCellMethodCall; $node->args = $args; - $node->name = new Identifier($conditionalSetValue->getNewSetMethod()); - + $node->name = new \PhpParser\Node\Identifier($conditionalSetValue->getNewSetMethod()); return $node; } - return null; } } diff --git a/rules/PHPOffice/Rector/MethodCall/ChangeConditionalSetConditionRector.php b/rules/PHPOffice/Rector/MethodCall/ChangeConditionalSetConditionRector.php index aa1e716b1d7..aa33ea672e5 100644 --- a/rules/PHPOffice/Rector/MethodCall/ChangeConditionalSetConditionRector.php +++ b/rules/PHPOffice/Rector/MethodCall/ChangeConditionalSetConditionRector.php @@ -1,7 +1,6 @@ setCondition() to setConditions()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change argument PHPExcel_Style_Conditional->setCondition() to setConditions()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run(): void @@ -37,8 +31,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run(): void @@ -48,47 +41,38 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isObjectType($node->var, new ObjectType('PHPExcel_Style_Conditional'))) { + if (!$this->isObjectType($node->var, new \PHPStan\Type\ObjectType('PHPExcel_Style_Conditional'))) { return null; } - - if (! $this->isName($node->name, 'setCondition')) { + if (!$this->isName($node->name, 'setCondition')) { return null; } - - $node->name = new Identifier('setConditions'); + $node->name = new \PhpParser\Node\Identifier('setConditions'); $this->castArgumentToArrayIfNotArrayType($node); - return $node; } - - private function castArgumentToArrayIfNotArrayType(MethodCall $methodCall): void + private function castArgumentToArrayIfNotArrayType(\PhpParser\Node\Expr\MethodCall $methodCall) : void { $firstArgumentValue = $methodCall->args[0]->value; $firstArgumentStaticType = $this->getStaticType($firstArgumentValue); - if ($firstArgumentStaticType instanceof ArrayType) { + if ($firstArgumentStaticType instanceof \PHPStan\Type\ArrayType) { return; } - // cast to array if not an array - $methodCall->args[0]->value = new Array_($firstArgumentValue); + $methodCall->args[0]->value = new \PhpParser\Node\Expr\Cast\Array_($firstArgumentValue); } } diff --git a/rules/PHPOffice/Rector/MethodCall/ChangeDuplicateStyleArrayToApplyFromArrayRector.php b/rules/PHPOffice/Rector/MethodCall/ChangeDuplicateStyleArrayToApplyFromArrayRector.php index b3df34ff587..011e99f183f 100644 --- a/rules/PHPOffice/Rector/MethodCall/ChangeDuplicateStyleArrayToApplyFromArrayRector.php +++ b/rules/PHPOffice/Rector/MethodCall/ChangeDuplicateStyleArrayToApplyFromArrayRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isObjectType($node->var, new ObjectType('PHPExcel_Worksheet'))) { + if (!$this->isObjectType($node->var, new \PHPStan\Type\ObjectType('PHPExcel_Worksheet'))) { return null; } - - if (! $this->nodeNameResolver->isName($node->name, 'duplicateStyleArray')) { + if (!$this->nodeNameResolver->isName($node->name, 'duplicateStyleArray')) { return null; } - $variable = clone $node->var; - // pop out 2nd argument $secondArgument = $node->args[1]; unset($node->args[1]); - - $getStyleMethodCall = new MethodCall($variable, 'getStyle', [$secondArgument]); + $getStyleMethodCall = new \PhpParser\Node\Expr\MethodCall($variable, 'getStyle', [$secondArgument]); $node->var = $getStyleMethodCall; - $node->name = new Identifier('applyFromArray'); - + $node->name = new \PhpParser\Node\Identifier('applyFromArray'); return $node; } } diff --git a/rules/PHPOffice/Rector/MethodCall/GetDefaultStyleToGetParentRector.php b/rules/PHPOffice/Rector/MethodCall/GetDefaultStyleToGetParentRector.php index bc71fc25203..1614ea9e5bc 100644 --- a/rules/PHPOffice/Rector/MethodCall/GetDefaultStyleToGetParentRector.php +++ b/rules/PHPOffice/Rector/MethodCall/GetDefaultStyleToGetParentRector.php @@ -1,7 +1,6 @@ getDefaultStyle() to getParent()->getDefaultStyle()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Methods to (new Worksheet())->getDefaultStyle() to getParent()->getDefaultStyle()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -34,8 +28,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -45,37 +38,29 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isObjectType($node->var, new ObjectType('PHPExcel_Worksheet'))) { + if (!$this->isObjectType($node->var, new \PHPStan\Type\ObjectType('PHPExcel_Worksheet'))) { return null; } - - if (! $this->isName($node->name, 'getDefaultStyle')) { + if (!$this->isName($node->name, 'getDefaultStyle')) { return null; } - $variable = clone $node->var; - - $getParentMethodCall = new MethodCall($variable, 'getParent'); + $getParentMethodCall = new \PhpParser\Node\Expr\MethodCall($variable, 'getParent'); $node->var = $getParentMethodCall; - return $node; } } diff --git a/rules/PHPOffice/Rector/MethodCall/IncreaseColumnIndexRector.php b/rules/PHPOffice/Rector/MethodCall/IncreaseColumnIndexRector.php index 5ad782f409f..e313dd89b2d 100644 --- a/rules/PHPOffice/Rector/MethodCall/IncreaseColumnIndexRector.php +++ b/rules/PHPOffice/Rector/MethodCall/IncreaseColumnIndexRector.php @@ -1,7 +1,6 @@ worksheetObjectTypes = [ - new ObjectType('PHPExcel_Worksheet'), - new ObjectType('PHPExcel_Worksheet_PageSetup'), - ]; + $this->worksheetObjectTypes = [new \PHPStan\Type\ObjectType('PHPExcel_Worksheet'), new \PHPStan\Type\ObjectType('PHPExcel_Worksheet_PageSetup')]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Column index changed from 0 to 1 - run only ONCE! changes current value without memory', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Column index changed from 0 to 1 - run only ONCE! changes current value without memory', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run(): void @@ -53,8 +42,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run(): void @@ -64,108 +52,88 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->nodeTypeResolver->isObjectTypes($node->var, $this->worksheetObjectTypes)) { + if (!$this->nodeTypeResolver->isObjectTypes($node->var, $this->worksheetObjectTypes)) { return null; } - - if (! $this->isName($node->name, '*ByColumnAndRow')) { + if (!$this->isName($node->name, '*ByColumnAndRow')) { return null; } - // increase column value $firstArgumentValue = $node->args[0]->value; - if ($firstArgumentValue instanceof LNumber) { + if ($firstArgumentValue instanceof \PhpParser\Node\Scalar\LNumber) { ++$firstArgumentValue->value; } - - if ($firstArgumentValue instanceof BinaryOp) { + if ($firstArgumentValue instanceof \PhpParser\Node\Expr\BinaryOp) { $this->refactorBinaryOp($firstArgumentValue); } - - if ($firstArgumentValue instanceof Variable) { + if ($firstArgumentValue instanceof \PhpParser\Node\Expr\Variable) { // check if for() value, rather update that $lNumber = $this->findPreviousForWithVariable($firstArgumentValue); - if (! $lNumber instanceof LNumber) { - $node->args[0]->value = new Plus($firstArgumentValue, new LNumber(1)); + if (!$lNumber instanceof \PhpParser\Node\Scalar\LNumber) { + $node->args[0]->value = new \PhpParser\Node\Expr\BinaryOp\Plus($firstArgumentValue, new \PhpParser\Node\Scalar\LNumber(1)); return null; } - ++$lNumber->value; } - return $node; } - - private function refactorBinaryOp(BinaryOp $binaryOp): void + private function refactorBinaryOp(\PhpParser\Node\Expr\BinaryOp $binaryOp) : void { - if ($binaryOp->left instanceof LNumber) { + if ($binaryOp->left instanceof \PhpParser\Node\Scalar\LNumber) { ++$binaryOp->left->value; return; } - - if ($binaryOp->right instanceof LNumber) { + if ($binaryOp->right instanceof \PhpParser\Node\Scalar\LNumber) { ++$binaryOp->right->value; return; } } - - private function findPreviousForWithVariable(Variable $variable): ?LNumber + private function findPreviousForWithVariable(\PhpParser\Node\Expr\Variable $variable) : ?\PhpParser\Node\Scalar\LNumber { - $for = $this->betterNodeFinder->findFirstPreviousOfTypes($variable, [For_::class]); - if (! $for instanceof For_) { + $for = $this->betterNodeFinder->findFirstPreviousOfTypes($variable, [\PhpParser\Node\Stmt\For_::class]); + if (!$for instanceof \PhpParser\Node\Stmt\For_) { return null; } - $variableName = $this->getName($variable); if ($variableName === null) { return null; } - $assignVariable = $this->findVariableAssignName($for->init, $variableName); - if (! $assignVariable instanceof Assign) { + if (!$assignVariable instanceof \PhpParser\Node\Expr\Assign) { return null; } - $assignedExpr = $assignVariable->expr; - if ($assignedExpr instanceof LNumber) { + if ($assignedExpr instanceof \PhpParser\Node\Scalar\LNumber) { return $assignedExpr; } - return null; } - /** * @param Node[] $node */ - private function findVariableAssignName(array $node, string $variableName): ?Node + private function findVariableAssignName(array $node, string $variableName) : ?\PhpParser\Node { - return $this->betterNodeFinder->findFirst($node, function (Node $node) use ($variableName): bool { - if (! $node instanceof Assign) { - return false; + return $this->betterNodeFinder->findFirst($node, function (\PhpParser\Node $node) use($variableName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - if (! $node->var instanceof Variable) { - return false; + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeNameResolver->isName($node->var, $variableName); }); } diff --git a/rules/PHPOffice/Rector/MethodCall/RemoveSetTempDirOnExcelWriterRector.php b/rules/PHPOffice/Rector/MethodCall/RemoveSetTempDirOnExcelWriterRector.php index e3371a26231..4016307343b 100644 --- a/rules/PHPOffice/Rector/MethodCall/RemoveSetTempDirOnExcelWriterRector.php +++ b/rules/PHPOffice/Rector/MethodCall/RemoveSetTempDirOnExcelWriterRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isObjectType($node->var, new ObjectType('PHPExcel_Writer_Excel5'))) { + if (!$this->isObjectType($node->var, new \PHPStan\Type\ObjectType('PHPExcel_Writer_Excel5'))) { return null; } - - if (! $this->isName($node->name, 'setTempDir')) { + if (!$this->isName($node->name, 'setTempDir')) { return null; } - $this->removeNode($node); - return $node; } } diff --git a/rules/PHPOffice/Rector/StaticCall/AddRemovedDefaultValuesRector.php b/rules/PHPOffice/Rector/StaticCall/AddRemovedDefaultValuesRector.php index 71b4d8f0637..510d860e786 100644 --- a/rules/PHPOffice/Rector/StaticCall/AddRemovedDefaultValuesRector.php +++ b/rules/PHPOffice/Rector/StaticCall/AddRemovedDefaultValuesRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class, MethodCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Expr\MethodCall::class]; } - /** * @param StaticCall|MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - foreach (PHPExcelMethodDefaultValues::METHOD_NAMES_BY_TYPE_WITH_VALUE as $type => $defaultValuesByMethodName) { - if (! $this->isCallerObjectType($node, new ObjectType($type))) { + foreach (\Rector\PHPOffice\ValueObject\PHPExcelMethodDefaultValues::METHOD_NAMES_BY_TYPE_WITH_VALUE as $type => $defaultValuesByMethodName) { + if (!$this->isCallerObjectType($node, new \PHPStan\Type\ObjectType($type))) { continue; } - foreach ($defaultValuesByMethodName as $methodName => $defaultValuesByPosition) { - if (! $this->isName($node->name, $methodName)) { + if (!$this->isName($node->name, $methodName)) { continue; } - $this->refactorArgs($node, $defaultValuesByPosition); } } - return $node; } - /** * @param StaticCall|MethodCall $node * @param array $defaultValuesByPosition */ - private function refactorArgs(Node $node, array $defaultValuesByPosition): void + private function refactorArgs(\PhpParser\Node $node, array $defaultValuesByPosition) : void { foreach ($defaultValuesByPosition as $position => $defaultValue) { // value is already set if (isset($node->args[$position])) { continue; } - - if (is_string($defaultValue) && Strings::contains($defaultValue, '::')) { - [$className, $constant] = explode('::', $defaultValue); + if (\is_string($defaultValue) && \RectorPrefix20210509\Nette\Utils\Strings::contains($defaultValue, '::')) { + [$className, $constant] = \explode('::', $defaultValue); $classConstant = $this->nodeFactory->createClassConstFetch($className, $constant); - $arg = new Arg($classConstant); + $arg = new \PhpParser\Node\Arg($classConstant); } else { $arg = $this->nodeFactory->createArg($defaultValue); } - $node->args[$position] = $arg; } } - /** * @param StaticCall|MethodCall $node */ - private function isCallerObjectType(Node $node, ObjectType $objectType): bool + private function isCallerObjectType(\PhpParser\Node $node, \PHPStan\Type\ObjectType $objectType) : bool { - return $this->isObjectType($node instanceof MethodCall ? $node->var : $node->class, $objectType); + return $this->isObjectType($node instanceof \PhpParser\Node\Expr\MethodCall ? $node->var : $node->class, $objectType); } } diff --git a/rules/PHPOffice/Rector/StaticCall/CellStaticToCoordinateRector.php b/rules/PHPOffice/Rector/StaticCall/CellStaticToCoordinateRector.php index 066107f960d..38eb32d53d4 100644 --- a/rules/PHPOffice/Rector/StaticCall/CellStaticToCoordinateRector.php +++ b/rules/PHPOffice/Rector/StaticCall/CellStaticToCoordinateRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isObjectType($node->class, new ObjectType('PHPExcel_Cell'))) { + if (!$this->isObjectType($node->class, new \PHPStan\Type\ObjectType('PHPExcel_Cell'))) { return null; } - - if (! $this->isNames($node->name, self::DECOUPLED_METHODS)) { + if (!$this->isNames($node->name, self::DECOUPLED_METHODS)) { return null; } - - $node->class = new FullyQualified('PhpOffice\PhpSpreadsheet\Cell\Coordinate'); - + $node->class = new \PhpParser\Node\Name\FullyQualified('PhpOffice\\PhpSpreadsheet\\Cell\\Coordinate'); return $node; } } diff --git a/rules/PHPOffice/Rector/StaticCall/ChangeChartRendererRector.php b/rules/PHPOffice/Rector/StaticCall/ChangeChartRendererRector.php index 22db38dd49f..5f88fae13e5 100644 --- a/rules/PHPOffice/Rector/StaticCall/ChangeChartRendererRector.php +++ b/rules/PHPOffice/Rector/StaticCall/ChangeChartRendererRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $callerType = $this->nodeTypeResolver->resolve($node->class); - if (! $callerType->isSuperTypeOf(new ObjectType('PHPExcel_Settings'))->yes()) { + if (!$callerType->isSuperTypeOf(new \PHPStan\Type\ObjectType('PHPExcel_Settings'))->yes()) { return null; } - - if (! $this->nodeNameResolver->isName($node->name, 'setChartRenderer')) { + if (!$this->nodeNameResolver->isName($node->name, 'setChartRenderer')) { return null; } - - if (count($node->args) === 1) { + if (\count($node->args) === 1) { return null; } - - $arg = new Arg($this->nodeFactory->createClassConstReference( - 'PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph' - )); + $arg = new \PhpParser\Node\Arg($this->nodeFactory->createClassConstReference('PhpOffice\\PhpSpreadsheet\\Chart\\Renderer\\JpGraph')); $node->args = [$arg]; - return $node; } } diff --git a/rules/PHPOffice/Rector/StaticCall/ChangeDataTypeForValueRector.php b/rules/PHPOffice/Rector/StaticCall/ChangeDataTypeForValueRector.php index 9c00901ddc9..ae91db0aefc 100644 --- a/rules/PHPOffice/Rector/StaticCall/ChangeDataTypeForValueRector.php +++ b/rules/PHPOffice/Rector/StaticCall/ChangeDataTypeForValueRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $callerType = $this->nodeTypeResolver->resolve($node->class); - if (! $callerType->isSuperTypeOf(new ObjectType('PHPExcel_Cell_DataType'))->yes()) { + if (!$callerType->isSuperTypeOf(new \PHPStan\Type\ObjectType('PHPExcel_Cell_DataType'))->yes()) { return null; } - - if (! $this->nodeNameResolver->isName($node->name, 'dataTypeForValue')) { + if (!$this->nodeNameResolver->isName($node->name, 'dataTypeForValue')) { return null; } - - $node->class = new FullyQualified('PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder'); - + $node->class = new \PhpParser\Node\Name\FullyQualified('PhpOffice\\PhpSpreadsheet\\Cell\\DefaultValueBinder'); return $node; } } diff --git a/rules/PHPOffice/Rector/StaticCall/ChangeIOFactoryArgumentRector.php b/rules/PHPOffice/Rector/StaticCall/ChangeIOFactoryArgumentRector.php index 13a3fd2e282..151bd32f459 100644 --- a/rules/PHPOffice/Rector/StaticCall/ChangeIOFactoryArgumentRector.php +++ b/rules/PHPOffice/Rector/StaticCall/ChangeIOFactoryArgumentRector.php @@ -1,7 +1,6 @@ */ - private const OLD_TO_NEW_TYPE = [ - 'CSV' => 'Csv', - 'Excel2003XML' => 'Xml', - 'Excel2007' => 'Xlsx', - 'Excel5' => 'Xls', - 'Gnumeric' => 'Gnumeric', - 'HTML' => 'Html', - 'OOCalc' => 'Ods', - 'OpenDocument' => 'Ods', - 'PDF' => 'Pdf', - 'SYLK' => 'Slk', - ]; - - public function getRuleDefinition(): RuleDefinition + private const OLD_TO_NEW_TYPE = ['CSV' => 'Csv', 'Excel2003XML' => 'Xml', 'Excel2007' => 'Xlsx', 'Excel5' => 'Xls', 'Gnumeric' => 'Gnumeric', 'HTML' => 'Html', 'OOCalc' => 'Ods', 'OpenDocument' => 'Ods', 'PDF' => 'Pdf', 'SYLK' => 'Slk']; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change argument of PHPExcel_IOFactory::createReader(), PHPExcel_IOFactory::createWriter() and PHPExcel_IOFactory::identify()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change argument of PHPExcel_IOFactory::createReader(), PHPExcel_IOFactory::createWriter() and PHPExcel_IOFactory::identify()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run(): void @@ -50,8 +32,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run(): void @@ -60,40 +41,32 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isObjectType($node->class, new ObjectType('PHPExcel_IOFactory'))) { + if (!$this->isObjectType($node->class, new \PHPStan\Type\ObjectType('PHPExcel_IOFactory'))) { return null; } - - if (! $this->isNames($node->name, ['createReader', 'createWriter', 'identify'])) { + if (!$this->isNames($node->name, ['createReader', 'createWriter', 'identify'])) { return null; } - $firstArgumentValue = $this->valueResolver->getValue($node->args[0]->value); $newValue = self::OLD_TO_NEW_TYPE[$firstArgumentValue] ?? null; if ($newValue === null) { return null; } - - $node->args[0]->value = new String_($newValue); - + $node->args[0]->value = new \PhpParser\Node\Scalar\String_($newValue); return $node; } } diff --git a/rules/PHPOffice/Rector/StaticCall/ChangePdfWriterRector.php b/rules/PHPOffice/Rector/StaticCall/ChangePdfWriterRector.php index 6ed62f0c066..eb0154b9c8d 100644 --- a/rules/PHPOffice/Rector/StaticCall/ChangePdfWriterRector.php +++ b/rules/PHPOffice/Rector/StaticCall/ChangePdfWriterRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $callerType = $this->nodeTypeResolver->resolve($node->class); - if ($this->isSettingsPdfRendererStaticCall($callerType, $node)) { $this->removeNode($node); return null; } - - if ($callerType->isSuperTypeOf(new ObjectType('PHPExcel_IOFactory'))->yes() && $this->nodeNameResolver->isName( - $node->name, - 'createWriter' - )) { - if (! isset($node->args[1])) { + if ($callerType->isSuperTypeOf(new \PHPStan\Type\ObjectType('PHPExcel_IOFactory'))->yes() && $this->nodeNameResolver->isName($node->name, 'createWriter')) { + if (!isset($node->args[1])) { return null; } - $secondArgValue = $this->valueResolver->getValue($node->args[1]->value); - if (Strings::match($secondArgValue, '#pdf#i')) { - return new New_(new FullyQualified('PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf'), [$node->args[0]]); + if (\RectorPrefix20210509\Nette\Utils\Strings::match($secondArgValue, '#pdf#i')) { + return new \PhpParser\Node\Expr\New_(new \PhpParser\Node\Name\FullyQualified('PhpOffice\\PhpSpreadsheet\\Writer\\Pdf\\Mpdf'), [$node->args[0]]); } } - return $node; } - - private function isSettingsPdfRendererStaticCall(Type $callerType, StaticCall $staticCall): bool + private function isSettingsPdfRendererStaticCall(\PHPStan\Type\Type $callerType, \PhpParser\Node\Expr\StaticCall $staticCall) : bool { - if (! $callerType->isSuperTypeOf(new ObjectType('PHPExcel_Settings'))->yes()) { - return false; + if (!$callerType->isSuperTypeOf(new \PHPStan\Type\ObjectType('PHPExcel_Settings'))->yes()) { + return \false; } - return $this->nodeNameResolver->isNames($staticCall->name, ['setPdfRendererName', 'setPdfRenderer']); } } diff --git a/rules/PHPOffice/Rector/StaticCall/ChangeSearchLocationToRegisterReaderRector.php b/rules/PHPOffice/Rector/StaticCall/ChangeSearchLocationToRegisterReaderRector.php index 9724afce40e..e329e1d288b 100644 --- a/rules/PHPOffice/Rector/StaticCall/ChangeSearchLocationToRegisterReaderRector.php +++ b/rules/PHPOffice/Rector/StaticCall/ChangeSearchLocationToRegisterReaderRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $callerType = $this->nodeTypeResolver->resolve($node->class); - if (! $callerType->isSuperTypeOf(new ObjectType('PHPExcel_IOFactory'))->yes()) { + if (!$callerType->isSuperTypeOf(new \PHPStan\Type\ObjectType('PHPExcel_IOFactory'))->yes()) { return null; } - - if (! $this->isName($node->name, 'addSearchLocation')) { + if (!$this->isName($node->name, 'addSearchLocation')) { return null; } - - $node->class = new FullyQualified('PhpOffice\PhpSpreadsheet\IOFactory'); - $node->name = new Identifier('registerReader'); - + $node->class = new \PhpParser\Node\Name\FullyQualified('PhpOffice\\PhpSpreadsheet\\IOFactory'); + $node->name = new \PhpParser\Node\Identifier('registerReader'); // remove middle argument $args = $node->args; unset($args[1]); - - $node->args = array_values($args); - + $node->args = \array_values($args); return $node; } } diff --git a/rules/PHPOffice/ValueObject/ConditionalSetValue.php b/rules/PHPOffice/ValueObject/ConditionalSetValue.php index 511f826c1f8..6e8cf627b7d 100644 --- a/rules/PHPOffice/ValueObject/ConditionalSetValue.php +++ b/rules/PHPOffice/ValueObject/ConditionalSetValue.php @@ -1,7 +1,6 @@ oldMethod = $oldMethod; $this->newGetMethod = $newGetMethod; $this->argPosition = $argPosition; $this->newSetMethod = $newSetMethod; $this->hasRow = $hasRow; } - - public function getOldMethod(): string + public function getOldMethod() : string { return $this->oldMethod; } - - public function getArgPosition(): int + public function getArgPosition() : int { return $this->argPosition; } - - public function getNewGetMethod(): string + public function getNewGetMethod() : string { return $this->newGetMethod; } - - public function getNewSetMethod(): string + public function getNewSetMethod() : string { return $this->newSetMethod; } - - public function hasRow(): bool + public function hasRow() : bool { return $this->hasRow; } diff --git a/rules/PHPOffice/ValueObject/PHPExcelMethodDefaultValues.php b/rules/PHPOffice/ValueObject/PHPExcelMethodDefaultValues.php index e03cef88a4d..b9276930e28 100644 --- a/rules/PHPOffice/ValueObject/PHPExcelMethodDefaultValues.php +++ b/rules/PHPOffice/ValueObject/PHPExcelMethodDefaultValues.php @@ -1,7 +1,6 @@ >> */ - public const METHOD_NAMES_BY_TYPE_WITH_VALUE = [ - 'PHPExcel' => [ - 'setHasMacros' => [false], - 'setMacrosCode' => [null], - 'setMacrosCertificate' => [null], - 'setRibbonXMLData' => [null, null], - 'setRibbonBinObjects' => [null, null], - 'getRibbonBinObjects' => ['all'], - 'getSheetByCodeName' => [''], - 'createSheet' => [null], - 'removeSheetByIndex' => [0], - 'getSheet' => [0], - 'getSheetByName' => [''], - 'setActiveSheetIndex' => [0], - 'setActiveSheetIndexByName' => [''], - 'getCellXfByIndex' => [0], - 'getCellXfByHashCode' => [''], - 'cellXfExists' => [null], - 'removeCellXfByIndex' => [0], - 'getCellStyleXfByIndex' => [0], - 'getCellStyleXfByHashCode' => [''], - 'removeCellStyleXfByIndex' => [0], - ], - 'PHPExcel_CalcEngine_Logger' => [ - 'setWriteDebugLog' => [false], - 'setEchoDebugLog' => [false], - ], - 'PHPExcel_Calculation' => [ - 'setCalculationCacheEnabled' => [true], - 'setLocale' => ['en_us'], - ], - 'PHPExcel_Calculation_FormulaToken' => [ - 'setTokenType' => ['PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN'], - 'setTokenSubType' => ['PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING'], - ], - 'PHPExcel_Cell' => [ - 'setValue' => [null], - 'setValueExplicit' => [null, 'PHPExcel_Cell_DataType::TYPE_STRING'], - 'setCalculatedValue' => [null], - 'setDataType' => ['PHPExcel_Cell_DataType::TYPE_STRING'], - 'isInRange' => ['A1:A1'], - 'coordinateFromString' => ['A1'], - 'absoluteReference' => ['A1'], - 'absoluteCoordinate' => ['A1'], - 'splitRange' => ['A1:A1'], - 'rangeBoundaries' => ['A1:A1'], - 'rangeDimension' => ['A1:A1'], - 'getRangeBoundaries' => ['A1:A1'], - 'columnIndexFromString' => ['A'], - 'stringFromColumnIndex' => [0], - 'extractAllCellReferencesInRange' => ['A1'], - 'setXfIndex' => [0], - ], - 'PHPExcel_Cell_DataType' => [ - 'checkString' => [null], - 'checkErrorCode' => [null], - ], - 'PHPExcel_Cell_DataValidation' => [ - 'setFormula1' => [''], - 'setFormula2' => [''], - 'setType' => ['PHPExcel_Cell_DataValidation::TYPE_NONE'], - 'setErrorStyle' => ['PHPExcel_Cell_DataValidation::STYLE_STOP'], - 'setOperator' => [''], - 'setAllowBlank' => [false], - 'setShowDropDown' => [false], - 'setShowInputMessage' => [false], - 'setShowErrorMessage' => [false], - 'setErrorTitle' => [''], - 'setError' => [''], - 'setPromptTitle' => [''], - 'setPrompt' => [''], - ], - 'PHPExcel_Cell_DefaultValueBinder' => [ - 'dataTypeForValue' => [null], - ], - 'PHPExcel_Cell_Hyperlink' => [ - 'setUrl' => [''], - 'setTooltip' => [''], - ], - 'PHPExcel_Chart' => [ - 'setPlotVisibleOnly' => [true], - 'setDisplayBlanksAs' => ['0'], - 'setTopLeftOffset' => [null, null], - 'setBottomRightOffset' => [null, null], - ], - 'PHPExcel_Chart_DataSeries' => [ - 'setPlotType' => [''], - 'setPlotGrouping' => [null], - 'setPlotDirection' => [null], - 'setPlotStyle' => [null], - 'setSmoothLine' => [true], - ], - 'PHPExcel_Chart_DataSeriesValues' => [ - 'setDataType' => ['PHPExcel_Chart_DataSeriesValues::DATASERIES_TYPE_NUMBER'], - 'setDataSource' => [null, true], - 'setPointMarker' => [null], - 'setFormatCode' => [null], - 'setDataValues' => [[], true], - ], - 'PHPExcel_Chart_Layout' => [ - '__construct' => [[]], - ], - 'PHPExcel_Chart_Legend' => [ - 'setPosition' => ['PHPExcel_Chart_Legend::POSITION_RIGHT'], - 'setPositionXL' => ['PHPExcel_Chart_Legend::XL_LEGEND_POSITION_RIGHT'], - 'setOverlay' => [false], - ], - 'PHPExcel_Chart_PlotArea' => [ - '__construct' => [null, []], - 'setPlotSeries' => [[]], - ], - 'PHPExcel_Chart_Title' => [ - 'setCaption' => [null], - ], - 'PHPExcel_Comment' => [ - 'setAuthor' => [''], - 'setWidth' => ['96pt'], - 'setHeight' => ['55.5pt'], - 'setMarginLeft' => ['59.25pt'], - 'setMarginTop' => ['1.5pt'], - 'setVisible' => [false], - 'setAlignment' => ['Style\\Alignment::HORIZONTAL_GENERAL'], - ], - 'PHPExcel_DocumentProperties' => [ - 'setCreator' => [''], - 'setLastModifiedBy' => [''], - 'setCreated' => [null], - 'setModified' => [null], - 'setTitle' => [''], - 'setDescription' => [''], - 'setSubject' => [''], - 'setKeywords' => [''], - 'setCategory' => [''], - 'setCompany' => [''], - 'setManager' => [''], - ], - 'PHPExcel_DocumentSecurity' => [ - 'setLockRevision' => [false], - 'setLockStructure' => [false], - 'setLockWindows' => [false], - 'setRevisionsPassword' => ['', false], - 'setWorkbookPassword' => ['', false], - ], - 'PHPExcel_HashTable' => [ - 'addFromSource' => [null], - 'getIndexForHashCode' => [''], - 'getByIndex' => [0], - 'getByHashCode' => [''], - ], - 'PHPExcel_IOFactory' => [ - 'addSearchLocation' => ['', '', ''], - 'createReader' => [''], - ], - 'PHPExcel_NamedRange' => [ - 'setName' => [null], - 'setRange' => [null], - 'setLocalOnly' => [false], - ], - 'PHPExcel_Reader_Abstract' => [ - 'setReadDataOnly' => [false], - 'setReadEmptyCells' => [true], - 'setIncludeCharts' => [false], - 'setLoadSheetsOnly' => [null], - ], - 'PHPExcel_Reader_CSV' => [ - 'setInputEncoding' => ['UTF-8'], - 'setDelimiter' => [','], - 'setEnclosure' => ['\\'], - 'setSheetIndex' => [0], - 'setContiguous' => [false], - ], - 'PHPExcel_Reader_Excel2003XML' => [ - 'parseRichText' => [''], - ], - 'PHPExcel_Reader_Excel2007' => [ - 'parseRichText' => [null], - 'boolean' => [null], - ], - 'PHPExcel_Reader_Excel2007_Chart' => [ - 'parseRichText' => [null], - ], - 'PHPExcel_Reader_Excel2007_Theme' => [ - 'getColourByIndex' => [0], - ], - 'PHPExcel_Reader_Excel5' => [ - 'parseRichText' => [''], - ], - 'PHPExcel_Reader_Gnumeric' => [ - 'parseRichText' => [''], - ], - 'PHPExcel_Reader_HTML' => [ - 'setInputEncoding' => ['ANSI'], - 'setSheetIndex' => [0], - ], - 'PHPExcel_Reader_OOCalc' => [ - 'parseRichText' => [''], - ], - 'PHPExcel_Reader_SYLK' => [ - 'setInputEncoding' => ['ANSI'], - 'setSheetIndex' => [0], - ], - 'PHPExcel_RichText' => [ - 'createText' => [''], - 'createTextRun' => [''], - 'setRichTextElements' => [null], - ], - 'PHPExcel_RichText_TextElement' => [ - 'setText' => [''], - ], - 'PHPExcel_Settings' => [ - 'setLocale' => ['en_us'], - 'setLibXmlLoaderOptions' => [null], - ], - 'PHPExcel_Shared_CodePage' => [ - 'numberToName' => ['1252'], - ], - 'PHPExcel_Shared_Date' => [ - 'excelToDateTimeObject' => [0, null], - 'excelToTimestamp' => [0, null], - 'PHPToExcel' => [0], - 'timestampToExcel' => [0], - 'isDateTimeFormatCode' => [''], - 'stringToExcel' => [''], - ], - 'PHPExcel_Shared_Drawing' => [ - 'pixelsToEMU' => [0], - 'EMUToPixels' => [0], - 'pixelsToPoints' => [0], - 'pointsToPixels' => [0], - 'degreesToAngle' => [0], - 'angleToDegrees' => [0], - ], - 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer' => [ - 'setSpgr' => [false], - 'setStartCoordinates' => ['A1'], - 'setStartOffsetX' => [0], - 'setStartOffsetY' => [0], - 'setEndCoordinates' => ['A1'], - 'setEndOffsetX' => [0], - 'setEndOffsetY' => [0], - ], - 'PHPExcel_Shared_File' => [ - 'setUseUploadTempDirectory' => [false], - ], - 'PHPExcel_Shared_Font' => [ - 'setAutoSizeMethod' => ['PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX'], - 'setTrueTypeFontPath' => [''], - 'fontSizeToPixels' => ['11'], - 'inchSizeToPixels' => ['1'], - 'centimeterSizeToPixels' => ['1'], - ], - 'PHPExcel_Shared_OLE' => [ - 'localDateToOLE' => [null], - ], - 'PHPExcel_Shared_PasswordHasher' => [ - 'hashPassword' => [''], - ], - 'PHPExcel_Shared_String' => [ - 'controlCharacterOOXML2PHP' => [''], - 'controlCharacterPHP2OOXML' => [''], - 'isUTF8' => [''], - 'substring' => ['', 0, 0], - 'strToUpper' => [''], - 'strToLower' => [''], - 'strToTitle' => [''], - 'strCaseReverse' => [''], - 'setDecimalSeparator' => ['.'], - 'setThousandsSeparator' => [','], - 'setCurrencyCode' => ['$'], - 'SYLKtoUTF8' => [''], - ], - 'PHPExcel_Style' => [ - 'applyFromArray' => [null, true], - 'setConditionalStyles' => [null], - ], - 'PHPExcel_Style_Alignment' => [ - 'applyFromArray' => [null], - 'setHorizontal' => ['PHPExcel_Style_Alignment::HORIZONTAL_GENERAL'], - 'setVertical' => ['PHPExcel_Style_Alignment::VERTICAL_BOTTOM'], - 'setTextRotation' => [0], - 'setWrapText' => [false], - 'setShrinkToFit' => [false], - 'setIndent' => [0], - 'setReadorder' => [0], - ], - 'PHPExcel_Style_Border' => [ - 'applyFromArray' => [null], - 'setBorderStyle' => ['PHPExcel_Style_Border::BORDER_NONE'], - ], - 'PHPExcel_Style_Borders' => [ - 'applyFromArray' => [null], - 'setDiagonalDirection' => ['PHPExcel_Style_Borders::DIAGONAL_NONE'], - ], - 'PHPExcel_Style_Color' => [ - 'applyFromArray' => [null], - 'setARGB' => ['PHPExcel_Style_Color::COLOR_BLACK'], - 'setRGB' => ['000000'], - ], - 'PHPExcel_Style_Conditional' => [ - 'setConditionType' => ['PHPExcel_Style_Conditional::CONDITION_NONE'], - 'setOperatorType' => ['PHPExcel_Style_Conditional::OPERATOR_NONE'], - 'setText' => [null], - 'addCondition' => [''], - ], - 'PHPExcel_Style_Fill' => [ - 'applyFromArray' => [null], - 'setFillType' => ['PHPExcel_Style_Fill::FILL_NONE'], - 'setRotation' => [0], - ], - 'PHPExcel_Style_Font' => [ - 'applyFromArray' => [null], - 'setName' => ['Calibri'], - 'setSize' => ['10'], - 'setBold' => [false], - 'setItalic' => [false], - 'setSuperScript' => [false], - 'setSubScript' => [false], - 'setUnderline' => ['PHPExcel_Style_Font::UNDERLINE_NONE'], - 'setStrikethrough' => [false], - ], - 'PHPExcel_Style_NumberFormat' => [ - 'applyFromArray' => [null], - 'setFormatCode' => ['PHPExcel_Style_NumberFormat::FORMAT_GENERAL'], - 'setBuiltInFormatCode' => [0], - 'toFormattedString' => ['0', 'PHPExcel_Style_NumberFormat::FORMAT_GENERAL', null], - ], - 'PHPExcel_Style_Protection' => [ - 'applyFromArray' => [null], - 'setLocked' => ['PHPExcel_Style_Protection::PROTECTION_INHERIT'], - 'setHidden' => ['PHPExcel_Style_Protection::PROTECTION_INHERIT'], - ], - 'PHPExcel_Worksheet' => [ - 'getChartByIndex' => [null], - 'getChartByName' => [''], - 'setTitle' => ['Worksheet', true], - 'setSheetState' => ['PHPExcel_Worksheet::SHEETSTATE_VISIBLE'], - 'setCellValue' => ['A1', null, false], - 'setCellValueByColumnAndRow' => [0, '1', null, false], - 'setCellValueExplicit' => ['A1', null, 'PHPExcel_Cell_DataType::TYPE_STRING', false], - 'setCellValueExplicitByColumnAndRow' => [0, '1', null, 'PHPExcel_Cell_DataType::TYPE_STRING', false], - 'getCell' => ['A1', true], - 'getCellByColumnAndRow' => [0, '1', true], - 'cellExists' => ['A1'], - 'cellExistsByColumnAndRow' => [0, '1'], - 'getRowDimension' => ['1', true], - 'getColumnDimension' => ['A', true], - 'getColumnDimensionByColumn' => [0], - 'getStyle' => ['A1'], - 'getConditionalStyles' => ['A1'], - 'conditionalStylesExists' => ['A1'], - 'removeConditionalStyles' => ['A1'], - 'getStyleByColumnAndRow' => [0, '1', null, null], - 'setBreak' => ['A1', 'PHPExcel_Worksheet::BREAK_NONE'], - 'setBreakByColumnAndRow' => [0, '1', 'PHPExcel_Worksheet::BREAK_NONE'], - 'mergeCells' => ['A1:A1'], - 'mergeCellsByColumnAndRow' => [0, '1', 0, '1'], - 'unmergeCells' => ['A1:A1'], - 'unmergeCellsByColumnAndRow' => [0, '1', 0, '1'], - 'setMergeCells' => [[]], - 'protectCells' => ['A1', '', false], - 'protectCellsByColumnAndRow' => [0, '1', 0, '1', '', false], - 'unprotectCells' => ['A1'], - 'unprotectCellsByColumnAndRow' => [0, '1', 0, '1', '', false], - 'setAutoFilterByColumnAndRow' => [0, '1', 0, '1'], - 'freezePane' => [''], - 'freezePaneByColumnAndRow' => [0, '1'], - 'insertNewRowBefore' => ['1', '1'], - 'insertNewColumnBefore' => ['A', '1'], - 'insertNewColumnBeforeByIndex' => [0, '1'], - 'removeRow' => ['1', '1'], - 'removeColumn' => ['A', '1'], - 'removeColumnByIndex' => [0, '1'], - 'setShowGridlines' => [false], - 'setPrintGridlines' => [false], - 'setShowRowColHeaders' => [false], - 'setShowSummaryBelow' => [true], - 'setShowSummaryRight' => [true], - 'setComments' => [[]], - 'getComment' => ['A1'], - 'getCommentByColumnAndRow' => [0, '1'], - 'setSelectedCell' => ['A1'], - 'setSelectedCells' => ['A1'], - 'setSelectedCellByColumnAndRow' => [0, '1'], - 'setRightToLeft' => [false], - 'fromArray' => [null, null, 'A1', false], - 'rangeToArray' => ['A1', null, true, true, false], - 'namedRangeToArray' => ['', null, true, true, false], - 'getHyperlink' => ['A1'], - 'setHyperlink' => ['A1', null], - 'hyperlinkExists' => ['A1'], - 'getDataValidation' => ['A1'], - 'setDataValidation' => ['A1', null], - 'dataValidationExists' => ['A1'], - 'setCodeName' => [null], - ], - 'PHPExcel_Worksheet_AutoFilter' => [ - 'setRange' => [''], - 'getColumnByOffset' => [0], - 'shiftColumn' => [null, null], - ], - 'PHPExcel_Worksheet_AutoFilter_Column' => [ - 'setFilterType' => ['PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER'], - 'setJoin' => ['PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR'], - 'setAttributes' => [[]], - 'addRule' => [ - 1 => true, - ], - ], - 'PHPExcel_Worksheet_AutoFilter_Column_Rule' => [ - 'setRuleType' => ['PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER'], - 'setValue' => [''], - 'setOperator' => ['PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL'], - 'setGrouping' => [null], - 'setRule' => ['PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL', '', null], - ], - 'PHPExcel_Worksheet_BaseDrawing' => [ - 'setName' => [''], - 'setDescription' => [''], - 'setCoordinates' => ['A1'], - 'setOffsetX' => [0], - 'setOffsetY' => [0], - 'setWidth' => [0], - 'setHeight' => [0], - 'setWidthAndHeight' => [0, 0], - 'setResizeProportional' => [true], - 'setRotation' => [0], - ], - 'PHPExcel_Worksheet_CellIterator' => [ - 'setIterateOnlyExistingCells' => [true], - ], - 'PHPExcel_Worksheet_ColumnDimension' => [ - 'setWidth' => ['-1'], - 'setAutoSize' => [false], - ], - 'PHPExcel_Worksheet_Drawing' => [ - 'setPath' => ['', true], - ], - 'PHPExcel_Worksheet_Drawing_Shadow' => [ - 'setVisible' => [false], - 'setBlurRadius' => ['6'], - 'setDistance' => ['2'], - 'setDirection' => [0], - 'setAlignment' => [0], - 'setAlpha' => [0], - ], - 'PHPExcel_Worksheet_HeaderFooter' => [ - 'setDifferentOddEven' => [false], - 'setDifferentFirst' => [false], - 'setScaleWithDocument' => [true], - 'setAlignWithMargins' => [true], - ], - 'PHPExcel_Worksheet_HeaderFooterDrawing' => [ - 'setName' => [''], - 'setOffsetX' => [0], - 'setOffsetY' => [0], - 'setWidth' => [0], - 'setHeight' => [0], - 'setWidthAndHeight' => [0, 0], - 'setResizeProportional' => [true], - 'setPath' => ['', true], - ], - 'PHPExcel_Worksheet_MemoryDrawing' => [ - 'setImageResource' => [null], - 'setRenderingFunction' => ['PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT'], - 'setMimeType' => ['PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT'], - ], - 'PHPExcel_Worksheet_PageSetup' => [ - 'setPaperSize' => ['PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER'], - 'setOrientation' => ['PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT'], - 'setScale' => ['100', true], - 'setFitToPage' => [true], - 'setFitToHeight' => ['1', true], - 'setFitToWidth' => ['1', true], - 'setColumnsToRepeatAtLeft' => [null], - 'setColumnsToRepeatAtLeftByStartAndEnd' => ['A', 'A'], - 'setRowsToRepeatAtTop' => [null], - 'setRowsToRepeatAtTopByStartAndEnd' => ['1', '1'], - 'setHorizontalCentered' => [false], - 'setVerticalCentered' => [false], - 'setFirstPageNumber' => [null], - ], - 'PHPExcel_Worksheet_Protection' => [ - 'setSheet' => [false], - 'setObjects' => [false], - 'setScenarios' => [false], - 'setFormatCells' => [false], - 'setFormatColumns' => [false], - 'setFormatRows' => [false], - 'setInsertColumns' => [false], - 'setInsertRows' => [false], - 'setInsertHyperlinks' => [false], - 'setDeleteColumns' => [false], - 'setDeleteRows' => [false], - 'setSelectLockedCells' => [false], - 'setSort' => [false], - 'setAutoFilter' => [false], - 'setPivotTables' => [false], - 'setSelectUnlockedCells' => [false], - 'setPassword' => ['', false], - ], - 'PHPExcel_Worksheet_RowDimension' => [ - 'setRowHeight' => ['-1'], - 'setZeroHeight' => [false], - ], - 'PHPExcel_Worksheet_SheetView' => [ - 'setZoomScale' => ['100'], - 'setZoomScaleNormal' => ['100'], - 'setView' => [null], - ], - 'PHPExcel_Writer_Abstract' => [ - 'setIncludeCharts' => [false], - 'setPreCalculateFormulas' => [true], - 'setUseDiskCaching' => [false, null], - ], - 'PHPExcel_Writer_CSV' => [ - 'save' => [null], - 'setDelimiter' => [','], - 'setEnclosure' => ['\\'], - 'setLineEnding' => [PHP_EOL], - 'setUseBOM' => [false], - 'setIncludeSeparatorLine' => [false], - 'setExcelCompatibility' => [false], - 'setSheetIndex' => [0], - 'writeLine' => [null, null], - ], - 'PHPExcel_Writer_Excel2007' => [ - 'getWriterPart' => [''], - 'save' => [null], - 'setOffice2003Compatibility' => [false], - ], - 'PHPExcel_Writer_Excel2007_ContentTypes' => [ - 'getImageMimeType' => [''], - ], - 'PHPExcel_Writer_Excel2007_StringTable' => [ - 'writeStringTable' => [null], - 'flipStringTable' => [[]], - ], - 'PHPExcel_Writer_Excel5' => [ - 'save' => [null], - ], - 'PHPExcel_Writer_Excel5_Workbook' => [ - 'writeWorkbook' => [null], - ], - 'PHPExcel_Writer_Excel5_Worksheet' => [ - 'writeBIFF8CellRangeAddressFixed' => ['A1'], - ], - 'PHPExcel_Writer_HTML' => [ - 'save' => [null], - 'setSheetIndex' => [0], - 'setGenerateSheetNavigationBlock' => [true], - 'setImagesRoot' => ['.'], - 'setEmbedImages' => [true], - 'setUseInlineCss' => [false], - ], - 'PHPExcel_Writer_OpenDocument' => [ - 'getWriterPart' => [''], - 'save' => [null], - ], - 'PHPExcel_Writer_PDF' => [ - 'save' => [null], - ], - 'PHPExcel_Writer_PDF_Core' => [ - 'setPaperSize' => ['PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER'], - 'setOrientation' => ['PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT'], - 'setTempDir' => [''], - 'prepareForSave' => [null], - ], - 'PHPExcel_Writer_PDF_DomPDF' => [ - 'save' => [null], - ], - 'PHPExcel_Writer_PDF_mPDF' => [ - 'save' => [null], - ], - 'PHPExcel_Writer_PDF_tcPDF' => [ - 'save' => [null], - ], - ]; + public const METHOD_NAMES_BY_TYPE_WITH_VALUE = ['PHPExcel' => ['setHasMacros' => [\false], 'setMacrosCode' => [null], 'setMacrosCertificate' => [null], 'setRibbonXMLData' => [null, null], 'setRibbonBinObjects' => [null, null], 'getRibbonBinObjects' => ['all'], 'getSheetByCodeName' => [''], 'createSheet' => [null], 'removeSheetByIndex' => [0], 'getSheet' => [0], 'getSheetByName' => [''], 'setActiveSheetIndex' => [0], 'setActiveSheetIndexByName' => [''], 'getCellXfByIndex' => [0], 'getCellXfByHashCode' => [''], 'cellXfExists' => [null], 'removeCellXfByIndex' => [0], 'getCellStyleXfByIndex' => [0], 'getCellStyleXfByHashCode' => [''], 'removeCellStyleXfByIndex' => [0]], 'PHPExcel_CalcEngine_Logger' => ['setWriteDebugLog' => [\false], 'setEchoDebugLog' => [\false]], 'PHPExcel_Calculation' => ['setCalculationCacheEnabled' => [\true], 'setLocale' => ['en_us']], 'PHPExcel_Calculation_FormulaToken' => ['setTokenType' => ['PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN'], 'setTokenSubType' => ['PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING']], 'PHPExcel_Cell' => ['setValue' => [null], 'setValueExplicit' => [null, 'PHPExcel_Cell_DataType::TYPE_STRING'], 'setCalculatedValue' => [null], 'setDataType' => ['PHPExcel_Cell_DataType::TYPE_STRING'], 'isInRange' => ['A1:A1'], 'coordinateFromString' => ['A1'], 'absoluteReference' => ['A1'], 'absoluteCoordinate' => ['A1'], 'splitRange' => ['A1:A1'], 'rangeBoundaries' => ['A1:A1'], 'rangeDimension' => ['A1:A1'], 'getRangeBoundaries' => ['A1:A1'], 'columnIndexFromString' => ['A'], 'stringFromColumnIndex' => [0], 'extractAllCellReferencesInRange' => ['A1'], 'setXfIndex' => [0]], 'PHPExcel_Cell_DataType' => ['checkString' => [null], 'checkErrorCode' => [null]], 'PHPExcel_Cell_DataValidation' => ['setFormula1' => [''], 'setFormula2' => [''], 'setType' => ['PHPExcel_Cell_DataValidation::TYPE_NONE'], 'setErrorStyle' => ['PHPExcel_Cell_DataValidation::STYLE_STOP'], 'setOperator' => [''], 'setAllowBlank' => [\false], 'setShowDropDown' => [\false], 'setShowInputMessage' => [\false], 'setShowErrorMessage' => [\false], 'setErrorTitle' => [''], 'setError' => [''], 'setPromptTitle' => [''], 'setPrompt' => ['']], 'PHPExcel_Cell_DefaultValueBinder' => ['dataTypeForValue' => [null]], 'PHPExcel_Cell_Hyperlink' => ['setUrl' => [''], 'setTooltip' => ['']], 'PHPExcel_Chart' => ['setPlotVisibleOnly' => [\true], 'setDisplayBlanksAs' => ['0'], 'setTopLeftOffset' => [null, null], 'setBottomRightOffset' => [null, null]], 'PHPExcel_Chart_DataSeries' => ['setPlotType' => [''], 'setPlotGrouping' => [null], 'setPlotDirection' => [null], 'setPlotStyle' => [null], 'setSmoothLine' => [\true]], 'PHPExcel_Chart_DataSeriesValues' => ['setDataType' => ['PHPExcel_Chart_DataSeriesValues::DATASERIES_TYPE_NUMBER'], 'setDataSource' => [null, \true], 'setPointMarker' => [null], 'setFormatCode' => [null], 'setDataValues' => [[], \true]], 'PHPExcel_Chart_Layout' => ['__construct' => [[]]], 'PHPExcel_Chart_Legend' => ['setPosition' => ['PHPExcel_Chart_Legend::POSITION_RIGHT'], 'setPositionXL' => ['PHPExcel_Chart_Legend::XL_LEGEND_POSITION_RIGHT'], 'setOverlay' => [\false]], 'PHPExcel_Chart_PlotArea' => ['__construct' => [null, []], 'setPlotSeries' => [[]]], 'PHPExcel_Chart_Title' => ['setCaption' => [null]], 'PHPExcel_Comment' => ['setAuthor' => [''], 'setWidth' => ['96pt'], 'setHeight' => ['55.5pt'], 'setMarginLeft' => ['59.25pt'], 'setMarginTop' => ['1.5pt'], 'setVisible' => [\false], 'setAlignment' => ['Style\\Alignment::HORIZONTAL_GENERAL']], 'PHPExcel_DocumentProperties' => ['setCreator' => [''], 'setLastModifiedBy' => [''], 'setCreated' => [null], 'setModified' => [null], 'setTitle' => [''], 'setDescription' => [''], 'setSubject' => [''], 'setKeywords' => [''], 'setCategory' => [''], 'setCompany' => [''], 'setManager' => ['']], 'PHPExcel_DocumentSecurity' => ['setLockRevision' => [\false], 'setLockStructure' => [\false], 'setLockWindows' => [\false], 'setRevisionsPassword' => ['', \false], 'setWorkbookPassword' => ['', \false]], 'PHPExcel_HashTable' => ['addFromSource' => [null], 'getIndexForHashCode' => [''], 'getByIndex' => [0], 'getByHashCode' => ['']], 'PHPExcel_IOFactory' => ['addSearchLocation' => ['', '', ''], 'createReader' => ['']], 'PHPExcel_NamedRange' => ['setName' => [null], 'setRange' => [null], 'setLocalOnly' => [\false]], 'PHPExcel_Reader_Abstract' => ['setReadDataOnly' => [\false], 'setReadEmptyCells' => [\true], 'setIncludeCharts' => [\false], 'setLoadSheetsOnly' => [null]], 'PHPExcel_Reader_CSV' => ['setInputEncoding' => ['UTF-8'], 'setDelimiter' => [','], 'setEnclosure' => ['\\'], 'setSheetIndex' => [0], 'setContiguous' => [\false]], 'PHPExcel_Reader_Excel2003XML' => ['parseRichText' => ['']], 'PHPExcel_Reader_Excel2007' => ['parseRichText' => [null], 'boolean' => [null]], 'PHPExcel_Reader_Excel2007_Chart' => ['parseRichText' => [null]], 'PHPExcel_Reader_Excel2007_Theme' => ['getColourByIndex' => [0]], 'PHPExcel_Reader_Excel5' => ['parseRichText' => ['']], 'PHPExcel_Reader_Gnumeric' => ['parseRichText' => ['']], 'PHPExcel_Reader_HTML' => ['setInputEncoding' => ['ANSI'], 'setSheetIndex' => [0]], 'PHPExcel_Reader_OOCalc' => ['parseRichText' => ['']], 'PHPExcel_Reader_SYLK' => ['setInputEncoding' => ['ANSI'], 'setSheetIndex' => [0]], 'PHPExcel_RichText' => ['createText' => [''], 'createTextRun' => [''], 'setRichTextElements' => [null]], 'PHPExcel_RichText_TextElement' => ['setText' => ['']], 'PHPExcel_Settings' => ['setLocale' => ['en_us'], 'setLibXmlLoaderOptions' => [null]], 'PHPExcel_Shared_CodePage' => ['numberToName' => ['1252']], 'PHPExcel_Shared_Date' => ['excelToDateTimeObject' => [0, null], 'excelToTimestamp' => [0, null], 'PHPToExcel' => [0], 'timestampToExcel' => [0], 'isDateTimeFormatCode' => [''], 'stringToExcel' => ['']], 'PHPExcel_Shared_Drawing' => ['pixelsToEMU' => [0], 'EMUToPixels' => [0], 'pixelsToPoints' => [0], 'pointsToPixels' => [0], 'degreesToAngle' => [0], 'angleToDegrees' => [0]], 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer' => ['setSpgr' => [\false], 'setStartCoordinates' => ['A1'], 'setStartOffsetX' => [0], 'setStartOffsetY' => [0], 'setEndCoordinates' => ['A1'], 'setEndOffsetX' => [0], 'setEndOffsetY' => [0]], 'PHPExcel_Shared_File' => ['setUseUploadTempDirectory' => [\false]], 'PHPExcel_Shared_Font' => ['setAutoSizeMethod' => ['PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX'], 'setTrueTypeFontPath' => [''], 'fontSizeToPixels' => ['11'], 'inchSizeToPixels' => ['1'], 'centimeterSizeToPixels' => ['1']], 'PHPExcel_Shared_OLE' => ['localDateToOLE' => [null]], 'PHPExcel_Shared_PasswordHasher' => ['hashPassword' => ['']], 'PHPExcel_Shared_String' => ['controlCharacterOOXML2PHP' => [''], 'controlCharacterPHP2OOXML' => [''], 'isUTF8' => [''], 'substring' => ['', 0, 0], 'strToUpper' => [''], 'strToLower' => [''], 'strToTitle' => [''], 'strCaseReverse' => [''], 'setDecimalSeparator' => ['.'], 'setThousandsSeparator' => [','], 'setCurrencyCode' => ['$'], 'SYLKtoUTF8' => ['']], 'PHPExcel_Style' => ['applyFromArray' => [null, \true], 'setConditionalStyles' => [null]], 'PHPExcel_Style_Alignment' => ['applyFromArray' => [null], 'setHorizontal' => ['PHPExcel_Style_Alignment::HORIZONTAL_GENERAL'], 'setVertical' => ['PHPExcel_Style_Alignment::VERTICAL_BOTTOM'], 'setTextRotation' => [0], 'setWrapText' => [\false], 'setShrinkToFit' => [\false], 'setIndent' => [0], 'setReadorder' => [0]], 'PHPExcel_Style_Border' => ['applyFromArray' => [null], 'setBorderStyle' => ['PHPExcel_Style_Border::BORDER_NONE']], 'PHPExcel_Style_Borders' => ['applyFromArray' => [null], 'setDiagonalDirection' => ['PHPExcel_Style_Borders::DIAGONAL_NONE']], 'PHPExcel_Style_Color' => ['applyFromArray' => [null], 'setARGB' => ['PHPExcel_Style_Color::COLOR_BLACK'], 'setRGB' => ['000000']], 'PHPExcel_Style_Conditional' => ['setConditionType' => ['PHPExcel_Style_Conditional::CONDITION_NONE'], 'setOperatorType' => ['PHPExcel_Style_Conditional::OPERATOR_NONE'], 'setText' => [null], 'addCondition' => ['']], 'PHPExcel_Style_Fill' => ['applyFromArray' => [null], 'setFillType' => ['PHPExcel_Style_Fill::FILL_NONE'], 'setRotation' => [0]], 'PHPExcel_Style_Font' => ['applyFromArray' => [null], 'setName' => ['Calibri'], 'setSize' => ['10'], 'setBold' => [\false], 'setItalic' => [\false], 'setSuperScript' => [\false], 'setSubScript' => [\false], 'setUnderline' => ['PHPExcel_Style_Font::UNDERLINE_NONE'], 'setStrikethrough' => [\false]], 'PHPExcel_Style_NumberFormat' => ['applyFromArray' => [null], 'setFormatCode' => ['PHPExcel_Style_NumberFormat::FORMAT_GENERAL'], 'setBuiltInFormatCode' => [0], 'toFormattedString' => ['0', 'PHPExcel_Style_NumberFormat::FORMAT_GENERAL', null]], 'PHPExcel_Style_Protection' => ['applyFromArray' => [null], 'setLocked' => ['PHPExcel_Style_Protection::PROTECTION_INHERIT'], 'setHidden' => ['PHPExcel_Style_Protection::PROTECTION_INHERIT']], 'PHPExcel_Worksheet' => ['getChartByIndex' => [null], 'getChartByName' => [''], 'setTitle' => ['Worksheet', \true], 'setSheetState' => ['PHPExcel_Worksheet::SHEETSTATE_VISIBLE'], 'setCellValue' => ['A1', null, \false], 'setCellValueByColumnAndRow' => [0, '1', null, \false], 'setCellValueExplicit' => ['A1', null, 'PHPExcel_Cell_DataType::TYPE_STRING', \false], 'setCellValueExplicitByColumnAndRow' => [0, '1', null, 'PHPExcel_Cell_DataType::TYPE_STRING', \false], 'getCell' => ['A1', \true], 'getCellByColumnAndRow' => [0, '1', \true], 'cellExists' => ['A1'], 'cellExistsByColumnAndRow' => [0, '1'], 'getRowDimension' => ['1', \true], 'getColumnDimension' => ['A', \true], 'getColumnDimensionByColumn' => [0], 'getStyle' => ['A1'], 'getConditionalStyles' => ['A1'], 'conditionalStylesExists' => ['A1'], 'removeConditionalStyles' => ['A1'], 'getStyleByColumnAndRow' => [0, '1', null, null], 'setBreak' => ['A1', 'PHPExcel_Worksheet::BREAK_NONE'], 'setBreakByColumnAndRow' => [0, '1', 'PHPExcel_Worksheet::BREAK_NONE'], 'mergeCells' => ['A1:A1'], 'mergeCellsByColumnAndRow' => [0, '1', 0, '1'], 'unmergeCells' => ['A1:A1'], 'unmergeCellsByColumnAndRow' => [0, '1', 0, '1'], 'setMergeCells' => [[]], 'protectCells' => ['A1', '', \false], 'protectCellsByColumnAndRow' => [0, '1', 0, '1', '', \false], 'unprotectCells' => ['A1'], 'unprotectCellsByColumnAndRow' => [0, '1', 0, '1', '', \false], 'setAutoFilterByColumnAndRow' => [0, '1', 0, '1'], 'freezePane' => [''], 'freezePaneByColumnAndRow' => [0, '1'], 'insertNewRowBefore' => ['1', '1'], 'insertNewColumnBefore' => ['A', '1'], 'insertNewColumnBeforeByIndex' => [0, '1'], 'removeRow' => ['1', '1'], 'removeColumn' => ['A', '1'], 'removeColumnByIndex' => [0, '1'], 'setShowGridlines' => [\false], 'setPrintGridlines' => [\false], 'setShowRowColHeaders' => [\false], 'setShowSummaryBelow' => [\true], 'setShowSummaryRight' => [\true], 'setComments' => [[]], 'getComment' => ['A1'], 'getCommentByColumnAndRow' => [0, '1'], 'setSelectedCell' => ['A1'], 'setSelectedCells' => ['A1'], 'setSelectedCellByColumnAndRow' => [0, '1'], 'setRightToLeft' => [\false], 'fromArray' => [null, null, 'A1', \false], 'rangeToArray' => ['A1', null, \true, \true, \false], 'namedRangeToArray' => ['', null, \true, \true, \false], 'getHyperlink' => ['A1'], 'setHyperlink' => ['A1', null], 'hyperlinkExists' => ['A1'], 'getDataValidation' => ['A1'], 'setDataValidation' => ['A1', null], 'dataValidationExists' => ['A1'], 'setCodeName' => [null]], 'PHPExcel_Worksheet_AutoFilter' => ['setRange' => [''], 'getColumnByOffset' => [0], 'shiftColumn' => [null, null]], 'PHPExcel_Worksheet_AutoFilter_Column' => ['setFilterType' => ['PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER'], 'setJoin' => ['PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR'], 'setAttributes' => [[]], 'addRule' => [1 => \true]], 'PHPExcel_Worksheet_AutoFilter_Column_Rule' => ['setRuleType' => ['PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER'], 'setValue' => [''], 'setOperator' => ['PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL'], 'setGrouping' => [null], 'setRule' => ['PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL', '', null]], 'PHPExcel_Worksheet_BaseDrawing' => ['setName' => [''], 'setDescription' => [''], 'setCoordinates' => ['A1'], 'setOffsetX' => [0], 'setOffsetY' => [0], 'setWidth' => [0], 'setHeight' => [0], 'setWidthAndHeight' => [0, 0], 'setResizeProportional' => [\true], 'setRotation' => [0]], 'PHPExcel_Worksheet_CellIterator' => ['setIterateOnlyExistingCells' => [\true]], 'PHPExcel_Worksheet_ColumnDimension' => ['setWidth' => ['-1'], 'setAutoSize' => [\false]], 'PHPExcel_Worksheet_Drawing' => ['setPath' => ['', \true]], 'PHPExcel_Worksheet_Drawing_Shadow' => ['setVisible' => [\false], 'setBlurRadius' => ['6'], 'setDistance' => ['2'], 'setDirection' => [0], 'setAlignment' => [0], 'setAlpha' => [0]], 'PHPExcel_Worksheet_HeaderFooter' => ['setDifferentOddEven' => [\false], 'setDifferentFirst' => [\false], 'setScaleWithDocument' => [\true], 'setAlignWithMargins' => [\true]], 'PHPExcel_Worksheet_HeaderFooterDrawing' => ['setName' => [''], 'setOffsetX' => [0], 'setOffsetY' => [0], 'setWidth' => [0], 'setHeight' => [0], 'setWidthAndHeight' => [0, 0], 'setResizeProportional' => [\true], 'setPath' => ['', \true]], 'PHPExcel_Worksheet_MemoryDrawing' => ['setImageResource' => [null], 'setRenderingFunction' => ['PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT'], 'setMimeType' => ['PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT']], 'PHPExcel_Worksheet_PageSetup' => ['setPaperSize' => ['PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER'], 'setOrientation' => ['PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT'], 'setScale' => ['100', \true], 'setFitToPage' => [\true], 'setFitToHeight' => ['1', \true], 'setFitToWidth' => ['1', \true], 'setColumnsToRepeatAtLeft' => [null], 'setColumnsToRepeatAtLeftByStartAndEnd' => ['A', 'A'], 'setRowsToRepeatAtTop' => [null], 'setRowsToRepeatAtTopByStartAndEnd' => ['1', '1'], 'setHorizontalCentered' => [\false], 'setVerticalCentered' => [\false], 'setFirstPageNumber' => [null]], 'PHPExcel_Worksheet_Protection' => ['setSheet' => [\false], 'setObjects' => [\false], 'setScenarios' => [\false], 'setFormatCells' => [\false], 'setFormatColumns' => [\false], 'setFormatRows' => [\false], 'setInsertColumns' => [\false], 'setInsertRows' => [\false], 'setInsertHyperlinks' => [\false], 'setDeleteColumns' => [\false], 'setDeleteRows' => [\false], 'setSelectLockedCells' => [\false], 'setSort' => [\false], 'setAutoFilter' => [\false], 'setPivotTables' => [\false], 'setSelectUnlockedCells' => [\false], 'setPassword' => ['', \false]], 'PHPExcel_Worksheet_RowDimension' => ['setRowHeight' => ['-1'], 'setZeroHeight' => [\false]], 'PHPExcel_Worksheet_SheetView' => ['setZoomScale' => ['100'], 'setZoomScaleNormal' => ['100'], 'setView' => [null]], 'PHPExcel_Writer_Abstract' => ['setIncludeCharts' => [\false], 'setPreCalculateFormulas' => [\true], 'setUseDiskCaching' => [\false, null]], 'PHPExcel_Writer_CSV' => ['save' => [null], 'setDelimiter' => [','], 'setEnclosure' => ['\\'], 'setLineEnding' => [\PHP_EOL], 'setUseBOM' => [\false], 'setIncludeSeparatorLine' => [\false], 'setExcelCompatibility' => [\false], 'setSheetIndex' => [0], 'writeLine' => [null, null]], 'PHPExcel_Writer_Excel2007' => ['getWriterPart' => [''], 'save' => [null], 'setOffice2003Compatibility' => [\false]], 'PHPExcel_Writer_Excel2007_ContentTypes' => ['getImageMimeType' => ['']], 'PHPExcel_Writer_Excel2007_StringTable' => ['writeStringTable' => [null], 'flipStringTable' => [[]]], 'PHPExcel_Writer_Excel5' => ['save' => [null]], 'PHPExcel_Writer_Excel5_Workbook' => ['writeWorkbook' => [null]], 'PHPExcel_Writer_Excel5_Worksheet' => ['writeBIFF8CellRangeAddressFixed' => ['A1']], 'PHPExcel_Writer_HTML' => ['save' => [null], 'setSheetIndex' => [0], 'setGenerateSheetNavigationBlock' => [\true], 'setImagesRoot' => ['.'], 'setEmbedImages' => [\true], 'setUseInlineCss' => [\false]], 'PHPExcel_Writer_OpenDocument' => ['getWriterPart' => [''], 'save' => [null]], 'PHPExcel_Writer_PDF' => ['save' => [null]], 'PHPExcel_Writer_PDF_Core' => ['setPaperSize' => ['PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER'], 'setOrientation' => ['PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT'], 'setTempDir' => [''], 'prepareForSave' => [null]], 'PHPExcel_Writer_PDF_DomPDF' => ['save' => [null]], 'PHPExcel_Writer_PDF_mPDF' => ['save' => [null]], 'PHPExcel_Writer_PDF_tcPDF' => ['save' => [null]]]; } diff --git a/rules/PSR4/Collector/RenamedClassesCollector.php b/rules/PSR4/Collector/RenamedClassesCollector.php index c114db3750b..f00e890446c 100644 --- a/rules/PSR4/Collector/RenamedClassesCollector.php +++ b/rules/PSR4/Collector/RenamedClassesCollector.php @@ -1,11 +1,9 @@ */ private $oldToNewClass = []; - /** * @var RenamedClassesDataCollector */ private $renamedClassesDataCollector; - - public function __construct(RenamedClassesDataCollector $renamedClassesDataCollector) + public function __construct(\Rector\Core\Configuration\RenamedClassesDataCollector $renamedClassesDataCollector) { $this->renamedClassesDataCollector = $renamedClassesDataCollector; } - - public function addClassRename(string $oldClass, string $newClass): void + public function addClassRename(string $oldClass, string $newClass) : void { $this->oldToNewClass[$oldClass] = $newClass; } - /** * @return array */ - public function getOldToNewClasses(): array + public function getOldToNewClasses() : array { - return array_merge($this->oldToNewClass, $this->renamedClassesDataCollector->getOldToNewClasses()); + return \array_merge($this->oldToNewClass, $this->renamedClassesDataCollector->getOldToNewClasses()); } } diff --git a/rules/PSR4/Composer/PSR4AutoloadPathsProvider.php b/rules/PSR4/Composer/PSR4AutoloadPathsProvider.php index c97043bca1b..5a04ec8fd58 100644 --- a/rules/PSR4/Composer/PSR4AutoloadPathsProvider.php +++ b/rules/PSR4/Composer/PSR4AutoloadPathsProvider.php @@ -1,63 +1,50 @@ > */ private $cachedComposerJsonPSR4AutoloadPaths = []; - /** * @var JsonFileSystem */ private $jsonFileSystem; - - public function __construct(JsonFileSystem $jsonFileSystem) + public function __construct(\RectorPrefix20210509\Symplify\SmartFileSystem\Json\JsonFileSystem $jsonFileSystem) { $this->jsonFileSystem = $jsonFileSystem; } - /** * @return array */ - public function provide(): array + public function provide() : array { if ($this->cachedComposerJsonPSR4AutoloadPaths !== []) { return $this->cachedComposerJsonPSR4AutoloadPaths; } - $composerJson = $this->jsonFileSystem->loadFilePathToJson($this->getComposerJsonPath()); - $psr4Autoloads = array_merge( - $composerJson[ComposerJsonSection::AUTOLOAD]['psr-4'] ?? [], - $composerJson[ComposerJsonSection::AUTOLOAD_DEV]['psr-4'] ?? [] - ); - + $psr4Autoloads = \array_merge($composerJson[\RectorPrefix20210509\Symplify\ComposerJsonManipulator\ValueObject\ComposerJsonSection::AUTOLOAD]['psr-4'] ?? [], $composerJson[\RectorPrefix20210509\Symplify\ComposerJsonManipulator\ValueObject\ComposerJsonSection::AUTOLOAD_DEV]['psr-4'] ?? []); $this->cachedComposerJsonPSR4AutoloadPaths = $this->removeEmptyNamespaces($psr4Autoloads); - return $this->cachedComposerJsonPSR4AutoloadPaths; } - - private function getComposerJsonPath(): string + private function getComposerJsonPath() : string { // assume the project has "composer.json" in root directory - return getcwd() . '/composer.json'; + return \getcwd() . '/composer.json'; } - /** * @param array> $psr4Autoloads * @return array> */ - private function removeEmptyNamespaces(array $psr4Autoloads): array + private function removeEmptyNamespaces(array $psr4Autoloads) : array { - return array_filter($psr4Autoloads, function (string $psr4Autoload): bool { + return \array_filter($psr4Autoloads, function (string $psr4Autoload) : bool { return $psr4Autoload !== ''; - }, ARRAY_FILTER_USE_KEY); + }, \ARRAY_FILTER_USE_KEY); } } diff --git a/rules/PSR4/Composer/PSR4NamespaceMatcher.php b/rules/PSR4/Composer/PSR4NamespaceMatcher.php index e0ae94af191..29c361c029c 100644 --- a/rules/PSR4/Composer/PSR4NamespaceMatcher.php +++ b/rules/PSR4/Composer/PSR4NamespaceMatcher.php @@ -1,59 +1,48 @@ psr4AutoloadPathsProvider = $psr4AutoloadPathsProvider; } - - public function getExpectedNamespace(File $file, Node $node): ?string + public function getExpectedNamespace(\Rector\Core\ValueObject\Application\File $file, \PhpParser\Node $node) : ?string { $smartFileInfo = $file->getSmartFileInfo(); $psr4Autoloads = $this->psr4AutoloadPathsProvider->provide(); - foreach ($psr4Autoloads as $namespace => $path) { // remove extra slash - $paths = is_array($path) ? $path : [$path]; - + $paths = \is_array($path) ? $path : [$path]; foreach ($paths as $path) { - $path = rtrim($path, '/'); - if (! Strings::startsWith($smartFileInfo->getRelativeDirectoryPath(), $path)) { + $path = \rtrim($path, '/'); + if (!\RectorPrefix20210509\Nette\Utils\Strings::startsWith($smartFileInfo->getRelativeDirectoryPath(), $path)) { continue; } - $expectedNamespace = $namespace . $this->resolveExtraNamespace($smartFileInfo, $path); - - return rtrim($expectedNamespace, '\\'); + return \rtrim($expectedNamespace, '\\'); } } - return null; } - /** * Get the extra path that is not included in root PSR-4 namespace */ - private function resolveExtraNamespace(SmartFileInfo $smartFileInfo, string $path): string + private function resolveExtraNamespace(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo, string $path) : string { - $extraNamespace = Strings::substring($smartFileInfo->getRelativeDirectoryPath(), Strings::length($path) + 1); - $extraNamespace = Strings::replace($extraNamespace, '#/#', '\\'); - - return trim($extraNamespace); + $extraNamespace = \RectorPrefix20210509\Nette\Utils\Strings::substring($smartFileInfo->getRelativeDirectoryPath(), \RectorPrefix20210509\Nette\Utils\Strings::length($path) + 1); + $extraNamespace = \RectorPrefix20210509\Nette\Utils\Strings::replace($extraNamespace, '#/#', '\\'); + return \trim($extraNamespace); } } diff --git a/rules/PSR4/Contract/PSR4AutoloadNamespaceMatcherInterface.php b/rules/PSR4/Contract/PSR4AutoloadNamespaceMatcherInterface.php index d1d78496342..c4e359ba39a 100644 --- a/rules/PSR4/Contract/PSR4AutoloadNamespaceMatcherInterface.php +++ b/rules/PSR4/Contract/PSR4AutoloadNamespaceMatcherInterface.php @@ -1,13 +1,11 @@ nodeNameResolver = $nodeNameResolver; $this->classNaming = $classNaming; } - - public function isClassLikeAndFileInfoMatch(File $file, ClassLike $classLike): bool + public function isClassLikeAndFileInfoMatch(\Rector\Core\ValueObject\Application\File $file, \PhpParser\Node\Stmt\ClassLike $classLike) : bool { $className = $this->nodeNameResolver->getName($classLike); if ($className === null) { - return false; + return \false; } - $smartFileInfo = $file->getSmartFileInfo(); - $baseFileName = $this->clearNameFromTestingPrefix($smartFileInfo->getBasenameWithoutSuffix()); $classShortName = $this->classNaming->getShortName($className); - return $baseFileName === $classShortName; } - - public function clearNameFromTestingPrefix(string $name): string + public function clearNameFromTestingPrefix(string $name) : string { - return Strings::replace($name, self::TESTING_PREFIX_REGEX, ''); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($name, self::TESTING_PREFIX_REGEX, ''); } } diff --git a/rules/PSR4/FileRelocationResolver.php b/rules/PSR4/FileRelocationResolver.php index 7491aa73932..009634ef757 100644 --- a/rules/PSR4/FileRelocationResolver.php +++ b/rules/PSR4/FileRelocationResolver.php @@ -1,15 +1,13 @@ fileInfoDeletionAnalyzer = $fileInfoDeletionAnalyzer; } - /** * @param string[] $groupNames */ - public function createNewFileDestination( - SmartFileInfo $smartFileInfo, - string $suffixName, - array $groupNames - ): string { + public function createNewFileDestination(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo, string $suffixName, array $groupNames) : string + { $newDirectory = $this->resolveRootDirectory($smartFileInfo, $suffixName, $groupNames); $filename = $this->fileInfoDeletionAnalyzer->clearNameFromTestingPrefix($smartFileInfo->getFilename()); - return $newDirectory . DIRECTORY_SEPARATOR . $filename; + return $newDirectory . \DIRECTORY_SEPARATOR . $filename; } - /** * @param string[] $groupNames */ - public function resolveNewNamespaceName(Namespace_ $namespace, string $suffixName, array $groupNames): string + public function resolveNewNamespaceName(\PhpParser\Node\Stmt\Namespace_ $namespace, string $suffixName, array $groupNames) : string { /** @var Name $name */ $name = $namespace->name; $currentNamespaceParts = $name->parts; - - return $this->resolveNearestRootWithCategory( - $currentNamespaceParts, - $suffixName, - self::NAMESPACE_SEPARATOR, - $groupNames - ); + return $this->resolveNearestRootWithCategory($currentNamespaceParts, $suffixName, self::NAMESPACE_SEPARATOR, $groupNames); } - - public function resolveNewFileLocationFromOldClassToNewClass( - SmartFileInfo $smartFileInfo, - string $oldClass, - string $newClass - ): string { + public function resolveNewFileLocationFromOldClassToNewClass(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo, string $oldClass, string $newClass) : string + { $beforeToAfterPart = $this->resolveBeforeToAfterPartBetweenClassNames($oldClass, $newClass); - return $this->replaceRelativeFilePathsWithBeforeAfter($smartFileInfo, $beforeToAfterPart); } - /** * @param string[] $groupNames */ - private function resolveRootDirectory(SmartFileInfo $smartFileInfo, string $suffixName, array $groupNames): string + private function resolveRootDirectory(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo, string $suffixName, array $groupNames) : string { - if (Strings::startsWith($smartFileInfo->getRealPathDirectory(), '/tmp')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::startsWith($smartFileInfo->getRealPathDirectory(), '/tmp')) { $currentTraversePath = $smartFileInfo->getRealPathDirectory(); } else { $currentTraversePath = $smartFileInfo->getRelativeDirectoryPath(); } - - $currentDirectoryParts = explode(DIRECTORY_SEPARATOR, $currentTraversePath); - - return $this->resolveNearestRootWithCategory( - $currentDirectoryParts, - $suffixName, - DIRECTORY_SEPARATOR, - $groupNames - ); + $currentDirectoryParts = \explode(\DIRECTORY_SEPARATOR, $currentTraversePath); + return $this->resolveNearestRootWithCategory($currentDirectoryParts, $suffixName, \DIRECTORY_SEPARATOR, $groupNames); } - /** * @param string[] $groupNames * @param string[] $nameParts */ - private function resolveNearestRootWithCategory( - array $nameParts, - string $suffixName, - string $separator, - array $groupNames - ): string { - $reversedNameParts = array_reverse($nameParts); - + private function resolveNearestRootWithCategory(array $nameParts, string $suffixName, string $separator, array $groupNames) : string + { + $reversedNameParts = \array_reverse($nameParts); $removedParts = []; - $hasStopped = false; - + $hasStopped = \false; foreach ($reversedNameParts as $key => $reversedNamePart) { unset($reversedNameParts[$key]); - - if (in_array($reversedNamePart, $groupNames, true)) { - $hasStopped = true; + if (\in_array($reversedNamePart, $groupNames, \true)) { + $hasStopped = \true; break; } - $removedParts[] = $reversedNamePart; } - - if (! $hasStopped) { + if (!$hasStopped) { $rootNameParts = $nameParts; $rootNameParts[] = $suffixName; } else { - $rootNameParts = array_reverse($reversedNameParts); + $rootNameParts = \array_reverse($reversedNameParts); $rootNameParts[] = $suffixName; - if ($removedParts !== []) { - $rootNameParts = array_merge($rootNameParts, $removedParts); + $rootNameParts = \array_merge($rootNameParts, $removedParts); } } - - return implode($separator, $rootNameParts); + return \implode($separator, $rootNameParts); } - /** * @return string[] */ - private function resolveBeforeToAfterPartBetweenClassNames(string $oldClass, string $newClass): array + private function resolveBeforeToAfterPartBetweenClassNames(string $oldClass, string $newClass) : array { - $oldClassNameParts = explode(self::NAMESPACE_SEPARATOR, $oldClass); - $newClassNameParts = explode(self::NAMESPACE_SEPARATOR, $newClass); - + $oldClassNameParts = \explode(self::NAMESPACE_SEPARATOR, $oldClass); + $newClassNameParts = \explode(self::NAMESPACE_SEPARATOR, $newClass); $beforeToAfterParts = []; foreach ($oldClassNameParts as $key => $oldClassNamePart) { - if (! isset($newClassNameParts[$key])) { + if (!isset($newClassNameParts[$key])) { continue; } - $newClassNamePart = $newClassNameParts[$key]; if ($oldClassNamePart === $newClassNamePart) { continue; } - $beforeToAfterParts[$oldClassNamePart] = $newClassNamePart; } - return $beforeToAfterParts; } - /** * @param string[] $beforeToAfterPart */ - private function replaceRelativeFilePathsWithBeforeAfter( - SmartFileInfo $oldSmartFileInfo, - array $beforeToAfterPart - ): string { + private function replaceRelativeFilePathsWithBeforeAfter(\Symplify\SmartFileSystem\SmartFileInfo $oldSmartFileInfo, array $beforeToAfterPart) : string + { // A. first "dir has changed" dummy detection - $relativeFilePathParts = Strings::split( - $oldSmartFileInfo->getRelativeFilePath(), - '#' . DIRECTORY_SEPARATOR . '#' - ); - + $relativeFilePathParts = \RectorPrefix20210509\Nette\Utils\Strings::split($oldSmartFileInfo->getRelativeFilePath(), '#' . \DIRECTORY_SEPARATOR . '#'); foreach ($relativeFilePathParts as $key => $relativeFilePathPart) { - if (! isset($beforeToAfterPart[$relativeFilePathPart])) { + if (!isset($beforeToAfterPart[$relativeFilePathPart])) { continue; } - $relativeFilePathParts[$key] = $beforeToAfterPart[$relativeFilePathPart]; - // clear from further use unset($beforeToAfterPart[$relativeFilePathPart]); } - - return implode(DIRECTORY_SEPARATOR, $relativeFilePathParts); + return \implode(\DIRECTORY_SEPARATOR, $relativeFilePathParts); } } diff --git a/rules/PSR4/NodeManipulator/FullyQualifyStmtsAnalyzer.php b/rules/PSR4/NodeManipulator/FullyQualifyStmtsAnalyzer.php index 86a17b6c269..550b350154a 100644 --- a/rules/PSR4/NodeManipulator/FullyQualifyStmtsAnalyzer.php +++ b/rules/PSR4/NodeManipulator/FullyQualifyStmtsAnalyzer.php @@ -1,7 +1,6 @@ parameterProvider = $parameterProvider; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; } - /** * @param Stmt[] $nodes */ - public function process(array $nodes): void + public function process(array $nodes) : void { // no need to - if ($this->parameterProvider->provideBoolParameter(Option::AUTO_IMPORT_NAMES)) { + if ($this->parameterProvider->provideBoolParameter(\Rector\Core\Configuration\Option::AUTO_IMPORT_NAMES)) { return; } - // FQNize all class names - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (Node $node): ?FullyQualified { - if (! $node instanceof Name) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (\PhpParser\Node $node) : ?FullyQualified { + if (!$node instanceof \PhpParser\Node\Name) { return null; } - $fullyQualifiedName = $this->nodeNameResolver->getName($node); - if (in_array($fullyQualifiedName, ['self', 'parent', 'static'], true)) { + if (\in_array($fullyQualifiedName, ['self', 'parent', 'static'], \true)) { return null; } - if ($this->isNativeConstant($node)) { return null; } - - return new FullyQualified($fullyQualifiedName); + return new \PhpParser\Node\Name\FullyQualified($fullyQualifiedName); }); } - - private function isNativeConstant(Name $name): bool + private function isNativeConstant(\PhpParser\Node\Name $name) : bool { - $parent = $name->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof ConstFetch) { - return false; + $parent = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Expr\ConstFetch) { + return \false; } - - $scope = $name->getAttribute(AttributeKey::SCOPE); - if (! $this->reflectionProvider->hasConstant($name, $scope)) { - return false; + $scope = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$this->reflectionProvider->hasConstant($name, $scope)) { + return \false; } - $constantReflection = $this->reflectionProvider->getConstant($name, $scope); - return $constantReflection instanceof RuntimeConstantReflection; + return $constantReflection instanceof \PHPStan\Reflection\Constant\RuntimeConstantReflection; } } diff --git a/rules/PSR4/NodeManipulator/NamespaceManipulator.php b/rules/PSR4/NodeManipulator/NamespaceManipulator.php index 364f224bbfb..fb0c805f9fc 100644 --- a/rules/PSR4/NodeManipulator/NamespaceManipulator.php +++ b/rules/PSR4/NodeManipulator/NamespaceManipulator.php @@ -1,21 +1,18 @@ stmts as $key => $namespaceStatement) { - if (! $namespaceStatement instanceof ClassLike) { + if (!$namespaceStatement instanceof \PhpParser\Node\Stmt\ClassLike) { continue; } - unset($namespace->stmts[$key]); } } diff --git a/rules/PSR4/Rector/FileWithoutNamespace/NormalizeNamespaceByPSR4ComposerAutoloadRector.php b/rules/PSR4/Rector/FileWithoutNamespace/NormalizeNamespaceByPSR4ComposerAutoloadRector.php index 7e19f98cb06..4e735d69457 100644 --- a/rules/PSR4/Rector/FileWithoutNamespace/NormalizeNamespaceByPSR4ComposerAutoloadRector.php +++ b/rules/PSR4/Rector/FileWithoutNamespace/NormalizeNamespaceByPSR4ComposerAutoloadRector.php @@ -1,7 +1,6 @@ psr4AutoloadNamespaceMatcher = $psr4AutoloadNamespaceMatcher; $this->fullyQualifyStmtsAnalyzer = $fullyQualifyStmtsAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - $description = sprintf( - 'Adds namespace to namespace-less files or correct namespace to match PSR-4 in `composer.json` autoload section. Run with combination with "%s"', - MultipleClassFileToPsr4ClassesRector::class - ); - - return new RuleDefinition($description, [ - new ComposerJsonAwareCodeSample( - <<<'CODE_SAMPLE' + $description = \sprintf('Adds namespace to namespace-less files or correct namespace to match PSR-4 in `composer.json` autoload section. Run with combination with "%s"', \Rector\PSR4\Rector\Namespace_\MultipleClassFileToPsr4ClassesRector::class); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition($description, [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ComposerJsonAwareCodeSample(<<<'CODE_SAMPLE' // src/SomeClass.php class SomeClass { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' // src/SomeClass.php namespace App\CustomNamespace; @@ -65,8 +51,7 @@ class SomeClass { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' { "autoload": { "psr-4": { @@ -75,64 +60,50 @@ CODE_SAMPLE } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Namespace_::class, FileWithoutNamespace::class]; + return [\PhpParser\Node\Stmt\Namespace_::class, \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace::class]; } - /** * @param FileWithoutNamespace|Namespace_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $expectedNamespace = $this->psr4AutoloadNamespaceMatcher->getExpectedNamespace($this->file, $node); if ($expectedNamespace === null) { return null; } - // is namespace and already correctly named? - if ($node instanceof Namespace_ && $this->isName($node, $expectedNamespace)) { + if ($node instanceof \PhpParser\Node\Stmt\Namespace_ && $this->isName($node, $expectedNamespace)) { return null; } - // to put declare_strict types on correct place - if ($node instanceof FileWithoutNamespace) { + if ($node instanceof \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace) { return $this->refactorFileWithoutNamespace($node, $expectedNamespace); } - - $node->name = new Name($expectedNamespace); + $node->name = new \PhpParser\Node\Name($expectedNamespace); $this->fullyQualifyStmtsAnalyzer->process($node->stmts); - return $node; } - - private function refactorFileWithoutNamespace( - FileWithoutNamespace $fileWithoutNamespace, - string $expectedNamespace - ): FileWithoutNamespace { + private function refactorFileWithoutNamespace(\Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace $fileWithoutNamespace, string $expectedNamespace) : \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace + { $nodes = $fileWithoutNamespace->stmts; - $nodesWithStrictTypesThenNamespace = []; foreach ($nodes as $key => $fileWithoutNamespace) { - if ($fileWithoutNamespace instanceof Declare_) { + if ($fileWithoutNamespace instanceof \PhpParser\Node\Stmt\Declare_) { $nodesWithStrictTypesThenNamespace[] = $fileWithoutNamespace; unset($nodes[$key]); } } - - $namespace = new Namespace_(new Name($expectedNamespace), $nodes); + $namespace = new \PhpParser\Node\Stmt\Namespace_(new \PhpParser\Node\Name($expectedNamespace), $nodes); $nodesWithStrictTypesThenNamespace[] = $namespace; - $this->fullyQualifyStmtsAnalyzer->process($nodes); - // @todo update to a new class node, like FileWithNamespace - return new FileWithoutNamespace($nodesWithStrictTypesThenNamespace); + return new \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace($nodesWithStrictTypesThenNamespace); } } diff --git a/rules/PSR4/Rector/Namespace_/MultipleClassFileToPsr4ClassesRector.php b/rules/PSR4/Rector/Namespace_/MultipleClassFileToPsr4ClassesRector.php index 9adefd08fa3..9342fc85b2a 100644 --- a/rules/PSR4/Rector/Namespace_/MultipleClassFileToPsr4ClassesRector.php +++ b/rules/PSR4/Rector/Namespace_/MultipleClassFileToPsr4ClassesRector.php @@ -1,7 +1,6 @@ namespaceManipulator = $namespaceManipulator; $this->fileInfoDeletionAnalyzer = $fileInfoDeletionAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change multiple classes in one file to standalone PSR-4 classes.', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change multiple classes in one file to standalone PSR-4 classes.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' namespace App\Exceptions; use Exception; @@ -59,8 +48,7 @@ final class SecondException extends Exception { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' // new file: "app/Exceptions/FirstException.php" namespace App\Exceptions; @@ -79,131 +67,103 @@ final class SecondException extends Exception { } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Namespace_::class, FileWithoutNamespace::class]; + return [\PhpParser\Node\Stmt\Namespace_::class, \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace::class]; } - /** * @param Namespace_|FileWithoutNamespace $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->hasAtLeastTwoClassLikes($node)) { + if (!$this->hasAtLeastTwoClassLikes($node)) { return null; } - $nodeToReturn = null; - if ($node instanceof Namespace_) { + if ($node instanceof \PhpParser\Node\Stmt\Namespace_) { $nodeToReturn = $this->refactorNamespace($node); } - - if ($node instanceof FileWithoutNamespace) { + if ($node instanceof \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace) { $nodeToReturn = $this->refactorFileWithoutNamespace($node); } - // 1. remove this node if ($nodeToReturn !== null) { return $nodeToReturn; } - $smartFileInfo = $this->file->getSmartFileInfo(); - // 2. nothing to return - remove the file $this->removedAndAddedFilesCollector->removeFile($smartFileInfo); return null; } - - private function hasAtLeastTwoClassLikes(Node $node): bool + private function hasAtLeastTwoClassLikes(\PhpParser\Node $node) : bool { $classes = $this->betterNodeFinder->findClassLikes($node); - return count($classes) > 1; + return \count($classes) > 1; } - - private function refactorNamespace(Namespace_ $namespace): ?Namespace_ + private function refactorNamespace(\PhpParser\Node\Stmt\Namespace_ $namespace) : ?\PhpParser\Node\Stmt\Namespace_ { /** @var ClassLike[] $classLikes */ $classLikes = $this->betterNodeFinder->findClassLikes($namespace->stmts); - $this->namespaceManipulator->removeClassLikes($namespace); - $nodeToReturn = null; foreach ($classLikes as $classLike) { $newNamespace = clone $namespace; $newNamespace->stmts[] = $classLike; - // 1. is the class that will be kept in original file? if ($this->fileInfoDeletionAnalyzer->isClassLikeAndFileInfoMatch($this->file, $classLike)) { $nodeToReturn = $newNamespace; continue; } - // 2. new file $this->printNewNodes($classLike, $newNamespace); } - return $nodeToReturn; } - - private function refactorFileWithoutNamespace(FileWithoutNamespace $fileWithoutNamespace): ?FileWithoutNamespace + private function refactorFileWithoutNamespace(\Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace $fileWithoutNamespace) : ?\Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace { /** @var ClassLike[] $classLikes */ $classLikes = $this->betterNodeFinder->findClassLikes($fileWithoutNamespace->stmts); - $nodeToReturn = null; - foreach ($classLikes as $classLike) { // 1. is the class that will be kept in original file? if ($this->fileInfoDeletionAnalyzer->isClassLikeAndFileInfoMatch($this->file, $classLike)) { $nodeToReturn = $fileWithoutNamespace; continue; } - // 2. is new file $this->printNewNodes($classLike, $fileWithoutNamespace); } - return $nodeToReturn; } - /** * @param Namespace_|FileWithoutNamespace $mainNode */ - private function printNewNodes(ClassLike $classLike, Node $mainNode): void + private function printNewNodes(\PhpParser\Node\Stmt\ClassLike $classLike, \PhpParser\Node $mainNode) : void { $smartFileInfo = $this->file->getSmartFileInfo(); - $declares = []; - $declare = $this->betterNodeFinder->findFirstPreviousOfTypes($mainNode, [Declare_::class]); - if ($declare instanceof Declare_) { + $declare = $this->betterNodeFinder->findFirstPreviousOfTypes($mainNode, [\PhpParser\Node\Stmt\Declare_::class]); + if ($declare instanceof \PhpParser\Node\Stmt\Declare_) { $declares = [$declare]; } - - if ($mainNode instanceof FileWithoutNamespace) { - $nodesToPrint = array_merge($declares, [$classLike]); + if ($mainNode instanceof \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace) { + $nodesToPrint = \array_merge($declares, [$classLike]); } else { - $nodesToPrint = array_merge($declares, [$mainNode]); + $nodesToPrint = \array_merge($declares, [$mainNode]); } - $fileDestination = $this->createClassLikeFileDestination($classLike, $smartFileInfo); - $this->removedAndAddedFilesCollector->removeFile($smartFileInfo); - - $addedFileWithNodes = new AddedFileWithNodes($fileDestination, $nodesToPrint); + $addedFileWithNodes = new \Rector\FileSystemRector\ValueObject\AddedFileWithNodes($fileDestination, $nodesToPrint); $this->removedAndAddedFilesCollector->addAddedFile($addedFileWithNodes); } - - private function createClassLikeFileDestination(ClassLike $classLike, SmartFileInfo $smartFileInfo): string + private function createClassLikeFileDestination(\PhpParser\Node\Stmt\ClassLike $classLike, \Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : string { - $currentDirectory = dirname($smartFileInfo->getRealPath()); - return $currentDirectory . DIRECTORY_SEPARATOR . $classLike->name . '.php'; + $currentDirectory = \dirname($smartFileInfo->getRealPath()); + return $currentDirectory . \DIRECTORY_SEPARATOR . $classLike->name . '.php'; } } diff --git a/rules/Php52/Rector/Property/VarToPublicPropertyRector.php b/rules/Php52/Rector/Property/VarToPublicPropertyRector.php index 8c5d81397c3..04e21536f63 100644 --- a/rules/Php52/Rector/Property/VarToPublicPropertyRector.php +++ b/rules/Php52/Rector/Property/VarToPublicPropertyRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { // explicitly public if ($node->flags !== 0) { return null; } - $this->visibilityManipulator->makePublic($node); - return $node; } } diff --git a/rules/Php52/Rector/Switch_/ContinueToBreakInSwitchRector.php b/rules/Php52/Rector/Switch_/ContinueToBreakInSwitchRector.php index b5b33f630fd..7b65d9c7b8b 100644 --- a/rules/Php52/Rector/Switch_/ContinueToBreakInSwitchRector.php +++ b/rules/Php52/Rector/Switch_/ContinueToBreakInSwitchRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Switch_::class]; + return [\PhpParser\Node\Stmt\Switch_::class]; } - /** * @param Switch_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($node->cases as $case) { foreach ($case->stmts as $key => $caseStmt) { - if (! $caseStmt instanceof Continue_) { + if (!$caseStmt instanceof \PhpParser\Node\Stmt\Continue_) { continue; } - $case->stmts[$key] = $this->processContinueStatement($caseStmt); } } - return $node; } - - private function processContinueStatement(Continue_ $continue): Stmt + private function processContinueStatement(\PhpParser\Node\Stmt\Continue_ $continue) : \PhpParser\Node\Stmt { if ($continue->num === null) { - return new Break_(); + return new \PhpParser\Node\Stmt\Break_(); } - - if ($continue->num instanceof LNumber) { + if ($continue->num instanceof \PhpParser\Node\Scalar\LNumber) { $continueNumber = $this->valueResolver->getValue($continue->num); if ($continueNumber <= 1) { - return new Break_(); + return new \PhpParser\Node\Stmt\Break_(); } - } elseif ($continue->num instanceof Variable) { + } elseif ($continue->num instanceof \PhpParser\Node\Expr\Variable) { return $this->processVariableNum($continue, $continue->num); } - return $continue; } - - private function processVariableNum(Continue_ $continue, Variable $numVariable): Stmt + private function processVariableNum(\PhpParser\Node\Stmt\Continue_ $continue, \PhpParser\Node\Expr\Variable $numVariable) : \PhpParser\Node\Stmt { $staticType = $this->getStaticType($numVariable); - if (! $staticType instanceof ConstantType) { + if (!$staticType instanceof \PHPStan\Type\ConstantType) { return $continue; } - if (! $staticType instanceof ConstantIntegerType) { + if (!$staticType instanceof \PHPStan\Type\Constant\ConstantIntegerType) { return $continue; } if ($staticType->getValue() > 1) { return $continue; } - return new Break_(); + return new \PhpParser\Node\Stmt\Break_(); } } diff --git a/rules/Php53/Rector/AssignRef/ClearReturnNewByReferenceRector.php b/rules/Php53/Rector/AssignRef/ClearReturnNewByReferenceRector.php index 8e204f57f3a..99697c64500 100644 --- a/rules/Php53/Rector/AssignRef/ClearReturnNewByReferenceRector.php +++ b/rules/Php53/Rector/AssignRef/ClearReturnNewByReferenceRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [AssignRef::class]; + return [\PhpParser\Node\Expr\AssignRef::class]; } - /** * @param AssignRef $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof New_) { + if (!$node->expr instanceof \PhpParser\Node\Expr\New_) { return null; } - - return new Assign($node->var, $node->expr); + return new \PhpParser\Node\Expr\Assign($node->var, $node->expr); } } diff --git a/rules/Php53/Rector/FuncCall/DirNameFileConstantToDirConstantRector.php b/rules/Php53/Rector/FuncCall/DirNameFileConstantToDirConstantRector.php index 58848fdf4f3..f3e2f2fc0b8 100644 --- a/rules/Php53/Rector/FuncCall/DirNameFileConstantToDirConstantRector.php +++ b/rules/Php53/Rector/FuncCall/DirNameFileConstantToDirConstantRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::DIR_CONSTANT)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::DIR_CONSTANT)) { return null; } - - if (! $this->isName($node, 'dirname')) { + if (!$this->isName($node, 'dirname')) { return null; } - - if (count($node->args) !== 1) { + if (\count($node->args) !== 1) { return null; } - $firstArgValue = $node->args[0]->value; - if (! $firstArgValue instanceof File) { + if (!$firstArgValue instanceof \PhpParser\Node\Scalar\MagicConst\File) { return null; } - - return new Dir(); + return new \PhpParser\Node\Scalar\MagicConst\Dir(); } } diff --git a/rules/Php53/Rector/Ternary/TernaryToElvisRector.php b/rules/Php53/Rector/Ternary/TernaryToElvisRector.php index fc851c778a3..376878715c1 100644 --- a/rules/Php53/Rector/Ternary/TernaryToElvisRector.php +++ b/rules/Php53/Rector/Ternary/TernaryToElvisRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::ELVIS_OPERATOR)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::ELVIS_OPERATOR)) { return null; } - - if (! $this->nodeComparator->areNodesEqual($node->cond, $node->if)) { + if (!$this->nodeComparator->areNodesEqual($node->cond, $node->if)) { return null; } - - $node->setAttribute(AttributeKey::ORIGINAL_NODE, null); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); $node->if = null; - return $node; } } diff --git a/rules/Php53/Rector/Variable/ReplaceHttpServerVarsByServerRector.php b/rules/Php53/Rector/Variable/ReplaceHttpServerVarsByServerRector.php index 90a4c818e62..25afd061441 100644 --- a/rules/Php53/Rector/Variable/ReplaceHttpServerVarsByServerRector.php +++ b/rules/Php53/Rector/Variable/ReplaceHttpServerVarsByServerRector.php @@ -1,7 +1,6 @@ */ - private const VARIABLE_RENAME_MAP = [ - 'HTTP_SERVER_VARS' => '_SERVER', - 'HTTP_GET_VARS' => '_GET', - 'HTTP_POST_VARS' => '_POST', - 'HTTP_POST_FILES' => '_FILES', - 'HTTP_SESSION_VARS' => '_SESSION', - 'HTTP_ENV_VARS' => '_ENV', - 'HTTP_COOKIE_VARS' => '_COOKIE', - ]; - - public function getRuleDefinition(): RuleDefinition + private const VARIABLE_RENAME_MAP = ['HTTP_SERVER_VARS' => '_SERVER', 'HTTP_GET_VARS' => '_GET', 'HTTP_POST_VARS' => '_POST', 'HTTP_POST_FILES' => '_FILES', 'HTTP_SESSION_VARS' => '_SESSION', 'HTTP_ENV_VARS' => '_ENV', 'HTTP_COOKIE_VARS' => '_COOKIE']; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Rename old $HTTP_* variable names to new replacements', - [new CodeSample('$serverVars = $HTTP_SERVER_VARS;', '$serverVars = $_SERVER;')] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Rename old $HTTP_* variable names to new replacements', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('$serverVars = $HTTP_SERVER_VARS;', '$serverVars = $_SERVER;')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Variable::class]; + return [\PhpParser\Node\Expr\Variable::class]; } - /** * @param Variable $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach (self::VARIABLE_RENAME_MAP as $oldName => $newName) { - if (! $this->isName($node, $oldName)) { + if (!$this->isName($node, $oldName)) { continue; } - $node->name = $newName; return $node; } - return null; } } diff --git a/rules/Php54/Rector/Break_/RemoveZeroBreakContinueRector.php b/rules/Php54/Rector/Break_/RemoveZeroBreakContinueRector.php index ffa6e1d6e4b..31592d944ea 100644 --- a/rules/Php54/Rector/Break_/RemoveZeroBreakContinueRector.php +++ b/rules/Php54/Rector/Break_/RemoveZeroBreakContinueRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Break_::class, Continue_::class]; + return [\PhpParser\Node\Stmt\Break_::class, \PhpParser\Node\Stmt\Continue_::class]; } - /** * @param Break_|Continue_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->num === null) { return null; } - - if ($node->num instanceof LNumber) { + if ($node->num instanceof \PhpParser\Node\Scalar\LNumber) { $number = $this->valueResolver->getValue($node->num); if ($number > 1) { return null; } - if ($number === 0) { $node->num = null; return $node; } - return null; } - - if ($node->num instanceof Variable) { + if ($node->num instanceof \PhpParser\Node\Expr\Variable) { return $this->processVariableNum($node, $node->num); } - return null; } - /** * @param Break_|Continue_ $stmt */ - private function processVariableNum(Stmt $stmt, Variable $numVariable): ?Node + private function processVariableNum(\PhpParser\Node\Stmt $stmt, \PhpParser\Node\Expr\Variable $numVariable) : ?\PhpParser\Node { $staticType = $this->getStaticType($numVariable); - - if ($staticType instanceof ConstantType) { - if ($staticType instanceof ConstantIntegerType) { + if ($staticType instanceof \PHPStan\Type\ConstantType) { + if ($staticType instanceof \PHPStan\Type\Constant\ConstantIntegerType) { if ($staticType->getValue() === 0) { $stmt->num = null; return $stmt; } - if ($staticType->getValue() > 0) { - $stmt->num = new LNumber($staticType->getValue()); + $stmt->num = new \PhpParser\Node\Scalar\LNumber($staticType->getValue()); return $stmt; } } - return $stmt; } - // remove variable $stmt->num = null; - return null; } } diff --git a/rules/Php54/Rector/FuncCall/RemoveReferenceFromCallRector.php b/rules/Php54/Rector/FuncCall/RemoveReferenceFromCallRector.php index a2b864217e0..c03abcf85c7 100644 --- a/rules/Php54/Rector/FuncCall/RemoveReferenceFromCallRector.php +++ b/rules/Php54/Rector/FuncCall/RemoveReferenceFromCallRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($node->args as $nodeArg) { if ($nodeArg->byRef) { - $nodeArg->byRef = false; + $nodeArg->byRef = \false; } } - return $node; } } diff --git a/rules/Php55/NodeFactory/AnonymousFunctionNodeFactory.php b/rules/Php55/NodeFactory/AnonymousFunctionNodeFactory.php index 368facbae15..3a4c35a9f3b 100644 --- a/rules/Php55/NodeFactory/AnonymousFunctionNodeFactory.php +++ b/rules/Php55/NodeFactory/AnonymousFunctionNodeFactory.php @@ -1,10 +1,9 @@ \d+)#'; - + private const DIM_FETCH_REGEX = '#(\\$|\\\\|\\x0)(?\\d+)#'; /** * @var Parser */ private $parser; - /** * @var SimpleCallableNodeTraverser */ private $simpleCallableNodeTraverser; - - public function __construct(SimpleCallableNodeTraverser $simpleCallableNodeTraverser, Parser $parser) + public function __construct(\RectorPrefix20210509\Symplify\Astral\NodeTraverser\SimpleCallableNodeTraverser $simpleCallableNodeTraverser, \PhpParser\Parser $parser) { $this->parser = $parser; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - - public function createAnonymousFunctionFromString(Expr $expr): ?Closure + public function createAnonymousFunctionFromString(\PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr\Closure { - if (! $expr instanceof String_) { + if (!$expr instanceof \PhpParser\Node\Scalar\String_) { // not supported yet - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $phpCode = 'value . ';'; $contentNodes = (array) $this->parser->parse($phpCode); - - $anonymousFunction = new Closure(); - + $anonymousFunction = new \PhpParser\Node\Expr\Closure(); $firstNode = $contentNodes[0] ?? null; - if (! $firstNode instanceof Expression) { + if (!$firstNode instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $stmt = $firstNode->expr; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmt, function (Node $node): Node { - if (! $node instanceof String_) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmt, function (\PhpParser\Node $node) : Node { + if (!$node instanceof \PhpParser\Node\Scalar\String_) { return $node; } - - $match = Strings::match($node->value, self::DIM_FETCH_REGEX); - if (! $match) { + $match = \RectorPrefix20210509\Nette\Utils\Strings::match($node->value, self::DIM_FETCH_REGEX); + if (!$match) { return $node; } - - $matchesVariable = new Variable('matches'); - - return new ArrayDimFetch($matchesVariable, new LNumber((int) $match['number'])); + $matchesVariable = new \PhpParser\Node\Expr\Variable('matches'); + return new \PhpParser\Node\Expr\ArrayDimFetch($matchesVariable, new \PhpParser\Node\Scalar\LNumber((int) $match['number'])); }); - - $anonymousFunction->stmts[] = new Return_($stmt); - $anonymousFunction->params[] = new Param(new Variable('matches')); - + $anonymousFunction->stmts[] = new \PhpParser\Node\Stmt\Return_($stmt); + $anonymousFunction->params[] = new \PhpParser\Node\Param(new \PhpParser\Node\Expr\Variable('matches')); return $anonymousFunction; } } diff --git a/rules/Php55/Rector/Class_/ClassConstantToSelfClassRector.php b/rules/Php55/Rector/Class_/ClassConstantToSelfClassRector.php index e8f2d2b5fe0..36f5b9a52d6 100644 --- a/rules/Php55/Rector/Class_/ClassConstantToSelfClassRector.php +++ b/rules/Php55/Rector/Class_/ClassConstantToSelfClassRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Scalar\MagicConst\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::CLASSNAME_CONSTANT)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::CLASSNAME_CONSTANT)) { return null; } - return $this->nodeFactory->createSelfFetchConstant('class', $node); } } diff --git a/rules/Php55/Rector/FuncCall/PregReplaceEModifierRector.php b/rules/Php55/Rector/FuncCall/PregReplaceEModifierRector.php index 32ab890913d..3364abb27e0 100644 --- a/rules/Php55/Rector/FuncCall/PregReplaceEModifierRector.php +++ b/rules/Php55/Rector/FuncCall/PregReplaceEModifierRector.php @@ -1,7 +1,6 @@ regexMatcher = $regexMatcher; $this->anonymousFunctionNodeFactory = $anonymousFunctionNodeFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'The /e modifier is no longer supported, use preg_replace_callback instead', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('The /e modifier is no longer supported, use preg_replace_callback instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -53,8 +44,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -65,46 +55,36 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'preg_replace')) { + if (!$this->isName($node, 'preg_replace')) { return null; } - $firstArgumentValue = $node->args[0]->value; $patternWithoutE = $this->regexMatcher->resolvePatternExpressionWithoutEIfFound($firstArgumentValue); - if (! $patternWithoutE instanceof Expr) { + if (!$patternWithoutE instanceof \PhpParser\Node\Expr) { return null; } - $secondArgumentValue = $node->args[1]->value; - $anonymousFunction = $this->anonymousFunctionNodeFactory->createAnonymousFunctionFromString( - $secondArgumentValue - ); - if (! $anonymousFunction instanceof Closure) { + $anonymousFunction = $this->anonymousFunctionNodeFactory->createAnonymousFunctionFromString($secondArgumentValue); + if (!$anonymousFunction instanceof \PhpParser\Node\Expr\Closure) { return null; } - - $node->name = new Name('preg_replace_callback'); + $node->name = new \PhpParser\Node\Name('preg_replace_callback'); $node->args[0]->value = $patternWithoutE; $node->args[1]->value = $anonymousFunction; - return $node; } } diff --git a/rules/Php55/Rector/String_/StringClassNameToClassConstantRector.php b/rules/Php55/Rector/String_/StringClassNameToClassConstantRector.php index 6f05936a3ba..b9ea671dfd8 100644 --- a/rules/Php55/Rector/String_/StringClassNameToClassConstantRector.php +++ b/rules/Php55/Rector/String_/StringClassNameToClassConstantRector.php @@ -1,7 +1,6 @@ classLikeExistenceChecker = $classLikeExistenceChecker; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replace string class names by ::class constant', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replace string class names by ::class constant', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class AnotherClass { } @@ -69,8 +61,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class AnotherClass { } @@ -83,90 +74,70 @@ class SomeClass } } CODE_SAMPLE -, - [ - self::CLASSES_TO_SKIP => ['ClassName', 'AnotherClassName'], - ] - ), - ]); +, [self::CLASSES_TO_SKIP => ['ClassName', 'AnotherClassName']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [String_::class]; + return [\PhpParser\Node\Scalar\String_::class]; } - /** * @param String_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::CLASSNAME_CONSTANT)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::CLASSNAME_CONSTANT)) { return null; } - $classLikeName = $node->value; - // remove leading slash - $classLikeName = ltrim($classLikeName, '\\'); + $classLikeName = \ltrim($classLikeName, '\\'); if ($classLikeName === '') { return null; } - if ($this->shouldSkip($classLikeName, $node)) { return null; } - - $fullyQualified = new FullyQualified($classLikeName); - return new ClassConstFetch($fullyQualified, 'class'); + $fullyQualified = new \PhpParser\Node\Name\FullyQualified($classLikeName); + return new \PhpParser\Node\Expr\ClassConstFetch($fullyQualified, 'class'); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { - if (! isset($configuration[self::CLASSES_TO_SKIP])) { + if (!isset($configuration[self::CLASSES_TO_SKIP])) { return; } - $this->classesToSkip = $configuration[self::CLASSES_TO_SKIP]; } - - private function isPartOfIsAFuncCall(String_ $string): bool + private function isPartOfIsAFuncCall(\PhpParser\Node\Scalar\String_ $string) : bool { - $parent = $string->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Arg) { - return false; + $parent = $string->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Arg) { + return \false; } - - $parentParent = $parent->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentParent instanceof FuncCall) { - return false; + $parentParent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentParent instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - return $this->nodeNameResolver->isName($parentParent, 'is_a'); } - - private function shouldSkip(string $classLikeName, String_ $string): bool + private function shouldSkip(string $classLikeName, \PhpParser\Node\Scalar\String_ $string) : bool { - if (! $this->classLikeExistenceChecker->doesClassLikeInsensitiveExists($classLikeName)) { - return true; + if (!$this->classLikeExistenceChecker->doesClassLikeInsensitiveExists($classLikeName)) { + return \true; } - - if (StaticRectorStrings::isInArrayInsensitive($classLikeName, $this->classesToSkip)) { - return true; + if (\Rector\Core\Util\StaticRectorStrings::isInArrayInsensitive($classLikeName, $this->classesToSkip)) { + return \true; } - if ($this->isPartOfIsAFuncCall($string)) { - return true; + return \true; } - // allow class strings to be part of class const arrays, as probably on purpose - $parentClassConst = $this->betterNodeFinder->findParentType($string, ClassConst::class); - return $parentClassConst instanceof ClassConst; + $parentClassConst = $this->betterNodeFinder->findParentType($string, \PhpParser\Node\Stmt\ClassConst::class); + return $parentClassConst instanceof \PhpParser\Node\Stmt\ClassConst; } } diff --git a/rules/Php55/RegexMatcher.php b/rules/Php55/RegexMatcher.php index 4984dc01292..f021b8fc6c4 100644 --- a/rules/Php55/RegexMatcher.php +++ b/rules/Php55/RegexMatcher.php @@ -1,97 +1,78 @@ \w+)$#'; - + private const LETTER_SUFFIX_REGEX = '#(?\\w+)$#'; /** * @var ValueResolver */ private $valueResolver; - - public function __construct(ValueResolver $valueResolver) + public function __construct(\Rector\Core\PhpParser\Node\Value\ValueResolver $valueResolver) { $this->valueResolver = $valueResolver; } - - public function resolvePatternExpressionWithoutEIfFound(Expr $expr): ?Expr + public function resolvePatternExpressionWithoutEIfFound(\PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr { - if ($expr instanceof String_) { + if ($expr instanceof \PhpParser\Node\Scalar\String_) { $pattern = $this->valueResolver->getValue($expr); - - if (! is_string($pattern)) { + if (!\is_string($pattern)) { return null; } - $delimiter = $pattern[0]; - if (! is_string($delimiter)) { - throw new ShouldNotHappenException(); + if (!\is_string($delimiter)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - /** @var string $modifiers */ - $modifiers = Strings::after($pattern, $delimiter, -1); - if (! Strings::contains($modifiers, 'e')) { + $modifiers = \RectorPrefix20210509\Nette\Utils\Strings::after($pattern, $delimiter, -1); + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($modifiers, 'e')) { return null; } - $patternWithoutE = $this->createPatternWithoutE($pattern, $delimiter, $modifiers); - return new String_($patternWithoutE); + return new \PhpParser\Node\Scalar\String_($patternWithoutE); } - - if ($expr instanceof Concat) { + if ($expr instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { return $this->matchConcat($expr); } - return null; } - - private function createPatternWithoutE(string $pattern, string $delimiter, string $modifiers): string + private function createPatternWithoutE(string $pattern, string $delimiter, string $modifiers) : string { - $modifiersWithoutE = Strings::replace($modifiers, '#e#', ''); - - return Strings::before($pattern, $delimiter, -1) . $delimiter . $modifiersWithoutE; + $modifiersWithoutE = \RectorPrefix20210509\Nette\Utils\Strings::replace($modifiers, '#e#', ''); + return \RectorPrefix20210509\Nette\Utils\Strings::before($pattern, $delimiter, -1) . $delimiter . $modifiersWithoutE; } - - private function matchConcat(Concat $concat): ?Expr + private function matchConcat(\PhpParser\Node\Expr\BinaryOp\Concat $concat) : ?\PhpParser\Node\Expr { $lastItem = $concat->right; - if (! $lastItem instanceof String_) { + if (!$lastItem instanceof \PhpParser\Node\Scalar\String_) { return null; } - - $matches = Strings::match($lastItem->value, self::LETTER_SUFFIX_REGEX); - if (! isset($matches['modifiers'])) { + $matches = \RectorPrefix20210509\Nette\Utils\Strings::match($lastItem->value, self::LETTER_SUFFIX_REGEX); + if (!isset($matches['modifiers'])) { return null; } - - if (! Strings::contains($matches['modifiers'], 'e')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($matches['modifiers'], 'e')) { return null; } - // replace last "e" in the code - $lastItem->value = Strings::replace($lastItem->value, self::LAST_E_REGEX, '$1$2'); - + $lastItem->value = \RectorPrefix20210509\Nette\Utils\Strings::replace($lastItem->value, self::LAST_E_REGEX, '$1$2'); return $concat; } } diff --git a/rules/Php56/Rector/FuncCall/PowToExpRector.php b/rules/Php56/Rector/FuncCall/PowToExpRector.php index f1203c94e8b..2ab6cd0dd63 100644 --- a/rules/Php56/Rector/FuncCall/PowToExpRector.php +++ b/rules/Php56/Rector/FuncCall/PowToExpRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::EXP_OPERATOR)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::EXP_OPERATOR)) { return null; } - - if (! $this->isName($node, 'pow')) { + if (!$this->isName($node, 'pow')) { return null; } - - if (count($node->args) !== 2) { + if (\count($node->args) !== 2) { return null; } - $firstArgument = $node->args[0]->value; $secondArgument = $node->args[1]->value; - - return new Pow($firstArgument, $secondArgument); + return new \PhpParser\Node\Expr\BinaryOp\Pow($firstArgument, $secondArgument); } } diff --git a/rules/Php56/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector.php b/rules/Php56/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector.php index d83c2ecf9ff..5c9a82a93f1 100644 --- a/rules/Php56/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector.php +++ b/rules/Php56/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Function_::class, Closure::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Expr\Closure::class]; } - /** * @param ClassMethod|Function_|Closure $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $this->definedVariables = []; - $undefinedVariables = $this->collectUndefinedVariableScope($node); if ($undefinedVariables === []) { return null; } - $variablesInitiation = []; foreach ($undefinedVariables as $undefinedVariable) { - if (in_array($undefinedVariable, $this->definedVariables, true)) { + if (\in_array($undefinedVariable, $this->definedVariables, \true)) { continue; } - - $value = $this->isArray($undefinedVariable, (array) $node->stmts) - ? new Array_([]) - : $this->nodeFactory->createNull(); - - $variablesInitiation[] = new Expression(new Assign(new Variable($undefinedVariable), $value)); + $value = $this->isArray($undefinedVariable, (array) $node->stmts) ? new \PhpParser\Node\Expr\Array_([]) : $this->nodeFactory->createNull(); + $variablesInitiation[] = new \PhpParser\Node\Stmt\Expression(new \PhpParser\Node\Expr\Assign(new \PhpParser\Node\Expr\Variable($undefinedVariable), $value)); } - - $node->stmts = array_merge($variablesInitiation, (array) $node->stmts); - + $node->stmts = \array_merge($variablesInitiation, (array) $node->stmts); return $node; } - /** * @param ClassMethod|Function_|Closure $node * @return string[] */ - private function collectUndefinedVariableScope(Node $node): array + private function collectUndefinedVariableScope(\PhpParser\Node $node) : array { $undefinedVariables = []; - - $this->traverseNodesWithCallable((array) $node->stmts, function (Node $node) use (&$undefinedVariables): ?int { + $this->traverseNodesWithCallable((array) $node->stmts, function (\PhpParser\Node $node) use(&$undefinedVariables) : ?int { // entering new scope - break! - if ($node instanceof FunctionLike && ! $node instanceof ArrowFunction) { - return NodeTraverser::STOP_TRAVERSAL; + if ($node instanceof \PhpParser\Node\FunctionLike && !$node instanceof \PhpParser\Node\Expr\ArrowFunction) { + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; } - - if ($node instanceof Foreach_) { + if ($node instanceof \PhpParser\Node\Stmt\Foreach_) { // handled above $this->collectDefinedVariablesFromForeach($node); - return NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; } - - if (! $node instanceof Variable) { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { return null; } - if ($this->shouldSkipVariable($node)) { return null; } - /** @var string $variableName */ $variableName = $this->getName($node); - // defined 100 % /** @var Scope $scope */ - $scope = $node->getAttribute(AttributeKey::SCOPE); + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); if ($scope->hasVariableType($variableName)->yes()) { return null; } - $undefinedVariables[] = $variableName; - return null; }); - - return array_unique($undefinedVariables); + return \array_unique($undefinedVariables); } - /** * @param Stmt[] $stmts */ - private function isArray(string $undefinedVariable, array $stmts): bool + private function isArray(string $undefinedVariable, array $stmts) : bool { - return (bool) $this->betterNodeFinder->findFirst($stmts, function (Node $node) use ( - $undefinedVariable - ): bool { - if (! $node instanceof ArrayDimFetch) { - return false; + return (bool) $this->betterNodeFinder->findFirst($stmts, function (\PhpParser\Node $node) use($undefinedVariable) : bool { + if (!$node instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + return \false; } - return $this->isName($node->var, $undefinedVariable); }); } - - private function collectDefinedVariablesFromForeach(Foreach_ $foreach): void + private function collectDefinedVariablesFromForeach(\PhpParser\Node\Stmt\Foreach_ $foreach) : void { - $this->traverseNodesWithCallable($foreach->stmts, function (Node $node): void { - if ($node instanceof Assign || $node instanceof AssignRef) { - if (! $node->var instanceof Variable) { + $this->traverseNodesWithCallable($foreach->stmts, function (\PhpParser\Node $node) : void { + if ($node instanceof \PhpParser\Node\Expr\Assign || $node instanceof \PhpParser\Node\Expr\AssignRef) { + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { return; } - $variableName = $this->getName($node->var); if ($variableName === null) { return; } - $this->definedVariables[] = $variableName; } }); } - - private function shouldSkipVariable(Variable $variable): bool + private function shouldSkipVariable(\PhpParser\Node\Expr\Variable $variable) : bool { - $parentNode = $variable->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Node) { - return true; + $parentNode = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node) { + return \true; } - - if ($parentNode instanceof Global_) { - return true; + if ($parentNode instanceof \PhpParser\Node\Stmt\Global_) { + return \true; } - - if ($parentNode instanceof Node && - ( - $parentNode instanceof Assign || $parentNode instanceof AssignRef || $this->isStaticVariable( - $parentNode - ) - )) { - return true; + if ($parentNode instanceof \PhpParser\Node && ($parentNode instanceof \PhpParser\Node\Expr\Assign || $parentNode instanceof \PhpParser\Node\Expr\AssignRef || $this->isStaticVariable($parentNode))) { + return \true; } - - if ($parentNode instanceof Unset_ || $parentNode instanceof UnsetCast) { - return true; + if ($parentNode instanceof \PhpParser\Node\Stmt\Unset_ || $parentNode instanceof \PhpParser\Node\Expr\Cast\Unset_) { + return \true; } - // list() = | [$values] = defines variables as null if ($this->isListAssign($parentNode)) { - return true; + return \true; } - - $nodeScope = $variable->getAttribute(AttributeKey::SCOPE); - if (! $nodeScope instanceof Scope) { - return true; + $nodeScope = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$nodeScope instanceof \PHPStan\Analyser\Scope) { + return \true; } - $variableName = $this->getName($variable); - // skip $this, as probably in outer scope if ($variableName === 'this') { - return true; + return \true; } - return $variableName === null; } - - private function isStaticVariable(Node $parentNode): bool + private function isStaticVariable(\PhpParser\Node $parentNode) : bool { // definition of static variable - if ($parentNode instanceof StaticVar) { - $parentParentNode = $parentNode->getAttribute(AttributeKey::PARENT_NODE); - if ($parentParentNode instanceof Static_) { - return true; + if ($parentNode instanceof \PhpParser\Node\Stmt\StaticVar) { + $parentParentNode = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentParentNode instanceof \PhpParser\Node\Stmt\Static_) { + return \true; } } - - return false; + return \false; } - - private function isListAssign(Node $node): bool + private function isListAssign(\PhpParser\Node $node) : bool { - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof List_) { - return true; + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\List_) { + return \true; } - - return $parentNode instanceof Array_; + return $parentNode instanceof \PhpParser\Node\Expr\Array_; } } diff --git a/rules/Php70/EregToPcreTransformer.php b/rules/Php70/EregToPcreTransformer.php index ba11bf2ef60..1a2b47252f7 100644 --- a/rules/Php70/EregToPcreTransformer.php +++ b/rules/Php70/EregToPcreTransformer.php @@ -1,12 +1,10 @@ '[:alpha:]', ':blank:' => '[:blank:]', ':cntrl:' => '[:cntrl:]', - ':digit:' => '\d', + ':digit:' => '\\d', ':graph:' => '[:graph:]', ':lower:' => '[:lower:]', ':print:' => '[:print:]', ':punct:' => '[:punct:]', // should include VT - ':space:' => '\013\s', + ':space:' => '013\\s', ':upper:' => '[:upper:]', ':xdigit:' => '[:xdigit:]', ]; - /** * @var string * @see https://regex101.com/r/htpXFg/1 */ - private const BOUND_REGEX = '/^(?<' . self::MINIMAL_NUMBER_PART . '>\d|[1-9]\d|1\d\d| - 2[0-4]\d|25[0-5]) - (?,(?<' . self::MAXIMAL_NUMBER_PART . '>\d|[1-9]\d|1\d\d| - 2[0-4]\d|25[0-5])?)?$/x'; - + private const BOUND_REGEX = '/^(?<' . self::MINIMAL_NUMBER_PART . '>\\d|[1-9]\\d|1\\d\\d| + 2[0-4]\\d|25[0-5]) + (?,(?<' . self::MAXIMAL_NUMBER_PART . '>\\d|[1-9]\\d|1\\d\\d| + 2[0-4]\\d|25[0-5])?)?$/x'; /** * @var string */ private const MINIMAL_NUMBER_PART = 'minimal_number'; - /** * @var string */ private const MAXIMAL_NUMBER_PART = 'maximal_number'; - /** * @var string */ private $pcreDelimiter; - /** * @var string[] */ private $icache = []; - /** * @var string[] */ private $cache = []; - /** * Change this via services configuratoin in rector.php if you need it * Single type is chosen to prevent every regular with different delimiter. @@ -75,20 +66,17 @@ final class EregToPcreTransformer { $this->pcreDelimiter = $pcreDelimiter; } - - public function transform(string $ereg, bool $isCaseInsensitive): string + public function transform(string $ereg, bool $isCaseInsensitive) : string { - if (! Strings::contains($ereg, $this->pcreDelimiter)) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($ereg, $this->pcreDelimiter)) { return $this->ere2pcre($ereg, $isCaseInsensitive); } - // fallback - $quotedEreg = preg_quote($ereg, '#'); + $quotedEreg = \preg_quote($ereg, '#'); return $this->ere2pcre($quotedEreg, $isCaseInsensitive); } - // converts the ERE $s into the PCRE $r. triggers error on any invalid input. - private function ere2pcre(string $content, bool $ignorecase): string + private function ere2pcre(string $content, bool $ignorecase) : string { if ($ignorecase) { if (isset($this->icache[$content])) { @@ -98,27 +86,24 @@ final class EregToPcreTransformer return $this->cache[$content]; } [$r, $i] = $this->_ere2pcre($content, 0); - if ($i !== strlen($content)) { - throw new InvalidEregException('unescaped metacharacter ")"'); + if ($i !== \strlen($content)) { + throw new \Rector\Php70\Exception\InvalidEregException('unescaped metacharacter ")"'); } - if ($ignorecase) { return $this->icache[$content] = '#' . $r . '#mi'; } - return $this->cache[$content] = '#' . $r . '#m'; } - /** * Recursively converts ERE into PCRE, starting at the position $i. * * @return mixed[] */ - private function _ere2pcre(string $content, int $i): array + private function _ere2pcre(string $content, int $i) : array { $r = ['']; $rr = 0; - $l = strlen($content); + $l = \strlen($content); while ($i < $l) { // atom $char = $content[$i]; @@ -133,26 +118,24 @@ final class EregToPcreTransformer ++$i; } if ($i >= $l) { - throw new InvalidEregException('"[" does not have a matching "]"'); + throw new \Rector\Php70\Exception\InvalidEregException('"[" does not have a matching "]"'); } - $start = true; - + $start = \true; $i = (int) $i; [$cls, $i] = $this->processSquareBracket($content, $i, $l, $cls, $start); - if ($i >= $l) { - throw new InvalidEregException('"[" does not have a matching "]"'); + throw new \Rector\Php70\Exception\InvalidEregException('"[" does not have a matching "]"'); } $r[$rr] .= '[' . $cls . ']'; } elseif ($char === ')') { break; } elseif ($char === '*' || $char === '+' || $char === '?') { - throw new InvalidEregException('unescaped metacharacter "' . $char . '"'); + throw new \Rector\Php70\Exception\InvalidEregException('unescaped metacharacter "' . $char . '"'); } elseif ($char === '{') { - if ($i + 1 < $l && Strings::contains('0123456789', $content[$i + 1])) { - $r[$rr] .= '\{'; + if ($i + 1 < $l && \RectorPrefix20210509\Nette\Utils\Strings::contains('0123456789', $content[$i + 1])) { + $r[$rr] .= '\\{'; } else { - throw new InvalidEregException('unescaped metacharacter "' . $char . '"'); + throw new \Rector\Php70\Exception\InvalidEregException('unescaped metacharacter "' . $char . '"'); } } elseif ($char === '.') { $r[$rr] .= $char; @@ -162,7 +145,7 @@ final class EregToPcreTransformer continue; } elseif ($char === '|') { if ($r[$rr] === '') { - throw new InvalidEregException('empty branch'); + throw new \Rector\Php70\Exception\InvalidEregException('empty branch'); } $r[] = ''; ++$rr; @@ -170,7 +153,7 @@ final class EregToPcreTransformer continue; } elseif ($char === '\\') { if (++$i >= $l) { - throw new InvalidEregException('an invalid escape sequence at the end'); + throw new \Rector\Php70\Exception\InvalidEregException('an invalid escape sequence at the end'); } $r[$rr] .= $this->_ere2pcre_escape($content[$i]); } else { @@ -188,22 +171,18 @@ final class EregToPcreTransformer ++$i; } elseif ($char === '{') { $i = (int) $i; - $i = $this->processCurlyBracket($content, $i, $r, $rr); } } - if ($r[$rr] === '') { - throw new InvalidEregException('empty regular expression or branch'); + throw new \Rector\Php70\Exception\InvalidEregException('empty regular expression or branch'); } - - return [implode('|', $r), $i]; + return [\implode('|', $r), $i]; } - /** * @param mixed[] $r */ - private function processBracket(string $content, int $i, int $l, array &$r, int $rr): int + private function processBracket(string $content, int $i, int $l, array &$r, int $rr) : int { // special case if ($i + 1 < $l && $content[$i + 1] === ')') { @@ -213,118 +192,102 @@ final class EregToPcreTransformer $position = $i + 1; [$t, $ii] = $this->_ere2pcre($content, $position); if ($ii >= $l || $content[$ii] !== ')') { - throw new InvalidEregException('"(" does not have a matching ")"'); + throw new \Rector\Php70\Exception\InvalidEregException('"(" does not have a matching ")"'); } $r[$rr] .= '(' . $t . ')'; $i = $ii; } - return $i; } - /** * @return mixed[] */ - private function processSquareBracket(string $s, int $i, int $l, string $cls, bool $start): array + private function processSquareBracket(string $s, int $i, int $l, string $cls, bool $start) : array { do { - if ($s[$i] === '[' && $i + 1 < $l && Strings::contains('.=:', $s[$i + 1])) { + if ($s[$i] === '[' && $i + 1 < $l && \RectorPrefix20210509\Nette\Utils\Strings::contains('.=:', $s[$i + 1])) { /** @var string $cls */ [$cls, $i] = $this->processCharacterClass($s, $i, $cls); } else { $a = $s[$i]; ++$i; - if ($a === '-' && ! $start && ! ($i < $l && $s[$i] === ']')) { - throw new InvalidEregException('"-" is invalid for the start character in the brackets'); + if ($a === '-' && !$start && !($i < $l && $s[$i] === ']')) { + throw new \Rector\Php70\Exception\InvalidEregException('"-" is invalid for the start character in the brackets'); } if ($i < $l && $s[$i] === '-') { $b = $s[++$i]; ++$i; if ($b === ']') { - $cls .= $this->_ere2pcre_escape($a) . '\-'; + $cls .= $this->_ere2pcre_escape($a) . '\\-'; break; - } elseif (ord($a) > ord($b)) { - throw new InvalidEregException(sprintf('an invalid character range %d-%d"', $a, $b)); + } elseif (\ord($a) > \ord($b)) { + throw new \Rector\Php70\Exception\InvalidEregException(\sprintf('an invalid character range %d-%d"', $a, $b)); } $cls .= $this->_ere2pcre_escape($a) . '-' . $this->_ere2pcre_escape($b); } else { $cls .= $this->_ere2pcre_escape($a); } } - $start = false; + $start = \false; } while ($i < $l && $s[$i] !== ']'); - return [$cls, $i]; } - - private function _ere2pcre_escape(string $content): string + private function _ere2pcre_escape(string $content) : string { if ($content === "\0") { - throw new InvalidEregException('a literal null byte in the regex'); + throw new \Rector\Php70\Exception\InvalidEregException('a literal null byte in the regex'); } - - if (Strings::contains('\^$.[]|()?*+{}-/', $content)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::contains('\\^$.[]|()?*+{}-/', $content)) { return '\\' . $content; } - return $content; } - /** * @param mixed[] $r */ - private function processCurlyBracket(string $s, int $i, array &$r, int $rr): int + private function processCurlyBracket(string $s, int $i, array &$r, int $rr) : int { - $ii = strpos($s, '}', $i); - if ($ii === false) { - throw new InvalidEregException('"{" does not have a matching "}"'); + $ii = \strpos($s, '}', $i); + if ($ii === \false) { + throw new \Rector\Php70\Exception\InvalidEregException('"{" does not have a matching "}"'); } - $start = $i + 1; $length = $ii - ($i + 1); - $bound = Strings::substring($s, $start, $length); - - $matches = Strings::match($bound, self::BOUND_REGEX); + $bound = \RectorPrefix20210509\Nette\Utils\Strings::substring($s, $start, $length); + $matches = \RectorPrefix20210509\Nette\Utils\Strings::match($bound, self::BOUND_REGEX); if ($matches === null) { - throw new InvalidEregException('an invalid bound'); + throw new \Rector\Php70\Exception\InvalidEregException('an invalid bound'); } - if (isset($matches[self::MAXIMAL_NUMBER_PART])) { if ($matches[self::MINIMAL_NUMBER_PART] > $matches[self::MAXIMAL_NUMBER_PART]) { - throw new InvalidEregException('an invalid bound'); + throw new \Rector\Php70\Exception\InvalidEregException('an invalid bound'); } - $r[$rr] .= '{' . $matches[self::MINIMAL_NUMBER_PART] . ',' . $matches[self::MAXIMAL_NUMBER_PART] . '}'; } elseif (isset($matches['comma'])) { $r[$rr] .= '{' . $matches[self::MINIMAL_NUMBER_PART] . ',}'; } else { $r[$rr] .= '{' . $matches[self::MINIMAL_NUMBER_PART] . '}'; } - return $ii + 1; } - /** * @return int[]|string[] */ - private function processCharacterClass(string $content, int $i, string $cls): array + private function processCharacterClass(string $content, int $i, string $cls) : array { $offset = $i; - $ii = strpos($content, ']', $offset); - if ($ii === false) { - throw new InvalidEregException('"[" does not have a matching "]"'); + $ii = \strpos($content, ']', $offset); + if ($ii === \false) { + throw new \Rector\Php70\Exception\InvalidEregException('"[" does not have a matching "]"'); } - $start = $i + 1; - $length = $ii - ($i + 1); - $ccls = Strings::substring($content, $start, $length); - if (! isset(self::CHARACTER_CLASS_MAP[$ccls])) { - throw new InvalidEregException('an invalid or unsupported character class [' . $ccls . ']'); + $ccls = \RectorPrefix20210509\Nette\Utils\Strings::substring($content, $start, $length); + if (!isset(self::CHARACTER_CLASS_MAP[$ccls])) { + throw new \Rector\Php70\Exception\InvalidEregException('an invalid or unsupported character class [' . $ccls . ']'); } $cls .= self::CHARACTER_CLASS_MAP[$ccls]; $i = $ii + 1; - return [$cls, $i]; } } diff --git a/rules/Php70/Exception/InvalidEregException.php b/rules/Php70/Exception/InvalidEregException.php index 4531c7092b6..c1ef21e8764 100644 --- a/rules/Php70/Exception/InvalidEregException.php +++ b/rules/Php70/Exception/InvalidEregException.php @@ -1,11 +1,9 @@ getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - // catch only classes without namespace if ($scope->getNamespace() !== null) { - return false; + return \false; } - if ($classMethod->isAbstract()) { - return false; + return \false; } - if ($classMethod->isStatic()) { - return false; + return \false; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - - return ! $classReflection->isAnonymous(); + return !$classReflection->isAnonymous(); } } diff --git a/rules/Php70/NodeAnalyzer/VariableNaming.php b/rules/Php70/NodeAnalyzer/VariableNaming.php index 72f7d036aa6..b397e207c0a 100644 --- a/rules/Php70/NodeAnalyzer/VariableNaming.php +++ b/rules/Php70/NodeAnalyzer/VariableNaming.php @@ -1,10 +1,9 @@ nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; $this->valueResolver = $valueResolver; } - - public function resolveFromNodeWithScopeCountAndFallbackName( - Expr $expr, - Scope $scope, - string $fallbackName - ): string { + public function resolveFromNodeWithScopeCountAndFallbackName(\PhpParser\Node\Expr $expr, \PHPStan\Analyser\Scope $scope, string $fallbackName) : string + { $name = $this->resolveFromNode($expr); if ($name === null) { $name = $fallbackName; } - - if (Strings::contains($name, '\\')) { - $name = (string) Strings::after($name, '\\', - 1); + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($name, '\\')) { + $name = (string) \RectorPrefix20210509\Nette\Utils\Strings::after($name, '\\', -1); } - $countedValueName = $this->createCountedValueName($name, $scope); - return lcfirst($countedValueName); + return \lcfirst($countedValueName); } - - public function createCountedValueName(string $valueName, ?Scope $scope): string + public function createCountedValueName(string $valueName, ?\PHPStan\Analyser\Scope $scope) : string { if ($scope === null) { return $valueName; } - // make sure variable name is unique - if (! $scope->hasVariableType($valueName)->yes()) { + if (!$scope->hasVariableType($valueName)->yes()) { return $valueName; } - // we need to add number suffix until the variable is unique $i = 2; $countedValueNamePart = $valueName; @@ -95,181 +78,137 @@ final class VariableNaming $valueName = $countedValueNamePart . $i; ++$i; } - return $valueName; } - - public function resolveFromNodeAndType(Node $node, Type $type): ?string + public function resolveFromNodeAndType(\PhpParser\Node $node, \PHPStan\Type\Type $type) : ?string { $variableName = $this->resolveBareFromNode($node); if ($variableName === null) { return null; } - // adjust static to specific class - if ($variableName === 'this' && $type instanceof ThisType) { + if ($variableName === 'this' && $type instanceof \PHPStan\Type\ThisType) { $shortClassName = $this->nodeNameResolver->getShortName($type->getClassName()); - $variableName = lcfirst($shortClassName); + $variableName = \lcfirst($shortClassName); } - - $stringy = new Stringy($variableName); + $stringy = new \RectorPrefix20210509\Stringy\Stringy($variableName); return (string) $stringy->camelize(); } - - public function resolveFromFuncCallFirstArgumentWithSuffix( - FuncCall $funcCall, - string $suffix, - string $fallbackName, - ?Scope $scope - ): string { + public function resolveFromFuncCallFirstArgumentWithSuffix(\PhpParser\Node\Expr\FuncCall $funcCall, string $suffix, string $fallbackName, ?\PHPStan\Analyser\Scope $scope) : string + { $bareName = $this->resolveBareFuncCallArgumentName($funcCall, $fallbackName, $suffix); return $this->createCountedValueName($bareName, $scope); } - - private function resolveFromNode(Node $node): ?string + private function resolveFromNode(\PhpParser\Node $node) : ?string { $nodeType = $this->nodeTypeResolver->getStaticType($node); return $this->resolveFromNodeAndType($node, $nodeType); } - - private function unwrapNode(Node $node): ?Node + private function unwrapNode(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof Arg) { + if ($node instanceof \PhpParser\Node\Arg) { return $node->value; } - - if ($node instanceof Cast) { + if ($node instanceof \PhpParser\Node\Expr\Cast) { return $node->expr; } - - if ($node instanceof Ternary) { + if ($node instanceof \PhpParser\Node\Expr\Ternary) { return $node->if; } - return $node; } - - private function resolveParamNameFromArrayDimFetch(ArrayDimFetch $arrayDimFetch): ?string + private function resolveParamNameFromArrayDimFetch(\PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch) : ?string { - while ($arrayDimFetch instanceof ArrayDimFetch) { - if ($arrayDimFetch->dim instanceof Scalar) { + while ($arrayDimFetch instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + if ($arrayDimFetch->dim instanceof \PhpParser\Node\Scalar) { $valueName = $this->nodeNameResolver->getName($arrayDimFetch->var); $dimName = $this->valueResolver->getValue($arrayDimFetch->dim); - - $stringy = new Stringy($dimName); + $stringy = new \RectorPrefix20210509\Stringy\Stringy($dimName); $dimName = (string) $stringy->upperCamelize(); - return $valueName . $dimName; } - $arrayDimFetch = $arrayDimFetch->var; } - return $this->resolveBareFromNode($arrayDimFetch); } - - private function resolveBareFromNode(Node $node): ?string + private function resolveBareFromNode(\PhpParser\Node $node) : ?string { $node = $this->unwrapNode($node); - - if ($node instanceof ArrayDimFetch) { + if ($node instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return $this->resolveParamNameFromArrayDimFetch($node); } - - if ($node instanceof PropertyFetch) { + if ($node instanceof \PhpParser\Node\Expr\PropertyFetch) { return $this->resolveFromPropertyFetch($node); } - - if ($node instanceof MethodCall || $node instanceof NullsafeMethodCall || $node instanceof StaticCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall || $node instanceof \PhpParser\Node\Expr\NullsafeMethodCall || $node instanceof \PhpParser\Node\Expr\StaticCall) { return $this->resolveFromMethodCall($node); } - - if ($node instanceof New_) { + if ($node instanceof \PhpParser\Node\Expr\New_) { return $this->resolveFromNew($node); } - - if ($node instanceof FuncCall) { + if ($node instanceof \PhpParser\Node\Expr\FuncCall) { return $this->resolveFromNode($node->name); } - - if (! $node instanceof Node) { - throw new NotImplementedYetException(); + if (!$node instanceof \PhpParser\Node) { + throw new \Rector\Core\Exception\NotImplementedYetException(); } - $paramName = $this->nodeNameResolver->getName($node); if ($paramName !== null) { return $paramName; } - - if ($node instanceof String_) { + if ($node instanceof \PhpParser\Node\Scalar\String_) { return $node->value; } - return null; } - - private function resolveFromNew(New_ $new): string + private function resolveFromNew(\PhpParser\Node\Expr\New_ $new) : string { - if ($new->class instanceof Name) { + if ($new->class instanceof \PhpParser\Node\Name) { $className = $this->nodeNameResolver->getName($new->class); return $this->nodeNameResolver->getShortName($className); } - - throw new NotImplementedYetException(); + throw new \Rector\Core\Exception\NotImplementedYetException(); } - /** * @param MethodCall|NullsafeMethodCall|StaticCall $node */ - private function resolveFromMethodCall(Node $node): ?string + private function resolveFromMethodCall(\PhpParser\Node $node) : ?string { - if ($node->name instanceof MethodCall) { + if ($node->name instanceof \PhpParser\Node\Expr\MethodCall) { return $this->resolveFromMethodCall($node->name); } - $methodName = $this->nodeNameResolver->getName($node->name); - if (! is_string($methodName)) { + if (!\is_string($methodName)) { return null; } - return $methodName; } - - private function resolveFromPropertyFetch(PropertyFetch $propertyFetch): string + private function resolveFromPropertyFetch(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : string { $varName = $this->nodeNameResolver->getName($propertyFetch->var); - if (! is_string($varName)) { - throw new NotImplementedYetException(); + if (!\is_string($varName)) { + throw new \Rector\Core\Exception\NotImplementedYetException(); } - $propertyName = $this->nodeNameResolver->getName($propertyFetch->name); - if (! is_string($propertyName)) { - throw new NotImplementedYetException(); + if (!\is_string($propertyName)) { + throw new \Rector\Core\Exception\NotImplementedYetException(); } - if ($varName === 'this') { return $propertyName; } - - return $varName . ucfirst($propertyName); + return $varName . \ucfirst($propertyName); } - - private function resolveBareFuncCallArgumentName( - FuncCall $funcCall, - string $fallbackName, - string $suffix - ): string { + private function resolveBareFuncCallArgumentName(\PhpParser\Node\Expr\FuncCall $funcCall, string $fallbackName, string $suffix) : string + { $argumentValue = $funcCall->args[0]->value; - if ($argumentValue instanceof MethodCall || $argumentValue instanceof StaticCall) { + if ($argumentValue instanceof \PhpParser\Node\Expr\MethodCall || $argumentValue instanceof \PhpParser\Node\Expr\StaticCall) { $name = $this->nodeNameResolver->getName($argumentValue->name); } else { $name = $this->nodeNameResolver->getName($argumentValue); } - if ($name === null) { return $fallbackName; } - return $name . $suffix; } } diff --git a/rules/Php70/Rector/Assign/ListSplitStringRector.php b/rules/Php70/Rector/Assign/ListSplitStringRector.php index b7bb0238150..c6f36c047b4 100644 --- a/rules/Php70/Rector/Assign/ListSplitStringRector.php +++ b/rules/Php70/Rector/Assign/ListSplitStringRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->var instanceof List_) { + if (!$node->var instanceof \PhpParser\Node\Expr\List_) { return null; } - - if (! $this->nodeTypeResolver->isStaticType($node->expr, StringType::class)) { + if (!$this->nodeTypeResolver->isStaticType($node->expr, \PHPStan\Type\StringType::class)) { return null; } - $node->expr = $this->nodeFactory->createFuncCall('str_split', [$node->expr]); - return $node; } } diff --git a/rules/Php70/Rector/Assign/ListSwapArrayOrderRector.php b/rules/Php70/Rector/Assign/ListSwapArrayOrderRector.php index 30f424d32c8..fe44fa4e363 100644 --- a/rules/Php70/Rector/Assign/ListSwapArrayOrderRector.php +++ b/rules/Php70/Rector/Assign/ListSwapArrayOrderRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::LIST_SWAP_ORDER)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::LIST_SWAP_ORDER)) { return null; } - - if (! $node->var instanceof List_) { + if (!$node->var instanceof \PhpParser\Node\Expr\List_) { return null; } - $printedVariables = []; foreach ($node->var->items as $arrayItem) { - if (! $arrayItem instanceof ArrayItem) { + if (!$arrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - - if ($arrayItem->value instanceof ArrayDimFetch && $arrayItem->value->dim === null) { + if ($arrayItem->value instanceof \PhpParser\Node\Expr\ArrayDimFetch && $arrayItem->value->dim === null) { $printedVariables[] = $this->print($arrayItem->value->var); } else { return null; } } - // relevant only in 1 variable type - $uniqueVariables = array_unique($printedVariables); - if (count($uniqueVariables) !== 1) { + $uniqueVariables = \array_unique($printedVariables); + if (\count($uniqueVariables) !== 1) { return null; } - // wrap with array_reverse, to reflect reverse assign order in left $node->expr = $this->nodeFactory->createFuncCall('array_reverse', [$node->expr]); - return $node; } } diff --git a/rules/Php70/Rector/Break_/BreakNotInLoopOrSwitchToReturnRector.php b/rules/Php70/Rector/Break_/BreakNotInLoopOrSwitchToReturnRector.php index 7d09b264d47..70fdaee24d8 100644 --- a/rules/Php70/Rector/Break_/BreakNotInLoopOrSwitchToReturnRector.php +++ b/rules/Php70/Rector/Break_/BreakNotInLoopOrSwitchToReturnRector.php @@ -1,7 +1,6 @@ contextAnalyzer = $contextAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Convert break outside for/foreach/switch context to return', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Convert break outside for/foreach/switch context to return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -49,8 +41,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -63,34 +54,27 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Break_::class]; + return [\PhpParser\Node\Stmt\Break_::class]; } - /** * @param Break_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->contextAnalyzer->isInLoop($node)) { return null; } - if ($this->contextAnalyzer->isInIf($node)) { - return new Return_(); + return new \PhpParser\Node\Stmt\Return_(); } - $this->removeNode($node); - return $node; } } diff --git a/rules/Php70/Rector/ClassMethod/Php4ConstructorRector.php b/rules/Php70/Rector/ClassMethod/Php4ConstructorRector.php index 9fb322951d5..f048d0cd048 100644 --- a/rules/Php70/Rector/ClassMethod/Php4ConstructorRector.php +++ b/rules/Php70/Rector/ClassMethod/Php4ConstructorRector.php @@ -1,7 +1,6 @@ php4ConstructorClassMethodAnalyzer = $php4ConstructorClassMethodAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes PHP 4 style constructor to __construct.', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes PHP 4 style constructor to __construct.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function SomeClass() @@ -52,8 +44,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function __construct() @@ -61,157 +52,123 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->php4ConstructorClassMethodAnalyzer->detect($node)) { + if (!$this->php4ConstructorClassMethodAnalyzer->detect($node)) { return null; } - - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - // process parent call references first $this->processClassMethodStatementsForParentConstructorCalls($node); - // not PSR-4 constructor - if (! $this->nodeNameResolver->areNamesEqual($classLike, $node)) { + if (!$this->nodeNameResolver->areNamesEqual($classLike, $node)) { return null; } - - $classMethod = $classLike->getMethod(MethodName::CONSTRUCT); - + $classMethod = $classLike->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); // does it already have a __construct method? - if (! $classMethod instanceof ClassMethod) { - $node->name = new Identifier(MethodName::CONSTRUCT); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + $node->name = new \PhpParser\Node\Identifier(\Rector\Core\ValueObject\MethodName::CONSTRUCT); } - if ($node->stmts === null) { return null; } - - if (count($node->stmts) === 1) { + if (\count($node->stmts) === 1) { /** @var Expression|Expr $stmt */ $stmt = $node->stmts[0]; - if (! $stmt instanceof Expression) { + if (!$stmt instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - if ($this->isLocalMethodCallNamed($stmt->expr, MethodName::CONSTRUCT)) { + if ($this->isLocalMethodCallNamed($stmt->expr, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { $this->removeNode($node); - return null; } } - return $node; } - - private function processClassMethodStatementsForParentConstructorCalls(ClassMethod $classMethod): void + private function processClassMethodStatementsForParentConstructorCalls(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { - if (! is_iterable($classMethod->stmts)) { + if (!\is_iterable($classMethod->stmts)) { return; } - foreach ($classMethod->stmts as $methodStmt) { - if (! $methodStmt instanceof Expression) { + if (!$methodStmt instanceof \PhpParser\Node\Stmt\Expression) { continue; } - $methodStmt = $methodStmt->expr; - if (! $methodStmt instanceof StaticCall) { + if (!$methodStmt instanceof \PhpParser\Node\Expr\StaticCall) { continue; } - $this->processParentPhp4ConstructCall($methodStmt); } } - - private function processParentPhp4ConstructCall(StaticCall $staticCall): void + private function processParentPhp4ConstructCall(\PhpParser\Node\Expr\StaticCall $staticCall) : void { $parentClassName = $this->resolveParentClassName($staticCall); - // no parent class if ($parentClassName === null) { return; } - - if (! $staticCall->class instanceof Name) { + if (!$staticCall->class instanceof \PhpParser\Node\Name) { return; } - // rename ParentClass if ($this->isName($staticCall->class, $parentClassName)) { - $staticCall->class = new Name('parent'); + $staticCall->class = new \PhpParser\Node\Name('parent'); } - - if (! $this->isName($staticCall->class, 'parent')) { + if (!$this->isName($staticCall->class, 'parent')) { return; } - // it's not a parent PHP 4 constructor call - if (! $this->isName($staticCall->name, $parentClassName)) { + if (!$this->isName($staticCall->name, $parentClassName)) { return; } - - $staticCall->name = new Identifier(MethodName::CONSTRUCT); + $staticCall->name = new \PhpParser\Node\Identifier(\Rector\Core\ValueObject\MethodName::CONSTRUCT); } - - private function resolveParentClassName(StaticCall $staticCall): ?string + private function resolveParentClassName(\PhpParser\Node\Expr\StaticCall $staticCall) : ?string { - $scope = $staticCall->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $staticCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } $classReflection = $scope->getClassReflection(); - - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - $parentClassReflection = $classReflection->getParentClass(); - if (! $parentClassReflection instanceof ClassReflection) { + if (!$parentClassReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - return $parentClassReflection->getName(); } - - private function isLocalMethodCallNamed(Expr $expr, string $name): bool + private function isLocalMethodCallNamed(\PhpParser\Node\Expr $expr, string $name) : bool { - if (! $expr instanceof MethodCall) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - - if ($expr->var instanceof StaticCall) { - return false; + if ($expr->var instanceof \PhpParser\Node\Expr\StaticCall) { + return \false; } - - if ($expr->var instanceof MethodCall) { - return false; + if ($expr->var instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - - if (! $this->isName($expr->var, 'this')) { - return false; + if (!$this->isName($expr->var, 'this')) { + return \false; } - return $this->isName($expr->name, $name); } } diff --git a/rules/Php70/Rector/FuncCall/CallUserMethodRector.php b/rules/Php70/Rector/FuncCall/CallUserMethodRector.php index 02bf8a7de50..b64ca570458 100644 --- a/rules/Php70/Rector/FuncCall/CallUserMethodRector.php +++ b/rules/Php70/Rector/FuncCall/CallUserMethodRector.php @@ -1,7 +1,6 @@ */ - private const OLD_TO_NEW_FUNCTIONS = [ - 'call_user_method' => 'call_user_func', - 'call_user_method_array' => 'call_user_func_array', - ]; - - public function getRuleDefinition(): RuleDefinition + private const OLD_TO_NEW_FUNCTIONS = ['call_user_method' => 'call_user_func', 'call_user_method_array' => 'call_user_func_array']; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes call_user_method()/call_user_method_array() to call_user_func()/call_user_func_array()', - [ - new CodeSample( - 'call_user_method($method, $obj, "arg1", "arg2");', - 'call_user_func(array(&$obj, "method"), "arg1", "arg2");' - ), - ] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes call_user_method()/call_user_method_array() to call_user_func()/call_user_func_array()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('call_user_method($method, $obj, "arg1", "arg2");', 'call_user_func(array(&$obj, "method"), "arg1", "arg2");')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $oldFunctionNames = array_keys(self::OLD_TO_NEW_FUNCTIONS); - if (! $this->isNames($node, $oldFunctionNames)) { + $oldFunctionNames = \array_keys(self::OLD_TO_NEW_FUNCTIONS); + if (!$this->isNames($node, $oldFunctionNames)) { return null; } - $newName = self::OLD_TO_NEW_FUNCTIONS[$this->getName($node)]; - $node->name = new Name($newName); - + $node->name = new \PhpParser\Node\Name($newName); $oldArgs = $node->args; - unset($node->args[1]); - $newArgs = [$this->nodeFactory->createArg([$oldArgs[1]->value, $oldArgs[0]->value])]; - unset($oldArgs[0]); unset($oldArgs[1]); - $node->args = $this->appendArgs($newArgs, $oldArgs); - return $node; } } diff --git a/rules/Php70/Rector/FuncCall/EregToPregMatchRector.php b/rules/Php70/Rector/FuncCall/EregToPregMatchRector.php index a9d198b300a..85e1ae983c0 100644 --- a/rules/Php70/Rector/FuncCall/EregToPregMatchRector.php +++ b/rules/Php70/Rector/FuncCall/EregToPregMatchRector.php @@ -1,10 +1,9 @@ */ - private const OLD_NAMES_TO_NEW_ONES = [ - 'ereg' => 'preg_match', - 'eregi' => 'preg_match', - 'ereg_replace' => 'preg_replace', - 'eregi_replace' => 'preg_replace', - 'split' => 'preg_split', - 'spliti' => 'preg_split', - ]; - + private const OLD_NAMES_TO_NEW_ONES = ['ereg' => 'preg_match', 'eregi' => 'preg_match', 'ereg_replace' => 'preg_replace', 'eregi_replace' => 'preg_replace', 'split' => 'preg_split', 'spliti' => 'preg_split']; /** * @var EregToPcreTransformer */ private $eregToPcreTransformer; - - public function __construct(EregToPcreTransformer $eregToPcreTransformer) + public function __construct(\Rector\Php70\EregToPcreTransformer $eregToPcreTransformer) { $this->eregToPcreTransformer = $eregToPcreTransformer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes ereg*() to preg*() calls', - [new CodeSample('ereg("hi")', 'preg_match("#hi#");')] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes ereg*() to preg*() calls', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('ereg("hi")', 'preg_match("#hi#");')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $functionName = $this->getName($node); if ($functionName === null) { return null; } - - if (! isset(self::OLD_NAMES_TO_NEW_ONES[$functionName])) { + if (!isset(self::OLD_NAMES_TO_NEW_ONES[$functionName])) { return null; } - $patternNode = $node->args[0]->value; - if ($patternNode instanceof String_) { + if ($patternNode instanceof \PhpParser\Node\Scalar\String_) { $this->processStringPattern($node, $patternNode, $functionName); - } elseif ($patternNode instanceof Variable) { + } elseif ($patternNode instanceof \PhpParser\Node\Expr\Variable) { $this->processVariablePattern($node, $patternNode, $functionName); } - $this->processSplitLimitArgument($node, $functionName); - - $node->name = new Name(self::OLD_NAMES_TO_NEW_ONES[$functionName]); - + $node->name = new \PhpParser\Node\Name(self::OLD_NAMES_TO_NEW_ONES[$functionName]); // ereg|eregi 3rd argument return value fix - if (in_array($functionName, ['ereg', 'eregi'], true) && isset($node->args[2])) { - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Assign) { + if (\in_array($functionName, ['ereg', 'eregi'], \true) && isset($node->args[2])) { + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\Assign) { return $this->createTernaryWithStrlenOfFirstMatch($node); } } - return $node; } - - private function processStringPattern(FuncCall $funcCall, String_ $string, string $functionName): void + private function processStringPattern(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Scalar\String_ $string, string $functionName) : void { $pattern = $string->value; $pattern = $this->eregToPcreTransformer->transform($pattern, $this->isCaseInsensitiveFunction($functionName)); - - $funcCall->args[0]->value = new String_($pattern); + $funcCall->args[0]->value = new \PhpParser\Node\Scalar\String_($pattern); } - - private function processVariablePattern(FuncCall $funcCall, Variable $variable, string $functionName): void + private function processVariablePattern(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr\Variable $variable, string $functionName) : void { - $pregQuotePatternNode = $this->nodeFactory->createFuncCall('preg_quote', [ - new Arg($variable), - new Arg(new String_('#')), - ]); - - $startConcat = new Concat(new String_('#'), $pregQuotePatternNode); - + $pregQuotePatternNode = $this->nodeFactory->createFuncCall('preg_quote', [new \PhpParser\Node\Arg($variable), new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_('#'))]); + $startConcat = new \PhpParser\Node\Expr\BinaryOp\Concat(new \PhpParser\Node\Scalar\String_('#'), $pregQuotePatternNode); $endDelimiter = $this->isCaseInsensitiveFunction($functionName) ? '#mi' : '#m'; - $concat = new Concat($startConcat, new String_($endDelimiter)); - + $concat = new \PhpParser\Node\Expr\BinaryOp\Concat($startConcat, new \PhpParser\Node\Scalar\String_($endDelimiter)); $funcCall->args[0]->value = $concat; } - /** * Equivalent of: * split(' ', 'hey Tom', 0); * ↓ * preg_split('# #', 'hey Tom', 1); */ - private function processSplitLimitArgument(FuncCall $funcCall, string $functionName): void + private function processSplitLimitArgument(\PhpParser\Node\Expr\FuncCall $funcCall, string $functionName) : void { - if (! Strings::startsWith($functionName, 'split')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::startsWith($functionName, 'split')) { return; } - // 3rd argument - $limit, 0 → 1 - if (! isset($funcCall->args[2])) { + if (!isset($funcCall->args[2])) { return; } - - if (! $funcCall->args[2]->value instanceof LNumber) { + if (!$funcCall->args[2]->value instanceof \PhpParser\Node\Scalar\LNumber) { return; } - /** @var LNumber $limitNumberNode */ $limitNumberNode = $funcCall->args[2]->value; if ($limitNumberNode->value !== 0) { return; } - $limitNumberNode->value = 1; } - - private function createTernaryWithStrlenOfFirstMatch(FuncCall $funcCall): Ternary + private function createTernaryWithStrlenOfFirstMatch(\PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\Ternary { - $arrayDimFetch = new ArrayDimFetch($funcCall->args[2]->value, new LNumber(0)); + $arrayDimFetch = new \PhpParser\Node\Expr\ArrayDimFetch($funcCall->args[2]->value, new \PhpParser\Node\Scalar\LNumber(0)); $strlenFuncCall = $this->nodeFactory->createFuncCall('strlen', [$arrayDimFetch]); - - return new Ternary($funcCall, $strlenFuncCall, $this->nodeFactory->createFalse()); + return new \PhpParser\Node\Expr\Ternary($funcCall, $strlenFuncCall, $this->nodeFactory->createFalse()); } - - private function isCaseInsensitiveFunction(string $functionName): bool + private function isCaseInsensitiveFunction(string $functionName) : bool { - if (Strings::contains($functionName, 'eregi')) { - return true; + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($functionName, 'eregi')) { + return \true; } - return Strings::contains($functionName, 'spliti'); + return \RectorPrefix20210509\Nette\Utils\Strings::contains($functionName, 'spliti'); } } diff --git a/rules/Php70/Rector/FuncCall/MultiDirnameRector.php b/rules/Php70/Rector/FuncCall/MultiDirnameRector.php index 4021f1ae554..0a5e2f53dd2 100644 --- a/rules/Php70/Rector/FuncCall/MultiDirnameRector.php +++ b/rules/Php70/Rector/FuncCall/MultiDirnameRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::DIRNAME_LEVELS)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::DIRNAME_LEVELS)) { return null; } - $this->nestingLevel = 0; - - if (! $this->isName($node, self::DIRNAME)) { + if (!$this->isName($node, self::DIRNAME)) { return null; } - $activeFuncCallNode = $node; $lastFuncCallNode = $node; - while ($activeFuncCallNode = $this->matchNestedDirnameFuncCall($activeFuncCallNode)) { $lastFuncCallNode = $activeFuncCallNode; } - // nothing to improve if ($this->nestingLevel < 2) { return $activeFuncCallNode; } - $node->args[0] = $lastFuncCallNode->args[0]; - $node->args[1] = new Arg(new LNumber($this->nestingLevel)); - + $node->args[1] = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\LNumber($this->nestingLevel)); return $node; } - - private function matchNestedDirnameFuncCall(FuncCall $funcCall): ?FuncCall + private function matchNestedDirnameFuncCall(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr\FuncCall { - if (! $this->isName($funcCall, self::DIRNAME)) { + if (!$this->isName($funcCall, self::DIRNAME)) { return null; } - - if (count($funcCall->args) >= 3) { + if (\count($funcCall->args) >= 3) { return null; } - // dirname($path, ); - if (count($funcCall->args) === 2) { - if (! $funcCall->args[1]->value instanceof LNumber) { + if (\count($funcCall->args) === 2) { + if (!$funcCall->args[1]->value instanceof \PhpParser\Node\Scalar\LNumber) { return null; } - /** @var LNumber $levelNumber */ $levelNumber = $funcCall->args[1]->value; - $this->nestingLevel += $levelNumber->value; } else { ++$this->nestingLevel; } - $nestedFuncCallNode = $funcCall->args[0]->value; - if (! $nestedFuncCallNode instanceof FuncCall) { + if (!$nestedFuncCallNode instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - if ($this->isName($nestedFuncCallNode, self::DIRNAME)) { return $nestedFuncCallNode; } - return null; } } diff --git a/rules/Php70/Rector/FuncCall/NonVariableToVariableOnFunctionCallRector.php b/rules/Php70/Rector/FuncCall/NonVariableToVariableOnFunctionCallRector.php index 63e0de38efd..d53320f1c3d 100644 --- a/rules/Php70/Rector/FuncCall/NonVariableToVariableOnFunctionCallRector.php +++ b/rules/Php70/Rector/FuncCall/NonVariableToVariableOnFunctionCallRector.php @@ -1,7 +1,6 @@ callReflectionResolver = $callReflectionResolver; $this->variableNaming = $variableNaming; $this->parentScopeFinder = $parentScopeFinder; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Transform non variable like arguments to variable where a function or method expects an argument passed by reference', - [new CodeSample('reset(a());', '$a = a(); reset($a);')] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Transform non variable like arguments to variable where a function or method expects an argument passed by reference', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('reset(a());', '$a = a(); reset($a);')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class, MethodCall::class, StaticCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class, \PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param FuncCall|MethodCall|StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $arguments = $this->getNonVariableArguments($node); if ($arguments === []) { return null; } - $scopeNode = $this->parentScopeFinder->find($node); if ($scopeNode === null) { return null; } - - $currentScope = $scopeNode->getAttribute(AttributeKey::SCOPE); - if (! $currentScope instanceof MutatingScope) { + $currentScope = $scopeNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$currentScope instanceof \PHPStan\Analyser\MutatingScope) { return null; } - foreach ($arguments as $key => $argument) { $replacements = $this->getReplacementsFor($argument, $currentScope, $scopeNode); - - $current = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); - - $currentStatement = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); - $this->addNodeBeforeNode( - $replacements->getAssign(), - $current instanceof Return_ ? $current : $currentStatement - ); - + $current = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); + $currentStatement = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); + $this->addNodeBeforeNode($replacements->getAssign(), $current instanceof \PhpParser\Node\Stmt\Return_ ? $current : $currentStatement); $node->args[$key]->value = $replacements->getVariable(); - // add variable name to scope, so we prevent duplication of new variable of the same name - $currentScope = $currentScope->assignExpression( - $replacements->getVariable(), - $currentScope->getType($replacements->getVariable()) - ); + $currentScope = $currentScope->assignExpression($replacements->getVariable(), $currentScope->getType($replacements->getVariable())); } - - $scopeNode->setAttribute(AttributeKey::SCOPE, $currentScope); - + $scopeNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE, $currentScope); return $node; } - /** * @param FuncCall|MethodCall|StaticCall $node * * @return Expr[] */ - private function getNonVariableArguments(Node $node): array + private function getNonVariableArguments(\PhpParser\Node $node) : array { $arguments = []; - - $parametersAcceptor = $this->callReflectionResolver->resolveParametersAcceptor( - $this->callReflectionResolver->resolveCall($node), - $node - ); - - if (! $parametersAcceptor instanceof ParametersAcceptor) { + $parametersAcceptor = $this->callReflectionResolver->resolveParametersAcceptor($this->callReflectionResolver->resolveCall($node), $node); + if (!$parametersAcceptor instanceof \PHPStan\Reflection\ParametersAcceptor) { return []; } - /** @var ParameterReflection $parameterReflection */ foreach ($parametersAcceptor->getParameters() as $key => $parameterReflection) { // omitted optional parameter - if (! isset($node->args[$key])) { + if (!isset($node->args[$key])) { continue; } - if ($parameterReflection->passedByReference()->no()) { continue; } - $argument = $node->args[$key]->value; - if ($this->isVariableLikeNode($argument)) { continue; } - $arguments[$key] = $argument; } - return $arguments; } - - private function getReplacementsFor(Expr $expr, MutatingScope $mutatingScope, Node $scopeNode): VariableAssignPair + private function getReplacementsFor(\PhpParser\Node\Expr $expr, \PHPStan\Analyser\MutatingScope $mutatingScope, \PhpParser\Node $scopeNode) : \Rector\Php70\ValueObject\VariableAssignPair { /** @var Assign|AssignOp|AssignRef $expr */ if ($this->isAssign($expr) && $this->isVariableLikeNode($expr->var)) { - return new VariableAssignPair($expr->var, $expr); + return new \Rector\Php70\ValueObject\VariableAssignPair($expr->var, $expr); } - - $variableName = $this->variableNaming->resolveFromNodeWithScopeCountAndFallbackName( - $expr, - $mutatingScope, - 'tmp' - ); - - $variable = new Variable($variableName); - + $variableName = $this->variableNaming->resolveFromNodeWithScopeCountAndFallbackName($expr, $mutatingScope, 'tmp'); + $variable = new \PhpParser\Node\Expr\Variable($variableName); // add a new scope with this variable - $newVariableAwareScope = $mutatingScope->assignExpression($variable, new MixedType()); - $scopeNode->setAttribute(AttributeKey::SCOPE, $newVariableAwareScope); - - return new VariableAssignPair($variable, new Assign($variable, $expr)); + $newVariableAwareScope = $mutatingScope->assignExpression($variable, new \PHPStan\Type\MixedType()); + $scopeNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE, $newVariableAwareScope); + return new \Rector\Php70\ValueObject\VariableAssignPair($variable, new \PhpParser\Node\Expr\Assign($variable, $expr)); } - - private function isVariableLikeNode(Node $node): bool + private function isVariableLikeNode(\PhpParser\Node $node) : bool { - return $node instanceof Variable - || $node instanceof ArrayDimFetch - || $node instanceof PropertyFetch - || $node instanceof StaticPropertyFetch; + return $node instanceof \PhpParser\Node\Expr\Variable || $node instanceof \PhpParser\Node\Expr\ArrayDimFetch || $node instanceof \PhpParser\Node\Expr\PropertyFetch || $node instanceof \PhpParser\Node\Expr\StaticPropertyFetch; } - - private function isAssign(Expr $expr): bool + private function isAssign(\PhpParser\Node\Expr $expr) : bool { - if ($expr instanceof Assign) { - return true; + if ($expr instanceof \PhpParser\Node\Expr\Assign) { + return \true; } - - if ($expr instanceof AssignRef) { - return true; + if ($expr instanceof \PhpParser\Node\Expr\AssignRef) { + return \true; } - - return $expr instanceof AssignOp; + return $expr instanceof \PhpParser\Node\Expr\AssignOp; } } diff --git a/rules/Php70/Rector/FuncCall/RandomFunctionRector.php b/rules/Php70/Rector/FuncCall/RandomFunctionRector.php index f1d79e04f82..a20f579780f 100644 --- a/rules/Php70/Rector/FuncCall/RandomFunctionRector.php +++ b/rules/Php70/Rector/FuncCall/RandomFunctionRector.php @@ -1,7 +1,6 @@ */ - private const OLD_TO_NEW_FUNCTION_NAMES = [ - 'getrandmax' => 'mt_getrandmax', - 'srand' => 'mt_srand', - 'mt_rand' => 'random_int', - 'rand' => 'random_int', - ]; - - public function getRuleDefinition(): RuleDefinition + private const OLD_TO_NEW_FUNCTION_NAMES = ['getrandmax' => 'mt_getrandmax', 'srand' => 'mt_srand', 'mt_rand' => 'random_int', 'rand' => 'random_int']; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes rand, srand and getrandmax by new mt_* alternatives.', - [new CodeSample('rand();', 'mt_rand();')] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes rand, srand and getrandmax by new mt_* alternatives.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('rand();', 'mt_rand();')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::CSPRNG_FUNCTIONS)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::CSPRNG_FUNCTIONS)) { return null; } - foreach (self::OLD_TO_NEW_FUNCTION_NAMES as $oldFunctionName => $newFunctionName) { if ($this->isName($node, $oldFunctionName)) { - $node->name = new Name($newFunctionName); - + $node->name = new \PhpParser\Node\Name($newFunctionName); // special case: random_int(); → random_int(0, getrandmax()); if ($newFunctionName === 'random_int' && $node->args === []) { - $node->args[0] = new Arg(new LNumber(0)); - $node->args[1] = new Arg($this->nodeFactory->createFuncCall('mt_getrandmax')); + $node->args[0] = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\LNumber(0)); + $node->args[1] = new \PhpParser\Node\Arg($this->nodeFactory->createFuncCall('mt_getrandmax')); } - return $node; } } - return $node; } } diff --git a/rules/Php70/Rector/FuncCall/RenameMktimeWithoutArgsToTimeRector.php b/rules/Php70/Rector/FuncCall/RenameMktimeWithoutArgsToTimeRector.php index a800b3dda4b..4f99be9aef5 100644 --- a/rules/Php70/Rector/FuncCall/RenameMktimeWithoutArgsToTimeRector.php +++ b/rules/Php70/Rector/FuncCall/RenameMktimeWithoutArgsToTimeRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'mktime')) { + if (!$this->isName($node, 'mktime')) { return null; } - if ($node->args !== []) { return null; } - - $node->name = new Name('time'); - + $node->name = new \PhpParser\Node\Name('time'); return $node; } } diff --git a/rules/Php70/Rector/FunctionLike/ExceptionHandlerTypehintRector.php b/rules/Php70/Rector/FunctionLike/ExceptionHandlerTypehintRector.php index 77bccc89014..cec3ba35ab6 100644 --- a/rules/Php70/Rector/FunctionLike/ExceptionHandlerTypehintRector.php +++ b/rules/Php70/Rector/FunctionLike/ExceptionHandlerTypehintRector.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, ClassMethod::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param Function_|ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::THROWABLE_TYPE)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::THROWABLE_TYPE)) { return null; } - // exception handle has 1 param exactly - if (count($node->params) !== 1) { + if (\count($node->params) !== 1) { return null; } - $paramNode = $node->params[0]; if ($paramNode->type === null) { return null; } - // handle only Exception typehint - $actualType = $paramNode->type instanceof NullableType ? $this->getName( - $paramNode->type->type - ) : $this->getName($paramNode->type); + $actualType = $paramNode->type instanceof \PhpParser\Node\NullableType ? $this->getName($paramNode->type->type) : $this->getName($paramNode->type); if ($actualType !== 'Exception') { return null; } - // is probably handling exceptions - if (! Strings::match((string) $node->name, self::HANDLE_INSENSITIVE_REGEX)) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::match((string) $node->name, self::HANDLE_INSENSITIVE_REGEX)) { return null; } - - if (! $paramNode->type instanceof NullableType) { - $paramNode->type = new FullyQualified('Throwable'); + if (!$paramNode->type instanceof \PhpParser\Node\NullableType) { + $paramNode->type = new \PhpParser\Node\Name\FullyQualified('Throwable'); } else { - $paramNode->type->type = new FullyQualified('Throwable'); + $paramNode->type->type = new \PhpParser\Node\Name\FullyQualified('Throwable'); } - return $node; } } diff --git a/rules/Php70/Rector/If_/IfToSpaceshipRector.php b/rules/Php70/Rector/If_/IfToSpaceshipRector.php index be25fa1a045..2bcdd212c2d 100644 --- a/rules/Php70/Rector/If_/IfToSpaceshipRector.php +++ b/rules/Php70/Rector/If_/IfToSpaceshipRector.php @@ -1,7 +1,6 @@ where useful', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes if/else to spaceship <=> where useful', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -80,8 +68,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -92,34 +79,27 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::SPACESHIP)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SPACESHIP)) { return null; } - - if (! $node->cond instanceof Equal && ! $node->cond instanceof Identical) { + if (!$node->cond instanceof \PhpParser\Node\Expr\BinaryOp\Equal && !$node->cond instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { return null; } - $this->reset(); - $this->matchOnEqualFirstValueAndSecondValue($node); if ($this->firstValue === null) { return null; @@ -127,122 +107,96 @@ CODE_SAMPLE if ($this->secondValue === null) { return null; } - /** @var Equal|Identical $condition */ $condition = $node->cond; - - if (! $this->areVariablesEqual($condition, $this->firstValue, $this->secondValue)) { + if (!$this->areVariablesEqual($condition, $this->firstValue, $this->secondValue)) { return null; } - // is spaceship return values? if ([$this->onGreater, $this->onEqual, $this->onSmaller] !== [-1, 0, 1]) { return null; } - if ($this->nextNode !== null) { $this->removeNode($this->nextNode); } - // spaceship ready! - $spaceship = new Spaceship($this->secondValue, $this->firstValue); - - return new Return_($spaceship); + $spaceship = new \PhpParser\Node\Expr\BinaryOp\Spaceship($this->secondValue, $this->firstValue); + return new \PhpParser\Node\Stmt\Return_($spaceship); } - - private function reset(): void + private function reset() : void { $this->onEqual = null; $this->onSmaller = null; $this->onGreater = null; - $this->firstValue = null; $this->secondValue = null; } - - private function matchOnEqualFirstValueAndSecondValue(If_ $if): void + private function matchOnEqualFirstValueAndSecondValue(\PhpParser\Node\Stmt\If_ $if) : void { $this->matchOnEqual($if); - if ($if->else !== null) { $this->processElse($if->else); } else { - $this->nextNode = $if->getAttribute(AttributeKey::NEXT_NODE); - if ($this->nextNode instanceof Return_ && $this->nextNode->expr instanceof Ternary) { + $this->nextNode = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if ($this->nextNode instanceof \PhpParser\Node\Stmt\Return_ && $this->nextNode->expr instanceof \PhpParser\Node\Expr\Ternary) { /** @var Ternary $ternary */ $ternary = $this->nextNode->expr; $this->processTernary($ternary); } } } - - private function areVariablesEqual(BinaryOp $binaryOp, Expr $firstValue, Expr $secondValue): bool + private function areVariablesEqual(\PhpParser\Node\Expr\BinaryOp $binaryOp, \PhpParser\Node\Expr $firstValue, \PhpParser\Node\Expr $secondValue) : bool { - if ($this->nodeComparator->areNodesEqual($binaryOp->left, $firstValue) && $this->nodeComparator->areNodesEqual( - $binaryOp->right, - $secondValue - )) { - return true; + if ($this->nodeComparator->areNodesEqual($binaryOp->left, $firstValue) && $this->nodeComparator->areNodesEqual($binaryOp->right, $secondValue)) { + return \true; } - if (! $this->nodeComparator->areNodesEqual($binaryOp->right, $firstValue)) { - return false; + if (!$this->nodeComparator->areNodesEqual($binaryOp->right, $firstValue)) { + return \false; } return $this->nodeComparator->areNodesEqual($binaryOp->left, $secondValue); } - - private function matchOnEqual(If_ $if): void + private function matchOnEqual(\PhpParser\Node\Stmt\If_ $if) : void { - if (count($if->stmts) !== 1) { + if (\count($if->stmts) !== 1) { return; } - $onlyIfStmt = $if->stmts[0]; - - if ($onlyIfStmt instanceof Return_) { + if ($onlyIfStmt instanceof \PhpParser\Node\Stmt\Return_) { if ($onlyIfStmt->expr === null) { return; } - $this->onEqual = $this->valueResolver->getValue($onlyIfStmt->expr); } } - - private function processElse(Else_ $else): void + private function processElse(\PhpParser\Node\Stmt\Else_ $else) : void { - if (count($else->stmts) !== 1) { + if (\count($else->stmts) !== 1) { return; } - - if (! $else->stmts[0] instanceof Return_) { + if (!$else->stmts[0] instanceof \PhpParser\Node\Stmt\Return_) { return; } - /** @var Return_ $returnNode */ $returnNode = $else->stmts[0]; - if ($returnNode->expr instanceof Ternary) { + if ($returnNode->expr instanceof \PhpParser\Node\Expr\Ternary) { $this->processTernary($returnNode->expr); } } - - private function processTernary(Ternary $ternary): void + private function processTernary(\PhpParser\Node\Expr\Ternary $ternary) : void { - if ($ternary->cond instanceof Smaller) { + if ($ternary->cond instanceof \PhpParser\Node\Expr\BinaryOp\Smaller) { $this->firstValue = $ternary->cond->left; $this->secondValue = $ternary->cond->right; - if ($ternary->if !== null) { $this->onSmaller = $this->valueResolver->getValue($ternary->if); } - $this->onGreater = $this->valueResolver->getValue($ternary->else); - } elseif ($ternary->cond instanceof Greater) { + } elseif ($ternary->cond instanceof \PhpParser\Node\Expr\BinaryOp\Greater) { $this->firstValue = $ternary->cond->right; $this->secondValue = $ternary->cond->left; - if ($ternary->if !== null) { $this->onGreater = $this->valueResolver->getValue($ternary->if); } - $this->onSmaller = $this->valueResolver->getValue($ternary->else); } } diff --git a/rules/Php70/Rector/List_/EmptyListRector.php b/rules/Php70/Rector/List_/EmptyListRector.php index f4f56bb554c..9ee8b35f93a 100644 --- a/rules/Php70/Rector/List_/EmptyListRector.php +++ b/rules/Php70/Rector/List_/EmptyListRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [List_::class]; + return [\PhpParser\Node\Expr\List_::class]; } - /** * @param List_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($node->items as $item) { if ($item !== null) { return null; } } - - $node->items[0] = new ArrayItem(new Variable('unusedGenerated')); - + $node->items[0] = new \PhpParser\Node\Expr\ArrayItem(new \PhpParser\Node\Expr\Variable('unusedGenerated')); return $node; } } diff --git a/rules/Php70/Rector/MethodCall/ThisCallOnStaticMethodToStaticCallRector.php b/rules/Php70/Rector/MethodCall/ThisCallOnStaticMethodToStaticCallRector.php index 2e7f01c85aa..f84088b08ae 100644 --- a/rules/Php70/Rector/MethodCall/ThisCallOnStaticMethodToStaticCallRector.php +++ b/rules/Php70/Rector/MethodCall/ThisCallOnStaticMethodToStaticCallRector.php @@ -1,7 +1,6 @@ staticAnalyzer = $staticAnalyzer; $this->methodReflectionProvider = $methodReflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes $this->call() to static method to static call', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes $this->call() to static method to static call', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public static function run() @@ -58,8 +49,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public static function run() @@ -72,77 +62,62 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->var instanceof Variable) { + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - - if (! $this->nodeNameResolver->isName($node->var, 'this')) { + if (!$this->nodeNameResolver->isName($node->var, 'this')) { return null; } - $methodName = $this->getName($node->name); if ($methodName === null) { return null; } - // skip PHPUnit calls, as they accept both self:: and $this-> formats - if ($this->isObjectType($node->var, new ObjectType('PHPUnit\Framework\TestCase'))) { + if ($this->isObjectType($node->var, new \PHPStan\Type\ObjectType('PHPUnit\\Framework\\TestCase'))) { return null; } - /** @var class-string $className */ - $className = $node->getAttribute(AttributeKey::CLASS_NAME); - if (! is_string($className)) { + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + if (!\is_string($className)) { return null; } - $isStaticMethod = $this->staticAnalyzer->isStaticMethod($methodName, $className); - if (! $isStaticMethod) { + if (!$isStaticMethod) { return null; } - $classReference = $this->resolveClassSelf($node); return $this->nodeFactory->createStaticCall($classReference, $methodName, $node->args); } - - private function resolveClassSelf(MethodCall $methodCall): string + private function resolveClassSelf(\PhpParser\Node\Expr\MethodCall $methodCall) : string { - $classLike = $methodCall->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return 'static'; } - if ($classLike->isFinal()) { return 'self'; } - $methodReflection = $this->methodReflectionProvider->provideByMethodCall($methodCall); - if (! $methodReflection instanceof PhpMethodReflection) { + if (!$methodReflection instanceof \PHPStan\Reflection\Php\PhpMethodReflection) { return 'static'; } - - if (! $methodReflection->isPrivate()) { + if (!$methodReflection->isPrivate()) { return 'static'; } - return 'self'; } } diff --git a/rules/Php70/Rector/StaticCall/StaticCallOnNonStaticToInstanceCallRector.php b/rules/Php70/Rector/StaticCall/StaticCallOnNonStaticToInstanceCallRector.php index 60fd5279db6..d83c418c762 100644 --- a/rules/Php70/Rector/StaticCall/StaticCallOnNonStaticToInstanceCallRector.php +++ b/rules/Php70/Rector/StaticCall/StaticCallOnNonStaticToInstanceCallRector.php @@ -1,7 +1,6 @@ classMethodManipulator = $classMethodManipulator; $this->staticAnalyzer = $staticAnalyzer; $this->reflectionProvider = $reflectionProvider; $this->parentClassScopeResolver = $parentClassScopeResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes static call to instance call, where not useful', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes static call to instance call, where not useful', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class Something { public function doWork() @@ -82,8 +67,7 @@ class Another } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class Something { public function doWork() @@ -99,30 +83,24 @@ class Another } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node->name instanceof Expr) { + if ($node->name instanceof \PhpParser\Node\Expr) { return null; } - $methodName = $this->getName($node->name); - $className = $this->resolveStaticCallClassName($node); if ($methodName === null) { return null; @@ -130,78 +108,61 @@ CODE_SAMPLE if ($className === null) { return null; } - if ($this->shouldSkip($methodName, $className, $node)) { return null; } - if ($this->isInstantiable($className)) { - $new = new New_($node->class); - - return new MethodCall($new, $node->name, $node->args); + $new = new \PhpParser\Node\Expr\New_($node->class); + return new \PhpParser\Node\Expr\MethodCall($new, $node->name, $node->args); } - // can we add static to method? $classMethodNode = $this->nodeRepository->findClassMethod($className, $methodName); - if (! $classMethodNode instanceof ClassMethod) { + if (!$classMethodNode instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - if ($this->classMethodManipulator->isStaticClassMethod($classMethodNode)) { return null; } - $this->visibilityManipulator->makeStatic($classMethodNode); - return null; } - - private function resolveStaticCallClassName(StaticCall $staticCall): ?string + private function resolveStaticCallClassName(\PhpParser\Node\Expr\StaticCall $staticCall) : ?string { - if ($staticCall->class instanceof PropertyFetch) { + if ($staticCall->class instanceof \PhpParser\Node\Expr\PropertyFetch) { $objectType = $this->getObjectType($staticCall->class); - if ($objectType instanceof ObjectType) { + if ($objectType instanceof \PHPStan\Type\ObjectType) { return $objectType->getClassName(); } } - return $this->getName($staticCall->class); } - - private function shouldSkip(string $methodName, string $className, StaticCall $staticCall): bool + private function shouldSkip(string $methodName, string $className, \PhpParser\Node\Expr\StaticCall $staticCall) : bool { $isStaticMethod = $this->staticAnalyzer->isStaticMethod($methodName, $className); if ($isStaticMethod) { - return true; + return \true; } - if ($this->isNames($staticCall->class, ['self', 'parent', 'static', 'class'])) { - return true; + return \true; } - $parentClassName = $this->parentClassScopeResolver->resolveParentClassName($staticCall); return $className === $parentClassName; } - - private function isInstantiable(string $className): bool + private function isInstantiable(string $className) : bool { - if (! $this->reflectionProvider->hasClass($className)) { - return false; + if (!$this->reflectionProvider->hasClass($className)) { + return \false; } - $classReflection = $this->reflectionProvider->getClass($className); $reflectionClass = $classReflection->getNativeReflection(); - $reflectionMethod = $reflectionClass->getConstructor(); - if (! $reflectionMethod instanceof ReflectionMethod) { - return true; + if (!$reflectionMethod instanceof \ReflectionMethod) { + return \true; } - - if (! $reflectionMethod->isPublic()) { - return false; + if (!$reflectionMethod->isPublic()) { + return \false; } - // required parameters in constructor, nothing we can do - return ! (bool) $reflectionMethod->getNumberOfRequiredParameters(); + return !(bool) $reflectionMethod->getNumberOfRequiredParameters(); } } diff --git a/rules/Php70/Rector/Switch_/ReduceMultipleDefaultSwitchRector.php b/rules/Php70/Rector/Switch_/ReduceMultipleDefaultSwitchRector.php index bb0aaee03d3..18707205a69 100644 --- a/rules/Php70/Rector/Switch_/ReduceMultipleDefaultSwitchRector.php +++ b/rules/Php70/Rector/Switch_/ReduceMultipleDefaultSwitchRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Switch_::class]; + return [\PhpParser\Node\Stmt\Switch_::class]; } - /** * @param Switch_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $defaultCases = []; foreach ($node->cases as $case) { if ($case->cond !== null) { continue; } - $defaultCases[] = $case; } - - if (count($defaultCases) < 2) { + if (\count($defaultCases) < 2) { return null; } - $this->removeExtraDefaultCases($defaultCases); - return $node; } - /** * @param Case_[] $defaultCases */ - private function removeExtraDefaultCases(array $defaultCases): void + private function removeExtraDefaultCases(array $defaultCases) : void { // keep only last - array_pop($defaultCases); + \array_pop($defaultCases); foreach ($defaultCases as $defaultCase) { $this->keepStatementsToParentCase($defaultCase); $this->removeNode($defaultCase); } } - - private function keepStatementsToParentCase(Case_ $case): void + private function keepStatementsToParentCase(\PhpParser\Node\Stmt\Case_ $case) : void { - $previousNode = $case->getAttribute(AttributeKey::PREVIOUS_NODE); - if (! $previousNode instanceof Case_) { + $previousNode = $case->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if (!$previousNode instanceof \PhpParser\Node\Stmt\Case_) { return; } - if ($previousNode->stmts === []) { $previousNode->stmts = $case->stmts; $case->stmts = []; diff --git a/rules/Php70/Rector/Ternary/TernaryToNullCoalescingRector.php b/rules/Php70/Rector/Ternary/TernaryToNullCoalescingRector.php index dca7242982d..9c85f427df2 100644 --- a/rules/Php70/Rector/Ternary/TernaryToNullCoalescingRector.php +++ b/rules/Php70/Rector/Ternary/TernaryToNullCoalescingRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::NULL_COALESCE)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::NULL_COALESCE)) { return null; } - - if ($node->cond instanceof Isset_) { + if ($node->cond instanceof \PhpParser\Node\Expr\Isset_) { return $this->processTernaryWithIsset($node); } - - if ($node->cond instanceof Identical) { + if ($node->cond instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { $checkedNode = $node->else; $fallbackNode = $node->if; - } elseif ($node->cond instanceof NotIdentical) { + } elseif ($node->cond instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical) { $checkedNode = $node->if; $fallbackNode = $node->else; } else { @@ -66,51 +54,43 @@ final class TernaryToNullCoalescingRector extends AbstractRector if ($checkedNode === null) { return null; } - if (! $fallbackNode instanceof Expr) { + if (!$fallbackNode instanceof \PhpParser\Node\Expr) { return null; } - /** @var Identical|NotIdentical $ternaryCompareNode */ $ternaryCompareNode = $node->cond; if ($this->isNullMatch($ternaryCompareNode->left, $ternaryCompareNode->right, $checkedNode)) { - return new Coalesce($checkedNode, $fallbackNode); + return new \PhpParser\Node\Expr\BinaryOp\Coalesce($checkedNode, $fallbackNode); } if ($this->isNullMatch($ternaryCompareNode->right, $ternaryCompareNode->left, $checkedNode)) { - return new Coalesce($checkedNode, $fallbackNode); + return new \PhpParser\Node\Expr\BinaryOp\Coalesce($checkedNode, $fallbackNode); } - return null; } - - private function processTernaryWithIsset(Ternary $ternary): ?Coalesce + private function processTernaryWithIsset(\PhpParser\Node\Expr\Ternary $ternary) : ?\PhpParser\Node\Expr\BinaryOp\Coalesce { if ($ternary->if === null) { return null; } - /** @var Isset_ $issetNode */ $issetNode = $ternary->cond; // none or multiple isset values cannot be handled here - if (! isset($issetNode->vars[0])) { + if (!isset($issetNode->vars[0])) { return null; } - if (count($issetNode->vars) > 1) { + if (\count($issetNode->vars) > 1) { return null; } - if ($this->nodeComparator->areNodesEqual($ternary->if, $issetNode->vars[0])) { - return new Coalesce($ternary->if, $ternary->else); + return new \PhpParser\Node\Expr\BinaryOp\Coalesce($ternary->if, $ternary->else); } - return null; } - - private function isNullMatch(Expr $possibleNullExpr, Node $firstNode, Node $secondNode): bool + private function isNullMatch(\PhpParser\Node\Expr $possibleNullExpr, \PhpParser\Node $firstNode, \PhpParser\Node $secondNode) : bool { - if (! $this->valueResolver->isNull($possibleNullExpr)) { - return false; + if (!$this->valueResolver->isNull($possibleNullExpr)) { + return \false; } - return $this->nodeComparator->areNodesEqual($firstNode, $secondNode); } } diff --git a/rules/Php70/Rector/Ternary/TernaryToSpaceshipRector.php b/rules/Php70/Rector/Ternary/TernaryToSpaceshipRector.php index 2122d61edaa..c6c96d2991e 100644 --- a/rules/Php70/Rector/Ternary/TernaryToSpaceshipRector.php +++ b/rules/Php70/Rector/Ternary/TernaryToSpaceshipRector.php @@ -1,7 +1,6 @@ spaceship instead of ternary with same effect', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Use <=> spaceship instead of ternary with same effect', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' function order_func($a, $b) { return ($a < $b) ? -1 : (($a > $b) ? 1 : 0); } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' function order_func($a, $b) { return $a <=> $b; } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::SPACESHIP)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SPACESHIP)) { return null; } - if ($this->shouldSkip($node)) { return null; } - /** @var Ternary $nestedTernary */ $nestedTernary = $node->else; - $spaceshipNode = $this->processSmallerThanTernary($node, $nestedTernary); if ($spaceshipNode !== null) { return $spaceshipNode; } - return $this->processGreaterThanTernary($node, $nestedTernary); } - - private function shouldSkip(Ternary $ternary): bool + private function shouldSkip(\PhpParser\Node\Expr\Ternary $ternary) : bool { - if (! $ternary->cond instanceof BinaryOp) { - return true; + if (!$ternary->cond instanceof \PhpParser\Node\Expr\BinaryOp) { + return \true; } - - if (! $ternary->else instanceof Ternary) { - return true; + if (!$ternary->else instanceof \PhpParser\Node\Expr\Ternary) { + return \true; } - $nestedTernary = $ternary->else; - - if (! $nestedTernary->cond instanceof BinaryOp) { - return true; - } - - // $a X $b ? . : ($a X $b ? . : .) - if (! $this->nodeComparator->areNodesEqual($ternary->cond->left, $nestedTernary->cond->left)) { - return true; + if (!$nestedTernary->cond instanceof \PhpParser\Node\Expr\BinaryOp) { + return \true; } // $a X $b ? . : ($a X $b ? . : .) - return ! $this->nodeComparator->areNodesEqual($ternary->cond->right, $nestedTernary->cond->right); + if (!$this->nodeComparator->areNodesEqual($ternary->cond->left, $nestedTernary->cond->left)) { + return \true; + } + // $a X $b ? . : ($a X $b ? . : .) + return !$this->nodeComparator->areNodesEqual($ternary->cond->right, $nestedTernary->cond->right); } - /** * Matches "$a < $b ? -1 : ($a > $b ? 1 : 0)" */ - private function processSmallerThanTernary(Ternary $node, Ternary $nestedTernary): ?Spaceship + private function processSmallerThanTernary(\PhpParser\Node\Expr\Ternary $node, \PhpParser\Node\Expr\Ternary $nestedTernary) : ?\PhpParser\Node\Expr\BinaryOp\Spaceship { - if (! $node->cond instanceof Smaller) { + if (!$node->cond instanceof \PhpParser\Node\Expr\BinaryOp\Smaller) { return null; } - - if (! $nestedTernary->cond instanceof Greater) { + if (!$nestedTernary->cond instanceof \PhpParser\Node\Expr\BinaryOp\Greater) { return null; } - - if (! $this->valueResolver->areValues([$node->if, $nestedTernary->if, $nestedTernary->else], [-1, 1, 0])) { + if (!$this->valueResolver->areValues([$node->if, $nestedTernary->if, $nestedTernary->else], [-1, 1, 0])) { return null; } - - return new Spaceship($node->cond->left, $node->cond->right); + return new \PhpParser\Node\Expr\BinaryOp\Spaceship($node->cond->left, $node->cond->right); } - /** * Matches "$a > $b ? -1 : ($a < $b ? 1 : 0)" */ - private function processGreaterThanTernary(Ternary $node, Ternary $nestedTernary): ?Spaceship + private function processGreaterThanTernary(\PhpParser\Node\Expr\Ternary $node, \PhpParser\Node\Expr\Ternary $nestedTernary) : ?\PhpParser\Node\Expr\BinaryOp\Spaceship { - if (! $node->cond instanceof Greater) { + if (!$node->cond instanceof \PhpParser\Node\Expr\BinaryOp\Greater) { return null; } - - if (! $nestedTernary->cond instanceof Smaller) { + if (!$nestedTernary->cond instanceof \PhpParser\Node\Expr\BinaryOp\Smaller) { return null; } - - if (! $this->valueResolver->areValues([$node->if, $nestedTernary->if, $nestedTernary->else], [-1, 1, 0])) { + if (!$this->valueResolver->areValues([$node->if, $nestedTernary->if, $nestedTernary->else], [-1, 1, 0])) { return null; } - - return new Spaceship($node->cond->right, $node->cond->left); + return new \PhpParser\Node\Expr\BinaryOp\Spaceship($node->cond->right, $node->cond->left); } } diff --git a/rules/Php70/Rector/Variable/WrapVariableVariableNameInCurlyBracesRector.php b/rules/Php70/Rector/Variable/WrapVariableVariableNameInCurlyBracesRector.php index 9594a6cef33..03a7c50769b 100644 --- a/rules/Php70/Rector/Variable/WrapVariableVariableNameInCurlyBracesRector.php +++ b/rules/Php70/Rector/Variable/WrapVariableVariableNameInCurlyBracesRector.php @@ -1,7 +1,6 @@ bar; } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' function run($foo) { global ${$foo->bar}; } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Variable::class]; + return [\PhpParser\Node\Expr\Variable::class]; } - /** * @param Variable $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $nodeName = $node->name; - - if (! $nodeName instanceof PropertyFetch && ! $nodeName instanceof Variable) { + if (!$nodeName instanceof \PhpParser\Node\Expr\PropertyFetch && !$nodeName instanceof \PhpParser\Node\Expr\Variable) { return null; } - if ($node->getEndTokenPos() !== $nodeName->getEndTokenPos()) { return null; } - - if ($nodeName instanceof PropertyFetch) { - return new Variable(new PropertyFetch($nodeName->var, $nodeName->name)); + if ($nodeName instanceof \PhpParser\Node\Expr\PropertyFetch) { + return new \PhpParser\Node\Expr\Variable(new \PhpParser\Node\Expr\PropertyFetch($nodeName->var, $nodeName->name)); } - - return new Variable(new Variable($nodeName->name)); + return new \PhpParser\Node\Expr\Variable(new \PhpParser\Node\Expr\Variable($nodeName->name)); } } diff --git a/rules/Php70/ValueObject/VariableAssignPair.php b/rules/Php70/ValueObject/VariableAssignPair.php index 7cb868ed058..fe17bea60f9 100644 --- a/rules/Php70/ValueObject/VariableAssignPair.php +++ b/rules/Php70/ValueObject/VariableAssignPair.php @@ -1,7 +1,6 @@ variable = $variable; $this->assign = $node; } - /** * @return Variable|ArrayDimFetch|PropertyFetch|StaticPropertyFetch */ - public function getVariable(): Expr + public function getVariable() : \PhpParser\Node\Expr { return $this->variable; } - /** * @return Assign|AssignOp|AssignRef */ - public function getAssign(): Expr + public function getAssign() : \PhpParser\Node\Expr { return $this->assign; } diff --git a/rules/Php71/IsArrayAndDualCheckToAble.php b/rules/Php71/IsArrayAndDualCheckToAble.php index 1ad4431477e..243ba2bcaf1 100644 --- a/rules/Php71/IsArrayAndDualCheckToAble.php +++ b/rules/Php71/IsArrayAndDualCheckToAble.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->binaryOpManipulator = $binaryOpManipulator; } - - public function processBooleanOr(BooleanOr $booleanOr, string $type, string $newMethodName): ?FuncCall + public function processBooleanOr(\PhpParser\Node\Expr\BinaryOp\BooleanOr $booleanOr, string $type, string $newMethodName) : ?\PhpParser\Node\Expr\FuncCall { - $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode( - $booleanOr, - Instanceof_::class, - FuncCall::class - ); - - if (! $twoNodeMatch instanceof TwoNodeMatch) { + $twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode($booleanOr, \PhpParser\Node\Expr\Instanceof_::class, \PhpParser\Node\Expr\FuncCall::class); + if (!$twoNodeMatch instanceof \Rector\Php71\ValueObject\TwoNodeMatch) { return null; } - /** @var Instanceof_ $instanceOf */ $instanceOf = $twoNodeMatch->getFirstExpr(); - /** @var FuncCall $funcCall */ $funcCall = $twoNodeMatch->getSecondExpr(); - $instanceOfClass = $instanceOf->class; - if ($instanceOfClass instanceof Expr) { + if ($instanceOfClass instanceof \PhpParser\Node\Expr) { return null; } - if ((string) $instanceOfClass !== $type) { return null; } - - if (! $this->nodeNameResolver->isName($funcCall, 'is_array')) { + if (!$this->nodeNameResolver->isName($funcCall, 'is_array')) { return null; } - // both use same var - if (! $funcCall->args[0]->value instanceof Variable) { + if (!$funcCall->args[0]->value instanceof \PhpParser\Node\Expr\Variable) { return null; } - /** @var Variable $firstVarNode */ $firstVarNode = $funcCall->args[0]->value; - - if (! $instanceOf->expr instanceof Variable) { + if (!$instanceOf->expr instanceof \PhpParser\Node\Expr\Variable) { return null; } - /** @var Variable $secondVarNode */ $secondVarNode = $instanceOf->expr; - // are they same variables if ($firstVarNode->name !== $secondVarNode->name) { return null; } - - return new FuncCall(new Name($newMethodName), [new Arg($firstVarNode)]); + return new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name($newMethodName), [new \PhpParser\Node\Arg($firstVarNode)]); } } diff --git a/rules/Php71/NodeAnalyzer/CountableAnalyzer.php b/rules/Php71/NodeAnalyzer/CountableAnalyzer.php index 094401587fd..ca95d70b785 100644 --- a/rules/Php71/NodeAnalyzer/CountableAnalyzer.php +++ b/rules/Php71/NodeAnalyzer/CountableAnalyzer.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; } - - public function isCastableArrayType(Expr $expr): bool + public function isCastableArrayType(\PhpParser\Node\Expr $expr) : bool { - if (! $expr instanceof PropertyFetch) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - $callerObjectType = $this->nodeTypeResolver->resolve($expr->var); - $propertyName = $this->nodeNameResolver->getName($expr->name); - if (! is_string($propertyName)) { - return false; + if (!\is_string($propertyName)) { + return \false; } - - if ($callerObjectType instanceof UnionType) { + if ($callerObjectType instanceof \PHPStan\Type\UnionType) { $callerObjectType = $callerObjectType->getTypes()[0]; } - - if (! $callerObjectType instanceof TypeWithClassName) { - return false; + if (!$callerObjectType instanceof \PHPStan\Type\TypeWithClassName) { + return \false; } - - if (is_a($callerObjectType->getClassName(), Stmt::class, true)) { - return false; + if (\is_a($callerObjectType->getClassName(), \PhpParser\Node\Stmt::class, \true)) { + return \false; } - - if (is_a($callerObjectType->getClassName(), Array_::class, true)) { - return false; + if (\is_a($callerObjectType->getClassName(), \PhpParser\Node\Expr\Array_::class, \true)) { + return \false; } - // this must be handled reflection, as PHPStan ReflectionProvider does not provide default values for properties in any way - $classReflection = $this->reflectionProvider->getClass($callerObjectType->getClassName()); - $nativeReflectionClass = $classReflection->getNativeReflection(); $propertiesDefaults = $nativeReflectionClass->getDefaultProperties(); - - if (! array_key_exists($propertyName, $propertiesDefaults)) { - return false; + if (!\array_key_exists($propertyName, $propertiesDefaults)) { + return \false; } - $propertyDefaultValue = $propertiesDefaults[$propertyName]; return $propertyDefaultValue === null; } diff --git a/rules/Php71/NodeFinder/EmptyStringDefaultPropertyFinder.php b/rules/Php71/NodeFinder/EmptyStringDefaultPropertyFinder.php index 0a89c760035..3a7d8cffbd9 100644 --- a/rules/Php71/NodeFinder/EmptyStringDefaultPropertyFinder.php +++ b/rules/Php71/NodeFinder/EmptyStringDefaultPropertyFinder.php @@ -1,7 +1,6 @@ */ private $propertyPropertiesByClassName = []; - - public function __construct(BetterNodeFinder $betterNodeFinder) + public function __construct(\Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder) { $this->betterNodeFinder = $betterNodeFinder; } - /** * @return PropertyProperty[] */ - public function find(Assign $assign): array + public function find(\PhpParser\Node\Expr\Assign $assign) : array { - $classLike = $assign->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return []; } - - $className = $assign->getAttribute(AttributeKey::CLASS_NAME); - if (! is_string($className)) { + $className = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + if (!\is_string($className)) { return []; } - if (isset($this->propertyPropertiesByClassName[$className])) { return $this->propertyPropertiesByClassName[$className]; } - /** @var PropertyProperty[] $propertyProperties */ - $propertyProperties = $this->betterNodeFinder->find($classLike, function (Node $node): bool { - if (! $node instanceof PropertyProperty) { - return false; + $propertyProperties = $this->betterNodeFinder->find($classLike, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Stmt\PropertyProperty) { + return \false; } - if ($node->default === null) { - return false; + return \false; } - return $this->isEmptyString($node->default); }); - $this->propertyPropertiesByClassName[$className] = $propertyProperties; - return $propertyProperties; } - - private function isEmptyString(Expr $expr): bool + private function isEmptyString(\PhpParser\Node\Expr $expr) : bool { - if (! $expr instanceof String_) { - return false; + if (!$expr instanceof \PhpParser\Node\Scalar\String_) { + return \false; } - return $expr->value === ''; } } diff --git a/rules/Php71/Rector/Assign/AssignArrayToStringRector.php b/rules/Php71/Rector/Assign/AssignArrayToStringRector.php index f349d565e50..8f88644fa88 100644 --- a/rules/Php71/Rector/Assign/AssignArrayToStringRector.php +++ b/rules/Php71/Rector/Assign/AssignArrayToStringRector.php @@ -1,7 +1,6 @@ emptyStringDefaultPropertyFinder = $emptyStringDefaultPropertyFinder; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'String cannot be turned into array by assignment anymore', - [new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('String cannot be turned into array by assignment anymore', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $string = ''; $string[] = 1; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $string = []; $string[] = 1; CODE_SAMPLE - )] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $this->emptyStringProperties = $this->emptyStringDefaultPropertyFinder->find($node); - // only array with no explicit key assign, e.g. "$value[] = 5"; - if (! $node->var instanceof ArrayDimFetch) { + if (!$node->var instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return null; } - if ($node->var->dim !== null) { return null; } - $arrayDimFetchNode = $node->var; - /** @var Variable|PropertyFetch|StaticPropertyFetch|Expr $variable */ $variable = $arrayDimFetchNode->var; - // set default value to property - if (($variable instanceof PropertyFetch || $variable instanceof StaticPropertyFetch) && - $this->refactorPropertyFetch($variable) - ) { + if (($variable instanceof \PhpParser\Node\Expr\PropertyFetch || $variable instanceof \PhpParser\Node\Expr\StaticPropertyFetch) && $this->refactorPropertyFetch($variable)) { return $node; } - // fallback to variable, property or static property = '' set if ($this->processVariable($node, $variable)) { return $node; } - - $isFoundPrev = (bool) $this->betterNodeFinder->findFirstPreviousOfNode($variable, function (Node $node) use ( - $variable - ): bool { + $isFoundPrev = (bool) $this->betterNodeFinder->findFirstPreviousOfNode($variable, function (\PhpParser\Node $node) use($variable) : bool { return $this->nodeComparator->areNodesEqual($node, $variable); }); - - if (! $isFoundPrev) { + if (!$isFoundPrev) { return null; } - // there is "$string[] = ...;", which would cause error in PHP 7+ // fallback - if no array init found, retype to (array) - $assign = new Assign($variable, new ArrayCast($variable)); + $assign = new \PhpParser\Node\Expr\Assign($variable, new \PhpParser\Node\Expr\Cast\Array_($variable)); $this->addNodeAfterNode(clone $node, $node); - return $assign; } - /** * @param PropertyFetch|StaticPropertyFetch $propertyFetchExpr */ - private function refactorPropertyFetch(Expr $propertyFetchExpr): bool + private function refactorPropertyFetch(\PhpParser\Node\Expr $propertyFetchExpr) : bool { foreach ($this->emptyStringProperties as $emptyStringProperty) { - if (! $this->nodeNameResolver->areNamesEqual($emptyStringProperty, $propertyFetchExpr)) { + if (!$this->nodeNameResolver->areNamesEqual($emptyStringProperty, $propertyFetchExpr)) { continue; } - - $emptyStringProperty->default = new Array_(); - return true; + $emptyStringProperty->default = new \PhpParser\Node\Expr\Array_(); + return \true; } - - return false; + return \false; } - /** * @param Variable|PropertyFetch|StaticPropertyFetch|Expr $expr */ - private function processVariable(Assign $assign, Expr $expr): bool + private function processVariable(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Expr $expr) : bool { if ($this->shouldSkipVariable($expr)) { - return true; + return \true; } - - $variableAssign = $this->betterNodeFinder->findFirstPrevious($assign, function (Node $node) use ($expr): bool { - if (! $node instanceof Assign) { - return false; + $variableAssign = $this->betterNodeFinder->findFirstPrevious($assign, function (\PhpParser\Node $node) use($expr) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - if (! $this->nodeComparator->areNodesEqual($node->var, $expr)) { - return false; + if (!$this->nodeComparator->areNodesEqual($node->var, $expr)) { + return \false; } - // we look for variable assign = string - if (! $node->expr instanceof String_) { - return false; + if (!$node->expr instanceof \PhpParser\Node\Scalar\String_) { + return \false; } - return $this->valueResolver->isValue($node->expr, ''); }); - - if ($variableAssign instanceof Assign) { - $variableAssign->expr = new Array_(); - return true; + if ($variableAssign instanceof \PhpParser\Node\Expr\Assign) { + $variableAssign->expr = new \PhpParser\Node\Expr\Array_(); + return \true; } - - return false; + return \false; } - - private function shouldSkipVariable(Expr $expr): bool + private function shouldSkipVariable(\PhpParser\Node\Expr $expr) : bool { $staticType = $this->getStaticType($expr); - if ($staticType instanceof ErrorType) { - return false; + if ($staticType instanceof \PHPStan\Type\ErrorType) { + return \false; } - - if ($staticType instanceof UnionType) { - return ! ($staticType->isSuperTypeOf(new ArrayType(new MixedType(), new MixedType()))->yes() && - $staticType->isSuperTypeOf(new ConstantStringType('')) - ->yes()); + if ($staticType instanceof \PHPStan\Type\UnionType) { + return !($staticType->isSuperTypeOf(new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()))->yes() && $staticType->isSuperTypeOf(new \PHPStan\Type\Constant\ConstantStringType(''))->yes()); } - - return ! $staticType instanceof StringType; + return !$staticType instanceof \PHPStan\Type\StringType; } } diff --git a/rules/Php71/Rector/BinaryOp/BinaryOpBetweenNumberAndStringRector.php b/rules/Php71/Rector/BinaryOp/BinaryOpBetweenNumberAndStringRector.php index 28cecf935fc..d4648fff2ff 100644 --- a/rules/Php71/Rector/BinaryOp/BinaryOpBetweenNumberAndStringRector.php +++ b/rules/Php71/Rector/BinaryOp/BinaryOpBetweenNumberAndStringRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [BinaryOp::class]; + return [\PhpParser\Node\Expr\BinaryOp::class]; } - /** * @param BinaryOp $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof Concat) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { return null; } - if ($node instanceof Coalesce) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Coalesce) { return null; } - if ($this->isStringOrStaticNonNumbericString($node->left) && $this->nodeTypeResolver->isNumberType( - $node->right - )) { - $node->left = new LNumber(0); - + if ($this->isStringOrStaticNonNumbericString($node->left) && $this->nodeTypeResolver->isNumberType($node->right)) { + $node->left = new \PhpParser\Node\Scalar\LNumber(0); return $node; } - - if ($this->isStringOrStaticNonNumbericString($node->right) && $this->nodeTypeResolver->isNumberType( - $node->left - )) { - $node->right = new LNumber(0); - + if ($this->isStringOrStaticNonNumbericString($node->right) && $this->nodeTypeResolver->isNumberType($node->left)) { + $node->right = new \PhpParser\Node\Scalar\LNumber(0); return $node; } - return null; } - - private function isStringOrStaticNonNumbericString(Expr $expr): bool + private function isStringOrStaticNonNumbericString(\PhpParser\Node\Expr $expr) : bool { // replace only scalar values, not variables/constants/etc. - if (! $expr instanceof Scalar && ! $expr instanceof Variable) { - return false; + if (!$expr instanceof \PhpParser\Node\Scalar && !$expr instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - $value = null; $exprStaticType = $this->getStaticType($expr); - - if ($expr instanceof String_) { + if ($expr instanceof \PhpParser\Node\Scalar\String_) { $value = $expr->value; - } elseif ($exprStaticType instanceof ConstantStringType) { + } elseif ($exprStaticType instanceof \PHPStan\Type\Constant\ConstantStringType) { $value = $exprStaticType->getValue(); } else { - return false; + return \false; } - - return ! is_numeric($value); + return !\is_numeric($value); } } diff --git a/rules/Php71/Rector/BooleanOr/IsIterableRector.php b/rules/Php71/Rector/BooleanOr/IsIterableRector.php index c648328cbfb..b1ca60dc633 100644 --- a/rules/Php71/Rector/BooleanOr/IsIterableRector.php +++ b/rules/Php71/Rector/BooleanOr/IsIterableRector.php @@ -1,7 +1,6 @@ isArrayAndDualCheckToAble = $isArrayAndDualCheckToAble; $this->reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes is_array + Traversable check to is_iterable', - [new CodeSample('is_array($foo) || $foo instanceof Traversable;', 'is_iterable($foo);')] - ); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes is_array + Traversable check to is_iterable', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('is_array($foo) || $foo instanceof Traversable;', 'is_iterable($foo);')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [BooleanOr::class]; + return [\PhpParser\Node\Expr\BinaryOp\BooleanOr::class]; } - /** * @param BooleanOr $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip()) { return null; } - return $this->isArrayAndDualCheckToAble->processBooleanOr($node, 'Traversable', 'is_iterable') ?: $node; } - - private function shouldSkip(): bool + private function shouldSkip() : bool { - if ($this->reflectionProvider->hasFunction(new Name('is_iterable'), null)) { - return false; + if ($this->reflectionProvider->hasFunction(new \PhpParser\Node\Name('is_iterable'), null)) { + return \false; } - - return ! $this->isAtLeastPhpVersion(PhpVersionFeature::IS_ITERABLE); + return !$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::IS_ITERABLE); } } diff --git a/rules/Php71/Rector/ClassConst/PublicConstantVisibilityRector.php b/rules/Php71/Rector/ClassConst/PublicConstantVisibilityRector.php index c40993e8a64..9ed5f671c41 100644 --- a/rules/Php71/Rector/ClassConst/PublicConstantVisibilityRector.php +++ b/rules/Php71/Rector/ClassConst/PublicConstantVisibilityRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassConst::class]; + return [\PhpParser\Node\Stmt\ClassConst::class]; } - /** * @param ClassConst $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::CONSTANT_VISIBILITY)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::CONSTANT_VISIBILITY)) { return null; } - // already non-public - if (! $node->isPublic()) { + if (!$node->isPublic()) { return null; } - // explicitly public if ($node->flags !== 0) { return null; } - $this->visibilityManipulator->makePublic($node); - return $node; } } diff --git a/rules/Php71/Rector/FuncCall/CountOnNullRector.php b/rules/Php71/Rector/FuncCall/CountOnNullRector.php index 0cc799d2039..0f01b242177 100644 --- a/rules/Php71/Rector/FuncCall/CountOnNullRector.php +++ b/rules/Php71/Rector/FuncCall/CountOnNullRector.php @@ -1,7 +1,6 @@ countableTypeAnalyzer = $countableTypeAnalyzer; $this->countableAnalyzer = $countableAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes count() on null to safe ternary check', - [new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes count() on null to safe ternary check', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $values = null; $count = count($values); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $values = null; $count = count((array) $values); CODE_SAMPLE - )] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $countedNode = $node->args[0]->value; if ($this->countableTypeAnalyzer->isCountableType($countedNode)) { return null; } - // this can lead to false positive by phpstan, but that's best we can do $onlyValueType = $this->getStaticType($countedNode); - if ($onlyValueType instanceof ArrayType) { - if (! $this->countableAnalyzer->isCastableArrayType($countedNode)) { + if ($onlyValueType instanceof \PHPStan\Type\ArrayType) { + if (!$this->countableAnalyzer->isCastableArrayType($countedNode)) { return null; } - return $this->castToArray($countedNode, $node); } - - if ($this->nodeTypeResolver->isNullableTypeOfSpecificType($countedNode, ArrayType::class)) { + if ($this->nodeTypeResolver->isNullableTypeOfSpecificType($countedNode, \PHPStan\Type\ArrayType::class)) { return $this->castToArray($countedNode, $node); } - - if ($this->nodeTypeResolver->isNullableType($countedNode) || $this->nodeTypeResolver->isStaticType( - $countedNode, - NullType::class - )) { - $identical = new Identical($countedNode, $this->nodeFactory->createNull()); - $ternary = new Ternary($identical, new LNumber(0), $node); + if ($this->nodeTypeResolver->isNullableType($countedNode) || $this->nodeTypeResolver->isStaticType($countedNode, \PHPStan\Type\NullType::class)) { + $identical = new \PhpParser\Node\Expr\BinaryOp\Identical($countedNode, $this->nodeFactory->createNull()); + $ternary = new \PhpParser\Node\Expr\Ternary($identical, new \PhpParser\Node\Scalar\LNumber(0), $node); // prevent infinity loop re-resolution - $node->setAttribute(self::ALREADY_CHANGED_ON_COUNT, true); + $node->setAttribute(self::ALREADY_CHANGED_ON_COUNT, \true); return $ternary; } - - if ($this->isAtLeastPhpVersion(PhpVersionFeature::IS_COUNTABLE)) { - $conditionNode = new FuncCall(new Name('is_countable'), [new Arg($countedNode)]); + if ($this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::IS_COUNTABLE)) { + $conditionNode = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('is_countable'), [new \PhpParser\Node\Arg($countedNode)]); } else { - $instanceof = new Instanceof_($countedNode, new FullyQualified('Countable')); - $conditionNode = new BooleanOr($this->nodeFactory->createFuncCall( - 'is_array', - [new Arg($countedNode)] - ), $instanceof); + $instanceof = new \PhpParser\Node\Expr\Instanceof_($countedNode, new \PhpParser\Node\Name\FullyQualified('Countable')); + $conditionNode = new \PhpParser\Node\Expr\BinaryOp\BooleanOr($this->nodeFactory->createFuncCall('is_array', [new \PhpParser\Node\Arg($countedNode)]), $instanceof); } - // prevent infinity loop re-resolution - $node->setAttribute(self::ALREADY_CHANGED_ON_COUNT, true); - - return new Ternary($conditionNode, $node, new LNumber(0)); + $node->setAttribute(self::ALREADY_CHANGED_ON_COUNT, \true); + return new \PhpParser\Node\Expr\Ternary($conditionNode, $node, new \PhpParser\Node\Scalar\LNumber(0)); } - - private function shouldSkip(FuncCall $funcCall): bool + private function shouldSkip(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - if (! $this->isName($funcCall, 'count')) { - return true; + if (!$this->isName($funcCall, 'count')) { + return \true; } - $alreadyChangedOnCount = $funcCall->getAttribute(self::ALREADY_CHANGED_ON_COUNT); - // check if it has some condition before already, if so, probably it's already handled if ($alreadyChangedOnCount) { - return true; + return \true; } - - $parentNode = $funcCall->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Ternary) { - return true; + $parentNode = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\Ternary) { + return \true; } - - if (! isset($funcCall->args[0])) { - return true; + if (!isset($funcCall->args[0])) { + return \true; } - // skip node in trait, as impossible to analyse - $classLike = $funcCall->getAttribute(AttributeKey::CLASS_NODE); - return $classLike instanceof Trait_; + $classLike = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + return $classLike instanceof \PhpParser\Node\Stmt\Trait_; } - - private function castToArray(Expr $countedExpr, FuncCall $funcCall): FuncCall + private function castToArray(\PhpParser\Node\Expr $countedExpr, \PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr\FuncCall { - $castArray = new Array_($countedExpr); - $funcCall->args = [new Arg($castArray)]; - + $castArray = new \PhpParser\Node\Expr\Cast\Array_($countedExpr); + $funcCall->args = [new \PhpParser\Node\Arg($castArray)]; return $funcCall; } } diff --git a/rules/Php71/Rector/FuncCall/RemoveExtraParametersRector.php b/rules/Php71/Rector/FuncCall/RemoveExtraParametersRector.php index 785b1976e0c..e16a2403a77 100644 --- a/rules/Php71/Rector/FuncCall/RemoveExtraParametersRector.php +++ b/rules/Php71/Rector/FuncCall/RemoveExtraParametersRector.php @@ -1,7 +1,6 @@ callReflectionResolver = $callReflectionResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove extra parameters', [ - new CodeSample('strlen("asdf", 1);', 'strlen("asdf");'), - ]); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove extra parameters', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample('strlen("asdf", 1);', 'strlen("asdf");')]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class, MethodCall::class, StaticCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class, \PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param FuncCall|MethodCall|StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - // unreliable count of arguments $functionLikeReflection = $this->callReflectionResolver->resolveCall($node); - if ($functionLikeReflection instanceof UnionTypeMethodReflection) { + if ($functionLikeReflection instanceof \PHPStan\Reflection\Type\UnionTypeMethodReflection) { return null; } - if ($functionLikeReflection === null) { return null; } - $maximumAllowedParameterCount = $this->resolveMaximumAllowedParameterCount($functionLikeReflection); - - $numberOfArguments = count($node->args); + $numberOfArguments = \count($node->args); if ($numberOfArguments <= $maximumAllowedParameterCount) { return null; } - for ($i = $maximumAllowedParameterCount; $i <= $numberOfArguments; ++$i) { unset($node->args[$i]); } - return $node; } - /** * @param FuncCall|MethodCall|StaticCall $node */ - private function shouldSkip(Node $node): bool + private function shouldSkip(\PhpParser\Node $node) : bool { if ($node->args === []) { - return true; + return \true; } - - if ($node instanceof StaticCall) { - if (! $node->class instanceof Name) { - return true; + if ($node instanceof \PhpParser\Node\Expr\StaticCall) { + if (!$node->class instanceof \PhpParser\Node\Name) { + return \true; } - if ($this->isName($node->class, 'parent')) { - return true; + return \true; } } - $functionReflection = $this->callReflectionResolver->resolveCall($node); if ($functionReflection === null) { - return true; + return \true; } - if ($functionReflection->getVariants() === []) { - return true; + return \true; } - return $this->hasVariadicParameters($functionReflection->getVariants()); } - /** * @param MethodReflection|FunctionReflection $reflection */ - private function resolveMaximumAllowedParameterCount(object $reflection): int + private function resolveMaximumAllowedParameterCount($reflection) : int { $parameterCounts = [0]; foreach ($reflection->getVariants() as $parametersAcceptor) { - $parameterCounts[] = count($parametersAcceptor->getParameters()); + $parameterCounts[] = \count($parametersAcceptor->getParameters()); } - - return (int) max($parameterCounts); + return (int) \max($parameterCounts); } - /** * @param ParametersAcceptor[] $parameterAcceptors */ - private function hasVariadicParameters(array $parameterAcceptors): bool + private function hasVariadicParameters(array $parameterAcceptors) : bool { foreach ($parameterAcceptors as $parameterAcceptor) { // can be any number of arguments → nothing to limit here if ($parameterAcceptor->isVariadic()) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/Php71/Rector/List_/ListToArrayDestructRector.php b/rules/Php71/Rector/List_/ListToArrayDestructRector.php index 6c288677f1d..15b98bb3e98 100644 --- a/rules/Php71/Rector/List_/ListToArrayDestructRector.php +++ b/rules/Php71/Rector/List_/ListToArrayDestructRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [List_::class]; + return [\PhpParser\Node\Expr\List_::class]; } - /** * @param List_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::ARRAY_DESTRUCT)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::ARRAY_DESTRUCT)) { return null; } - - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - - if ($parentNode instanceof Assign && $parentNode->var === $node) { - return new Array_($node->items); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\Assign && $parentNode->var === $node) { + return new \PhpParser\Node\Expr\Array_($node->items); } - if (! $parentNode instanceof Foreach_) { + if (!$parentNode instanceof \PhpParser\Node\Stmt\Foreach_) { return null; } if ($parentNode->valueVar !== $node) { return null; } - return new Array_($node->items); + return new \PhpParser\Node\Expr\Array_($node->items); } } diff --git a/rules/Php71/Rector/Name/ReservedObjectRector.php b/rules/Php71/Rector/Name/ReservedObjectRector.php index 1e0dea43ccb..de226e31557 100644 --- a/rules/Php71/Rector/Name/ReservedObjectRector.php +++ b/rules/Php71/Rector/Name/ReservedObjectRector.php @@ -1,7 +1,6 @@ */ private $reservedKeywordsToReplacements = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes reserved "Object" name to "Object" where can be configured', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes reserved "Object" name to "Object" where can be configured', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class Object { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SmartObject { } CODE_SAMPLE - , - [ - self::RESERVED_KEYWORDS_TO_REPLACEMENTS => [ - 'ReservedObject' => 'SmartObject', - 'Object' => 'AnotherSmartObject', - ], - ] - ), - ] - ); +, [self::RESERVED_KEYWORDS_TO_REPLACEMENTS => ['ReservedObject' => 'SmartObject', 'Object' => 'AnotherSmartObject']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identifier::class, Name::class]; + return [\PhpParser\Node\Identifier::class, \PhpParser\Node\Name::class]; } - /** * @param Identifier|Name $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof Identifier) { + if ($node instanceof \PhpParser\Node\Identifier) { return $this->processIdentifier($node); } - return $this->processName($node); } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->reservedKeywordsToReplacements = $configuration[self::RESERVED_KEYWORDS_TO_REPLACEMENTS] ?? []; } - - private function processIdentifier(Identifier $identifier): Identifier + private function processIdentifier(\PhpParser\Node\Identifier $identifier) : \PhpParser\Node\Identifier { foreach ($this->reservedKeywordsToReplacements as $reservedKeyword => $replacement) { - if (! $this->isName($identifier, $reservedKeyword)) { + if (!$this->isName($identifier, $reservedKeyword)) { continue; } - $identifier->name = $replacement; return $identifier; } - return $identifier; } - - private function processName(Name $name): Name + private function processName(\PhpParser\Node\Name $name) : \PhpParser\Node\Name { // we look for "extends " - $parentNode = $name->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // "Object" can part of namespace name - if ($parentNode instanceof Namespace_) { + if ($parentNode instanceof \PhpParser\Node\Stmt\Namespace_) { return $name; } - // process lass part foreach ($this->reservedKeywordsToReplacements as $reservedKeyword => $replacement) { - if (strtolower($name->getLast()) === strtolower($reservedKeyword)) { - $name->parts[count($name->parts) - 1] = $replacement; - + if (\strtolower($name->getLast()) === \strtolower($reservedKeyword)) { + $name->parts[\count($name->parts) - 1] = $replacement; // invoke override - $name->setAttribute(AttributeKey::ORIGINAL_NODE, null); + $name->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); } } - return $name; } } diff --git a/rules/Php71/Rector/TryCatch/MultiExceptionCatchRector.php b/rules/Php71/Rector/TryCatch/MultiExceptionCatchRector.php index 98114248c1a..14ee83a5f4d 100644 --- a/rules/Php71/Rector/TryCatch/MultiExceptionCatchRector.php +++ b/rules/Php71/Rector/TryCatch/MultiExceptionCatchRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [TryCatch::class]; + return [\PhpParser\Node\Stmt\TryCatch::class]; } - /** * @param TryCatch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::MULTI_EXCEPTION_CATCH)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::MULTI_EXCEPTION_CATCH)) { return null; } - - if (count($node->catches) < 2) { + if (\count($node->catches) < 2) { return null; } - $catchKeysByContent = $this->collectCatchKeysByContent($node); /** @var Catch_[] $catchKeys */ foreach ($catchKeysByContent as $catchKeys) { // no duplicates - $count = count($catchKeys); + $count = \count($catchKeys); if ($count < 2) { continue; } - $collectedTypes = $this->collectTypesFromCatchedByIds($node, $catchKeys); - /** @var Catch_ $firstCatch */ - $firstCatch = array_shift($catchKeys); + $firstCatch = \array_shift($catchKeys); $firstCatch->types = $collectedTypes; - foreach ($catchKeys as $catchKey) { $this->removeNode($catchKey); } } - return $node; } - /** * @return array */ - private function collectCatchKeysByContent(TryCatch $tryCatch): array + private function collectCatchKeysByContent(\PhpParser\Node\Stmt\TryCatch $tryCatch) : array { $catchKeysByContent = []; foreach ($tryCatch->catches as $catch) { $catchContent = $this->print($catch->stmts); $catchKeysByContent[$catchContent][] = $catch; } - return $catchKeysByContent; } - /** * @param Catch_[] $catches * @return Name[] */ - private function collectTypesFromCatchedByIds(TryCatch $tryCatch, array $catches): array + private function collectTypesFromCatchedByIds(\PhpParser\Node\Stmt\TryCatch $tryCatch, array $catches) : array { $collectedTypes = []; - foreach ($catches as $catch) { - $collectedTypes = array_merge($collectedTypes, $catch->types); + $collectedTypes = \array_merge($collectedTypes, $catch->types); } - return $collectedTypes; } } diff --git a/rules/Php71/ValueObject/TwoNodeMatch.php b/rules/Php71/ValueObject/TwoNodeMatch.php index e3e2b836217..4faa371f98e 100644 --- a/rules/Php71/ValueObject/TwoNodeMatch.php +++ b/rules/Php71/ValueObject/TwoNodeMatch.php @@ -1,35 +1,29 @@ firstExpr = $firstExpr; $this->secondExpr = $secondExpr; } - - public function getFirstExpr(): Expr + public function getFirstExpr() : \PhpParser\Node\Expr { return $this->firstExpr; } - - public function getSecondExpr(): Expr + public function getSecondExpr() : \PhpParser\Node\Expr { return $this->secondExpr; } diff --git a/rules/Php72/NodeFactory/AnonymousFunctionFactory.php b/rules/Php72/NodeFactory/AnonymousFunctionFactory.php index d98c47369d8..55f5fde7a23 100644 --- a/rules/Php72/NodeFactory/AnonymousFunctionFactory.php +++ b/rules/Php72/NodeFactory/AnonymousFunctionFactory.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; } - /** * @param Param[] $params * @param Stmt[] $stmts * @param Identifier|Name|NullableType|UnionType|null $returnTypeNode */ - public function create(array $params, array $stmts, ?Node $returnTypeNode): Closure + public function create(array $params, array $stmts, ?\PhpParser\Node $returnTypeNode) : \PhpParser\Node\Expr\Closure { $useVariables = $this->createUseVariablesFromParams($stmts, $params); - - $anonymousFunctionNode = new Closure(); + $anonymousFunctionNode = new \PhpParser\Node\Expr\Closure(); $anonymousFunctionNode->params = $params; - foreach ($useVariables as $useVariable) { - $anonymousFunctionNode->uses[] = new ClosureUse($useVariable); + $anonymousFunctionNode->uses[] = new \PhpParser\Node\Expr\ClosureUse($useVariable); } - - if ($returnTypeNode instanceof Node) { + if ($returnTypeNode instanceof \PhpParser\Node) { $anonymousFunctionNode->returnType = $returnTypeNode; } - $anonymousFunctionNode->stmts = $stmts; return $anonymousFunctionNode; } - /** * @param Node[] $nodes * @param Param[] $paramNodes * @return Variable[] */ - private function createUseVariablesFromParams(array $nodes, array $paramNodes): array + private function createUseVariablesFromParams(array $nodes, array $paramNodes) : array { $paramNames = []; foreach ($paramNodes as $paramNode) { $paramNames[] = $this->nodeNameResolver->getName($paramNode); } - - $variableNodes = $this->betterNodeFinder->findInstanceOf($nodes, Variable::class); - + $variableNodes = $this->betterNodeFinder->findInstanceOf($nodes, \PhpParser\Node\Expr\Variable::class); /** @var Variable[] $filteredVariables */ $filteredVariables = []; $alreadyAssignedVariables = []; foreach ($variableNodes as $variableNode) { // "$this" is allowed - if ($this->nodeNameResolver-> isName($variableNode, 'this')) { + if ($this->nodeNameResolver->isName($variableNode, 'this')) { continue; } - $variableName = $this->nodeNameResolver->getName($variableNode); if ($variableName === null) { continue; } - - if (in_array($variableName, $paramNames, true)) { + if (\in_array($variableName, $paramNames, \true)) { continue; } - - $parentNode = $variableNode->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Assign) { + $parentNode = $variableNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\Assign) { $alreadyAssignedVariables[] = $variableName; } - if ($this->nodeNameResolver->isNames($variableNode, $alreadyAssignedVariables)) { continue; } - $filteredVariables[$variableName] = $variableNode; } - return $filteredVariables; } } diff --git a/rules/Php72/Rector/Assign/ListEachRector.php b/rules/Php72/Rector/Assign/ListEachRector.php index 955465f226c..ceebd361d70 100644 --- a/rules/Php72/Rector/Assign/ListEachRector.php +++ b/rules/Php72/Rector/Assign/ListEachRector.php @@ -1,7 +1,6 @@ assignManipulator = $assignManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'each() function is deprecated, use key() and current() instead', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('each() function is deprecated, use key() and current() instead', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' list($key, $callback) = each($callbacks); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $key = key($callbacks); $callback = current($callbacks); next($callbacks); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var List_ $listNode */ $listNode = $node->var; - /** @var FuncCall $eachFuncCall */ $eachFuncCall = $node->expr; - // only key: list($key, ) = each($values); if ($listNode->items[0] && $listNode->items[1] === null) { $keyFuncCall = $this->nodeFactory->createFuncCall('key', $eachFuncCall->args); - return new Assign($listNode->items[0]->value, $keyFuncCall); + return new \PhpParser\Node\Expr\Assign($listNode->items[0]->value, $keyFuncCall); } - // only value: list(, $value) = each($values); if ($listNode->items[1] && $listNode->items[0] === null) { $nextFuncCall = $this->nodeFactory->createFuncCall('next', $eachFuncCall->args); $this->addNodeAfterNode($nextFuncCall, $node); - $currentFuncCall = $this->nodeFactory->createFuncCall('current', $eachFuncCall->args); - $secondArrayItem = $listNode->items[1]; - return new Assign($secondArrayItem->value, $currentFuncCall); + return new \PhpParser\Node\Expr\Assign($secondArrayItem->value, $currentFuncCall); } - // both: list($key, $value) = each($values); // ↓ // $key = key($values); // $value = current($values); // next($values); $currentFuncCall = $this->nodeFactory->createFuncCall('current', $eachFuncCall->args); - $secondArrayItem = $listNode->items[1]; - if (! $secondArrayItem instanceof ArrayItem) { - throw new ShouldNotHappenException(); + if (!$secondArrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $assign = new Assign($secondArrayItem->value, $currentFuncCall); + $assign = new \PhpParser\Node\Expr\Assign($secondArrayItem->value, $currentFuncCall); $this->addNodeAfterNode($assign, $node); - $nextFuncCall = $this->nodeFactory->createFuncCall('next', $eachFuncCall->args); $this->addNodeAfterNode($nextFuncCall, $node); - $keyFuncCall = $this->nodeFactory->createFuncCall('key', $eachFuncCall->args); - $firstArrayItem = $listNode->items[0]; - if (! $firstArrayItem instanceof ArrayItem) { - throw new ShouldNotHappenException(); + if (!$firstArrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - return new Assign($firstArrayItem->value, $keyFuncCall); + return new \PhpParser\Node\Expr\Assign($firstArrayItem->value, $keyFuncCall); } - - private function shouldSkip(Assign $assign): bool + private function shouldSkip(\PhpParser\Node\Expr\Assign $assign) : bool { - if (! $this->assignManipulator->isListToEachAssign($assign)) { - return true; + if (!$this->assignManipulator->isListToEachAssign($assign)) { + return \true; } - // assign should be top level, e.g. not in a while loop - $parentNode = $assign->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Expression) { - return true; + $parentNode = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Stmt\Expression) { + return \true; } - /** @var List_ $listNode */ $listNode = $assign->var; - - if (count($listNode->items) !== 2) { - return true; + if (\count($listNode->items) !== 2) { + return \true; } // empty list → cannot handle if ($listNode->items[0] !== null) { - return false; + return \false; } return $listNode->items[1] === null; } diff --git a/rules/Php72/Rector/Assign/ReplaceEachAssignmentWithKeyCurrentRector.php b/rules/Php72/Rector/Assign/ReplaceEachAssignmentWithKeyCurrentRector.php index 4ee6b090368..068580071b9 100644 --- a/rules/Php72/Rector/Assign/ReplaceEachAssignmentWithKeyCurrentRector.php +++ b/rules/Php72/Rector/Assign/ReplaceEachAssignmentWithKeyCurrentRector.php @@ -1,7 +1,6 @@ 1, 'a' => 2]; $eachedArray = each($array); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $array = ['b' => 1, 'a' => 2]; $eachedArray[1] = current($array); $eachedArray['value'] = current($array); @@ -45,94 +39,70 @@ $eachedArray[0] = key($array); $eachedArray['key'] = key($array); next($array); CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var FuncCall $eachFuncCall */ $eachFuncCall = $node->expr; $eachedVariable = $eachFuncCall->args[0]->value; - $assignVariable = $node->var; - $newNodes = $this->createNewNodes($assignVariable, $eachedVariable); $this->addNodesAfterNode($newNodes, $node); $this->removeNode($node); - return null; } - - private function shouldSkip(Assign $assign): bool + private function shouldSkip(\PhpParser\Node\Expr\Assign $assign) : bool { - if (! $assign->expr instanceof FuncCall) { - return true; + if (!$assign->expr instanceof \PhpParser\Node\Expr\FuncCall) { + return \true; } - - if (! $this->nodeNameResolver->isName($assign->expr, 'each')) { - return true; + if (!$this->nodeNameResolver->isName($assign->expr, 'each')) { + return \true; } - - $parentNode = $assign->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof While_) { - return true; + $parentNode = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Stmt\While_) { + return \true; } // skip assign to List - if (! $parentNode instanceof Assign) { - return false; + if (!$parentNode instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - return $parentNode->var instanceof List_; + return $parentNode->var instanceof \PhpParser\Node\Expr\List_; } - /** * @return array */ - private function createNewNodes(Expr $assignVariable, Expr $eachedVariable): array + private function createNewNodes(\PhpParser\Node\Expr $assignVariable, \PhpParser\Node\Expr $eachedVariable) : array { $newNodes = []; - $newNodes[] = $this->createDimFetchAssignWithFuncCall($assignVariable, $eachedVariable, 1, 'current'); $newNodes[] = $this->createDimFetchAssignWithFuncCall($assignVariable, $eachedVariable, 'value', 'current'); - $newNodes[] = $this->createDimFetchAssignWithFuncCall($assignVariable, $eachedVariable, 0, self::KEY); $newNodes[] = $this->createDimFetchAssignWithFuncCall($assignVariable, $eachedVariable, self::KEY, self::KEY); - - $newNodes[] = $this->nodeFactory->createFuncCall('next', [new Arg($eachedVariable)]); - + $newNodes[] = $this->nodeFactory->createFuncCall('next', [new \PhpParser\Node\Arg($eachedVariable)]); return $newNodes; } - /** * @param string|int $dimValue */ - private function createDimFetchAssignWithFuncCall( - Expr $assignVariable, - Expr $eachedVariable, - $dimValue, - string $functionName - ): Assign { - $dim = BuilderHelpers::normalizeValue($dimValue); - $arrayDimFetch = new ArrayDimFetch($assignVariable, $dim); - - return new Assign($arrayDimFetch, $this->nodeFactory->createFuncCall( - $functionName, - [new Arg($eachedVariable)] - )); + private function createDimFetchAssignWithFuncCall(\PhpParser\Node\Expr $assignVariable, \PhpParser\Node\Expr $eachedVariable, $dimValue, string $functionName) : \PhpParser\Node\Expr\Assign + { + $dim = \PhpParser\BuilderHelpers::normalizeValue($dimValue); + $arrayDimFetch = new \PhpParser\Node\Expr\ArrayDimFetch($assignVariable, $dim); + return new \PhpParser\Node\Expr\Assign($arrayDimFetch, $this->nodeFactory->createFuncCall($functionName, [new \PhpParser\Node\Arg($eachedVariable)])); } } diff --git a/rules/Php72/Rector/FuncCall/CreateFunctionToAnonymousFunctionRector.php b/rules/Php72/Rector/FuncCall/CreateFunctionToAnonymousFunctionRector.php index af51bbee1e4..81d21380c03 100644 --- a/rules/Php72/Rector/FuncCall/CreateFunctionToAnonymousFunctionRector.php +++ b/rules/Php72/Rector/FuncCall/CreateFunctionToAnonymousFunctionRector.php @@ -1,7 +1,6 @@ inlineCodeParser = $inlineCodeParser; $this->anonymousFunctionFactory = $anonymousFunctionFactory; $this->reservedKeywordAnalyzer = $reservedKeywordAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Use anonymous functions instead of deprecated create_function()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Use anonymous functions instead of deprecated create_function()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class ClassWithCreateFunction { public function run() @@ -72,8 +59,7 @@ class ClassWithCreateFunction } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class ClassWithCreateFunction { public function run() @@ -84,88 +70,71 @@ class ClassWithCreateFunction } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node * @return Closure|null */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'create_function')) { + if (!$this->isName($node, 'create_function')) { return null; } - $params = $this->createParamsFromString($node->args[0]->value); $stmts = $this->parseStringToBody($node->args[1]->value); - $refactored = $this->anonymousFunctionFactory->create($params, $stmts, null); foreach ($refactored->uses as $key => $use) { $variableName = $this->getName($use->var); if ($variableName === null) { continue; } - if ($this->reservedKeywordAnalyzer->isNativeVariable($variableName)) { unset($refactored->uses[$key]); } } - return $refactored; } - /** * @return Param[] */ - private function createParamsFromString(Expr $expr): array + private function createParamsFromString(\PhpParser\Node\Expr $expr) : array { $content = $this->inlineCodeParser->stringify($expr); $content = 'inlineCodeParser->parse($content); - /** @var Expression $expression */ $expression = $nodes[0]; - /** @var Assign $assign */ $assign = $expression->expr; - $function = $assign->expr; - if (! $function instanceof Closure) { - throw new ShouldNotHappenException(); + if (!$function instanceof \PhpParser\Node\Expr\Closure) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - return $function->params; } - /** * @return Expression[]|Stmt[] */ - private function parseStringToBody(Expr $expr): array + private function parseStringToBody(\PhpParser\Node\Expr $expr) : array { - if (! $expr instanceof String_ && ! $expr instanceof Encapsed && ! $expr instanceof Concat) { + if (!$expr instanceof \PhpParser\Node\Scalar\String_ && !$expr instanceof \PhpParser\Node\Scalar\Encapsed && !$expr instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { // special case of code elsewhere return [$this->createEval($expr)]; } - $expr = $this->inlineCodeParser->stringify($expr); return $this->inlineCodeParser->parse($expr); } - - private function createEval(Expr $expr): Expression + private function createEval(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Stmt\Expression { - $evalFuncCall = new FuncCall(new Name('eval'), [new Arg($expr)]); - return new Expression($evalFuncCall); + $evalFuncCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('eval'), [new \PhpParser\Node\Arg($expr)]); + return new \PhpParser\Node\Stmt\Expression($evalFuncCall); } } diff --git a/rules/Php72/Rector/FuncCall/GetClassOnNullRector.php b/rules/Php72/Rector/FuncCall/GetClassOnNullRector.php index a8a72572ab8..4c78f895e4d 100644 --- a/rules/Php72/Rector/FuncCall/GetClassOnNullRector.php +++ b/rules/Php72/Rector/FuncCall/GetClassOnNullRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'get_class')) { + if (!$this->isName($node, 'get_class')) { return null; } - $firstArgValue = $node->args[0]->value; - // only relevant inside the class - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - - if (! $scope->isInClass()) { + if (!$scope->isInClass()) { return null; } - // possibly already changed if ($this->shouldSkip($node)) { return null; } - - if (! $this->nodeTypeResolver->isNullableType($firstArgValue) && ! $this->nodeTypeResolver->isStaticType( - $firstArgValue, - NullType::class - )) { + if (!$this->nodeTypeResolver->isNullableType($firstArgValue) && !$this->nodeTypeResolver->isStaticType($firstArgValue, \PHPStan\Type\NullType::class)) { return null; } - - $notIdentical = new NotIdentical($firstArgValue, $this->nodeFactory->createNull()); + $notIdentical = new \PhpParser\Node\Expr\BinaryOp\NotIdentical($firstArgValue, $this->nodeFactory->createNull()); $funcCall = $this->createGetClassFuncCall($node); $selfClassConstFetch = $this->nodeFactory->createClassConstReference('self'); - - return new Ternary($notIdentical, $funcCall, $selfClassConstFetch); + return new \PhpParser\Node\Expr\Ternary($notIdentical, $funcCall, $selfClassConstFetch); } - - private function shouldSkip(FuncCall $funcCall): bool + private function shouldSkip(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - $isJustAdded = (bool) $funcCall->getAttribute(AttributeKey::DO_NOT_CHANGE); + $isJustAdded = (bool) $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::DO_NOT_CHANGE); if ($isJustAdded) { - return true; + return \true; } - - $classLike = $funcCall->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return true; + $classLike = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \true; } - - $parent = $funcCall->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Ternary) { + $parent = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Expr\Ternary) { if ($this->isIdenticalToNotNull($funcCall, $parent)) { - return true; + return \true; } - return $this->isNotIdenticalToNull($funcCall, $parent); } - - return false; + return \false; } - - private function createGetClassFuncCall(FuncCall $oldFuncCall): FuncCall + private function createGetClassFuncCall(\PhpParser\Node\Expr\FuncCall $oldFuncCall) : \PhpParser\Node\Expr\FuncCall { - $funcCall = new FuncCall($oldFuncCall->name, $oldFuncCall->args); - $funcCall->setAttribute(AttributeKey::DO_NOT_CHANGE, true); - + $funcCall = new \PhpParser\Node\Expr\FuncCall($oldFuncCall->name, $oldFuncCall->args); + $funcCall->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::DO_NOT_CHANGE, \true); return $funcCall; } - /** * E.g. "$value === [!null] ? get_class($value)" */ - private function isIdenticalToNotNull(FuncCall $funcCall, Ternary $ternary): bool + private function isIdenticalToNotNull(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr\Ternary $ternary) : bool { - if (! $ternary->cond instanceof Identical) { - return false; + if (!$ternary->cond instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { + return \false; } - - if ($this->nodeComparator->areNodesEqual( - $ternary->cond->left, - $funcCall->args[0]->value - ) && ! $this->valueResolver->isNull($ternary->cond->right)) { - return true; + if ($this->nodeComparator->areNodesEqual($ternary->cond->left, $funcCall->args[0]->value) && !$this->valueResolver->isNull($ternary->cond->right)) { + return \true; } - if (! $this->nodeComparator->areNodesEqual($ternary->cond->right, $funcCall->args[0]->value)) { - return false; + if (!$this->nodeComparator->areNodesEqual($ternary->cond->right, $funcCall->args[0]->value)) { + return \false; } - return ! $this->valueResolver->isNull($ternary->cond->left); + return !$this->valueResolver->isNull($ternary->cond->left); } - /** * E.g. "$value !== null ? get_class($value)" */ - private function isNotIdenticalToNull(FuncCall $funcCall, Ternary $ternary): bool + private function isNotIdenticalToNull(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr\Ternary $ternary) : bool { - if (! $ternary->cond instanceof NotIdentical) { - return false; + if (!$ternary->cond instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical) { + return \false; } - - if ($this->nodeComparator->areNodesEqual( - $ternary->cond->left, - $funcCall->args[0]->value - ) && $this->valueResolver->isNull($ternary->cond->right)) { - return true; + if ($this->nodeComparator->areNodesEqual($ternary->cond->left, $funcCall->args[0]->value) && $this->valueResolver->isNull($ternary->cond->right)) { + return \true; } - if (! $this->nodeComparator->areNodesEqual($ternary->cond->right, $funcCall->args[0]->value)) { - return false; + if (!$this->nodeComparator->areNodesEqual($ternary->cond->right, $funcCall->args[0]->value)) { + return \false; } return $this->valueResolver->isNull($ternary->cond->left); } diff --git a/rules/Php72/Rector/FuncCall/IsObjectOnIncompleteClassRector.php b/rules/Php72/Rector/FuncCall/IsObjectOnIncompleteClassRector.php index a16c24f3827..ebc77baa18f 100644 --- a/rules/Php72/Rector/FuncCall/IsObjectOnIncompleteClassRector.php +++ b/rules/Php72/Rector/FuncCall/IsObjectOnIncompleteClassRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'is_object')) { + if (!$this->isName($node, 'is_object')) { return null; } - - $incompleteClassObjectType = new ObjectType('__PHP_Incomplete_Class'); - if (! $this->isObjectType($node->args[0]->value, $incompleteClassObjectType)) { + $incompleteClassObjectType = new \PHPStan\Type\ObjectType('__PHP_Incomplete_Class'); + if (!$this->isObjectType($node->args[0]->value, $incompleteClassObjectType)) { return null; } - if ($this->shouldSkip($node)) { return null; } - - return new BooleanNot($node); + return new \PhpParser\Node\Expr\BooleanNot($node); } - - private function shouldSkip(FuncCall $funcCall): bool + private function shouldSkip(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - $parentNode = $funcCall->getAttribute(AttributeKey::PARENT_NODE); - return $parentNode instanceof BooleanNot; + $parentNode = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + return $parentNode instanceof \PhpParser\Node\Expr\BooleanNot; } } diff --git a/rules/Php72/Rector/FuncCall/ParseStrWithResultArgumentRector.php b/rules/Php72/Rector/FuncCall/ParseStrWithResultArgumentRector.php index 602ad12fd68..21a5d1dae1b 100644 --- a/rules/Php72/Rector/FuncCall/ParseStrWithResultArgumentRector.php +++ b/rules/Php72/Rector/FuncCall/ParseStrWithResultArgumentRector.php @@ -1,7 +1,6 @@ query); $data = get_defined_vars(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' parse_str($this->query, $result); $data = $result; CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'parse_str')) { + if (!$this->isName($node, 'parse_str')) { return null; } - if (isset($node->args[1])) { return null; } - - $resultVariable = new Variable('result'); - $node->args[1] = new Arg($resultVariable); - - $expression = $node->getAttribute(AttributeKey::CURRENT_STATEMENT); + $resultVariable = new \PhpParser\Node\Expr\Variable('result'); + $node->args[1] = new \PhpParser\Node\Arg($resultVariable); + $expression = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); if ($expression === null) { return null; } - - $nextExpression = $expression->getAttribute(AttributeKey::NEXT_NODE); + $nextExpression = $expression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); if ($nextExpression === null) { return null; } - - $this->traverseNodesWithCallable($nextExpression, function (Node $node) use ($resultVariable): ?Variable { - if (! $node instanceof FuncCall) { + $this->traverseNodesWithCallable($nextExpression, function (\PhpParser\Node $node) use($resultVariable) : ?Variable { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->isName($node, 'get_defined_vars')) { + if (!$this->isName($node, 'get_defined_vars')) { return null; } - return $resultVariable; }); - return $node; } } diff --git a/rules/Php72/Rector/FuncCall/StringifyDefineRector.php b/rules/Php72/Rector/FuncCall/StringifyDefineRector.php index e91696ed8c2..835d34b33b2 100644 --- a/rules/Php72/Rector/FuncCall/StringifyDefineRector.php +++ b/rules/Php72/Rector/FuncCall/StringifyDefineRector.php @@ -1,7 +1,6 @@ stringTypeAnalyzer = $stringTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Make first argument of define() string', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Make first argument of define() string', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run(int $a) @@ -43,8 +37,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run(int $a) @@ -54,40 +47,33 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'define')) { + if (!$this->isName($node, 'define')) { return null; } - if ($this->stringTypeAnalyzer->isStringOrUnionStringOnlyType($node->args[0]->value)) { return null; } - - if ($node->args[0]->value instanceof ConstFetch) { + if ($node->args[0]->value instanceof \PhpParser\Node\Expr\ConstFetch) { $nodeName = $this->getName($node->args[0]->value); if ($nodeName === null) { return null; } - - $node->args[0]->value = new String_($nodeName); + $node->args[0]->value = new \PhpParser\Node\Scalar\String_($nodeName); } - return $node; } } diff --git a/rules/Php72/Rector/FuncCall/StringsAssertNakedRector.php b/rules/Php72/Rector/FuncCall/StringsAssertNakedRector.php index b7bc46ebdd9..a49f81307e6 100644 --- a/rules/Php72/Rector/FuncCall/StringsAssertNakedRector.php +++ b/rules/Php72/Rector/FuncCall/StringsAssertNakedRector.php @@ -1,7 +1,6 @@ parser = $parser; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'String asserts must be passed directly to assert()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('String asserts must be passed directly to assert()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' function nakedAssert() { assert('true === true'); assert("true === true"); } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' function nakedAssert() { assert(true === true); assert(true === true); } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'assert')) { + if (!$this->isName($node, 'assert')) { return null; } - - if (! $node->args[0]->value instanceof String_) { + if (!$node->args[0]->value instanceof \PhpParser\Node\Scalar\String_) { return null; } - /** @var String_ $stringNode */ $stringNode = $node->args[0]->value; - $phpCode = 'value . ';'; $contentNodes = $this->parser->parse($phpCode); - - if (! isset($contentNodes[0])) { + if (!isset($contentNodes[0])) { return null; } - - if (! $contentNodes[0] instanceof Expression) { + if (!$contentNodes[0] instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - $node->args[0] = new Arg($contentNodes[0]->expr); - + $node->args[0] = new \PhpParser\Node\Arg($contentNodes[0]->expr); return $node; } } diff --git a/rules/Php72/Rector/Unset_/UnsetCastRector.php b/rules/Php72/Rector/Unset_/UnsetCastRector.php index 5901e4e5e4a..fd60aa644b4 100644 --- a/rules/Php72/Rector/Unset_/UnsetCastRector.php +++ b/rules/Php72/Rector/Unset_/UnsetCastRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Unset_::class, Assign::class]; + return [\PhpParser\Node\Expr\Cast\Unset_::class, \PhpParser\Node\Expr\Assign::class]; } - /** * @param Unset_|Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof Assign) { - if ($node->expr instanceof Unset_) { + if ($node instanceof \PhpParser\Node\Expr\Assign) { + if ($node->expr instanceof \PhpParser\Node\Expr\Cast\Unset_) { $unset = $node->expr; - if ($this->nodeComparator->areNodesEqual($node->var, $unset->expr)) { return $this->nodeFactory->createFuncCall('unset', [$node->var]); } } - return null; } - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - - if ($parentNode instanceof Expression) { + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Stmt\Expression) { $this->removeNode($node); - return null; } - return $this->nodeFactory->createNull(); } } diff --git a/rules/Php72/Rector/While_/WhileEachToForeachRector.php b/rules/Php72/Rector/While_/WhileEachToForeachRector.php index 7be337e117a..0f223425af4 100644 --- a/rules/Php72/Rector/While_/WhileEachToForeachRector.php +++ b/rules/Php72/Rector/While_/WhileEachToForeachRector.php @@ -1,7 +1,6 @@ assignManipulator = $assignManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'each() function is deprecated, use foreach() instead.', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('each() function is deprecated, use foreach() instead.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' while (list($key, $callback) = each($callbacks)) { // ... } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' foreach ($callbacks as $key => $callback) { // ... } CODE_SAMPLE - ), - new CodeSample( - <<<'CODE_SAMPLE' +), new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' while (list($key) = each($callbacks)) { // ... } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' foreach (array_keys($callbacks) as $key) { // ... } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [While_::class]; + return [\PhpParser\Node\Stmt\While_::class]; } - /** * @param While_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->cond instanceof Assign) { + if (!$node->cond instanceof \PhpParser\Node\Expr\Assign) { return null; } - /** @var Assign $assignNode */ $assignNode = $node->cond; - if (! $this->assignManipulator->isListToEachAssign($assignNode)) { + if (!$this->assignManipulator->isListToEachAssign($assignNode)) { return null; } - /** @var FuncCall $eachFuncCall */ $eachFuncCall = $assignNode->expr; - /** @var List_ $listNode */ $listNode = $assignNode->var; - - $foreachedExpr = count($listNode->items) === 1 ? $this->nodeFactory->createFuncCall( - 'array_keys', - [$eachFuncCall->args[0]] - ) : $eachFuncCall->args[0]->value; - + $foreachedExpr = \count($listNode->items) === 1 ? $this->nodeFactory->createFuncCall('array_keys', [$eachFuncCall->args[0]]) : $eachFuncCall->args[0]->value; /** @var ArrayItem $arrayItem */ - $arrayItem = array_pop($listNode->items); - $foreach = new Foreach_($foreachedExpr, $arrayItem, [ - 'stmts' => $node->stmts, - ]); - + $arrayItem = \array_pop($listNode->items); + $foreach = new \PhpParser\Node\Stmt\Foreach_($foreachedExpr, $arrayItem, ['stmts' => $node->stmts]); $this->mirrorComments($foreach, $node); - // is key included? add it to foreach if ($listNode->items !== []) { /** @var ArrayItem|null $keyItem */ - $keyItem = array_pop($listNode->items); - + $keyItem = \array_pop($listNode->items); if ($keyItem !== null) { $foreach->keyVar = $keyItem->value; } } - return $foreach; } } diff --git a/rules/Php73/NodeTypeAnalyzer/NodeTypeAnalyzer.php b/rules/Php73/NodeTypeAnalyzer/NodeTypeAnalyzer.php index b26ffb537dd..dfd9498e34c 100644 --- a/rules/Php73/NodeTypeAnalyzer/NodeTypeAnalyzer.php +++ b/rules/Php73/NodeTypeAnalyzer/NodeTypeAnalyzer.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; } - - public function isStringTypeExpr(Expr $expr): bool + public function isStringTypeExpr(\PhpParser\Node\Expr $expr) : bool { $staticType = $this->nodeTypeResolver->getStaticType($expr); return $this->isStringType($staticType); } - - private function isStringType(Type $type): bool + private function isStringType(\PHPStan\Type\Type $type) : bool { - if ($type instanceof StringType) { - return true; + if ($type instanceof \PHPStan\Type\StringType) { + return \true; } - - if ($type instanceof AccessoryNumericStringType) { - return true; + if ($type instanceof \PHPStan\Type\Accessory\AccessoryNumericStringType) { + return \true; } - - if ($type instanceof IntersectionType || $type instanceof UnionType) { + if ($type instanceof \PHPStan\Type\IntersectionType || $type instanceof \PHPStan\Type\UnionType) { foreach ($type->getTypes() as $innerType) { - if (! $this->isStringType($innerType)) { - return false; + if (!$this->isStringType($innerType)) { + return \false; } } - - return true; + return \true; } - - return false; + return \false; } } diff --git a/rules/Php73/Rector/BooleanOr/IsCountableRector.php b/rules/Php73/Rector/BooleanOr/IsCountableRector.php index 45d06c429c0..8404e715d59 100644 --- a/rules/Php73/Rector/BooleanOr/IsCountableRector.php +++ b/rules/Php73/Rector/BooleanOr/IsCountableRector.php @@ -1,7 +1,6 @@ isArrayAndDualCheckToAble = $isArrayAndDualCheckToAble; $this->reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes is_array + Countable check to is_countable', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes is_array + Countable check to is_countable', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' is_array($foo) || $foo instanceof Countable; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' is_countable($foo); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [BooleanOr::class]; + return [\PhpParser\Node\Expr\BinaryOp\BooleanOr::class]; } - /** * @param BooleanOr $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip()) { return null; } - return $this->isArrayAndDualCheckToAble->processBooleanOr($node, 'Countable', 'is_countable') ?: $node; } - - private function shouldSkip(): bool + private function shouldSkip() : bool { - if ($this->reflectionProvider->hasFunction(new Name('is_countable'), null)) { - return false; + if ($this->reflectionProvider->hasFunction(new \PhpParser\Node\Name('is_countable'), null)) { + return \false; } - - return $this->isAtLeastPhpVersion(PhpVersionFeature::IS_COUNTABLE); + return $this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::IS_COUNTABLE); } } diff --git a/rules/Php73/Rector/ConstFetch/SensitiveConstantNameRector.php b/rules/Php73/Rector/ConstFetch/SensitiveConstantNameRector.php index e0889534b00..36665f90033 100644 --- a/rules/Php73/Rector/ConstFetch/SensitiveConstantNameRector.php +++ b/rules/Php73/Rector/ConstFetch/SensitiveConstantNameRector.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes case insensitive constants to sensitive ones.', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes case insensitive constants to sensitive ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' define('FOO', 42, true); var_dump(FOO); var_dump(foo); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' define('FOO', 42, true); var_dump(FOO); var_dump(FOO); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ConstFetch::class]; + return [\PhpParser\Node\Expr\ConstFetch::class]; } - /** * @param ConstFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $constantName = $this->getName($node); if ($constantName === null) { return null; } - - $uppercasedConstantName = strtoupper($constantName); - + $uppercasedConstantName = \strtoupper($constantName); // is system constant? - if (in_array($uppercasedConstantName, self::PHP_RESERVED_CONSTANTS, true)) { + if (\in_array($uppercasedConstantName, self::PHP_RESERVED_CONSTANTS, \true)) { return null; } - // constant is defined in current lower/upper case - $scope = $node->getAttribute(AttributeKey::SCOPE); - if ($this->reflectionProvider->hasConstant(new Name($constantName), $scope)) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if ($this->reflectionProvider->hasConstant(new \PhpParser\Node\Name($constantName), $scope)) { return null; } - // is uppercase, all good if ($constantName === $uppercasedConstantName) { return null; } - - $node->name = new FullyQualified($uppercasedConstantName); - + $node->name = new \PhpParser\Node\Name\FullyQualified($uppercasedConstantName); return $node; } } diff --git a/rules/Php73/Rector/FuncCall/ArrayKeyFirstLastRector.php b/rules/Php73/Rector/FuncCall/ArrayKeyFirstLastRector.php index e1b8d8459db..936ab339696 100644 --- a/rules/Php73/Rector/FuncCall/ArrayKeyFirstLastRector.php +++ b/rules/Php73/Rector/FuncCall/ArrayKeyFirstLastRector.php @@ -1,7 +1,6 @@ */ - private const PREVIOUS_TO_NEW_FUNCTIONS = [ - 'reset' => self::ARRAY_KEY_FIRST, - 'end' => self::ARRAY_KEY_LAST, - ]; - + private const PREVIOUS_TO_NEW_FUNCTIONS = ['reset' => self::ARRAY_KEY_FIRST, 'end' => self::ARRAY_KEY_LAST]; /** * @var ReflectionProvider */ private $reflectionProvider; - - public function __construct(ReflectionProvider $reflectionProvider) + public function __construct(\PHPStan\Reflection\ReflectionProvider $reflectionProvider) { $this->reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Make use of array_key_first() and array_key_last()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Make use of array_key_first() and array_key_last()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' reset($items); $firstKey = key($items); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $firstKey = array_key_first($items); CODE_SAMPLE - ), - new CodeSample( - <<<'CODE_SAMPLE' +), new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' end($items); $lastKey = key($items); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $lastKey = array_key_last($items); CODE_SAMPLE - ), - - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $nextExpression = $this->getNextExpression($node); - if (! $nextExpression instanceof Node) { + if (!$nextExpression instanceof \PhpParser\Node) { return null; } - $resetOrEndFuncCall = $node; - - $keyFuncCall = $this->betterNodeFinder->findFirst($nextExpression, function (Node $node) use ( - $resetOrEndFuncCall - ): bool { - if (! $node instanceof FuncCall) { - return false; + $keyFuncCall = $this->betterNodeFinder->findFirst($nextExpression, function (\PhpParser\Node $node) use($resetOrEndFuncCall) : bool { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - - if (! $this->isName($node, 'key')) { - return false; + if (!$this->isName($node, 'key')) { + return \false; } - return $this->nodeComparator->areNodesEqual($resetOrEndFuncCall->args[0], $node->args[0]); }); - - if (! $keyFuncCall instanceof FuncCall) { + if (!$keyFuncCall instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - $newName = self::PREVIOUS_TO_NEW_FUNCTIONS[$this->getName($node)]; - $keyFuncCall->name = new Name($newName); - + $keyFuncCall->name = new \PhpParser\Node\Name($newName); $this->removeNode($node); - return $node; } - - private function shouldSkip(FuncCall $funcCall): bool + private function shouldSkip(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - if (! $this->isNames($funcCall, ['reset', 'end'])) { - return true; + if (!$this->isNames($funcCall, ['reset', 'end'])) { + return \true; } - - if ($this->isAtLeastPhpVersion(PhpVersionFeature::ARRAY_KEY_FIRST_LAST)) { - return false; + if ($this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::ARRAY_KEY_FIRST_LAST)) { + return \false; } - - if (! $this->reflectionProvider->hasFunction(new Name(self::ARRAY_KEY_FIRST), null)) { - return true; + if (!$this->reflectionProvider->hasFunction(new \PhpParser\Node\Name(self::ARRAY_KEY_FIRST), null)) { + return \true; } - - return ! $this->reflectionProvider->hasFunction(new Name(self::ARRAY_KEY_LAST), null); + return !$this->reflectionProvider->hasFunction(new \PhpParser\Node\Name(self::ARRAY_KEY_LAST), null); } - - private function getNextExpression(FuncCall $funcCall): ?Node + private function getNextExpression(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node { - $currentExpression = $funcCall->getAttribute(AttributeKey::CURRENT_STATEMENT); - if (! $currentExpression instanceof Expression) { + $currentExpression = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); + if (!$currentExpression instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - return $currentExpression->getAttribute(AttributeKey::NEXT_NODE); + return $currentExpression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); } } diff --git a/rules/Php73/Rector/FuncCall/JsonThrowOnErrorRector.php b/rules/Php73/Rector/FuncCall/JsonThrowOnErrorRector.php index f78f3fe7d4d..a8b18ce6039 100644 --- a/rules/Php73/Rector/FuncCall/JsonThrowOnErrorRector.php +++ b/rules/Php73/Rector/FuncCall/JsonThrowOnErrorRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::JSON_EXCEPTION)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::JSON_EXCEPTION)) { return null; } - if ($this->shouldSkip($node)) { return null; } - if ($this->isName($node, 'json_encode')) { return $this->processJsonEncode($node); } - if ($this->isName($node, 'json_decode')) { return $this->processJsonDecode($node); } - return null; } - - private function shouldSkip(FuncCall $funcCall): bool + private function shouldSkip(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - if (! $this->isNames($funcCall, ['json_encode', 'json_decode'])) { - return true; + if (!$this->isNames($funcCall, ['json_encode', 'json_decode'])) { + return \true; } - - return (bool) $this->betterNodeFinder->findFirstNext($funcCall, function (Node $node): bool { - if (! $node instanceof FuncCall) { - return false; + return (bool) $this->betterNodeFinder->findFirstNext($funcCall, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - return $this->isNames($node, ['json_last_error', 'json_last_error_msg']); }); } - - private function processJsonEncode(FuncCall $funcCall): ?FuncCall + private function processJsonEncode(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr\FuncCall { if (isset($funcCall->args[1])) { return null; } - - $funcCall->args[1] = new Arg($this->createConstFetch('JSON_THROW_ON_ERROR')); - + $funcCall->args[1] = new \PhpParser\Node\Arg($this->createConstFetch('JSON_THROW_ON_ERROR')); return $funcCall; } - - private function processJsonDecode(FuncCall $funcCall): ?FuncCall + private function processJsonDecode(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr\FuncCall { if (isset($funcCall->args[3])) { return null; } - // set default to inter-args - if (! isset($funcCall->args[1])) { - $funcCall->args[1] = new Arg($this->nodeFactory->createNull()); + if (!isset($funcCall->args[1])) { + $funcCall->args[1] = new \PhpParser\Node\Arg($this->nodeFactory->createNull()); } - - if (! isset($funcCall->args[2])) { - $funcCall->args[2] = new Arg(new LNumber(512)); + if (!isset($funcCall->args[2])) { + $funcCall->args[2] = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\LNumber(512)); } - - $funcCall->args[3] = new Arg($this->createConstFetch('JSON_THROW_ON_ERROR')); - + $funcCall->args[3] = new \PhpParser\Node\Arg($this->createConstFetch('JSON_THROW_ON_ERROR')); return $funcCall; } - - private function createConstFetch(string $name): ConstFetch + private function createConstFetch(string $name) : \PhpParser\Node\Expr\ConstFetch { - return new ConstFetch(new Name($name)); + return new \PhpParser\Node\Expr\ConstFetch(new \PhpParser\Node\Name($name)); } } diff --git a/rules/Php73/Rector/FuncCall/RegexDashEscapeRector.php b/rules/Php73/Rector/FuncCall/RegexDashEscapeRector.php index 7958845cf5d..6377451c2ad 100644 --- a/rules/Php73/Rector/FuncCall/RegexDashEscapeRector.php +++ b/rules/Php73/Rector/FuncCall/RegexDashEscapeRector.php @@ -1,10 +1,9 @@ regexPatternArgumentManipulator->matchCallArgumentWithRegexPattern() call */ private const THREE_BACKSLASH_FOR_ESCAPE_NEXT_REGEX = '#(?<=[^\\\\])\\\\{2}(?=[^\\\\])#'; - /** * @var string * @see https://regex101.com/r/YgVJFp/1 */ - private const LEFT_HAND_UNESCAPED_DASH_REGEX = '#(\[.*?\\\\(w|s|d))-(?!\])#i'; - + private const LEFT_HAND_UNESCAPED_DASH_REGEX = '#(\\[.*?\\\\(w|s|d))-(?!\\])#i'; /** * @var string * @see https://regex101.com/r/TBVme9/3 */ - private const RIGHT_HAND_UNESCAPED_DASH_REGEX = '#(?regexPatternArgumentManipulator = $regexPatternArgumentManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Escape - in some cases', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Escape - in some cases', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' preg_match("#[\w-()]#", 'some text'); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' preg_match("#[\w\-()]#", 'some text'); CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class, StaticCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param FuncCall|StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $regexArguments = $this->regexPatternArgumentManipulator->matchCallArgumentWithRegexPattern($node); if ($regexArguments === []) { return null; } - foreach ($regexArguments as $regexArgument) { - if (Strings::match($regexArgument->value, self::THREE_BACKSLASH_FOR_ESCAPE_NEXT_REGEX)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($regexArgument->value, self::THREE_BACKSLASH_FOR_ESCAPE_NEXT_REGEX)) { continue; } - $this->escapeStringNode($regexArgument); } - return $node; } - - private function escapeStringNode(String_ $string): void + private function escapeStringNode(\PhpParser\Node\Scalar\String_ $string) : void { $stringValue = $string->value; - - if (Strings::match($stringValue, self::LEFT_HAND_UNESCAPED_DASH_REGEX)) { - $string->value = Strings::replace($stringValue, self::LEFT_HAND_UNESCAPED_DASH_REGEX, '$1\-'); + if (\RectorPrefix20210509\Nette\Utils\Strings::match($stringValue, self::LEFT_HAND_UNESCAPED_DASH_REGEX)) { + $string->value = \RectorPrefix20210509\Nette\Utils\Strings::replace($stringValue, self::LEFT_HAND_UNESCAPED_DASH_REGEX, '$1\\-'); // helped needed to skip re-escaping regular expression - $string->setAttribute(AttributeKey::IS_REGULAR_PATTERN, true); + $string->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_REGULAR_PATTERN, \true); return; } - - if (Strings::match($stringValue, self::RIGHT_HAND_UNESCAPED_DASH_REGEX)) { - $string->value = Strings::replace($stringValue, self::RIGHT_HAND_UNESCAPED_DASH_REGEX, '\-$1]'); + if (\RectorPrefix20210509\Nette\Utils\Strings::match($stringValue, self::RIGHT_HAND_UNESCAPED_DASH_REGEX)) { + $string->value = \RectorPrefix20210509\Nette\Utils\Strings::replace($stringValue, self::RIGHT_HAND_UNESCAPED_DASH_REGEX, '\\-$1]'); // helped needed to skip re-escaping regular expression - $string->setAttribute(AttributeKey::IS_REGULAR_PATTERN, true); + $string->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_REGULAR_PATTERN, \true); } } } diff --git a/rules/Php73/Rector/FuncCall/SensitiveDefineRector.php b/rules/Php73/Rector/FuncCall/SensitiveDefineRector.php index 091bdf5bfaa..04e9d7fadf5 100644 --- a/rules/Php73/Rector/FuncCall/SensitiveDefineRector.php +++ b/rules/Php73/Rector/FuncCall/SensitiveDefineRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'define')) { + if (!$this->isName($node, 'define')) { return null; } - - if (! isset($node->args[2])) { + if (!isset($node->args[2])) { return null; } - unset($node->args[2]); - return $node; } } diff --git a/rules/Php73/Rector/FuncCall/SetCookieRector.php b/rules/Php73/Rector/FuncCall/SetCookieRector.php index c978d93eae3..5f9e0035867 100644 --- a/rules/Php73/Rector/FuncCall/SetCookieRector.php +++ b/rules/Php73/Rector/FuncCall/SetCookieRector.php @@ -1,7 +1,6 @@ */ - private const KNOWN_OPTIONS = [ - 2 => 'expires', - 3 => 'path', - 4 => 'domain', - 5 => 'secure', - 6 => 'httponly', - ]; - - public function getRuleDefinition(): RuleDefinition + private const KNOWN_OPTIONS = [2 => 'expires', 3 => 'path', 4 => 'domain', 5 => 'secure', 6 => 'httponly']; + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Convert setcookie argument to PHP7.3 option array', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Convert setcookie argument to PHP7.3 option array', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' setcookie('name', $value, 360); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' setcookie('name', $value, ['expires' => 360]); CODE_SAMPLE - ), - new CodeSample( - <<<'CODE_SAMPLE' +), new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' setcookie('name', $name, 0, '', '', true, true); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' setcookie('name', $name, ['expires' => 0, 'path' => '', 'domain' => '', 'secure' => true, 'httponly' => true]); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var FuncCall $node */ $node->args = $this->composeNewArgs($node); - return $node; } - - private function shouldSkip(FuncCall $funcCall): bool + private function shouldSkip(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - if (! $this->isNames($funcCall, ['setcookie', 'setrawcookie'])) { - return true; + if (!$this->isNames($funcCall, ['setcookie', 'setrawcookie'])) { + return \true; } - - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::SETCOOKIE_ACCEPT_ARRAY_OPTIONS)) { - return true; + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SETCOOKIE_ACCEPT_ARRAY_OPTIONS)) { + return \true; } - - $argsCount = count($funcCall->args); - + $argsCount = \count($funcCall->args); if ($argsCount <= 2) { - return true; + return \true; } - - if ($funcCall->args[2]->value instanceof Array_) { - return true; + if ($funcCall->args[2]->value instanceof \PhpParser\Node\Expr\Array_) { + return \true; } - if ($argsCount === 3) { - return $funcCall->args[2]->value instanceof Variable; + return $funcCall->args[2]->value instanceof \PhpParser\Node\Expr\Variable; } - - return false; + return \false; } - /** * @return Arg[] */ - private function composeNewArgs(FuncCall $funcCall): array + private function composeNewArgs(\PhpParser\Node\Expr\FuncCall $funcCall) : array { $items = []; - $args = $funcCall->args; - $newArgs = []; $newArgs[] = $args[0]; $newArgs[] = $args[1]; - unset($args[0]); unset($args[1]); - foreach ($args as $idx => $arg) { - $newKey = new String_(self::KNOWN_OPTIONS[$idx]); - $items[] = new ArrayItem($arg->value, $newKey); + $newKey = new \PhpParser\Node\Scalar\String_(self::KNOWN_OPTIONS[$idx]); + $items[] = new \PhpParser\Node\Expr\ArrayItem($arg->value, $newKey); } - - $newArgs[] = new Arg(new Array_($items)); + $newArgs[] = new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\Array_($items)); return $newArgs; } } diff --git a/rules/Php73/Rector/FuncCall/StringifyStrNeedlesRector.php b/rules/Php73/Rector/FuncCall/StringifyStrNeedlesRector.php index 36f27359cbe..5786624cd3a 100644 --- a/rules/Php73/Rector/FuncCall/StringifyStrNeedlesRector.php +++ b/rules/Php73/Rector/FuncCall/StringifyStrNeedlesRector.php @@ -1,7 +1,6 @@ nodeTypeAnalyzer = $nodeTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Makes needles explicit strings', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Makes needles explicit strings', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' $needle = 5; $fivePosition = strpos('725', $needle); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $needle = 5; $fivePosition = strpos('725', (string) $needle); CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isNames($node, self::NEEDLE_STRING_SENSITIVE_FUNCTIONS)) { + if (!$this->isNames($node, self::NEEDLE_STRING_SENSITIVE_FUNCTIONS)) { return null; } - // is argument string? $needleArgNode = $node->args[1]->value; if ($this->nodeTypeAnalyzer->isStringTypeExpr($needleArgNode)) { return null; } - - if ($needleArgNode instanceof String_) { + if ($needleArgNode instanceof \PhpParser\Node\Expr\Cast\String_) { return null; } - - $node->args[1]->value = new String_($node->args[1]->value); - + $node->args[1]->value = new \PhpParser\Node\Expr\Cast\String_($node->args[1]->value); return $node; } } diff --git a/rules/Php73/Rector/String_/SensitiveHereNowDocRector.php b/rules/Php73/Rector/String_/SensitiveHereNowDocRector.php index a64cc69ef2c..2af3b88659e 100644 --- a/rules/Php73/Rector/String_/SensitiveHereNowDocRector.php +++ b/rules/Php73/Rector/String_/SensitiveHereNowDocRector.php @@ -1,99 +1,78 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [String_::class]; + return [\PhpParser\Node\Scalar\String_::class]; } - /** * @param String_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $kind = $node->getAttribute(AttributeKey::KIND); - if (! in_array($kind, [String_::KIND_HEREDOC, String_::KIND_NOWDOC], true)) { + $kind = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND); + if (!\in_array($kind, [\PhpParser\Node\Scalar\String_::KIND_HEREDOC, \PhpParser\Node\Scalar\String_::KIND_NOWDOC], \true)) { return null; } - // the doc label is not in the string → ok /** @var string $docLabel */ $docLabel = $node->getAttribute(self::ATTRIBUTE_DOC_LABEL); - - if (! Strings::contains($node->value, $docLabel)) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($node->value, $docLabel)) { return null; } - $node->setAttribute(self::ATTRIBUTE_DOC_LABEL, $this->uniquateDocLabel($node->value, $docLabel)); - // invoke redraw - $node->setAttribute(AttributeKey::ORIGINAL_NODE, null); - + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); return $node; } - - private function uniquateDocLabel(string $value, string $docLabel): string + private function uniquateDocLabel(string $value, string $docLabel) : string { $docLabel .= self::WRAP_SUFFIX; $docLabelCounterTemplate = $docLabel . '_%d'; - $i = 0; - while (Strings::contains($value, $docLabel)) { - $docLabel = sprintf($docLabelCounterTemplate, ++$i); + while (\RectorPrefix20210509\Nette\Utils\Strings::contains($value, $docLabel)) { + $docLabel = \sprintf($docLabelCounterTemplate, ++$i); } - return $docLabel; } } diff --git a/rules/Php74/NodeAnalyzer/ClosureArrowFunctionAnalyzer.php b/rules/Php74/NodeAnalyzer/ClosureArrowFunctionAnalyzer.php index 1b05dba1dca..1f47e6636c1 100644 --- a/rules/Php74/NodeAnalyzer/ClosureArrowFunctionAnalyzer.php +++ b/rules/Php74/NodeAnalyzer/ClosureArrowFunctionAnalyzer.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeComparator = $nodeComparator; } - - public function matchArrowFunctionExpr(Closure $closure): ?Expr + public function matchArrowFunctionExpr(\PhpParser\Node\Expr\Closure $closure) : ?\PhpParser\Node\Expr { - if (count($closure->stmts) !== 1) { + if (\count($closure->stmts) !== 1) { return null; } - $onlyStmt = $closure->stmts[0]; - if (! $onlyStmt instanceof Return_) { + if (!$onlyStmt instanceof \PhpParser\Node\Stmt\Return_) { return null; } - /** @var Return_ $return */ $return = $onlyStmt; if ($return->expr === null) { return null; } - if ($this->shouldSkipForUsedReferencedValue($closure, $return->expr)) { return null; } - return $return->expr; } - - private function shouldSkipForUsedReferencedValue(Closure $closure, Expr $expr): bool + private function shouldSkipForUsedReferencedValue(\PhpParser\Node\Expr\Closure $closure, \PhpParser\Node\Expr $expr) : bool { $referencedValues = $this->resolveReferencedUseVariablesFromClosure($closure); if ($referencedValues === []) { - return false; + return \false; } - - return (bool) $this->betterNodeFinder->findFirst([$expr], function (Node $node) use ( - $referencedValues - ): bool { + return (bool) $this->betterNodeFinder->findFirst([$expr], function (\PhpParser\Node $node) use($referencedValues) : bool { foreach ($referencedValues as $referencedValue) { if ($this->nodeComparator->areNodesEqual($node, $referencedValue)) { - return true; + return \true; } } - - return false; + return \false; }); } - /** * @return Variable[] */ - private function resolveReferencedUseVariablesFromClosure(Closure $closure): array + private function resolveReferencedUseVariablesFromClosure(\PhpParser\Node\Expr\Closure $closure) : array { $referencedValues = []; - /** @var ClosureUse $use */ foreach ($closure->uses as $use) { if ($use->byRef) { $referencedValues[] = $use->var; } } - return $referencedValues; } } diff --git a/rules/Php74/Rector/Assign/NullCoalescingOperatorRector.php b/rules/Php74/Rector/Assign/NullCoalescingOperatorRector.php index f16bb01cc89..0c97c930cdc 100644 --- a/rules/Php74/Rector/Assign/NullCoalescingOperatorRector.php +++ b/rules/Php74/Rector/Assign/NullCoalescingOperatorRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::NULL_COALESCE_ASSIGN)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::NULL_COALESCE_ASSIGN)) { return null; } - - if (! $node->expr instanceof Coalesce) { + if (!$node->expr instanceof \PhpParser\Node\Expr\BinaryOp\Coalesce) { return null; } - - if (! $this->nodeComparator->areNodesEqual($node->var, $node->expr->left)) { + if (!$this->nodeComparator->areNodesEqual($node->var, $node->expr->left)) { return null; } - - return new AssignCoalesce($node->var, $node->expr->right); + return new \PhpParser\Node\Expr\AssignOp\Coalesce($node->var, $node->expr->right); } } diff --git a/rules/Php74/Rector/Closure/ClosureToArrowFunctionRector.php b/rules/Php74/Rector/Closure/ClosureToArrowFunctionRector.php index e6d69ef73ee..dad28160b90 100644 --- a/rules/Php74/Rector/Closure/ClosureToArrowFunctionRector.php +++ b/rules/Php74/Rector/Closure/ClosureToArrowFunctionRector.php @@ -1,7 +1,6 @@ closureArrowFunctionAnalyzer = $closureArrowFunctionAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change closure to arrow function', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change closure to arrow function', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($meetups) @@ -46,8 +40,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($meetups) @@ -56,43 +49,35 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Closure::class]; + return [\PhpParser\Node\Expr\Closure::class]; } - /** * @param Closure $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::ARROW_FUNCTION)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::ARROW_FUNCTION)) { return null; } - $returnExpr = $this->closureArrowFunctionAnalyzer->matchArrowFunctionExpr($node); - if (! $returnExpr instanceof Expr) { + if (!$returnExpr instanceof \PhpParser\Node\Expr) { return null; } - - $arrowFunction = new ArrowFunction(); + $arrowFunction = new \PhpParser\Node\Expr\ArrowFunction(); $arrowFunction->params = $node->params; $arrowFunction->returnType = $node->returnType; $arrowFunction->byRef = $node->byRef; - $arrowFunction->expr = $returnExpr; - if ($node->static) { - $arrowFunction->static = true; + $arrowFunction->static = \true; } - return $arrowFunction; } } diff --git a/rules/Php74/Rector/Double/RealToFloatTypeCastRector.php b/rules/Php74/Rector/Double/RealToFloatTypeCastRector.php index 11523a6c4ff..b70c1f20bf9 100644 --- a/rules/Php74/Rector/Double/RealToFloatTypeCastRector.php +++ b/rules/Php74/Rector/Double/RealToFloatTypeCastRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Double::class]; + return [\PhpParser\Node\Expr\Cast\Double::class]; } - /** * @param Double $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $kind = $node->getAttribute(AttributeKey::KIND); - if ($kind !== Double::KIND_REAL) { + $kind = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND); + if ($kind !== \PhpParser\Node\Expr\Cast\Double::KIND_REAL) { return null; } - - $node->setAttribute(AttributeKey::KIND, Double::KIND_FLOAT); - $node->setAttribute(AttributeKey::ORIGINAL_NODE, null); - + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND, \PhpParser\Node\Expr\Cast\Double::KIND_FLOAT); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); return $node; } } diff --git a/rules/Php74/Rector/FuncCall/ArrayKeyExistsOnPropertyRector.php b/rules/Php74/Rector/FuncCall/ArrayKeyExistsOnPropertyRector.php index 47343014c2b..8d5af485c8f 100644 --- a/rules/Php74/Rector/FuncCall/ArrayKeyExistsOnPropertyRector.php +++ b/rules/Php74/Rector/FuncCall/ArrayKeyExistsOnPropertyRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'array_key_exists')) { + if (!$this->isName($node, 'array_key_exists')) { return null; } - - if (! $this->getStaticType($node->args[1]->value) instanceof ObjectType) { + if (!$this->getStaticType($node->args[1]->value) instanceof \PHPStan\Type\ObjectType) { return null; } - - $node->name = new Name('property_exists'); - $node->args = array_reverse($node->args); - + $node->name = new \PhpParser\Node\Name('property_exists'); + $node->args = \array_reverse($node->args); return $node; } } diff --git a/rules/Php74/Rector/FuncCall/ArraySpreadInsteadOfArrayMergeRector.php b/rules/Php74/Rector/FuncCall/ArraySpreadInsteadOfArrayMergeRector.php index 62ffe4ebe67..81e2f3f0d4d 100644 --- a/rules/Php74/Rector/FuncCall/ArraySpreadInsteadOfArrayMergeRector.php +++ b/rules/Php74/Rector/FuncCall/ArraySpreadInsteadOfArrayMergeRector.php @@ -1,7 +1,6 @@ arrayTypeAnalyzer = $arrayTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change array_merge() to spread operator, except values with possible string key values', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change array_merge() to spread operator, except values with possible string key values', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($iter1, $iter2) @@ -60,8 +52,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($iter1, $iter2) @@ -73,130 +64,103 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::ARRAY_SPREAD)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::ARRAY_SPREAD)) { return null; } - if ($this->isName($node, 'array_merge')) { return $this->refactorArray($node); } - return null; } - - private function refactorArray(FuncCall $funcCall): ?Array_ + private function refactorArray(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node\Expr\Array_ { - $array = new Array_(); - + $array = new \PhpParser\Node\Expr\Array_(); foreach ($funcCall->args as $arg) { // cannot handle unpacked arguments if ($arg->unpack) { return null; } - $value = $arg->value; if ($this->shouldSkipArrayForInvalidTypeOrKeys($value)) { return null; } - $value = $this->resolveValue($value); $array->items[] = $this->createUnpackedArrayItem($value); } - return $array; } - - private function shouldSkipArrayForInvalidTypeOrKeys(Expr $expr): bool + private function shouldSkipArrayForInvalidTypeOrKeys(\PhpParser\Node\Expr $expr) : bool { // we have no idea what it is → cannot change it - if (! $this->arrayTypeAnalyzer->isArrayType($expr)) { - return true; + if (!$this->arrayTypeAnalyzer->isArrayType($expr)) { + return \true; } - $arrayStaticType = $this->getStaticType($expr); if ($this->isConstantArrayTypeWithStringKeyType($arrayStaticType)) { - return true; + return \true; } - - if (! $arrayStaticType instanceof ArrayType) { - return true; + if (!$arrayStaticType instanceof \PHPStan\Type\ArrayType) { + return \true; } - // integer key type is required, @see https://twitter.com/nikita_ppv/status/1126470222838366209 - return ! $arrayStaticType->getKeyType() instanceof IntegerType; + return !$arrayStaticType->getKeyType() instanceof \PHPStan\Type\IntegerType; } - - private function resolveValue(Expr $expr): Expr + private function resolveValue(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { - if ($expr instanceof FuncCall && $this->isIteratorToArrayFuncCall($expr)) { + if ($expr instanceof \PhpParser\Node\Expr\FuncCall && $this->isIteratorToArrayFuncCall($expr)) { /** @var FuncCall $expr */ $expr = $expr->args[0]->value; } - - if (! $expr instanceof Ternary) { + if (!$expr instanceof \PhpParser\Node\Expr\Ternary) { return $expr; } - - if (! $expr->cond instanceof FuncCall) { + if (!$expr->cond instanceof \PhpParser\Node\Expr\FuncCall) { return $expr; } - - if (! $this->isName($expr->cond, 'is_array')) { + if (!$this->isName($expr->cond, 'is_array')) { return $expr; } - - if ($expr->if instanceof Variable && $this->isIteratorToArrayFuncCall($expr->else)) { + if ($expr->if instanceof \PhpParser\Node\Expr\Variable && $this->isIteratorToArrayFuncCall($expr->else)) { return $expr->if; } - return $expr; } - - private function createUnpackedArrayItem(Expr $expr): ArrayItem + private function createUnpackedArrayItem(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\ArrayItem { - return new ArrayItem($expr, null, false, [], true); + return new \PhpParser\Node\Expr\ArrayItem($expr, null, \false, [], \true); } - - private function isConstantArrayTypeWithStringKeyType(Type $type): bool + private function isConstantArrayTypeWithStringKeyType(\PHPStan\Type\Type $type) : bool { - if (! $type instanceof ConstantArrayType) { - return false; + if (!$type instanceof \PHPStan\Type\Constant\ConstantArrayType) { + return \false; } - foreach ($type->getKeyTypes() as $keyType) { // key cannot be string - if ($keyType instanceof ConstantStringType) { - return true; + if ($keyType instanceof \PHPStan\Type\Constant\ConstantStringType) { + return \true; } } - - return false; + return \false; } - - private function isIteratorToArrayFuncCall(Expr $expr): bool + private function isIteratorToArrayFuncCall(\PhpParser\Node\Expr $expr) : bool { - if (! $expr instanceof FuncCall) { - return false; + if (!$expr instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - return $this->nodeNameResolver->isName($expr, 'iterator_to_array'); } } diff --git a/rules/Php74/Rector/FuncCall/FilterVarToAddSlashesRector.php b/rules/Php74/Rector/FuncCall/FilterVarToAddSlashesRector.php index f46bb328da9..ffbdc1a7a3e 100644 --- a/rules/Php74/Rector/FuncCall/FilterVarToAddSlashesRector.php +++ b/rules/Php74/Rector/FuncCall/FilterVarToAddSlashesRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'filter_var')) { + if (!$this->isName($node, 'filter_var')) { return null; } - - if (! isset($node->args[1])) { + if (!isset($node->args[1])) { return null; } - - if (! $this->isName($node->args[1]->value, 'FILTER_SANITIZE_MAGIC_QUOTES')) { + if (!$this->isName($node->args[1]->value, 'FILTER_SANITIZE_MAGIC_QUOTES')) { return null; } - - $node->name = new Name('addslashes'); + $node->name = new \PhpParser\Node\Name('addslashes'); unset($node->args[1]); - return $node; } } diff --git a/rules/Php74/Rector/FuncCall/GetCalledClassToStaticClassRector.php b/rules/Php74/Rector/FuncCall/GetCalledClassToStaticClassRector.php index 3f31d3d1633..df19dd53b67 100644 --- a/rules/Php74/Rector/FuncCall/GetCalledClassToStaticClassRector.php +++ b/rules/Php74/Rector/FuncCall/GetCalledClassToStaticClassRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::CLASSNAME_CONSTANT)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::CLASSNAME_CONSTANT)) { return null; } - - if (! $this->isName($node, 'get_called_class')) { + if (!$this->isName($node, 'get_called_class')) { return null; } - return $this->nodeFactory->createClassConstFetch('static', 'class'); } } diff --git a/rules/Php74/Rector/FuncCall/MbStrrposEncodingArgumentPositionRector.php b/rules/Php74/Rector/FuncCall/MbStrrposEncodingArgumentPositionRector.php index a06759c1453..a11c3a40079 100644 --- a/rules/Php74/Rector/FuncCall/MbStrrposEncodingArgumentPositionRector.php +++ b/rules/Php74/Rector/FuncCall/MbStrrposEncodingArgumentPositionRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node, 'mb_strrpos')) { + if (!$this->isName($node, 'mb_strrpos')) { return null; } - - if (! isset($node->args[2])) { + if (!isset($node->args[2])) { return null; } - if (isset($node->args[3])) { return null; } - - if ($this->getStaticType($node->args[2]->value) instanceof IntegerType) { + if ($this->getStaticType($node->args[2]->value) instanceof \PHPStan\Type\IntegerType) { return null; } - $node->args[3] = $node->args[2]; - $node->args[2] = new Arg(new LNumber(0)); - + $node->args[2] = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\LNumber(0)); return $node; } } diff --git a/rules/Php74/Rector/Function_/ReservedFnFunctionRector.php b/rules/Php74/Rector/Function_/ReservedFnFunctionRector.php index 10a785a052c..ea84c200167 100644 --- a/rules/Php74/Rector/Function_/ReservedFnFunctionRector.php +++ b/rules/Php74/Rector/Function_/ReservedFnFunctionRector.php @@ -1,7 +1,6 @@ [ - 'fn' => 'someFunctionName', - ], - ] - ), - ]); +, [self::RESERVED_NAMES_TO_NEW_ONES => ['fn' => 'someFunctionName']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, FuncCall::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Expr\FuncCall::class]; } - /** * @param Function_|FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->reservedNamesToNewOnes as $reservedName => $newName) { - if (! $this->isName($node->name, $reservedName)) { + if (!$this->isName($node->name, $reservedName)) { continue; } - - if ($node instanceof FuncCall) { - $node->name = new Name($newName); + if ($node instanceof \PhpParser\Node\Expr\FuncCall) { + $node->name = new \PhpParser\Node\Name($newName); } else { - $node->name = new Identifier($newName); + $node->name = new \PhpParser\Node\Identifier($newName); } - return $node; } - return null; } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->reservedNamesToNewOnes = $configuration[self::RESERVED_NAMES_TO_NEW_ONES] ?? []; } diff --git a/rules/Php74/Rector/LNumber/AddLiteralSeparatorToNumberRector.php b/rules/Php74/Rector/LNumber/AddLiteralSeparatorToNumberRector.php index 4b6c60313a7..b75acfca4b8 100644 --- a/rules/Php74/Rector/LNumber/AddLiteralSeparatorToNumberRector.php +++ b/rules/Php74/Rector/LNumber/AddLiteralSeparatorToNumberRector.php @@ -1,10 +1,9 @@ limitValue = $limitValue; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Add "_" as thousands separator in numbers for higher or equals to limitValue config', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add "_" as thousands separator in numbers for higher or equals to limitValue config', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -70,8 +59,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -81,100 +69,77 @@ class SomeClass } } CODE_SAMPLE - , - [ - self::LIMIT_VALUE => 1000000, - ] - ), - ] - ); +, [self::LIMIT_VALUE => 1000000])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [LNumber::class, DNumber::class]; + return [\PhpParser\Node\Scalar\LNumber::class, \PhpParser\Node\Scalar\DNumber::class]; } - /** * @param LNumber|DNumber $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::LITERAL_SEPARATOR)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::LITERAL_SEPARATOR)) { return null; } - $numericValueAsString = (string) $node->value; if ($this->shouldSkip($node, $numericValueAsString)) { return null; } - - if (Strings::contains($numericValueAsString, '.')) { - [$mainPart, $decimalPart] = explode('.', $numericValueAsString); - + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($numericValueAsString, '.')) { + [$mainPart, $decimalPart] = \explode('.', $numericValueAsString); $chunks = $this->strSplitNegative($mainPart, self::GROUP_SIZE); - $literalSeparatedNumber = implode('_', $chunks) . '.' . $decimalPart; + $literalSeparatedNumber = \implode('_', $chunks) . '.' . $decimalPart; } else { $chunks = $this->strSplitNegative($numericValueAsString, self::GROUP_SIZE); - $literalSeparatedNumber = implode('_', $chunks); - + $literalSeparatedNumber = \implode('_', $chunks); // PHP converts: (string) 1000.0 -> "1000"! - if (is_float($node->value)) { + if (\is_float($node->value)) { $literalSeparatedNumber .= '.0'; } } - $node->value = $literalSeparatedNumber; - return $node; } - /** * @param LNumber|DNumber $node */ - private function shouldSkip(Node $node, string $numericValueAsString): bool + private function shouldSkip(\PhpParser\Node $node, string $numericValueAsString) : bool { if ($numericValueAsString < $this->limitValue) { - return true; + return \true; } - // already separated - if (Strings::contains($numericValueAsString, '_')) { - return true; + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($numericValueAsString, '_')) { + return \true; } - - $kind = $node->getAttribute(AttributeKey::KIND); - if (in_array($kind, [LNumber::KIND_BIN, LNumber::KIND_OCT, LNumber::KIND_HEX], true)) { - return true; + $kind = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND); + if (\in_array($kind, [\PhpParser\Node\Scalar\LNumber::KIND_BIN, \PhpParser\Node\Scalar\LNumber::KIND_OCT, \PhpParser\Node\Scalar\LNumber::KIND_HEX], \true)) { + return \true; } - // e+/e- - if (Strings::match($numericValueAsString, '#e#i')) { - return true; + if (\RectorPrefix20210509\Nette\Utils\Strings::match($numericValueAsString, '#e#i')) { + return \true; } - // too short - return Strings::length($numericValueAsString) <= self::GROUP_SIZE; + return \RectorPrefix20210509\Nette\Utils\Strings::length($numericValueAsString) <= self::GROUP_SIZE; } - /** * @return string[] */ - private function strSplitNegative(string $string, int $length): array + private function strSplitNegative(string $string, int $length) : array { - $inversed = strrev($string); - + $inversed = \strrev($string); /** @var string[] $chunks */ - $chunks = str_split($inversed, $length); - - $chunks = array_reverse($chunks); + $chunks = \str_split($inversed, $length); + $chunks = \array_reverse($chunks); foreach ($chunks as $key => $chunk) { - $chunks[$key] = strrev($chunk); + $chunks[$key] = \strrev($chunk); } - return $chunks; } } diff --git a/rules/Php74/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector.php b/rules/Php74/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector.php index 3a198645f27..369cacf26c1 100644 --- a/rules/Php74/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector.php +++ b/rules/Php74/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class, String_::class]; + return [\PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\Cast\String_::class]; } - /** * @param MethodCall|String_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { return $this->refactorMethodCall($node); } - - if ($node->expr instanceof MethodCall) { + if ($node->expr instanceof \PhpParser\Node\Expr\MethodCall) { return $this->refactorIfHasReturnTypeWasCalled($node->expr); } - if (! $node->expr instanceof Variable) { + if (!$node->expr instanceof \PhpParser\Node\Expr\Variable) { return null; } - if (! $this->isObjectType($node->expr, new ObjectType('ReflectionType'))) { + if (!$this->isObjectType($node->expr, new \PHPStan\Type\ObjectType('ReflectionType'))) { return null; } return $this->nodeFactory->createMethodCall($node->expr, self::GET_NAME); } - - private function refactorMethodCall(MethodCall $methodCall): ?Node + private function refactorMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node { $this->collectCallByVariable($methodCall); - if ($this->shouldSkipMethodCall($methodCall)) { return null; } - if ($this->isReflectionParameterGetTypeMethodCall($methodCall)) { return $this->refactorReflectionParameterGetName($methodCall); } - if ($this->isReflectionFunctionAbstractGetReturnTypeMethodCall($methodCall)) { return $this->refactorReflectionFunctionGetReturnType($methodCall); } - return null; } - - private function refactorIfHasReturnTypeWasCalled(MethodCall $methodCall): ?Node + private function refactorIfHasReturnTypeWasCalled(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node { - if (! $methodCall->var instanceof Variable) { + if (!$methodCall->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - $variableName = $this->getName($methodCall->var); - $callsByVariable = $this->callsByVariable[$variableName] ?? []; - // we already know it has return type - if (in_array('hasReturnType', $callsByVariable, true)) { + if (\in_array('hasReturnType', $callsByVariable, \true)) { return $this->nodeFactory->createMethodCall($methodCall, self::GET_NAME); } - return null; } - - private function collectCallByVariable(MethodCall $methodCall): void + private function collectCallByVariable(\PhpParser\Node\Expr\MethodCall $methodCall) : void { // bit workaround for now - if ($methodCall->var instanceof Variable) { + if ($methodCall->var instanceof \PhpParser\Node\Expr\Variable) { $variableName = $this->getName($methodCall->var); $methodName = $this->getName($methodCall->name); - if (! $variableName) { + if (!$variableName) { return; } - if (! $methodName) { + if (!$methodName) { return; } $this->callsByVariable[$variableName][] = $methodName; } } - - private function shouldSkipMethodCall(MethodCall $methodCall): bool + private function shouldSkipMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { - $scope = $methodCall->getAttribute(AttributeKey::SCOPE); + $scope = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); // just added node → skip it - if (! $scope instanceof Scope) { - return true; + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \true; } - // is to string retype? - $parentNode = $methodCall->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof String_) { - return false; + $parentNode = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\Cast\String_) { + return \false; } // probably already converted - return ! $parentNode instanceof Concat; + return !$parentNode instanceof \PhpParser\Node\Expr\BinaryOp\Concat; } - - private function isReflectionParameterGetTypeMethodCall(MethodCall $methodCall): bool + private function isReflectionParameterGetTypeMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { - if (! $this->isObjectType($methodCall->var, new ObjectType('ReflectionParameter'))) { - return false; + if (!$this->isObjectType($methodCall->var, new \PHPStan\Type\ObjectType('ReflectionParameter'))) { + return \false; } - return $this->isName($methodCall->name, 'getType'); } - - private function refactorReflectionParameterGetName(MethodCall $methodCall): Ternary + private function refactorReflectionParameterGetName(\PhpParser\Node\Expr\MethodCall $methodCall) : \PhpParser\Node\Expr\Ternary { $getNameMethodCall = $this->nodeFactory->createMethodCall($methodCall, self::GET_NAME); - - return new Ternary($methodCall, $getNameMethodCall, $this->nodeFactory->createNull()); + return new \PhpParser\Node\Expr\Ternary($methodCall, $getNameMethodCall, $this->nodeFactory->createNull()); } - - private function isReflectionFunctionAbstractGetReturnTypeMethodCall(MethodCall $methodCall): bool + private function isReflectionFunctionAbstractGetReturnTypeMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { - if (! $this->isObjectType($methodCall->var, new ObjectType('ReflectionFunctionAbstract'))) { - return false; + if (!$this->isObjectType($methodCall->var, new \PHPStan\Type\ObjectType('ReflectionFunctionAbstract'))) { + return \false; } - return $this->isName($methodCall->name, 'getReturnType'); } - - private function refactorReflectionFunctionGetReturnType(MethodCall $methodCall): Node + private function refactorReflectionFunctionGetReturnType(\PhpParser\Node\Expr\MethodCall $methodCall) : \PhpParser\Node { $refactoredMethodCall = $this->refactorIfHasReturnTypeWasCalled($methodCall); if ($refactoredMethodCall !== null) { return $refactoredMethodCall; } - $getNameMethodCall = $this->nodeFactory->createMethodCall($methodCall, self::GET_NAME); - return new Ternary($methodCall, $getNameMethodCall, $this->nodeFactory->createNull()); + return new \PhpParser\Node\Expr\Ternary($methodCall, $getNameMethodCall, $this->nodeFactory->createNull()); } } diff --git a/rules/Php74/Rector/Property/RestoreDefaultNullToNullableTypePropertyRector.php b/rules/Php74/Rector/Property/RestoreDefaultNullToNullableTypePropertyRector.php index cb2667ac6de..cfbcf8637e7 100644 --- a/rules/Php74/Rector/Property/RestoreDefaultNullToNullableTypePropertyRector.php +++ b/rules/Php74/Rector/Property/RestoreDefaultNullToNullableTypePropertyRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $onlyProperty = $node->props[0]; $onlyProperty->default = $this->nodeFactory->createNull(); - return $node; } - - private function shouldSkip(Property $property): bool + private function shouldSkip(\PhpParser\Node\Stmt\Property $property) : bool { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::TYPED_PROPERTIES)) { - return true; + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::TYPED_PROPERTIES)) { + return \true; } - - if (! $property->type instanceof NullableType) { - return true; + if (!$property->type instanceof \PhpParser\Node\NullableType) { + return \true; } - - if (count($property->props) > 1) { - return true; + if (\count($property->props) > 1) { + return \true; } - $onlyProperty = $property->props[0]; if ($onlyProperty->default !== null) { - return true; + return \true; } - // is variable assigned in constructor $propertyName = $this->getName($property); - return $this->isPropertyInitiatedInConstuctor($property, $propertyName); } - - private function isPropertyInitiatedInConstuctor(Property $property, string $propertyName): bool + private function isPropertyInitiatedInConstuctor(\PhpParser\Node\Stmt\Property $property, string $propertyName) : bool { - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return false; + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } - - $constructClassMethod = $classLike->getMethod(MethodName::CONSTRUCT); - if (! $constructClassMethod instanceof ClassMethod) { - return false; + $constructClassMethod = $classLike->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - - $isPropertyInitiated = false; - $this->traverseNodesWithCallable((array) $constructClassMethod->stmts, function (Node $node) use ( - $propertyName, - &$isPropertyInitiated - ): ?int { - if (! $node instanceof Assign) { + $isPropertyInitiated = \false; + $this->traverseNodesWithCallable((array) $constructClassMethod->stmts, function (\PhpParser\Node $node) use($propertyName, &$isPropertyInitiated) : ?int { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $this->nodeNameResolver->isLocalPropertyFetchNamed($node->var, $propertyName)) { + if (!$this->nodeNameResolver->isLocalPropertyFetchNamed($node->var, $propertyName)) { return null; } - - $isPropertyInitiated = true; - - return NodeTraverser::STOP_TRAVERSAL; + $isPropertyInitiated = \true; + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; }); - return $isPropertyInitiated; } } diff --git a/rules/Php74/Rector/Property/TypedPropertyRector.php b/rules/Php74/Rector/Property/TypedPropertyRector.php index 6de558a58d2..168c66554e7 100644 --- a/rules/Php74/Rector/Property/TypedPropertyRector.php +++ b/rules/Php74/Rector/Property/TypedPropertyRector.php @@ -1,7 +1,6 @@ propertyTypeInferer = $propertyTypeInferer; $this->vendorLockResolver = $vendorLockResolver; $this->doctrineTypeAnalyzer = $doctrineTypeAnalyzer; $this->varTagRemover = $varTagRemover; $this->reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Changes property `@var` annotations from annotation to type.', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes property `@var` annotations from annotation to type.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' final class SomeClass { /** @@ -102,171 +83,128 @@ final class SomeClass private count; } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { private int count; } CODE_SAMPLE - , - [ - self::CLASS_LIKE_TYPE_ONLY => false, - ] - ), - ] - ); +, [self::CLASS_LIKE_TYPE_ONLY => \false])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::TYPED_PROPERTIES)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::TYPED_PROPERTIES)) { return null; } - // type is already set → skip if ($node->type !== null) { return null; } - // skip multiple properties - if (count($node->props) > 1) { + if (\count($node->props) > 1) { return null; } - $varType = $this->propertyTypeInferer->inferProperty($node); - if ($varType instanceof MixedType) { + if ($varType instanceof \PHPStan\Type\MixedType) { return null; } - - if ($varType instanceof UnionType) { + if ($varType instanceof \PHPStan\Type\UnionType) { $types = $varType->getTypes(); - if (count($types) === 2 && $types[0] instanceof TemplateType) { - $node->type = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode( - $types[0]->getBound(), - TypeKind::KIND_PROPERTY - ); + if (\count($types) === 2 && $types[0] instanceof \PHPStan\Type\Generic\TemplateType) { + $node->type = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($types[0]->getBound(), \Rector\PHPStanStaticTypeMapper\ValueObject\TypeKind::KIND_PROPERTY); return $node; } } - - $propertyTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode( - $varType, - TypeKind::KIND_PROPERTY - ); - + $propertyTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($varType, \Rector\PHPStanStaticTypeMapper\ValueObject\TypeKind::KIND_PROPERTY); if ($this->isNullOrNonClassLikeTypeOrMixedOrVendorLockedIn($propertyTypeNode, $node)) { return null; } - $this->varTagRemover->removeVarPhpTagValueNodeIfNotComment($node, $varType); $this->removeDefaultValueForDoctrineCollection($node, $varType); $this->addDefaultValueNullForNullableType($node, $varType); - $node->type = $propertyTypeNode; - return $node; } - - public function configure(array $configuration): void + public function configure(array $configuration) : void { - $this->classLikeTypeOnly = $configuration[self::CLASS_LIKE_TYPE_ONLY] ?? false; + $this->classLikeTypeOnly = $configuration[self::CLASS_LIKE_TYPE_ONLY] ?? \false; } - /** * @param Name|NullableType|PhpParserUnionType|null $node */ - private function isNullOrNonClassLikeTypeOrMixedOrVendorLockedIn(?Node $node, Property $property): bool + private function isNullOrNonClassLikeTypeOrMixedOrVendorLockedIn(?\PhpParser\Node $node, \PhpParser\Node\Stmt\Property $property) : bool { - if (! $node instanceof Node) { - return true; + if (!$node instanceof \PhpParser\Node) { + return \true; } - // is not class-type and should be skipped if ($this->shouldSkipNonClassLikeType($node)) { - return true; + return \true; } - // false positive - if (! $node instanceof Name) { + if (!$node instanceof \PhpParser\Node\Name) { return $this->vendorLockResolver->isPropertyTypeChangeVendorLockedIn($property); } - - if (! $this->isName($node, 'mixed')) { + if (!$this->isName($node, 'mixed')) { return $this->vendorLockResolver->isPropertyTypeChangeVendorLockedIn($property); } - - return true; + return \true; } - /** * @param Name|NullableType|PhpParserUnionType $node */ - private function shouldSkipNonClassLikeType(Node $node): bool + private function shouldSkipNonClassLikeType(\PhpParser\Node $node) : bool { // unwrap nullable type - if ($node instanceof NullableType) { + if ($node instanceof \PhpParser\Node\NullableType) { $node = $node->type; } - $typeName = $this->getName($node); if ($typeName === 'null') { - return true; + return \true; } - if ($typeName === null) { - return false; + return \false; } - if ($typeName === 'callable') { - return true; + return \true; } - - if (! $this->classLikeTypeOnly) { - return false; + if (!$this->classLikeTypeOnly) { + return \false; } - - return ! $this->reflectionProvider->hasClass($typeName); + return !$this->reflectionProvider->hasClass($typeName); } - - private function removeDefaultValueForDoctrineCollection(Property $property, Type $propertyType): void + private function removeDefaultValueForDoctrineCollection(\PhpParser\Node\Stmt\Property $property, \PHPStan\Type\Type $propertyType) : void { - if (! $this->doctrineTypeAnalyzer->isDoctrineCollectionWithIterableUnionType($propertyType)) { + if (!$this->doctrineTypeAnalyzer->isDoctrineCollectionWithIterableUnionType($propertyType)) { return; } - $onlyProperty = $property->props[0]; $onlyProperty->default = null; } - - private function addDefaultValueNullForNullableType(Property $property, Type $propertyType): void + private function addDefaultValueNullForNullableType(\PhpParser\Node\Stmt\Property $property, \PHPStan\Type\Type $propertyType) : void { - if (! $propertyType instanceof UnionType) { + if (!$propertyType instanceof \PHPStan\Type\UnionType) { return; } - - if (! $propertyType->isSuperTypeOf(new NullType())->yes()) { + if (!$propertyType->isSuperTypeOf(new \PHPStan\Type\NullType())->yes()) { return; } - $onlyProperty = $property->props[0]; - // skip is already has value if ($onlyProperty->default !== null) { return; } - $onlyProperty->default = $this->nodeFactory->createNull(); } } diff --git a/rules/Php74/Rector/StaticCall/ExportToReflectionFunctionRector.php b/rules/Php74/Rector/StaticCall/ExportToReflectionFunctionRector.php index 0de169c2560..18885a7e812 100644 --- a/rules/Php74/Rector/StaticCall/ExportToReflectionFunctionRector.php +++ b/rules/Php74/Rector/StaticCall/ExportToReflectionFunctionRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->class instanceof Name) { + if (!$node->class instanceof \PhpParser\Node\Name) { return null; } - $callerType = $this->nodeTypeResolver->resolve($node->class); - if (! $callerType->isSuperTypeOf(new ObjectType('ReflectionFunction'))->yes()) { + if (!$callerType->isSuperTypeOf(new \PHPStan\Type\ObjectType('ReflectionFunction'))->yes()) { return null; } - - if (! $this->isName($node->name, 'export')) { + if (!$this->isName($node->name, 'export')) { return null; } - - $new = new New_($node->class, [new Arg($node->args[0]->value)]); - + $new = new \PhpParser\Node\Expr\New_($node->class, [new \PhpParser\Node\Arg($node->args[0]->value)]); if (isset($node->args[1]) && $this->valueResolver->isTrue($node->args[1]->value)) { - return new String_($new); + return new \PhpParser\Node\Expr\Cast\String_($new); } - return $new; } } diff --git a/rules/Php80/Contract/StrStartWithMatchAndRefactorInterface.php b/rules/Php80/Contract/StrStartWithMatchAndRefactorInterface.php index b2d32725c2f..438ba558dfa 100644 --- a/rules/Php80/Contract/StrStartWithMatchAndRefactorInterface.php +++ b/rules/Php80/Contract/StrStartWithMatchAndRefactorInterface.php @@ -1,7 +1,6 @@ strStartsWithFactory = $strStartsWithFactory; $this->nodeNameResolver = $nodeNameResolver; $this->nodeComparator = $nodeComparator; $this->strStartsWithFuncCallFactory = $strStartsWithFuncCallFactory; } - /** * @param Identical|NotIdentical $binaryOp */ - public function match(BinaryOp $binaryOp): ?StrStartsWith + public function match(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\Rector\Php80\ValueObject\StrStartsWith { - $isPositive = $binaryOp instanceof Identical; - - if ($binaryOp->left instanceof FuncCall && $this->nodeNameResolver->isName( - $binaryOp->left, - self::FUNCTION_NAME - )) { + $isPositive = $binaryOp instanceof \PhpParser\Node\Expr\BinaryOp\Identical; + if ($binaryOp->left instanceof \PhpParser\Node\Expr\FuncCall && $this->nodeNameResolver->isName($binaryOp->left, self::FUNCTION_NAME)) { return $this->strStartsWithFactory->createFromFuncCall($binaryOp->left, $isPositive); } - if (! $binaryOp->right instanceof FuncCall) { + if (!$binaryOp->right instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - if (! $this->nodeNameResolver->isName($binaryOp->right, self::FUNCTION_NAME)) { + if (!$this->nodeNameResolver->isName($binaryOp->right, self::FUNCTION_NAME)) { return null; } return $this->strStartsWithFactory->createFromFuncCall($binaryOp->right, $isPositive); } - - public function refactorStrStartsWith(StrStartsWith $strStartsWith): ?Node + public function refactorStrStartsWith(\Rector\Php80\ValueObject\StrStartsWith $strStartsWith) : ?\PhpParser\Node { $strncmpFuncCall = $strStartsWith->getFuncCall(); $needleExpr = $strStartsWith->getNeedleExpr(); - $secondArgumentValue = $strncmpFuncCall->args[2]->value; - if (! $secondArgumentValue instanceof FuncCall) { + if (!$secondArgumentValue instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->nodeNameResolver->isName($secondArgumentValue, 'strlen')) { + if (!$this->nodeNameResolver->isName($secondArgumentValue, 'strlen')) { return null; } - /** @var FuncCall $strlenFuncCall */ $strlenFuncCall = $strncmpFuncCall->args[2]->value; $strlenArgumentValue = $strlenFuncCall->args[0]->value; - - if (! $this->nodeComparator->areNodesEqual($needleExpr, $strlenArgumentValue)) { + if (!$this->nodeComparator->areNodesEqual($needleExpr, $strlenArgumentValue)) { return null; } - return $this->strStartsWithFuncCallFactory->createStrStartsWith($strStartsWith); } } diff --git a/rules/Php80/MatchAndRefactor/StrStartsWithMatchAndRefactor/StrposMatchAndRefactor.php b/rules/Php80/MatchAndRefactor/StrStartsWithMatchAndRefactor/StrposMatchAndRefactor.php index 849df11c736..6def71628c7 100644 --- a/rules/Php80/MatchAndRefactor/StrStartsWithMatchAndRefactor/StrposMatchAndRefactor.php +++ b/rules/Php80/MatchAndRefactor/StrStartsWithMatchAndRefactor/StrposMatchAndRefactor.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->valueResolver = $valueResolver; $this->strStartsWithFuncCallFactory = $strStartsWithFuncCallFactory; } - /** * @param Identical|NotIdentical $binaryOp */ - public function match(BinaryOp $binaryOp): ?StrStartsWith + public function match(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\Rector\Php80\ValueObject\StrStartsWith { - $isPositive = $binaryOp instanceof Identical; - - if ($binaryOp->left instanceof FuncCall && $this->nodeNameResolver->isName($binaryOp->left, 'strpos')) { - if (! $this->valueResolver->isValue($binaryOp->right, 0)) { + $isPositive = $binaryOp instanceof \PhpParser\Node\Expr\BinaryOp\Identical; + if ($binaryOp->left instanceof \PhpParser\Node\Expr\FuncCall && $this->nodeNameResolver->isName($binaryOp->left, 'strpos')) { + if (!$this->valueResolver->isValue($binaryOp->right, 0)) { return null; } - /** @var FuncCall $funcCall */ $funcCall = $binaryOp->left; $haystack = $funcCall->args[0]->value; $needle = $funcCall->args[1]->value; - - return new StrStartsWith($funcCall, $haystack, $needle, $isPositive); + return new \Rector\Php80\ValueObject\StrStartsWith($funcCall, $haystack, $needle, $isPositive); } - - if ($binaryOp->right instanceof FuncCall && $this->nodeNameResolver->isName($binaryOp->right, 'strpos')) { - if (! $this->valueResolver->isValue($binaryOp->left, 0)) { + if ($binaryOp->right instanceof \PhpParser\Node\Expr\FuncCall && $this->nodeNameResolver->isName($binaryOp->right, 'strpos')) { + if (!$this->valueResolver->isValue($binaryOp->left, 0)) { return null; } - /** @var FuncCall $funcCall */ $funcCall = $binaryOp->right; $haystack = $funcCall->args[0]->value; $needle = $funcCall->args[1]->value; - - return new StrStartsWith($funcCall, $haystack, $needle, $isPositive); + return new \Rector\Php80\ValueObject\StrStartsWith($funcCall, $haystack, $needle, $isPositive); } - return null; } - /** * @return FuncCall|BooleanNot */ - public function refactorStrStartsWith(StrStartsWith $strStartsWith): Node + public function refactorStrStartsWith(\Rector\Php80\ValueObject\StrStartsWith $strStartsWith) : \PhpParser\Node { $strposFuncCall = $strStartsWith->getFuncCall(); - $strposFuncCall->name = new Name('str_starts_with'); - + $strposFuncCall->name = new \PhpParser\Node\Name('str_starts_with'); return $this->strStartsWithFuncCallFactory->createStrStartsWith($strStartsWith); } } diff --git a/rules/Php80/MatchAndRefactor/StrStartsWithMatchAndRefactor/SubstrMatchAndRefactor.php b/rules/Php80/MatchAndRefactor/StrStartsWithMatchAndRefactor/SubstrMatchAndRefactor.php index 670e2024397..8253c59144d 100644 --- a/rules/Php80/MatchAndRefactor/StrStartsWithMatchAndRefactor/SubstrMatchAndRefactor.php +++ b/rules/Php80/MatchAndRefactor/StrStartsWithMatchAndRefactor/SubstrMatchAndRefactor.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->valueResolver = $valueResolver; $this->nodeComparator = $nodeComparator; $this->strStartsWithFuncCallFactory = $strStartsWithFuncCallFactory; } - /** * @param Identical|NotIdentical $binaryOp */ - public function match(BinaryOp $binaryOp): ?StrStartsWith + public function match(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\Rector\Php80\ValueObject\StrStartsWith { - $isPositive = $binaryOp instanceof Identical; - - if ($binaryOp->left instanceof FuncCall && $this->nodeNameResolver->isName($binaryOp->left, 'substr')) { + $isPositive = $binaryOp instanceof \PhpParser\Node\Expr\BinaryOp\Identical; + if ($binaryOp->left instanceof \PhpParser\Node\Expr\FuncCall && $this->nodeNameResolver->isName($binaryOp->left, 'substr')) { /** @var FuncCall $funcCall */ $funcCall = $binaryOp->left; $haystack = $funcCall->args[0]->value; - - return new StrStartsWith($funcCall, $haystack, $binaryOp->right, $isPositive); + return new \Rector\Php80\ValueObject\StrStartsWith($funcCall, $haystack, $binaryOp->right, $isPositive); } - - if ($binaryOp->right instanceof FuncCall && $this->nodeNameResolver->isName($binaryOp->right, 'substr')) { + if ($binaryOp->right instanceof \PhpParser\Node\Expr\FuncCall && $this->nodeNameResolver->isName($binaryOp->right, 'substr')) { /** @var FuncCall $funcCall */ $funcCall = $binaryOp->right; $haystack = $funcCall->args[0]->value; - - return new StrStartsWith($funcCall, $haystack, $binaryOp->left, $isPositive); + return new \Rector\Php80\ValueObject\StrStartsWith($funcCall, $haystack, $binaryOp->left, $isPositive); } - return null; } - - public function refactorStrStartsWith(StrStartsWith $strStartsWith): ?Node + public function refactorStrStartsWith(\Rector\Php80\ValueObject\StrStartsWith $strStartsWith) : ?\PhpParser\Node { $substrFuncCall = $strStartsWith->getFuncCall(); - if (! $this->valueResolver->isValue($substrFuncCall->args[1]->value, 0)) { + if (!$this->valueResolver->isValue($substrFuncCall->args[1]->value, 0)) { return null; } - $secondFuncCallArgValue = $substrFuncCall->args[2]->value; - if (! $secondFuncCallArgValue instanceof FuncCall) { + if (!$secondFuncCallArgValue instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->nodeNameResolver->isName($secondFuncCallArgValue, 'strlen')) { + if (!$this->nodeNameResolver->isName($secondFuncCallArgValue, 'strlen')) { return null; } - /** @var FuncCall $strlenFuncCall */ $strlenFuncCall = $substrFuncCall->args[2]->value; $needleExpr = $strlenFuncCall->args[0]->value; - $comparedNeedleExpr = $strStartsWith->getNeedleExpr(); - if (! $this->nodeComparator->areNodesEqual($needleExpr, $comparedNeedleExpr)) { + if (!$this->nodeComparator->areNodesEqual($needleExpr, $comparedNeedleExpr)) { return null; } - return $this->strStartsWithFuncCallFactory->createStrStartsWith($strStartsWith); } } diff --git a/rules/Php80/NodeAnalyzer/PromotedPropertyResolver.php b/rules/Php80/NodeAnalyzer/PromotedPropertyResolver.php index 14329c6d1e6..e866c060d1d 100644 --- a/rules/Php80/NodeAnalyzer/PromotedPropertyResolver.php +++ b/rules/Php80/NodeAnalyzer/PromotedPropertyResolver.php @@ -1,35 +1,30 @@ getMethod(MethodName::CONSTRUCT); - if (! $constructClassMethod instanceof ClassMethod) { + $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return []; } - $promotedPropertyParams = []; foreach ($constructClassMethod->getParams() as $param) { if ($param->flags === 0) { continue; } - $promotedPropertyParams[] = $param; } - return $promotedPropertyParams; } } diff --git a/rules/Php80/NodeAnalyzer/SwitchAnalyzer.php b/rules/Php80/NodeAnalyzer/SwitchAnalyzer.php index 4a9bf254211..59f23620460 100644 --- a/rules/Php80/NodeAnalyzer/SwitchAnalyzer.php +++ b/rules/Php80/NodeAnalyzer/SwitchAnalyzer.php @@ -1,51 +1,42 @@ cases); + $totalCases = \count($switch->cases); if ($totalCases === 1) { - return false; + return \false; } - foreach ($switch->cases as $key => $case) { if ($key === $totalCases - 1) { - return true; + return \true; } - foreach ($case->stmts as $caseStmt) { - if ($caseStmt instanceof Break_) { + if ($caseStmt instanceof \PhpParser\Node\Stmt\Break_) { continue 2; } } - - return false; + return \false; } - - return true; + return \true; } - - public function hasEachCaseSingleStmt(Switch_ $switch): bool + public function hasEachCaseSingleStmt(\PhpParser\Node\Stmt\Switch_ $switch) : bool { foreach ($switch->cases as $case) { - $stmtsWithoutBreak = array_filter($case->stmts, function (Node $node): bool { - return ! $node instanceof Break_; + $stmtsWithoutBreak = \array_filter($case->stmts, function (\PhpParser\Node $node) : bool { + return !$node instanceof \PhpParser\Node\Stmt\Break_; }); - - if (count($stmtsWithoutBreak) !== 1) { - return false; + if (\count($stmtsWithoutBreak) !== 1) { + return \false; } } - - return true; + return \true; } } diff --git a/rules/Php80/NodeFactory/StrStartsWithFuncCallFactory.php b/rules/Php80/NodeFactory/StrStartsWithFuncCallFactory.php index f9c1d79dc6f..6f11ce6d4ee 100644 --- a/rules/Php80/NodeFactory/StrStartsWithFuncCallFactory.php +++ b/rules/Php80/NodeFactory/StrStartsWithFuncCallFactory.php @@ -1,7 +1,6 @@ getHaystackExpr()), new Arg($strStartsWith->getNeedleExpr())]; - - $funcCall = new FuncCall(new Name('str_starts_with'), $args); + $args = [new \PhpParser\Node\Arg($strStartsWith->getHaystackExpr()), new \PhpParser\Node\Arg($strStartsWith->getNeedleExpr())]; + $funcCall = new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name('str_starts_with'), $args); if ($strStartsWith->isPositive()) { return $funcCall; } - - return new BooleanNot($funcCall); + return new \PhpParser\Node\Expr\BooleanNot($funcCall); } } diff --git a/rules/Php80/NodeManipulator/TokenManipulator.php b/rules/Php80/NodeManipulator/TokenManipulator.php index 71b9ab928e9..c970770cfb4 100644 --- a/rules/Php80/NodeManipulator/TokenManipulator.php +++ b/rules/Php80/NodeManipulator/TokenManipulator.php @@ -1,10 +1,9 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->valueResolver = $valueResolver; $this->nodeNameResolver = $nodeNameResolver; @@ -80,277 +65,214 @@ final class TokenManipulator $this->nodesToRemoveCollector = $nodesToRemoveCollector; $this->nodeComparator = $nodeComparator; } - /** * @param Node[] $nodes */ - public function refactorArrayToken(array $nodes, Expr $singleTokenExpr): void + public function refactorArrayToken(array $nodes, \PhpParser\Node\Expr $singleTokenExpr) : void { $this->replaceTokenDimFetchZeroWithGetTokenName($nodes, $singleTokenExpr); - // replace "$token[1]"; with "$token->value" - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (Node $node): ?PropertyFetch { - if (! $node instanceof ArrayDimFetch) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (\PhpParser\Node $node) : ?PropertyFetch { + if (!$node instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return null; } - - if (! $this->isArrayDimFetchWithDimIntegerValue($node, 1)) { + if (!$this->isArrayDimFetchWithDimIntegerValue($node, 1)) { return null; } - $tokenStaticType = $this->nodeTypeResolver->getStaticType($node->var); - if (! $tokenStaticType instanceof ArrayType) { + if (!$tokenStaticType instanceof \PHPStan\Type\ArrayType) { return null; } - - return new PropertyFetch($node->var, 'text'); + return new \PhpParser\Node\Expr\PropertyFetch($node->var, 'text'); }); } - /** * @param Node[] $nodes */ - public function refactorNonArrayToken(array $nodes, Expr $singleTokenExpr): void + public function refactorNonArrayToken(array $nodes, \PhpParser\Node\Expr $singleTokenExpr) : void { // replace "$content = $token;" → "$content = $token->text;" - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (Node $node) use ( - $singleTokenExpr - ) { - if (! $node instanceof Assign) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (\PhpParser\Node $node) use($singleTokenExpr) { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $this->nodeComparator->areNodesEqual($node->expr, $singleTokenExpr)) { + if (!$this->nodeComparator->areNodesEqual($node->expr, $singleTokenExpr)) { return null; } - $tokenStaticType = $this->nodeTypeResolver->getStaticType($node->expr); - if ($tokenStaticType instanceof ArrayType) { + if ($tokenStaticType instanceof \PHPStan\Type\ArrayType) { return null; } - - $node->expr = new PropertyFetch($singleTokenExpr, 'text'); + $node->expr = new \PhpParser\Node\Expr\PropertyFetch($singleTokenExpr, 'text'); }); - // replace "$name = null;" → "$name = $token->getTokenName();" - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (Node $node) use ( - $singleTokenExpr - ): ?Assign { - if (! $node instanceof Assign) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (\PhpParser\Node $node) use($singleTokenExpr) : ?Assign { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - $tokenStaticType = $this->nodeTypeResolver->getStaticType($node->expr); - if ($tokenStaticType instanceof ArrayType) { + if ($tokenStaticType instanceof \PHPStan\Type\ArrayType) { return null; } - if ($this->assignedNameExpr === null) { return null; } - - if (! $this->nodeComparator->areNodesEqual($node->var, $this->assignedNameExpr)) { + if (!$this->nodeComparator->areNodesEqual($node->var, $this->assignedNameExpr)) { return null; } - - if (! $this->valueResolver->isValue($node->expr, 'null')) { + if (!$this->valueResolver->isValue($node->expr, 'null')) { return null; } - - $node->expr = new MethodCall($singleTokenExpr, 'getTokenName'); - + $node->expr = new \PhpParser\Node\Expr\MethodCall($singleTokenExpr, 'getTokenName'); return $node; }); } - /** * @param Node[] $nodes */ - public function refactorTokenIsKind(array $nodes, Expr $singleTokenExpr): void + public function refactorTokenIsKind(array $nodes, \PhpParser\Node\Expr $singleTokenExpr) : void { - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (Node $node) use ( - $singleTokenExpr - ): ?MethodCall { - if (! $node instanceof Identical) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (\PhpParser\Node $node) use($singleTokenExpr) : ?MethodCall { + if (!$node instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { return null; } - $arrayDimFetchAndConstFetch = $this->matchArrayDimFetchAndConstFetch($node); - if (! $arrayDimFetchAndConstFetch instanceof ArrayDimFetchAndConstFetch) { + if (!$arrayDimFetchAndConstFetch instanceof \Rector\Php80\ValueObject\ArrayDimFetchAndConstFetch) { return null; } - - if (! $this->isArrayDimFetchWithDimIntegerValue($arrayDimFetchAndConstFetch->getArrayDimFetch(), 0)) { + if (!$this->isArrayDimFetchWithDimIntegerValue($arrayDimFetchAndConstFetch->getArrayDimFetch(), 0)) { return null; } - $arrayDimFetch = $arrayDimFetchAndConstFetch->getArrayDimFetch(); $constFetch = $arrayDimFetchAndConstFetch->getConstFetch(); - - if (! $this->nodeComparator->areNodesEqual($arrayDimFetch->var, $singleTokenExpr)) { + if (!$this->nodeComparator->areNodesEqual($arrayDimFetch->var, $singleTokenExpr)) { return null; } - $constName = $this->nodeNameResolver->getName($constFetch); if ($constName === null) { return null; } - - if (! Strings::match($constName, '#^T_#')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($constName, '#^T_#')) { return null; } - - return $this->createIsTConstTypeMethodCall( - $arrayDimFetch, - $arrayDimFetchAndConstFetch->getConstFetch() - ); + return $this->createIsTConstTypeMethodCall($arrayDimFetch, $arrayDimFetchAndConstFetch->getConstFetch()); }); } - /** * @param Node[] $nodes */ - public function removeIsArray(array $nodes, Variable $singleTokenVariable): void + public function removeIsArray(array $nodes, \PhpParser\Node\Expr\Variable $singleTokenVariable) : void { - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (Node $node) use ( - $singleTokenVariable - ) { - if (! $node instanceof FuncCall) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (\PhpParser\Node $node) use($singleTokenVariable) { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->nodeNameResolver->isName($node, 'is_array')) { + if (!$this->nodeNameResolver->isName($node, 'is_array')) { return null; } - - if (! $this->nodeComparator->areNodesEqual($node->args[0]->value, $singleTokenVariable)) { + if (!$this->nodeComparator->areNodesEqual($node->args[0]->value, $singleTokenVariable)) { return null; } - if ($this->shouldSkipNodeRemovalForPartOfIf($node)) { return null; } - // remove correct node $nodeToRemove = $this->matchParentNodeInCaseOfIdenticalTrue($node); - $this->nodesToRemoveCollector->addNodeToRemove($nodeToRemove); }); } - /** * Replace $token[0] with $token->getTokenName() call * * @param Node[] $nodes */ - private function replaceTokenDimFetchZeroWithGetTokenName(array $nodes, Expr $singleTokenExpr): void + private function replaceTokenDimFetchZeroWithGetTokenName(array $nodes, \PhpParser\Node\Expr $singleTokenExpr) : void { - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (Node $node) use ( - $singleTokenExpr - ): ?MethodCall { - if (! $node instanceof FuncCall) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, function (\PhpParser\Node $node) use($singleTokenExpr) : ?MethodCall { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->nodeNameResolver->isName($node, 'token_name')) { + if (!$this->nodeNameResolver->isName($node, 'token_name')) { return null; } - $possibleTokenArray = $node->args[0]->value; - if (! $possibleTokenArray instanceof ArrayDimFetch) { + if (!$possibleTokenArray instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return null; } - $tokenStaticType = $this->nodeTypeResolver->getStaticType($possibleTokenArray->var); - if (! $tokenStaticType instanceof ArrayType) { + if (!$tokenStaticType instanceof \PHPStan\Type\ArrayType) { return null; } - if ($possibleTokenArray->dim === null) { return null; } - - if (! $this->valueResolver->isValue($possibleTokenArray->dim, 0)) { + if (!$this->valueResolver->isValue($possibleTokenArray->dim, 0)) { return null; } - - if (! $this->nodeComparator->areNodesEqual($possibleTokenArray->var, $singleTokenExpr)) { + if (!$this->nodeComparator->areNodesEqual($possibleTokenArray->var, $singleTokenExpr)) { return null; } - // save token variable name for later - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Assign) { + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\Assign) { $this->assignedNameExpr = $parentNode->var; } - - return new MethodCall($singleTokenExpr, 'getTokenName'); + return new \PhpParser\Node\Expr\MethodCall($singleTokenExpr, 'getTokenName'); }); } - - private function isArrayDimFetchWithDimIntegerValue(ArrayDimFetch $arrayDimFetch, int $value): bool + private function isArrayDimFetchWithDimIntegerValue(\PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch, int $value) : bool { if ($arrayDimFetch->dim === null) { - return false; + return \false; } - return $this->valueResolver->isValue($arrayDimFetch->dim, $value); } - - private function matchArrayDimFetchAndConstFetch(Identical $identical): ?ArrayDimFetchAndConstFetch + private function matchArrayDimFetchAndConstFetch(\PhpParser\Node\Expr\BinaryOp\Identical $identical) : ?\Rector\Php80\ValueObject\ArrayDimFetchAndConstFetch { - if ($identical->left instanceof ArrayDimFetch && $identical->right instanceof ConstFetch) { - return new ArrayDimFetchAndConstFetch($identical->left, $identical->right); + if ($identical->left instanceof \PhpParser\Node\Expr\ArrayDimFetch && $identical->right instanceof \PhpParser\Node\Expr\ConstFetch) { + return new \Rector\Php80\ValueObject\ArrayDimFetchAndConstFetch($identical->left, $identical->right); } - if (! $identical->right instanceof ArrayDimFetch) { + if (!$identical->right instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return null; } - if (! $identical->left instanceof ConstFetch) { + if (!$identical->left instanceof \PhpParser\Node\Expr\ConstFetch) { return null; } - return new ArrayDimFetchAndConstFetch($identical->right, $identical->left); + return new \Rector\Php80\ValueObject\ArrayDimFetchAndConstFetch($identical->right, $identical->left); } - - private function createIsTConstTypeMethodCall(ArrayDimFetch $arrayDimFetch, ConstFetch $constFetch): MethodCall + private function createIsTConstTypeMethodCall(\PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch, \PhpParser\Node\Expr\ConstFetch $constFetch) : \PhpParser\Node\Expr\MethodCall { - return new MethodCall($arrayDimFetch->var, 'is', [new Arg($constFetch)]); + return new \PhpParser\Node\Expr\MethodCall($arrayDimFetch->var, 'is', [new \PhpParser\Node\Arg($constFetch)]); } - - private function shouldSkipNodeRemovalForPartOfIf(FuncCall $funcCall): bool + private function shouldSkipNodeRemovalForPartOfIf(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { - $parentNode = $funcCall->getAttribute(AttributeKey::PARENT_NODE); - + $parentNode = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // cannot remove x from if(x) - if ($parentNode instanceof If_ && $parentNode->cond === $funcCall) { - return true; + if ($parentNode instanceof \PhpParser\Node\Stmt\If_ && $parentNode->cond === $funcCall) { + return \true; } - - if ($parentNode instanceof BooleanNot) { - $parentParentNode = $parentNode->getAttribute(AttributeKey::PARENT_NODE); - if ($parentParentNode instanceof If_) { + if ($parentNode instanceof \PhpParser\Node\Expr\BooleanNot) { + $parentParentNode = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentParentNode instanceof \PhpParser\Node\Stmt\If_) { $parentParentNode->cond = $parentNode; - return true; + return \true; } } - - return false; + return \false; } - - private function matchParentNodeInCaseOfIdenticalTrue(FuncCall $funcCall): Expr + private function matchParentNodeInCaseOfIdenticalTrue(\PhpParser\Node\Expr\FuncCall $funcCall) : \PhpParser\Node\Expr { - $parentNode = $funcCall->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Identical) { - $isRightValueTrue = $this->valueResolver->isValue($parentNode->right, true); + $parentNode = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { + $isRightValueTrue = $this->valueResolver->isValue($parentNode->right, \true); if ($parentNode->left === $funcCall && $isRightValueTrue) { return $parentNode; } - - $isLeftValueTrue = $this->valueResolver->isValue($parentNode->left, true); + $isLeftValueTrue = $this->valueResolver->isValue($parentNode->left, \true); if ($parentNode->right === $funcCall && $isLeftValueTrue) { return $parentNode; } } - return $funcCall; } } diff --git a/rules/Php80/NodeResolver/ArgumentSorter.php b/rules/Php80/NodeResolver/ArgumentSorter.php index d33cc67e052..ed075f09bfd 100644 --- a/rules/Php80/NodeResolver/ArgumentSorter.php +++ b/rules/Php80/NodeResolver/ArgumentSorter.php @@ -1,12 +1,10 @@ nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; $this->nodeComparator = $nodeComparator; } - /** * @return PropertyPromotionCandidate[] */ - public function resolveFromClass(Class_ $class): array + public function resolveFromClass(\PhpParser\Node\Stmt\Class_ $class) : array { - $constructClassMethod = $class->getMethod(MethodName::CONSTRUCT); - if (! $constructClassMethod instanceof ClassMethod) { + $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return []; } - $propertyPromotionCandidates = []; foreach ($class->getProperties() as $property) { - if (count($property->props) !== 1) { + if (\count($property->props) !== 1) { continue; } - $propertyPromotionCandidate = $this->matchPropertyPromotionCandidate($property, $constructClassMethod); - if (! $propertyPromotionCandidate instanceof PropertyPromotionCandidate) { + if (!$propertyPromotionCandidate instanceof \Rector\Php80\ValueObject\PropertyPromotionCandidate) { continue; } - $propertyPromotionCandidates[] = $propertyPromotionCandidate; } - return $propertyPromotionCandidates; } - - private function matchPropertyPromotionCandidate( - Property $property, - ClassMethod $constructClassMethod - ): ?PropertyPromotionCandidate { + private function matchPropertyPromotionCandidate(\PhpParser\Node\Stmt\Property $property, \PhpParser\Node\Stmt\ClassMethod $constructClassMethod) : ?\Rector\Php80\ValueObject\PropertyPromotionCandidate + { $onlyProperty = $property->props[0]; - $propertyName = $this->nodeNameResolver->getName($onlyProperty); - $firstParamAsVariable = $this->resolveFirstParamUses($constructClassMethod); - // match property name to assign in constructor foreach ((array) $constructClassMethod->stmts as $stmt) { - if ($stmt instanceof Expression) { + if ($stmt instanceof \PhpParser\Node\Stmt\Expression) { $stmt = $stmt->expr; } - - if (! $stmt instanceof Assign) { + if (!$stmt instanceof \PhpParser\Node\Expr\Assign) { continue; } - $assign = $stmt; - if (! $this->nodeNameResolver->isLocalPropertyFetchNamed($assign->var, $propertyName)) { + if (!$this->nodeNameResolver->isLocalPropertyFetchNamed($assign->var, $propertyName)) { continue; } - // 1. is param // @todo 2. is default value $assignedExpr = $assign->expr; - - if (! $assignedExpr instanceof Variable) { + if (!$assignedExpr instanceof \PhpParser\Node\Expr\Variable) { continue; } - $matchedParam = $this->matchClassMethodParamByAssignedVariable($constructClassMethod, $assignedExpr); - if (! $matchedParam instanceof Param) { + if (!$matchedParam instanceof \PhpParser\Node\Param) { continue; } - // is param used above assign? if ($this->isParamUsedBeforeAssign($assignedExpr, $firstParamAsVariable)) { continue; } - - return new PropertyPromotionCandidate($property, $assign, $matchedParam); + return new \Rector\Php80\ValueObject\PropertyPromotionCandidate($property, $assign, $matchedParam); } - return null; } - /** * @return array */ - private function resolveFirstParamUses(ClassMethod $classMethod): array + private function resolveFirstParamUses(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $paramByFirstUsage = []; foreach ($classMethod->params as $param) { $paramName = $this->nodeNameResolver->getName($param); - - $firstParamVariable = $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (Node $node) use ( - $paramName - ): bool { - if (! $node instanceof Variable) { - return false; + $firstParamVariable = $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (\PhpParser\Node $node) use($paramName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeNameResolver->isName($node, $paramName); }); - - if (! $firstParamVariable instanceof Node) { + if (!$firstParamVariable instanceof \PhpParser\Node) { continue; } - $paramByFirstUsage[$paramName] = $firstParamVariable->getStartTokenPos(); } - return $paramByFirstUsage; } - - private function matchClassMethodParamByAssignedVariable( - ClassMethod $classMethod, - Variable $variable - ): ?Param { + private function matchClassMethodParamByAssignedVariable(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Expr\Variable $variable) : ?\PhpParser\Node\Param + { foreach ($classMethod->params as $param) { - if (! $this->nodeComparator->areNodesEqual($variable, $param->var)) { + if (!$this->nodeComparator->areNodesEqual($variable, $param->var)) { continue; } - return $param; } - return null; } - /** * @param array $firstParamAsVariable */ - private function isParamUsedBeforeAssign(Variable $variable, array $firstParamAsVariable): bool + private function isParamUsedBeforeAssign(\PhpParser\Node\Expr\Variable $variable, array $firstParamAsVariable) : bool { $variableName = $this->nodeNameResolver->getName($variable); - $firstVariablePosition = $firstParamAsVariable[$variableName] ?? null; if ($firstVariablePosition === null) { - return false; + return \false; } - return $firstVariablePosition < $variable->getStartTokenPos(); } } diff --git a/rules/Php80/NodeResolver/RequireOptionalParamResolver.php b/rules/Php80/NodeResolver/RequireOptionalParamResolver.php index 78587360984..d3fa4609874 100644 --- a/rules/Php80/NodeResolver/RequireOptionalParamResolver.php +++ b/rules/Php80/NodeResolver/RequireOptionalParamResolver.php @@ -1,20 +1,18 @@ cases as $case) { - if (! isset($case->stmts[0])) { + if (!isset($case->stmts[0])) { return []; } - $expr = $case->stmts[0]; - if ($expr instanceof Expression) { + if ($expr instanceof \PhpParser\Node\Stmt\Expression) { $expr = $expr->expr; } - - if ($expr instanceof Return_) { + if ($expr instanceof \PhpParser\Node\Stmt\Return_) { $returnedExpr = $expr->expr; - if (! $returnedExpr instanceof Expr) { + if (!$returnedExpr instanceof \PhpParser\Node\Expr) { return []; } - $condAndExpr[] = new CondAndExpr($case->cond, $returnedExpr, CondAndExpr::TYPE_RETURN); - } elseif ($expr instanceof Assign) { - $condAndExpr[] = new CondAndExpr($case->cond, $expr, CondAndExpr::TYPE_ASSIGN); - } elseif ($expr instanceof Expr) { - $condAndExpr[] = new CondAndExpr($case->cond, $expr, CondAndExpr::TYPE_NORMAL); + $condAndExpr[] = new \Rector\Php80\ValueObject\CondAndExpr($case->cond, $returnedExpr, \Rector\Php80\ValueObject\CondAndExpr::TYPE_RETURN); + } elseif ($expr instanceof \PhpParser\Node\Expr\Assign) { + $condAndExpr[] = new \Rector\Php80\ValueObject\CondAndExpr($case->cond, $expr, \Rector\Php80\ValueObject\CondAndExpr::TYPE_ASSIGN); + } elseif ($expr instanceof \PhpParser\Node\Expr) { + $condAndExpr[] = new \Rector\Php80\ValueObject\CondAndExpr($case->cond, $expr, \Rector\Php80\ValueObject\CondAndExpr::TYPE_NORMAL); } else { return []; } } - return $condAndExpr; } } diff --git a/rules/Php80/Rector/Catch_/RemoveUnusedVariableInCatchRector.php b/rules/Php80/Rector/Catch_/RemoveUnusedVariableInCatchRector.php index 1ab3fcc26c1..d68560a85eb 100644 --- a/rules/Php80/Rector/Catch_/RemoveUnusedVariableInCatchRector.php +++ b/rules/Php80/Rector/Catch_/RemoveUnusedVariableInCatchRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Catch_::class]; + return [\PhpParser\Node\Stmt\Catch_::class]; } - /** * @param Catch_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $caughtVar = $node->var; - if (! $caughtVar instanceof Variable) { + if (!$caughtVar instanceof \PhpParser\Node\Expr\Variable) { return null; } - if ($this->isVariableUsedInStmts($node->stmts, $caughtVar)) { return null; } - if ($this->isVariableUsedNext($node, $caughtVar)) { return null; } - $node->var = null; - return $node; } - /** * @param Node[] $nodes */ - private function isVariableUsedInStmts(array $nodes, Variable $variable): bool + private function isVariableUsedInStmts(array $nodes, \PhpParser\Node\Expr\Variable $variable) : bool { - return (bool) $this->betterNodeFinder->findFirst($nodes, function (Node $node) use ($variable): bool { - if (! $node instanceof Variable) { - return false; + return (bool) $this->betterNodeFinder->findFirst($nodes, function (\PhpParser\Node $node) use($variable) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeComparator->areNodesEqual($node, $variable); }); } - - private function isVariableUsedNext(Catch_ $catch, Variable $variable): bool + private function isVariableUsedNext(\PhpParser\Node\Stmt\Catch_ $catch, \PhpParser\Node\Expr\Variable $variable) : bool { - return (bool) $this->betterNodeFinder->findFirstNext($catch, function (Node $node) use ($variable): bool { + return (bool) $this->betterNodeFinder->findFirstNext($catch, function (\PhpParser\Node $node) use($variable) : bool { return $this->nodeComparator->areNodesEqual($node, $variable); }); } diff --git a/rules/Php80/Rector/ClassMethod/FinalPrivateToPrivateVisibilityRector.php b/rules/Php80/Rector/ClassMethod/FinalPrivateToPrivateVisibilityRector.php index f5e656d3ba8..edc3334f7c4 100644 --- a/rules/Php80/Rector/ClassMethod/FinalPrivateToPrivateVisibilityRector.php +++ b/rules/Php80/Rector/ClassMethod/FinalPrivateToPrivateVisibilityRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $this->visibilityManipulator->makeNonFinal($node); - return $node; } - - private function shouldSkip(ClassMethod $classMethod): bool + private function shouldSkip(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - if (! $classMethod->isFinal()) { - return true; + if (!$classMethod->isFinal()) { + return \true; } - return ! $classMethod->isPrivate(); + return !$classMethod->isPrivate(); } } diff --git a/rules/Php80/Rector/ClassMethod/OptionalParametersAfterRequiredRector.php b/rules/Php80/Rector/ClassMethod/OptionalParametersAfterRequiredRector.php index 9abdce1986d..25397820ff1 100644 --- a/rules/Php80/Rector/ClassMethod/OptionalParametersAfterRequiredRector.php +++ b/rules/Php80/Rector/ClassMethod/OptionalParametersAfterRequiredRector.php @@ -1,7 +1,6 @@ requireOptionalParamResolver = $requireOptionalParamResolver; $this->argumentSorter = $argumentSorter; $this->methodReflectionClassMethodResolver = $methodReflectionClassMethodResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Move required parameters after optional ones', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Move required parameters after optional ones', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeObject { public function run($optional = 1, $required) @@ -62,9 +51,7 @@ class SomeObject } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeObject { public function run($required, $optional = 1) @@ -72,115 +59,89 @@ class SomeObject } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, New_::class, MethodCall::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\New_::class, \PhpParser\Node\Expr\MethodCall::class]; } - /** * @param ClassMethod|New_|MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { return $this->refactorClassMethod($node); } - - if ($node instanceof New_) { + if ($node instanceof \PhpParser\Node\Expr\New_) { return $this->refactorNew($node); } - return $this->refactorMethodCall($node); } - - private function refactorClassMethod(ClassMethod $classMethod): ?ClassMethod + private function refactorClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PhpParser\Node\Stmt\ClassMethod { if ($classMethod->params === []) { return null; } - $expectedOrderParams = $this->requireOptionalParamResolver->resolve($classMethod); if ($classMethod->params === $expectedOrderParams) { return null; } - $classMethod->params = $expectedOrderParams; - return $classMethod; } - - private function refactorNew(New_ $new): ?New_ + private function refactorNew(\PhpParser\Node\Expr\New_ $new) : ?\PhpParser\Node\Expr\New_ { if ($new->args === []) { return null; } - $newClassType = $this->nodeTypeResolver->resolve($new->class); - if (! $newClassType instanceof TypeWithClassName) { + if (!$newClassType instanceof \PHPStan\Type\TypeWithClassName) { return null; } - - $classMethod = $this->methodReflectionClassMethodResolver->resolve( - $newClassType->getClassName(), - MethodName::CONSTRUCT - ); - if (! $classMethod instanceof ClassMethod) { + $classMethod = $this->methodReflectionClassMethodResolver->resolve($newClassType->getClassName(), \Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - $expectedOrderedParams = $this->requireOptionalParamResolver->resolve($classMethod); if ($expectedOrderedParams === $classMethod->getParams()) { return null; } - - if (count($new->args) !== count($classMethod->getParams())) { + if (\count($new->args) !== \count($classMethod->getParams())) { return null; } - $newArgs = $this->argumentSorter->sortArgsByExpectedParamOrder($new->args, $expectedOrderedParams); if ($new->args === $newArgs) { return null; } - $new->args = $newArgs; - return $new; } - - private function refactorMethodCall(MethodCall $methodCall): ?MethodCall + private function refactorMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node\Expr\MethodCall { $classMethod = $this->nodeRepository->findClassMethodByMethodCall($methodCall); - if (! $classMethod instanceof ClassMethod) { + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - // because parameters can be already changed - $originalClassMethod = $classMethod->getAttribute(AttributeKey::ORIGINAL_NODE); - if (! $originalClassMethod instanceof ClassMethod) { + $originalClassMethod = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE); + if (!$originalClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - $expectedOrderedParams = $this->requireOptionalParamResolver->resolve($originalClassMethod); if ($expectedOrderedParams === $classMethod->getParams()) { return null; } - - if (count($methodCall->args) !== count($classMethod->getParams())) { + if (\count($methodCall->args) !== \count($classMethod->getParams())) { return null; } - $newArgs = $this->argumentSorter->sortArgsByExpectedParamOrder($methodCall->args, $expectedOrderedParams); if ($methodCall->args === $newArgs) { return null; } - $methodCall->args = $newArgs; return $methodCall; } diff --git a/rules/Php80/Rector/ClassMethod/SetStateToStaticRector.php b/rules/Php80/Rector/ClassMethod/SetStateToStaticRector.php index 38838571be8..24526df6d96 100644 --- a/rules/Php80/Rector/ClassMethod/SetStateToStaticRector.php +++ b/rules/Php80/Rector/ClassMethod/SetStateToStaticRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $this->visibilityManipulator->makeStatic($node); - return $node; } - - private function shouldSkip(ClassMethod $classMethod): bool + private function shouldSkip(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - if (! $this->isName($classMethod, MethodName::SET_STATE)) { - return true; + if (!$this->isName($classMethod, \Rector\Core\ValueObject\MethodName::SET_STATE)) { + return \true; } return $classMethod->isStatic(); } diff --git a/rules/Php80/Rector/Class_/AnnotationToAttributeRector.php b/rules/Php80/Rector/Class_/AnnotationToAttributeRector.php index 7e3329eb38c..61eed16ba97 100644 --- a/rules/Php80/Rector/Class_/AnnotationToAttributeRector.php +++ b/rules/Php80/Rector/Class_/AnnotationToAttributeRector.php @@ -1,7 +1,6 @@ phpAttributeGroupFactory = $phpAttributeGroupFactory; $this->phpDocTagRemover = $phpDocTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change annotation to attribute', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change annotation to attribute', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' use Symfony\Component\Routing\Annotation\Route; class SymfonyRoute @@ -75,8 +64,7 @@ class SymfonyRoute } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use Symfony\Component\Routing\Annotation\Route; class SymfonyRoute @@ -87,96 +75,60 @@ class SymfonyRoute } } CODE_SAMPLE - , - [ - self::ANNOTATION_TO_ATTRIBUTE => [ - new AnnotationToAttribute( - 'Symfony\Component\Routing\Annotation\Route', - 'Symfony\Component\Routing\Annotation\Route' - ), - ], - ] - ), - ]); +, [self::ANNOTATION_TO_ATTRIBUTE => [new \Rector\Php80\ValueObject\AnnotationToAttribute('Symfony\\Component\\Routing\\Annotation\\Route', 'Symfony\\Component\\Routing\\Annotation\\Route')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ - Class_::class, - Property::class, - ClassMethod::class, - Function_::class, - Closure::class, - ArrowFunction::class, - ]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Stmt\Property::class, \PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Expr\Closure::class, \PhpParser\Node\Expr\ArrowFunction::class]; } - /** * @param Class_|Property|ClassMethod|Function_|Closure|ArrowFunction $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::ATTRIBUTES)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::ATTRIBUTES)) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNode($node); - if (! $phpDocInfo instanceof PhpDocInfo) { + if (!$phpDocInfo instanceof \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo) { return null; } - - $hasNewAttrGroups = false; - + $hasNewAttrGroups = \false; foreach ($this->annotationsToAttributes as $annotationToAttribute) { $tag = $annotationToAttribute->getTag(); - // 1. simple doc tags if ($phpDocInfo->hasByName($tag)) { // 1. remove php-doc tag $this->phpDocTagRemover->removeByName($phpDocInfo, $tag); - // 2. add attributes $node->attrGroups[] = $this->phpAttributeGroupFactory->createFromSimpleTag($annotationToAttribute); - - $hasNewAttrGroups = true; + $hasNewAttrGroups = \true; } - $doctrineAnnotationTagValueNode = $phpDocInfo->getByAnnotationClass($tag); - if (! $doctrineAnnotationTagValueNode instanceof DoctrineAnnotationTagValueNode) { + if (!$doctrineAnnotationTagValueNode instanceof \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode) { continue; } - // 1. remove php-doc tag $this->phpDocTagRemover->removeTagValueFromNode($phpDocInfo, $doctrineAnnotationTagValueNode); - // 2. add attributes - $node->attrGroups[] = $this->phpAttributeGroupFactory->create( - $doctrineAnnotationTagValueNode, - $annotationToAttribute - ); - - $hasNewAttrGroups = true; + $node->attrGroups[] = $this->phpAttributeGroupFactory->create($doctrineAnnotationTagValueNode, $annotationToAttribute); + $hasNewAttrGroups = \true; } - if ($hasNewAttrGroups) { return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $annotationsToAttributes = $configuration[self::ANNOTATION_TO_ATTRIBUTE] ?? []; - Assert::allIsInstanceOf($annotationsToAttributes, AnnotationToAttribute::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($annotationsToAttributes, \Rector\Php80\ValueObject\AnnotationToAttribute::class); $this->annotationsToAttributes = $annotationsToAttributes; } } diff --git a/rules/Php80/Rector/Class_/ClassPropertyAssignToConstructorPromotionRector.php b/rules/Php80/Rector/Class_/ClassPropertyAssignToConstructorPromotionRector.php index 17a1ee3249d..33700d9cac1 100644 --- a/rules/Php80/Rector/Class_/ClassPropertyAssignToConstructorPromotionRector.php +++ b/rules/Php80/Rector/Class_/ClassPropertyAssignToConstructorPromotionRector.php @@ -1,7 +1,6 @@ promotedPropertyResolver = $promotedPropertyResolver; $this->variableRenamer = $variableRenamer; $this->varTagRemover = $varTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change simple property init and assign to constructor promotion', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change simple property init and assign to constructor promotion', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public float $someVariable; @@ -69,8 +56,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function __construct(private float $someVariable = 0.0) @@ -78,94 +64,74 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $promotionCandidates = $this->promotedPropertyResolver->resolveFromClass($node); if ($promotionCandidates === []) { return null; } - /** @var ClassMethod $constructClassMethod */ - $constructClassMethod = $node->getMethod(MethodName::CONSTRUCT); - + $constructClassMethod = $node->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); $classMethodPhpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($constructClassMethod); - foreach ($promotionCandidates as $promotionCandidate) { // does property have some useful annotations? $property = $promotionCandidate->getProperty(); $param = $promotionCandidate->getParam(); - if ($param->variadic) { continue; } - $this->removeNode($property); $this->removeNode($promotionCandidate->getAssign()); - $property = $promotionCandidate->getProperty(); $paramName = $this->getName($param); - // rename also following calls $propertyName = $this->getName($property->props[0]); /** @var string $oldName */ $oldName = $this->getName($param->var); $this->variableRenamer->renameVariableInFunctionLike($constructClassMethod, null, $oldName, $propertyName); - $paramTagValueNode = $classMethodPhpDocInfo->getParamTagValueNodeByName($paramName); - - if (! $paramTagValueNode instanceof ParamTagValueNode) { + if (!$paramTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode) { $this->decorateParamWithPropertyPhpDocInfo($property, $param); } elseif ($paramTagValueNode->parameterName !== '$' . $propertyName) { $paramTagValueNode->parameterName = '$' . $propertyName; - $paramTagValueNode->setAttribute(PhpDocAttributeKey::ORIG_NODE, null); + $paramTagValueNode->setAttribute(\Rector\BetterPhpDocParser\ValueObject\PhpDocAttributeKey::ORIG_NODE, null); } - // property name has higher priority $propertyName = $this->getName($property); $param->var->name = $propertyName; $param->flags = $property->flags; $this->processNullableType($property, $param); } - return $node; } - - private function processNullableType(Property $property, Param $param): void + private function processNullableType(\PhpParser\Node\Stmt\Property $property, \PhpParser\Node\Param $param) : void { if ($this->nodeTypeResolver->isNullableType($property)) { $objectType = $this->getObjectType($property); $param->type = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($objectType); } } - - private function decorateParamWithPropertyPhpDocInfo(Property $property, Param $param): void + private function decorateParamWithPropertyPhpDocInfo(\PhpParser\Node\Stmt\Property $property, \PhpParser\Node\Param $param) : void { $propertyPhpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); $propertyPhpDocInfo->markAsChanged(); - - $param->setAttribute(AttributeKey::PHP_DOC_INFO, $propertyPhpDocInfo); - + $param->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, $propertyPhpDocInfo); // make sure the docblock is useful if ($param->type === null) { return; } - $paramType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); $this->varTagRemover->removeVarPhpTagValueNodeIfNotComment($param, $paramType); } diff --git a/rules/Php80/Rector/Class_/StringableForToStringRector.php b/rules/Php80/Rector/Class_/StringableForToStringRector.php index d3206ef3bc8..c7ee0a2bbdb 100644 --- a/rules/Php80/Rector/Class_/StringableForToStringRector.php +++ b/rules/Php80/Rector/Class_/StringableForToStringRector.php @@ -1,7 +1,6 @@ classManipulator = $classManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Add `Stringable` interface to classes with `__toString()` method', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add `Stringable` interface to classes with `__toString()` method', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function __toString() @@ -52,8 +43,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass implements Stringable { public function __toString(): string @@ -62,42 +52,33 @@ class SomeClass implements Stringable } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $toStringClassMethod = $node->getMethod('__toString'); - if (! $toStringClassMethod instanceof ClassMethod) { + if (!$toStringClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - - if ($this->classManipulator->hasInterface($node, new ObjectType(self::STRINGABLE))) { + if ($this->classManipulator->hasInterface($node, new \PHPStan\Type\ObjectType(self::STRINGABLE))) { return null; } - // add interface - $node->implements[] = new FullyQualified(self::STRINGABLE); - + $node->implements[] = new \PhpParser\Node\Name\FullyQualified(self::STRINGABLE); // add return type - if ($toStringClassMethod->returnType === null) { - $toStringClassMethod->returnType = new Name('string'); + $toStringClassMethod->returnType = new \PhpParser\Node\Name('string'); } - return $node; } } diff --git a/rules/Php80/Rector/FuncCall/ClassOnObjectRector.php b/rules/Php80/Rector/FuncCall/ClassOnObjectRector.php index 7811f1a9f27..15e6b2e4162 100644 --- a/rules/Php80/Rector/FuncCall/ClassOnObjectRector.php +++ b/rules/Php80/Rector/FuncCall/ClassOnObjectRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::CLASS_ON_OBJECT)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::CLASS_ON_OBJECT)) { return null; } - - if (! $this->nodeNameResolver->isName($node, 'get_class')) { + if (!$this->nodeNameResolver->isName($node, 'get_class')) { return null; } - - if (! isset($node->args[0])) { - return new ClassConstFetch(new Name('self'), 'class'); + if (!isset($node->args[0])) { + return new \PhpParser\Node\Expr\ClassConstFetch(new \PhpParser\Node\Name('self'), 'class'); } - $object = $node->args[0]->value; - - return new ClassConstFetch($object, 'class'); + return new \PhpParser\Node\Expr\ClassConstFetch($object, 'class'); } } diff --git a/rules/Php80/Rector/FuncCall/TokenGetAllToObjectRector.php b/rules/Php80/Rector/FuncCall/TokenGetAllToObjectRector.php index e3a90f33767..45676159875 100644 --- a/rules/Php80/Rector/FuncCall/TokenGetAllToObjectRector.php +++ b/rules/Php80/Rector/FuncCall/TokenGetAllToObjectRector.php @@ -1,7 +1,6 @@ tokenManipulator = $ifArrayTokenManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Complete missing constructor dependency instance by type', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Complete missing constructor dependency instance by type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -61,8 +53,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -75,101 +66,79 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->nodeNameResolver->isName($node, 'token_get_all')) { + if (!$this->nodeNameResolver->isName($node, 'token_get_all')) { return null; } - $this->refactorTokensVariable($node); - return $this->nodeFactory->createStaticCall('PhpToken', 'getAll', $node->args); } - - private function refactorTokensVariable(FuncCall $funcCall): void + private function refactorTokensVariable(\PhpParser\Node\Expr\FuncCall $funcCall) : void { - $assign = $funcCall->getAttribute(AttributeKey::PARENT_NODE); - if (! $assign instanceof Assign) { + $assign = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$assign instanceof \PhpParser\Node\Expr\Assign) { return; } - /** @var ClassMethod|Function_|null $classMethodOrFunction */ - $classMethodOrFunction = $this->betterNodeFinder->findParentTypes( - $funcCall, - [ClassMethod::class, Function_::class] - ); + $classMethodOrFunction = $this->betterNodeFinder->findParentTypes($funcCall, [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class]); if ($classMethodOrFunction === null) { return; } - // dummy approach, improve when needed $this->replaceGetNameOrGetValue($classMethodOrFunction, $assign->var); } - /** * @param ClassMethod|Function_ $functionLike */ - private function replaceGetNameOrGetValue(FunctionLike $functionLike, Expr $assignedExpr): void + private function replaceGetNameOrGetValue(\PhpParser\Node\FunctionLike $functionLike, \PhpParser\Node\Expr $assignedExpr) : void { $tokensForeaches = $this->findForeachesOverTokenVariable($functionLike, $assignedExpr); foreach ($tokensForeaches as $tokenForeach) { $this->refactorTokenInForeach($tokenForeach); } } - /** * @param ClassMethod|Function_ $functionLike * @return Foreach_[] */ - private function findForeachesOverTokenVariable(FunctionLike $functionLike, Expr $assignedExpr): array + private function findForeachesOverTokenVariable(\PhpParser\Node\FunctionLike $functionLike, \PhpParser\Node\Expr $assignedExpr) : array { - return $this->betterNodeFinder->find((array) $functionLike->stmts, function (Node $node) use ( - $assignedExpr - ): bool { - if (! $node instanceof Foreach_) { - return false; + return $this->betterNodeFinder->find((array) $functionLike->stmts, function (\PhpParser\Node $node) use($assignedExpr) : bool { + if (!$node instanceof \PhpParser\Node\Stmt\Foreach_) { + return \false; } - return $this->nodeComparator->areNodesEqual($node->expr, $assignedExpr); }); } - - private function refactorTokenInForeach(Foreach_ $tokensForeach): void + private function refactorTokenInForeach(\PhpParser\Node\Stmt\Foreach_ $tokensForeach) : void { $singleToken = $tokensForeach->valueVar; - if (! $singleToken instanceof Variable) { + if (!$singleToken instanceof \PhpParser\Node\Expr\Variable) { return; } - - $this->traverseNodesWithCallable($tokensForeach, function (Node $node) use ($singleToken) { + $this->traverseNodesWithCallable($tokensForeach, function (\PhpParser\Node $node) use($singleToken) { $this->tokenManipulator->refactorArrayToken([$node], $singleToken); $this->tokenManipulator->refactorNonArrayToken([$node], $singleToken); $this->tokenManipulator->refactorTokenIsKind([$node], $singleToken); - $this->tokenManipulator->removeIsArray([$node], $singleToken); - // drop if "If_" node not needed - if ($node instanceof If_ && $node->else !== null) { - if (! $this->nodeComparator->areNodesEqual($node->stmts, $node->else->stmts)) { + if ($node instanceof \PhpParser\Node\Stmt\If_ && $node->else !== null) { + if (!$this->nodeComparator->areNodesEqual($node->stmts, $node->else->stmts)) { return null; } - $this->unwrapStmts($node->stmts, $node); $this->removeNode($node); } diff --git a/rules/Php80/Rector/FunctionLike/UnionTypesRector.php b/rules/Php80/Rector/FunctionLike/UnionTypesRector.php index fd1d38630f9..4fdde433012 100644 --- a/rules/Php80/Rector/FunctionLike/UnionTypesRector.php +++ b/rules/Php80/Rector/FunctionLike/UnionTypesRector.php @@ -1,7 +1,6 @@ returnTagRemover = $returnTagRemover; $this->paramTagRemover = $paramTagRemover; $this->classMethodParamVendorLockResolver = $classMethodParamVendorLockResolver; $this->unionTypeAnalyzer = $unionTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change docs types to union types, where possible (properties are covered by TypedPropertiesRector)', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change docs types to union types, where possible (properties are covered by TypedPropertiesRector)', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -78,8 +63,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function go(array|int $number): bool|float @@ -87,104 +71,84 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Function_::class, Closure::class, ArrowFunction::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Expr\Closure::class, \PhpParser\Node\Expr\ArrowFunction::class]; } - /** * @param ClassMethod|Function_|Closure|ArrowFunction $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - $this->refactorParamTypes($node, $phpDocInfo); $this->refactorReturnType($node, $phpDocInfo); - $this->paramTagRemover->removeParamTagsIfUseless($phpDocInfo, $node); $this->returnTagRemover->removeReturnTagIfUseless($phpDocInfo, $node); - return $node; } - - private function isVendorLocked(ClassMethod $classMethod): bool + private function isVendorLocked(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { return $this->classMethodParamVendorLockResolver->isVendorLocked($classMethod); } - /** * @param ClassMethod|Function_|Closure|ArrowFunction $functionLike */ - private function refactorParamTypes(FunctionLike $functionLike, PhpDocInfo $phpDocInfo): void + private function refactorParamTypes(\PhpParser\Node\FunctionLike $functionLike, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void { - if ($functionLike instanceof ClassMethod && $this->isVendorLocked($functionLike)) { + if ($functionLike instanceof \PhpParser\Node\Stmt\ClassMethod && $this->isVendorLocked($functionLike)) { return; } - foreach ($functionLike->getParams() as $param) { if ($param->type !== null) { continue; } - /** @var string $paramName */ $paramName = $this->getName($param->var); $paramType = $phpDocInfo->getParamType($paramName); - if (! $paramType instanceof UnionType) { + if (!$paramType instanceof \PHPStan\Type\UnionType) { continue; } - if ($this->unionTypeAnalyzer->hasObjectWithoutClassType($paramType)) { $this->changeObjectWithoutClassType($param, $paramType); continue; } - $phpParserUnionType = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($paramType); - if (! $phpParserUnionType instanceof PhpParserUnionType) { + if (!$phpParserUnionType instanceof \PhpParser\Node\UnionType) { continue; } - $param->type = $phpParserUnionType; } } - - private function changeObjectWithoutClassType(Param $param, UnionType $unionType): void + private function changeObjectWithoutClassType(\PhpParser\Node\Param $param, \PHPStan\Type\UnionType $unionType) : void { - if (! $this->unionTypeAnalyzer->hasObjectWithoutClassTypeWithOnlyFullyQualifiedObjectType($unionType)) { + if (!$this->unionTypeAnalyzer->hasObjectWithoutClassTypeWithOnlyFullyQualifiedObjectType($unionType)) { return; } - - $param->type = new Name('object'); + $param->type = new \PhpParser\Node\Name('object'); } - /** * @param ClassMethod|Function_|Closure|ArrowFunction $functionLike */ - private function refactorReturnType(FunctionLike $functionLike, PhpDocInfo $phpDocInfo): void + private function refactorReturnType(\PhpParser\Node\FunctionLike $functionLike, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void { // do not override existing return type if ($functionLike->getReturnType() !== null) { return; } - $returnType = $phpDocInfo->getReturnType(); - if (! $returnType instanceof UnionType) { + if (!$returnType instanceof \PHPStan\Type\UnionType) { return; } - $phpParserUnionType = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($returnType); - if (! $phpParserUnionType instanceof PhpParserUnionType) { + if (!$phpParserUnionType instanceof \PhpParser\Node\UnionType) { return; } - $functionLike->returnType = $phpParserUnionType; } } diff --git a/rules/Php80/Rector/Identical/StrEndsWithRector.php b/rules/Php80/Rector/Identical/StrEndsWithRector.php index 931ccedffa3..0f769089b94 100644 --- a/rules/Php80/Rector/Identical/StrEndsWithRector.php +++ b/rules/Php80/Rector/Identical/StrEndsWithRector.php @@ -1,7 +1,6 @@ binaryOpAnalyzer = $binaryOpAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change helper functions to str_ends_with()', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change helper functions to str_ends_with()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -47,8 +41,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -57,93 +50,76 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identical::class, NotIdentical::class]; + return [\PhpParser\Node\Expr\BinaryOp\Identical::class, \PhpParser\Node\Expr\BinaryOp\NotIdentical::class]; } - /** * @param Identical|NotIdentical $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { return $this->refactorSubstr($node) ?? $this->refactorSubstrCompare($node); } - /** * Covers: * $isMatch = substr($haystack, -strlen($needle)) === $needle; */ - private function refactorSubstr(BinaryOp $binaryOp): ?FuncCall + private function refactorSubstr(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\PhpParser\Node\Expr\FuncCall { - if ($binaryOp->left instanceof FuncCall && $this->isName($binaryOp->left, 'substr')) { + if ($binaryOp->left instanceof \PhpParser\Node\Expr\FuncCall && $this->isName($binaryOp->left, 'substr')) { $substrFuncCall = $binaryOp->left; $comparedNeedleExpr = $binaryOp->right; - } elseif ($binaryOp->right instanceof FuncCall && $this->isName($binaryOp->right, 'substr')) { + } elseif ($binaryOp->right instanceof \PhpParser\Node\Expr\FuncCall && $this->isName($binaryOp->right, 'substr')) { $substrFuncCall = $binaryOp->right; $comparedNeedleExpr = $binaryOp->left; } else { return null; } - $haystack = $substrFuncCall->args[0]->value; - $needle = $this->matchUnaryMinusStrlenFuncCallArgValue($substrFuncCall->args[1]->value); - if (! $this->nodeComparator->areNodesEqual($needle, $comparedNeedleExpr)) { + if (!$this->nodeComparator->areNodesEqual($needle, $comparedNeedleExpr)) { return null; } - return $this->nodeFactory->createFuncCall('str_ends_with', [$haystack, $needle]); } - - private function refactorSubstrCompare(BinaryOp $binaryOp): ?FuncCall + private function refactorSubstrCompare(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\PhpParser\Node\Expr\FuncCall { $funcCallAndExpr = $this->binaryOpAnalyzer->matchFuncCallAndOtherExpr($binaryOp, 'substr_compare'); - if (! $funcCallAndExpr instanceof FuncCallAndExpr) { + if (!$funcCallAndExpr instanceof \Rector\Nette\ValueObject\FuncCallAndExpr) { return null; } - $expr = $funcCallAndExpr->getExpr(); - if (! $this->valueResolver->isValue($expr, 0)) { + if (!$this->valueResolver->isValue($expr, 0)) { return null; } - $substrCompareFuncCall = $funcCallAndExpr->getFuncCall(); $haystack = $substrCompareFuncCall->args[0]->value; $needle = $substrCompareFuncCall->args[1]->value; - $comparedNeedleExpr = $this->matchUnaryMinusStrlenFuncCallArgValue($substrCompareFuncCall->args[2]->value); - if (! $this->nodeComparator->areNodesEqual($needle, $comparedNeedleExpr)) { + if (!$this->nodeComparator->areNodesEqual($needle, $comparedNeedleExpr)) { return null; } - return $this->nodeFactory->createFuncCall('str_ends_with', [$haystack, $needle]); } - - private function matchUnaryMinusStrlenFuncCallArgValue(Node $node): ?Expr + private function matchUnaryMinusStrlenFuncCallArgValue(\PhpParser\Node $node) : ?\PhpParser\Node\Expr { - if (! $node instanceof UnaryMinus) { + if (!$node instanceof \PhpParser\Node\Expr\UnaryMinus) { return null; } - - if (! $node->expr instanceof FuncCall) { + if (!$node->expr instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->nodeNameResolver->isName($node->expr, 'strlen')) { + if (!$this->nodeNameResolver->isName($node->expr, 'strlen')) { return null; } - /** @var FuncCall $funcCall */ $funcCall = $node->expr; - return $funcCall->args[0]->value; } } diff --git a/rules/Php80/Rector/Identical/StrStartsWithRector.php b/rules/Php80/Rector/Identical/StrStartsWithRector.php index a59e9ff78f1..eb1f7a0f4c9 100644 --- a/rules/Php80/Rector/Identical/StrStartsWithRector.php +++ b/rules/Php80/Rector/Identical/StrStartsWithRector.php @@ -1,7 +1,6 @@ strStartWithMatchAndRefactors = $strStartWithMatchAndRefactors; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change helper functions to str_starts_with()', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change helper functions to str_starts_with()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -53,8 +45,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -65,33 +56,27 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identical::class, NotIdentical::class]; + return [\PhpParser\Node\Expr\BinaryOp\Identical::class, \PhpParser\Node\Expr\BinaryOp\NotIdentical::class]; } - /** * @param Identical|NotIdentical $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->strStartWithMatchAndRefactors as $strStartWithMatchAndRefactor) { $strStartsWithValueObject = $strStartWithMatchAndRefactor->match($node); - if (! $strStartsWithValueObject instanceof StrStartsWith) { + if (!$strStartsWithValueObject instanceof \Rector\Php80\ValueObject\StrStartsWith) { continue; } - return $strStartWithMatchAndRefactor->refactorStrStartsWith($strStartsWithValueObject); } - return null; } } diff --git a/rules/Php80/Rector/If_/NullsafeOperatorRector.php b/rules/Php80/Rector/If_/NullsafeOperatorRector.php index 863526d3d16..320e3ef0b1c 100644 --- a/rules/Php80/Rector/If_/NullsafeOperatorRector.php +++ b/rules/Php80/Rector/If_/NullsafeOperatorRector.php @@ -1,7 +1,6 @@ ifManipulator = $ifManipulator; $this->nullsafeManipulator = $nullsafeManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change if null check with nullsafe operator ?-> with full short circuiting', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change if null check with nullsafe operator ?-> with full short circuiting', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($someObject) @@ -68,8 +58,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($someObject) @@ -78,87 +67,68 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [If_::class]; + return [\PhpParser\Node\Stmt\If_::class]; } - /** * @param If_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $processNullSafeOperator = $this->processNullSafeOperatorIdentical($node); if ($processNullSafeOperator !== null) { /** @var Expression $prevNode */ - $prevNode = $node->getAttribute(AttributeKey::PREVIOUS_NODE); + $prevNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); $this->removeNode($prevNode); - return $processNullSafeOperator; } - return $this->processNullSafeOperatorNotIdentical($node); } - - private function processNullSafeOperatorIdentical(If_ $if, bool $isStartIf = true): ?Node + private function processNullSafeOperatorIdentical(\PhpParser\Node\Stmt\If_ $if, bool $isStartIf = \true) : ?\PhpParser\Node { $comparedNode = $this->ifManipulator->matchIfValueReturnValue($if); - if (! $comparedNode instanceof Expr) { + if (!$comparedNode instanceof \PhpParser\Node\Expr) { return null; } - - $prevNode = $if->getAttribute(AttributeKey::PREVIOUS_NODE); - $nextNode = $if->getAttribute(AttributeKey::NEXT_NODE); - - if (! $prevNode instanceof Node) { + $prevNode = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + $nextNode = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$prevNode instanceof \PhpParser\Node) { return null; } - - if (! $nextNode instanceof Node) { + if (!$nextNode instanceof \PhpParser\Node) { return null; } - - if (! $prevNode instanceof Expression) { + if (!$prevNode instanceof \PhpParser\Node\Stmt\Expression) { return null; } - - if (! $this->ifManipulator->isIfCondUsingAssignIdenticalVariable($if, $prevNode->expr)) { + if (!$this->ifManipulator->isIfCondUsingAssignIdenticalVariable($if, $prevNode->expr)) { return null; } - $prevExpr = $prevNode->expr; - if (! $prevExpr instanceof Assign) { + if (!$prevExpr instanceof \PhpParser\Node\Expr\Assign) { return null; } - return $this->processAssign($prevExpr, $prevNode, $nextNode, $isStartIf); } - - private function processNullSafeOperatorNotIdentical(If_ $if, ?Expr $expr = null): ?Node + private function processNullSafeOperatorNotIdentical(\PhpParser\Node\Stmt\If_ $if, ?\PhpParser\Node\Expr $expr = null) : ?\PhpParser\Node { $assign = $this->ifManipulator->matchIfNotNullNextAssignment($if); - if (! $assign instanceof Assign) { + if (!$assign instanceof \PhpParser\Node\Expr\Assign) { return null; } - $assignExpr = $assign->expr; if ($this->ifManipulator->isIfCondUsingAssignNotIdenticalVariable($if, $assignExpr)) { return null; } - /** @var Expression $expression */ - $expression = $assign->getAttribute(AttributeKey::PARENT_NODE); - - $nextNode = $expression->getAttribute(AttributeKey::NEXT_NODE); - + $expression = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + $nextNode = $expression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); /** @var NullsafeMethodCall|NullsafePropertyFetch $nullSafe */ $nullSafe = $this->nullsafeManipulator->processNullSafeExpr($assignExpr); if ($expr !== null) { @@ -167,182 +137,133 @@ CODE_SAMPLE /** @var NullsafeMethodCall|NullsafePropertyFetch $nullSafe */ $nullSafe = $this->nullsafeManipulator->processNullSafeExprResult($expr, $nullSafeIdentifier); } - $nextOfNextNode = $this->processIfMayInNextNode($nextNode); if ($nextOfNextNode !== null) { return $nextOfNextNode; } - - if (! $nextNode instanceof If_) { - return new Assign($assign->var, $nullSafe); + if (!$nextNode instanceof \PhpParser\Node\Stmt\If_) { + return new \PhpParser\Node\Expr\Assign($assign->var, $nullSafe); } - return $this->processNullSafeOperatorNotIdentical($nextNode, $nullSafe); } - - private function processAssign(Assign $assign, Expression $prevExpression, Node $nextNode, bool $isStartIf): ?Node + private function processAssign(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Stmt\Expression $prevExpression, \PhpParser\Node $nextNode, bool $isStartIf) : ?\PhpParser\Node { - if ($assign instanceof Assign && property_exists( - $assign->expr, - self::NAME - ) && property_exists($nextNode, 'expr') && property_exists($nextNode->expr, self::NAME)) { + if ($assign instanceof \PhpParser\Node\Expr\Assign && \property_exists($assign->expr, self::NAME) && \property_exists($nextNode, 'expr') && \property_exists($nextNode->expr, self::NAME)) { return $this->processAssignInCurrentNode($assign, $prevExpression, $nextNode, $isStartIf); } - return $this->processAssignMayInNextNode($nextNode); } - - private function processIfMayInNextNode(?Node $nextNode = null): ?Node + private function processIfMayInNextNode(?\PhpParser\Node $nextNode = null) : ?\PhpParser\Node { - if (! $nextNode instanceof Node) { + if (!$nextNode instanceof \PhpParser\Node) { return null; } - - $nextOfNextNode = $nextNode->getAttribute(AttributeKey::NEXT_NODE); + $nextOfNextNode = $nextNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); while ($nextOfNextNode) { - if ($nextOfNextNode instanceof If_) { + if ($nextOfNextNode instanceof \PhpParser\Node\Stmt\If_) { /** @var If_ $beforeIf */ - $beforeIf = $nextOfNextNode->getAttribute(AttributeKey::PARENT_NODE); + $beforeIf = $nextOfNextNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); $nullSafe = $this->processNullSafeOperatorNotIdentical($nextOfNextNode); - if (! $nullSafe instanceof NullsafeMethodCall && ! $nullSafe instanceof PropertyFetch) { + if (!$nullSafe instanceof \PhpParser\Node\Expr\NullsafeMethodCall && !$nullSafe instanceof \PhpParser\Node\Expr\PropertyFetch) { return $beforeIf; } - - $beforeIf->stmts[count($beforeIf->stmts) - 1] = new Expression($nullSafe); + $beforeIf->stmts[\count($beforeIf->stmts) - 1] = new \PhpParser\Node\Stmt\Expression($nullSafe); return $beforeIf; } - - $nextOfNextNode = $nextOfNextNode->getAttribute(AttributeKey::NEXT_NODE); + $nextOfNextNode = $nextOfNextNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); } - return null; } - - private function processAssignInCurrentNode( - Assign $assign, - Expression $expression, - Node $nextNode, - bool $isStartIf - ): ?Node { - $assignNullSafe = $isStartIf - ? $assign->expr - : $this->nullsafeManipulator->processNullSafeExpr($assign->expr); + private function processAssignInCurrentNode(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Stmt\Expression $expression, \PhpParser\Node $nextNode, bool $isStartIf) : ?\PhpParser\Node + { + $assignNullSafe = $isStartIf ? $assign->expr : $this->nullsafeManipulator->processNullSafeExpr($assign->expr); $nullSafe = $this->nullsafeManipulator->processNullSafeExprResult($assignNullSafe, $nextNode->expr->name); - - $prevAssign = $expression->getAttribute(AttributeKey::PREVIOUS_NODE); - if ($prevAssign instanceof If_) { + $prevAssign = $expression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if ($prevAssign instanceof \PhpParser\Node\Stmt\If_) { $nullSafe = $this->getNullSafeOnPrevAssignIsIf($prevAssign, $nextNode, $nullSafe); } - $this->removeNode($nextNode); - - if ($nextNode instanceof Return_) { + if ($nextNode instanceof \PhpParser\Node\Stmt\Return_) { $nextNode->expr = $nullSafe; return $nextNode; } - return $nullSafe; } - - private function processAssignMayInNextNode(Node $nextNode): ?Node + private function processAssignMayInNextNode(\PhpParser\Node $nextNode) : ?\PhpParser\Node { - if (! $nextNode instanceof Expression) { + if (!$nextNode instanceof \PhpParser\Node\Stmt\Expression) { return null; } - if (! $nextNode->expr instanceof Assign) { + if (!$nextNode->expr instanceof \PhpParser\Node\Expr\Assign) { return null; } - $mayNextIf = $nextNode->getAttribute(AttributeKey::NEXT_NODE); - if (! $mayNextIf instanceof If_) { + $mayNextIf = $nextNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if (!$mayNextIf instanceof \PhpParser\Node\Stmt\If_) { return null; } - if ($this->ifManipulator->isIfCondUsingAssignIdenticalVariable($mayNextIf, $nextNode->expr)) { - return $this->processNullSafeOperatorIdentical($mayNextIf, false); + return $this->processNullSafeOperatorIdentical($mayNextIf, \false); } - return null; } - - private function getNullSafeOnPrevAssignIsIf(If_ $if, Node $nextNode, ?Expr $expr): ?Expr + private function getNullSafeOnPrevAssignIsIf(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node $nextNode, ?\PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr { - $prevIf = $if->getAttribute(AttributeKey::PREVIOUS_NODE); - if (! $prevIf instanceof Expression) { + $prevIf = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if (!$prevIf instanceof \PhpParser\Node\Stmt\Expression) { return $expr; } - - if (! $this->ifManipulator->isIfCondUsingAssignIdenticalVariable($if, $prevIf->expr)) { + if (!$this->ifManipulator->isIfCondUsingAssignIdenticalVariable($if, $prevIf->expr)) { return $expr; } - $start = $prevIf; - - while ($prevIf instanceof Expression) { + while ($prevIf instanceof \PhpParser\Node\Stmt\Expression) { $expressionNode = $prevIf->expr; - if (! $expressionNode instanceof Assign) { + if (!$expressionNode instanceof \PhpParser\Node\Expr\Assign) { return null; } - $expr = $this->nullsafeManipulator->processNullSafeExpr($expressionNode->expr); - /** @var Node $prevPrevIf */ - $prevPrevIf = $prevIf->getAttribute(AttributeKey::PREVIOUS_NODE); + $prevPrevIf = $prevIf->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); /** @var Node $prevPrevPrevIf */ - $prevPrevPrevIf = $prevPrevIf->getAttribute(AttributeKey::PREVIOUS_NODE); - - if (! $prevPrevPrevIf instanceof Expression && $prevPrevPrevIf !== null) { + $prevPrevPrevIf = $prevPrevIf->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); + if (!$prevPrevPrevIf instanceof \PhpParser\Node\Stmt\Expression && $prevPrevPrevIf !== null) { $start = $this->getPreviousIf($prevPrevPrevIf); break; } - $prevIf = $prevPrevPrevIf; } - - if (! $expr instanceof NullsafeMethodCall && ! $expr instanceof NullsafePropertyFetch) { + if (!$expr instanceof \PhpParser\Node\Expr\NullsafeMethodCall && !$expr instanceof \PhpParser\Node\Expr\NullsafePropertyFetch) { return $expr; } - /** @var Expr $expr */ - $expr = $expr->var->getAttribute(AttributeKey::PARENT_NODE); + $expr = $expr->var->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); $expr = $this->getNullSafeAfterStartUntilBeforeEnd($start, $expr); - return $this->nullsafeManipulator->processNullSafeExprResult($expr, $nextNode->expr->name); } - - private function getPreviousIf(Node $node): ?Node + private function getPreviousIf(\PhpParser\Node $node) : ?\PhpParser\Node { /** @var If_ $if */ - $if = $node->getAttribute(AttributeKey::NEXT_NODE); - + $if = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); /** @var Expression $expression */ - $expression = $if->getAttribute(AttributeKey::NEXT_NODE); - + $expression = $if->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); /** @var Expression $nextExpression */ - $nextExpression = $expression->getAttribute(AttributeKey::NEXT_NODE); - - return $nextExpression->getAttribute(AttributeKey::NEXT_NODE); + $nextExpression = $expression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + return $nextExpression->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); } - - private function getNullSafeAfterStartUntilBeforeEnd(?Node $node, ?Expr $expr): ?Expr + private function getNullSafeAfterStartUntilBeforeEnd(?\PhpParser\Node $node, ?\PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr { while ($node) { $expr = $this->nullsafeManipulator->processNullSafeExprResult($expr, $node->expr->expr->name); - - $node = $node->getAttribute(AttributeKey::NEXT_NODE); + $node = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); while ($node) { /** @var If_ $if */ - $if = $node->getAttribute(AttributeKey::NEXT_NODE); - if ($node instanceof Expression && $this->ifManipulator->isIfCondUsingAssignIdenticalVariable( - $if, - $node->expr - )) { + $if = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if ($node instanceof \PhpParser\Node\Stmt\Expression && $this->ifManipulator->isIfCondUsingAssignIdenticalVariable($if, $node->expr)) { break; } - - $node = $node->getAttribute(AttributeKey::NEXT_NODE); + $node = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); } } - return $expr; } } diff --git a/rules/Php80/Rector/NotIdentical/StrContainsRector.php b/rules/Php80/Rector/NotIdentical/StrContainsRector.php index 782aab5e99e..6dfba619ab1 100644 --- a/rules/Php80/Rector/NotIdentical/StrContainsRector.php +++ b/rules/Php80/Rector/NotIdentical/StrContainsRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Identical::class, NotIdentical::class]; + return [\PhpParser\Node\Expr\BinaryOp\Identical::class, \PhpParser\Node\Expr\BinaryOp\NotIdentical::class]; } - /** * @param Identical|NotIdentical $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $funcCall = $this->matchIdenticalOrNotIdenticalToFalse($node); - - if (! $funcCall instanceof FuncCall) { + if (!$funcCall instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - $funcCall->name = new Name('str_contains'); - - if ($node instanceof Identical) { - return new BooleanNot($funcCall); + $funcCall->name = new \PhpParser\Node\Name('str_contains'); + if ($node instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { + return new \PhpParser\Node\Expr\BooleanNot($funcCall); } - return $funcCall; } - /** * @param Identical|NotIdentical $expr */ - private function matchIdenticalOrNotIdenticalToFalse(Expr $expr): ?FuncCall + private function matchIdenticalOrNotIdenticalToFalse(\PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr\FuncCall { if ($this->valueResolver->isFalse($expr->left)) { - if (! $expr->right instanceof FuncCall) { + if (!$expr->right instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->isNames($expr->right, self::OLD_STR_NAMES)) { + if (!$this->isNames($expr->right, self::OLD_STR_NAMES)) { return null; } - /** @var FuncCall $funcCall */ $funcCall = $expr->right; return $funcCall; } - if ($this->valueResolver->isFalse($expr->right)) { - if (! $expr->left instanceof FuncCall) { + if (!$expr->left instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - - if (! $this->isNames($expr->left, self::OLD_STR_NAMES)) { + if (!$this->isNames($expr->left, self::OLD_STR_NAMES)) { return null; } - /** @var FuncCall $funcCall */ $funcCall = $expr->left; return $funcCall; } - return null; } } diff --git a/rules/Php80/Rector/Switch_/ChangeSwitchToMatchRector.php b/rules/Php80/Rector/Switch_/ChangeSwitchToMatchRector.php index cc68726e677..e2f83394fed 100644 --- a/rules/Php80/Rector/Switch_/ChangeSwitchToMatchRector.php +++ b/rules/Php80/Rector/Switch_/ChangeSwitchToMatchRector.php @@ -1,7 +1,6 @@ switchExprsResolver = $switchExprsResolver; $this->switchAnalyzer = $switchAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change switch() to match()', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change switch() to match()', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -74,8 +66,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -88,158 +79,127 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Switch_::class]; + return [\PhpParser\Node\Stmt\Switch_::class]; } - /** * @param Switch_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipSwitch($node)) { return null; } - $condAndExprs = $this->switchExprsResolver->resolve($node); if ($condAndExprs === []) { return null; } - - if (! $this->haveCondAndExprsMatchPotential($condAndExprs)) { + if (!$this->haveCondAndExprsMatchPotential($condAndExprs)) { return null; } - $this->assignExpr = null; - - $isReturn = false; + $isReturn = \false; foreach ($condAndExprs as $condAndExpr) { - if ($condAndExpr->getKind() === CondAndExpr::TYPE_RETURN) { - $isReturn = true; + if ($condAndExpr->getKind() === \Rector\Php80\ValueObject\CondAndExpr::TYPE_RETURN) { + $isReturn = \true; break; } - $expr = $condAndExpr->getExpr(); - if (! $expr instanceof Assign) { + if (!$expr instanceof \PhpParser\Node\Expr\Assign) { return null; } } - $matchArms = $this->createMatchArmsFromCases($condAndExprs); - $match = new Match_($node->cond, $matchArms); - + $match = new \PhpParser\Node\Expr\Match_($node->cond, $matchArms); if ($isReturn) { - return new Return_($match); + return new \PhpParser\Node\Stmt\Return_($match); } - if ($this->assignExpr) { /** @var Expr $assignExpr */ $assignExpr = $this->assignExpr; return $this->changeToAssign($node, $match, $assignExpr); } - return $match; } - - private function changeToAssign(Switch_ $switch, Match_ $match, Expr $assignExpr): Assign + private function changeToAssign(\PhpParser\Node\Stmt\Switch_ $switch, \PhpParser\Node\Expr\Match_ $match, \PhpParser\Node\Expr $assignExpr) : \PhpParser\Node\Expr\Assign { - $prevInitializedAssign = $this->betterNodeFinder->findFirstPreviousOfNode($switch, function (Node $node) use ( - $assignExpr - ): bool { - return $node instanceof Assign && $this->nodeComparator->areNodesEqual($node->var, $assignExpr); + $prevInitializedAssign = $this->betterNodeFinder->findFirstPreviousOfNode($switch, function (\PhpParser\Node $node) use($assignExpr) : bool { + return $node instanceof \PhpParser\Node\Expr\Assign && $this->nodeComparator->areNodesEqual($node->var, $assignExpr); }); - - $assign = new Assign($assignExpr, $match); - if ($prevInitializedAssign instanceof Assign) { + $assign = new \PhpParser\Node\Expr\Assign($assignExpr, $match); + if ($prevInitializedAssign instanceof \PhpParser\Node\Expr\Assign) { /** @var Match_ $expr */ $expr = $assign->expr; - $expr->arms[] = new MatchArm(null, $prevInitializedAssign->expr); - - $parentAssign = $prevInitializedAssign->getAttribute(AttributeKey::PARENT_NODE); - if ($parentAssign instanceof Expression) { + $expr->arms[] = new \PhpParser\Node\MatchArm(null, $prevInitializedAssign->expr); + $parentAssign = $prevInitializedAssign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentAssign instanceof \PhpParser\Node\Stmt\Expression) { $this->removeNode($parentAssign); } } - return $assign; } - - private function shouldSkipSwitch(Switch_ $switch): bool + private function shouldSkipSwitch(\PhpParser\Node\Stmt\Switch_ $switch) : bool { - if (! $this->switchAnalyzer->hasEachCaseBreak($switch)) { - return true; + if (!$this->switchAnalyzer->hasEachCaseBreak($switch)) { + return \true; } - - return ! $this->switchAnalyzer->hasEachCaseSingleStmt($switch); + return !$this->switchAnalyzer->hasEachCaseSingleStmt($switch); } - /** * @param CondAndExpr[] $condAndExprs */ - private function haveCondAndExprsMatchPotential(array $condAndExprs): bool + private function haveCondAndExprsMatchPotential(array $condAndExprs) : bool { $uniqueCondAndExprKinds = $this->resolveUniqueKinds($condAndExprs); - if (count($uniqueCondAndExprKinds) > 1) { - return false; + if (\count($uniqueCondAndExprKinds) > 1) { + return \false; } - $assignVariableNames = []; foreach ($condAndExprs as $condAndExpr) { $expr = $condAndExpr->getExpr(); - if (! $expr instanceof Assign) { + if (!$expr instanceof \PhpParser\Node\Expr\Assign) { continue; } - $assignVariableNames[] = $this->getName($expr->var); } - - $assignVariableNames = array_unique($assignVariableNames); - return count($assignVariableNames) <= 1; + $assignVariableNames = \array_unique($assignVariableNames); + return \count($assignVariableNames) <= 1; } - /** * @param CondAndExpr[] $condAndExprs * @return MatchArm[] */ - private function createMatchArmsFromCases(array $condAndExprs): array + private function createMatchArmsFromCases(array $condAndExprs) : array { $matchArms = []; foreach ($condAndExprs as $condAndExpr) { $expr = $condAndExpr->getExpr(); - - if ($expr instanceof Assign) { + if ($expr instanceof \PhpParser\Node\Expr\Assign) { $this->assignExpr = $expr->var; $expr = $expr->expr; } - $condExpr = $condAndExpr->getCondExpr(); - - $condList = $condExpr instanceof Expr ? [$condExpr] : null; - $matchArms[] = new MatchArm($condList, $expr); + $condList = $condExpr instanceof \PhpParser\Node\Expr ? [$condExpr] : null; + $matchArms[] = new \PhpParser\Node\MatchArm($condList, $expr); } - return $matchArms; } - /** * @param CondAndExpr[] $condAndExprs * @return string[] */ - private function resolveUniqueKinds(array $condAndExprs): array + private function resolveUniqueKinds(array $condAndExprs) : array { $condAndExprKinds = []; foreach ($condAndExprs as $condAndExpr) { $condAndExprKinds[] = $condAndExpr->getKind(); } - - return array_unique($condAndExprKinds); + return \array_unique($condAndExprKinds); } } diff --git a/rules/Php80/Rector/Ternary/GetDebugTypeRector.php b/rules/Php80/Rector/Ternary/GetDebugTypeRector.php index 15f02122183..ab286270be9 100644 --- a/rules/Php80/Rector/Ternary/GetDebugTypeRector.php +++ b/rules/Php80/Rector/Ternary/GetDebugTypeRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Ternary::class]; + return [\PhpParser\Node\Expr\Ternary::class]; } - /** * @param Ternary $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - - if (! $this->areValuesIdentical($node)) { + if (!$this->areValuesIdentical($node)) { return null; } - /** @var FuncCall $funcCall */ $funcCall = $node->if; $firstExpr = $funcCall->args[0]->value; - return $this->nodeFactory->createFuncCall('get_debug_type', [$firstExpr]); } - - private function shouldSkip(Ternary $ternary): bool + private function shouldSkip(\PhpParser\Node\Expr\Ternary $ternary) : bool { - if (! $ternary->cond instanceof FuncCall) { - return true; + if (!$ternary->cond instanceof \PhpParser\Node\Expr\FuncCall) { + return \true; } - - if (! $this->nodeNameResolver->isName($ternary->cond, 'is_object')) { - return true; + if (!$this->nodeNameResolver->isName($ternary->cond, 'is_object')) { + return \true; } - - if (! $ternary->if instanceof FuncCall) { - return true; + if (!$ternary->if instanceof \PhpParser\Node\Expr\FuncCall) { + return \true; } - - if (! $this->nodeNameResolver->isName($ternary->if, 'get_class')) { - return true; + if (!$this->nodeNameResolver->isName($ternary->if, 'get_class')) { + return \true; } - - if (! $ternary->else instanceof FuncCall) { - return true; + if (!$ternary->else instanceof \PhpParser\Node\Expr\FuncCall) { + return \true; } - - return ! $this->nodeNameResolver->isName($ternary->else, 'gettype'); + return !$this->nodeNameResolver->isName($ternary->else, 'gettype'); } - - private function areValuesIdentical(Ternary $ternary): bool + private function areValuesIdentical(\PhpParser\Node\Expr\Ternary $ternary) : bool { /** @var FuncCall $isObjectFuncCall */ $isObjectFuncCall = $ternary->cond; $firstExpr = $isObjectFuncCall->args[0]->value; - /** @var FuncCall $getClassFuncCall */ $getClassFuncCall = $ternary->if; $secondExpr = $getClassFuncCall->args[0]->value; - /** @var FuncCall $gettypeFuncCall */ $gettypeFuncCall = $ternary->else; $thirdExpr = $gettypeFuncCall->args[0]->value; - - if (! $this->nodeComparator->areNodesEqual($firstExpr, $secondExpr)) { - return false; + if (!$this->nodeComparator->areNodesEqual($firstExpr, $secondExpr)) { + return \false; } - return $this->nodeComparator->areNodesEqual($firstExpr, $thirdExpr); } } diff --git a/rules/Php80/Reflection/MethodReflectionClassMethodResolver.php b/rules/Php80/Reflection/MethodReflectionClassMethodResolver.php index f1945fff973..279257be47d 100644 --- a/rules/Php80/Reflection/MethodReflectionClassMethodResolver.php +++ b/rules/Php80/Reflection/MethodReflectionClassMethodResolver.php @@ -1,54 +1,43 @@ reflectionProvider = $reflectionProvider; $this->methodReflectionToAstResolver = $methodReflectionToAstResolver; } - - public function resolve(string $className, string $methodName): ?ClassMethod + public function resolve(string $className, string $methodName) : ?\PhpParser\Node\Stmt\ClassMethod { - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return null; } - $classReflection = $this->reflectionProvider->getClass($className); if ($classReflection->isAnonymous()) { return null; } - - if (! $classReflection->hasMethod($methodName)) { + if (!$classReflection->hasMethod($methodName)) { return null; } - $constructorClassMethodReflection = $classReflection->getNativeMethod($methodName); - if (! $constructorClassMethodReflection instanceof PhpMethodReflection) { + if (!$constructorClassMethodReflection instanceof \PHPStan\Reflection\Php\PhpMethodReflection) { return null; } - return $this->methodReflectionToAstResolver->resolveProjectClassMethod($constructorClassMethodReflection); } } diff --git a/rules/Php80/ValueObject/AnnotationToAttribute.php b/rules/Php80/ValueObject/AnnotationToAttribute.php index 6b829712e35..e934874f60a 100644 --- a/rules/Php80/ValueObject/AnnotationToAttribute.php +++ b/rules/Php80/ValueObject/AnnotationToAttribute.php @@ -1,7 +1,6 @@ tag = $tag; $this->attributeClass = $attributeClass; } - /** * @return class-string|string */ - public function getTag(): string + public function getTag() : string { return $this->tag; } - /** * @return class-string */ - public function getAttributeClass(): string + public function getAttributeClass() : string { return $this->attributeClass; } diff --git a/rules/Php80/ValueObject/ArrayDimFetchAndConstFetch.php b/rules/Php80/ValueObject/ArrayDimFetchAndConstFetch.php index 524692bdc8a..9d043f0fa1d 100644 --- a/rules/Php80/ValueObject/ArrayDimFetchAndConstFetch.php +++ b/rules/Php80/ValueObject/ArrayDimFetchAndConstFetch.php @@ -1,36 +1,30 @@ arrayDimFetch = $arrayDimFetch; $this->constFetch = $constFetch; } - - public function getArrayDimFetch(): ArrayDimFetch + public function getArrayDimFetch() : \PhpParser\Node\Expr\ArrayDimFetch { return $this->arrayDimFetch; } - - public function getConstFetch(): ConstFetch + public function getConstFetch() : \PhpParser\Node\Expr\ConstFetch { return $this->constFetch; } diff --git a/rules/Php80/ValueObject/CondAndExpr.php b/rules/Php80/ValueObject/CondAndExpr.php index f0b737ec8ca..5cdf36892c9 100644 --- a/rules/Php80/ValueObject/CondAndExpr.php +++ b/rules/Php80/ValueObject/CondAndExpr.php @@ -1,61 +1,50 @@ condExpr = $condExpr; $this->expr = $expr; $this->kind = $kind; } - - public function getExpr(): Expr + public function getExpr() : \PhpParser\Node\Expr { return $this->expr; } - - public function getCondExpr(): ?Expr + public function getCondExpr() : ?\PhpParser\Node\Expr { return $this->condExpr; } - - public function getKind(): string + public function getKind() : string { return $this->kind; } diff --git a/rules/Php80/ValueObject/PropertyPromotionCandidate.php b/rules/Php80/ValueObject/PropertyPromotionCandidate.php index b21330d6c3f..c54c6968892 100644 --- a/rules/Php80/ValueObject/PropertyPromotionCandidate.php +++ b/rules/Php80/ValueObject/PropertyPromotionCandidate.php @@ -1,48 +1,40 @@ property = $property; $this->assign = $assign; $this->param = $param; } - - public function getProperty(): Property + public function getProperty() : \PhpParser\Node\Stmt\Property { return $this->property; } - - public function getAssign(): Assign + public function getAssign() : \PhpParser\Node\Expr\Assign { return $this->assign; } - - public function getParam(): Param + public function getParam() : \PhpParser\Node\Param { return $this->param; } diff --git a/rules/Php80/ValueObject/StrStartsWith.php b/rules/Php80/ValueObject/StrStartsWith.php index 19f729d7de9..6a3312696c3 100644 --- a/rules/Php80/ValueObject/StrStartsWith.php +++ b/rules/Php80/ValueObject/StrStartsWith.php @@ -1,58 +1,48 @@ funcCall = $funcCall; $this->haystackExpr = $haystackExpr; $this->isPositive = $isPositive; $this->needleExpr = $needleExpr; } - - public function getFuncCall(): FuncCall + public function getFuncCall() : \PhpParser\Node\Expr\FuncCall { return $this->funcCall; } - - public function getHaystackExpr(): Expr + public function getHaystackExpr() : \PhpParser\Node\Expr { return $this->haystackExpr; } - - public function isPositive(): bool + public function isPositive() : bool { return $this->isPositive; } - - public function getNeedleExpr(): Expr + public function getNeedleExpr() : \PhpParser\Node\Expr { return $this->needleExpr; } diff --git a/rules/Php80/ValueObjectFactory/StrStartsWithFactory.php b/rules/Php80/ValueObjectFactory/StrStartsWithFactory.php index 25da5fdfdd5..35ad18ebf07 100644 --- a/rules/Php80/ValueObjectFactory/StrStartsWithFactory.php +++ b/rules/Php80/ValueObjectFactory/StrStartsWithFactory.php @@ -1,19 +1,16 @@ args[0]->value; $needle = $funcCall->args[1]->value; - - return new StrStartsWith($funcCall, $haystack, $needle, $isPositive); + return new \Rector\Php80\ValueObject\StrStartsWith($funcCall, $haystack, $needle, $isPositive); } } diff --git a/rules/PhpSpecToPHPUnit/LetManipulator.php b/rules/PhpSpecToPHPUnit/LetManipulator.php index b42bfac57eb..af3a5cce1ff 100644 --- a/rules/PhpSpecToPHPUnit/LetManipulator.php +++ b/rules/PhpSpecToPHPUnit/LetManipulator.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; } - - public function isLetNeededInClass(Class_ $class): bool + public function isLetNeededInClass(\PhpParser\Node\Stmt\Class_ $class) : bool { foreach ($class->getMethods() as $classMethod) { // new test if ($this->nodeNameResolver->isName($classMethod, 'test*')) { continue; } - - $hasBeConstructedThrough = (bool) $this->betterNodeFinder->find( - (array) $classMethod->stmts, - function (Node $node): ?bool { - if (! $node instanceof MethodCall) { - return null; - } - - return $this->nodeNameResolver->isName($node->name, 'beConstructedThrough'); + $hasBeConstructedThrough = (bool) $this->betterNodeFinder->find((array) $classMethod->stmts, function (\PhpParser\Node $node) : ?bool { + if (!$node instanceof \PhpParser\Node\Expr\MethodCall) { + return null; } - ); - + return $this->nodeNameResolver->isName($node->name, 'beConstructedThrough'); + }); if ($hasBeConstructedThrough) { continue; } - - return true; + return \true; } - - return false; + return \false; } } diff --git a/rules/PhpSpecToPHPUnit/MatchersManipulator.php b/rules/PhpSpecToPHPUnit/MatchersManipulator.php index 8c38fa6feaf..ebd16b9e201 100644 --- a/rules/PhpSpecToPHPUnit/MatchersManipulator.php +++ b/rules/PhpSpecToPHPUnit/MatchersManipulator.php @@ -1,7 +1,6 @@ getMethod('getMatchers'); - if (! $classMethod instanceof ClassMethod) { + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return []; } - - if (! isset($classMethod->stmts[0])) { + if (!isset($classMethod->stmts[0])) { return []; } - - if (! $classMethod->stmts[0] instanceof Return_) { + if (!$classMethod->stmts[0] instanceof \PhpParser\Node\Stmt\Return_) { return []; } - /** @var Return_ $return */ $return = $classMethod->stmts[0]; - if (! $return->expr instanceof Array_) { + if (!$return->expr instanceof \PhpParser\Node\Expr\Array_) { return []; } - $keys = []; foreach ($return->expr->items as $arrayItem) { if ($arrayItem === null) { continue; } - - if ($arrayItem->key instanceof String_) { + if ($arrayItem->key instanceof \PhpParser\Node\Scalar\String_) { $keys[] = $arrayItem->key->value; } } - return $keys; } } diff --git a/rules/PhpSpecToPHPUnit/Naming/PhpSpecRenaming.php b/rules/PhpSpecToPHPUnit/Naming/PhpSpecRenaming.php index d078dfa00b0..5adb080242c 100644 --- a/rules/PhpSpecToPHPUnit/Naming/PhpSpecRenaming.php +++ b/rules/PhpSpecToPHPUnit/Naming/PhpSpecRenaming.php @@ -1,10 +1,9 @@ stringFormatConverter = $stringFormatConverter; $this->nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; } - - public function renameMethod(ClassMethod $classMethod): void + public function renameMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { if ($classMethod->isPrivate()) { return; } - $classMethodName = $this->nodeNameResolver->getName($classMethod); $classMethodName = $this->removeNamePrefixes($classMethodName); - // from PhpSpec to PHPUnit method naming convention $classMethodName = $this->stringFormatConverter->underscoreAndHyphenToCamelCase($classMethodName); - // add "test", so PHPUnit runs the method - if (! Strings::startsWith($classMethodName, 'test')) { - $classMethodName = 'test' . ucfirst($classMethodName); + if (!\RectorPrefix20210509\Nette\Utils\Strings::startsWith($classMethodName, 'test')) { + $classMethodName = 'test' . \ucfirst($classMethodName); } - - $classMethod->name = new Identifier($classMethodName); + $classMethod->name = new \PhpParser\Node\Identifier($classMethodName); } - - public function renameExtends(Class_ $class): void + public function renameExtends(\PhpParser\Node\Stmt\Class_ $class) : void { - $class->extends = new FullyQualified('PHPUnit\Framework\TestCase'); + $class->extends = new \PhpParser\Node\Name\FullyQualified('PHPUnit\\Framework\\TestCase'); } - - public function renameNamespace(Class_ $class): void + public function renameNamespace(\PhpParser\Node\Stmt\Class_ $class) : void { - $namespace = $this->betterNodeFinder->findParentType($class, Namespace_::class); - if (! $namespace instanceof Namespace_) { + $namespace = $this->betterNodeFinder->findParentType($class, \PhpParser\Node\Stmt\Namespace_::class); + if (!$namespace instanceof \PhpParser\Node\Stmt\Namespace_) { return; } - $namespaceName = $this->nodeNameResolver->getName($namespace); if ($namespaceName === null) { return; } - - $newNamespaceName = StaticRectorStrings::removePrefixes($namespaceName, ['spec\\']); - - $namespace->name = new Name('Tests\\' . $newNamespaceName); + $newNamespaceName = \Rector\Core\Util\StaticRectorStrings::removePrefixes($namespaceName, ['spec\\']); + $namespace->name = new \PhpParser\Node\Name('Tests\\' . $newNamespaceName); } - - public function renameClass(Class_ $class): void + public function renameClass(\PhpParser\Node\Stmt\Class_ $class) : void { $classShortName = $this->nodeNameResolver->getShortName($class); // anonymous class? if ($classShortName === '') { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - // 2. change class name - $newClassName = StaticRectorStrings::removeSuffixes($classShortName, [self::SPEC]); + $newClassName = \Rector\Core\Util\StaticRectorStrings::removeSuffixes($classShortName, [self::SPEC]); $newTestClassName = $newClassName . 'Test'; - - $class->name = new Identifier($newTestClassName); + $class->name = new \PhpParser\Node\Identifier($newTestClassName); } - - public function resolveObjectPropertyName(Class_ $class): string + public function resolveObjectPropertyName(\PhpParser\Node\Stmt\Class_ $class) : string { // anonymous class? if ($class->name === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $shortClassName = $this->nodeNameResolver->getShortName($class); - $bareClassName = StaticRectorStrings::removeSuffixes($shortClassName, [self::SPEC, 'Test']); - - return lcfirst($bareClassName); + $bareClassName = \Rector\Core\Util\StaticRectorStrings::removeSuffixes($shortClassName, [self::SPEC, 'Test']); + return \lcfirst($bareClassName); } - - public function resolveTestedClass(Node $node): string + public function resolveTestedClass(\PhpParser\Node $node) : string { /** @var string $className */ - $className = $node->getAttribute(AttributeKey::CLASS_NAME); - - $newClassName = StaticRectorStrings::removePrefixes($className, ['spec\\']); - - return StaticRectorStrings::removeSuffixes($newClassName, [self::SPEC]); + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + $newClassName = \Rector\Core\Util\StaticRectorStrings::removePrefixes($className, ['spec\\']); + return \Rector\Core\Util\StaticRectorStrings::removeSuffixes($newClassName, [self::SPEC]); } - - private function removeNamePrefixes(string $name): string + private function removeNamePrefixes(string $name) : string { $originalName = $name; - - $name = StaticRectorStrings::removePrefixes( - $name, - ['it_should_have_', 'it_should_be', 'it_should_', 'it_is_', 'it_', 'is_'] - ); - + $name = \Rector\Core\Util\StaticRectorStrings::removePrefixes($name, ['it_should_have_', 'it_should_be', 'it_should_', 'it_is_', 'it_', 'is_']); return $name ?: $originalName; } } diff --git a/rules/PhpSpecToPHPUnit/NodeFactory/AssertMethodCallFactory.php b/rules/PhpSpecToPHPUnit/NodeFactory/AssertMethodCallFactory.php index 149bc2a89f8..28052ab085a 100644 --- a/rules/PhpSpecToPHPUnit/NodeFactory/AssertMethodCallFactory.php +++ b/rules/PhpSpecToPHPUnit/NodeFactory/AssertMethodCallFactory.php @@ -1,7 +1,6 @@ nodeFactory = $nodeFactory; $this->nodeNameResolver = $nodeNameResolver; $this->valueResolver = $valueResolver; } - - public function createAssertMethod( - string $name, - Expr $value, - ?Expr $expected, - PropertyFetch $testedObjectPropertyFetch - ): MethodCall { - $this->isBoolAssert = false; - + public function createAssertMethod(string $name, \PhpParser\Node\Expr $value, ?\PhpParser\Node\Expr $expected, \PhpParser\Node\Expr\PropertyFetch $testedObjectPropertyFetch) : \PhpParser\Node\Expr\MethodCall + { + $this->isBoolAssert = \false; // special case with bool! if ($expected !== null) { $name = $this->resolveBoolMethodName($name, $expected); } - $assetMethodCall = $this->nodeFactory->createMethodCall('this', $name); - - if (! $this->isBoolAssert && $expected) { - $assetMethodCall->args[] = new Arg($this->thisToTestedObjectPropertyFetch( - $expected, - $testedObjectPropertyFetch - )); + if (!$this->isBoolAssert && $expected) { + $assetMethodCall->args[] = new \PhpParser\Node\Arg($this->thisToTestedObjectPropertyFetch($expected, $testedObjectPropertyFetch)); } - - $assetMethodCall->args[] = new Arg($this->thisToTestedObjectPropertyFetch($value, $testedObjectPropertyFetch)); - + $assetMethodCall->args[] = new \PhpParser\Node\Arg($this->thisToTestedObjectPropertyFetch($value, $testedObjectPropertyFetch)); return $assetMethodCall; } - - private function resolveBoolMethodName(string $name, Expr $expr): string + private function resolveBoolMethodName(string $name, \PhpParser\Node\Expr $expr) : string { - if (! $this->valueResolver->isTrueOrFalse($expr)) { + if (!$this->valueResolver->isTrueOrFalse($expr)) { return $name; } - $isFalse = $this->valueResolver->isFalse($expr); if ($name === 'assertSame') { - $this->isBoolAssert = true; + $this->isBoolAssert = \true; return $isFalse ? 'assertFalse' : 'assertTrue'; } - if ($name === 'assertNotSame') { - $this->isBoolAssert = true; + $this->isBoolAssert = \true; return $isFalse ? 'assertNotFalse' : 'assertNotTrue'; } - return $name; } - - private function thisToTestedObjectPropertyFetch(Expr $expr, PropertyFetch $propertyFetch): Expr + private function thisToTestedObjectPropertyFetch(\PhpParser\Node\Expr $expr, \PhpParser\Node\Expr\PropertyFetch $propertyFetch) : \PhpParser\Node\Expr { - if (! $expr instanceof Variable) { + if (!$expr instanceof \PhpParser\Node\Expr\Variable) { return $expr; } - - if (! $this->nodeNameResolver->isName($expr, 'this')) { + if (!$this->nodeNameResolver->isName($expr, 'this')) { return $expr; } - return $propertyFetch; } } diff --git a/rules/PhpSpecToPHPUnit/NodeFactory/BeConstructedWithAssignFactory.php b/rules/PhpSpecToPHPUnit/NodeFactory/BeConstructedWithAssignFactory.php index bdfaec90aae..0498377b68d 100644 --- a/rules/PhpSpecToPHPUnit/NodeFactory/BeConstructedWithAssignFactory.php +++ b/rules/PhpSpecToPHPUnit/NodeFactory/BeConstructedWithAssignFactory.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->valueResolver = $valueResolver; $this->nodeFactory = $nodeFactory; } - - public function create(MethodCall $methodCall, string $testedClass, PropertyFetch $propertyFetch): ?Assign + public function create(\PhpParser\Node\Expr\MethodCall $methodCall, string $testedClass, \PhpParser\Node\Expr\PropertyFetch $propertyFetch) : ?\PhpParser\Node\Expr\Assign { if ($this->nodeNameResolver->isName($methodCall->name, 'beConstructedWith')) { - $new = new New_(new FullyQualified($testedClass)); + $new = new \PhpParser\Node\Expr\New_(new \PhpParser\Node\Name\FullyQualified($testedClass)); $new->args = $methodCall->args; - - return new Assign($propertyFetch, $new); + return new \PhpParser\Node\Expr\Assign($propertyFetch, $new); } - if ($this->nodeNameResolver->isName($methodCall->name, 'beConstructedThrough')) { $methodName = $this->valueResolver->getValue($methodCall->args[0]->value); $staticCall = $this->nodeFactory->createStaticCall($testedClass, $methodName); - $this->moveConstructorArguments($methodCall, $staticCall); - - return new Assign($propertyFetch, $staticCall); + return new \PhpParser\Node\Expr\Assign($propertyFetch, $staticCall); } - return null; } - - private function moveConstructorArguments(MethodCall $methodCall, StaticCall $staticCall): void + private function moveConstructorArguments(\PhpParser\Node\Expr\MethodCall $methodCall, \PhpParser\Node\Expr\StaticCall $staticCall) : void { - if (! isset($methodCall->args[1])) { + if (!isset($methodCall->args[1])) { return; } - - if (! $methodCall->args[1]->value instanceof Array_) { + if (!$methodCall->args[1]->value instanceof \PhpParser\Node\Expr\Array_) { return; } - /** @var Array_ $array */ $array = $methodCall->args[1]->value; foreach ($array->items as $arrayItem) { - if (! $arrayItem instanceof ArrayItem) { + if (!$arrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - - $staticCall->args[] = new Arg($arrayItem->value); + $staticCall->args[] = new \PhpParser\Node\Arg($arrayItem->value); } } } diff --git a/rules/PhpSpecToPHPUnit/NodeFactory/DuringMethodCallFactory.php b/rules/PhpSpecToPHPUnit/NodeFactory/DuringMethodCallFactory.php index 4006c88b926..7c3a5c3c704 100644 --- a/rules/PhpSpecToPHPUnit/NodeFactory/DuringMethodCallFactory.php +++ b/rules/PhpSpecToPHPUnit/NodeFactory/DuringMethodCallFactory.php @@ -1,7 +1,6 @@ valueResolver = $valueResolver; $this->nodesToAddCollector = $nodesToAddCollector; } - - public function create(MethodCall $methodCall, PropertyFetch $propertyFetch): MethodCall + public function create(\PhpParser\Node\Expr\MethodCall $methodCall, \PhpParser\Node\Expr\PropertyFetch $propertyFetch) : \PhpParser\Node\Expr\MethodCall { - if (! isset($methodCall->args[0])) { - throw new ShouldNotHappenException(); + if (!isset($methodCall->args[0])) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $name = $this->valueResolver->getValue($methodCall->args[0]->value); - $thisObjectPropertyMethodCall = new MethodCall($propertyFetch, $name); - - if (isset($methodCall->args[1]) && $methodCall->args[1]->value instanceof Array_) { + $thisObjectPropertyMethodCall = new \PhpParser\Node\Expr\MethodCall($propertyFetch, $name); + if (isset($methodCall->args[1]) && $methodCall->args[1]->value instanceof \PhpParser\Node\Expr\Array_) { /** @var Array_ $array */ $array = $methodCall->args[1]->value; - if (isset($array->items[0])) { - $thisObjectPropertyMethodCall->args[] = new Arg($array->items[0]->value); + $thisObjectPropertyMethodCall->args[] = new \PhpParser\Node\Arg($array->items[0]->value); } } - /** @var MethodCall $parentMethodCall */ $parentMethodCall = $methodCall->var; - $parentMethodCall->name = new Identifier('expectException'); - + $parentMethodCall->name = new \PhpParser\Node\Identifier('expectException'); // add $this->object->someCall($withArgs) $this->nodesToAddCollector->addNodeAfterNode($thisObjectPropertyMethodCall, $methodCall); - return $parentMethodCall; } } diff --git a/rules/PhpSpecToPHPUnit/PHPUnitTypeDeclarationDecorator.php b/rules/PhpSpecToPHPUnit/PHPUnitTypeDeclarationDecorator.php index 22cb2ee8069..5388f051579 100644 --- a/rules/PhpSpecToPHPUnit/PHPUnitTypeDeclarationDecorator.php +++ b/rules/PhpSpecToPHPUnit/PHPUnitTypeDeclarationDecorator.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function decorate(ClassMethod $classMethod): void + public function decorate(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { - if (! $this->reflectionProvider->hasClass('PHPUnit\Framework\TestCase')) { + if (!$this->reflectionProvider->hasClass('PHPUnit\\Framework\\TestCase')) { return; } - // skip test run - if (StaticPHPUnitEnvironment::isPHPUnitRun()) { + if (\Rector\Testing\PHPUnit\StaticPHPUnitEnvironment::isPHPUnitRun()) { return; } - - $classReflection = $this->reflectionProvider->getClass('PHPUnit\Framework\TestCase'); + $classReflection = $this->reflectionProvider->getClass('PHPUnit\\Framework\\TestCase'); $reflectionClass = $classReflection->getNativeReflection(); - - $reflectionMethod = $reflectionClass->getMethod(MethodName::SET_UP); - if (! $reflectionMethod->hasReturnType()) { + $reflectionMethod = $reflectionClass->getMethod(\Rector\Core\ValueObject\MethodName::SET_UP); + if (!$reflectionMethod->hasReturnType()) { return; } - $returnType = (string) $reflectionMethod->getReturnType(); - $classMethod->returnType = new Identifier($returnType); + $classMethod->returnType = new \PhpParser\Node\Identifier($returnType); } } diff --git a/rules/PhpSpecToPHPUnit/PhpSpecMockCollector.php b/rules/PhpSpecToPHPUnit/PhpSpecMockCollector.php index 9d28d8a9727..a099751370b 100644 --- a/rules/PhpSpecToPHPUnit/PhpSpecMockCollector.php +++ b/rules/PhpSpecToPHPUnit/PhpSpecMockCollector.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - /** * @return mixed[] */ - public function resolveClassMocksFromParam(Class_ $class): array + public function resolveClassMocksFromParam(\PhpParser\Node\Stmt\Class_ $class) : array { $className = $this->nodeNameResolver->getName($class); - if (isset($this->mocks[$className]) && $this->mocks[$className] !== []) { return $this->mocks[$className]; } - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($class, function (Node $node): void { - if (! $node instanceof ClassMethod) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($class, function (\PhpParser\Node $node) : void { + if (!$node instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - - if (! $node->isPublic()) { + if (!$node->isPublic()) { return; } - foreach ($node->params as $param) { $this->addMockFromParam($param); } }); - // set default value if none was found - if (! isset($this->mocks[$className])) { + if (!isset($this->mocks[$className])) { $this->mocks[$className] = []; } - return $this->mocks[$className]; } - - public function isVariableMockInProperty(Variable $variable): bool + public function isVariableMockInProperty(\PhpParser\Node\Expr\Variable $variable) : bool { $variableName = $this->nodeNameResolver->getName($variable); - $className = $variable->getAttribute(AttributeKey::CLASS_NAME); - - return in_array($variableName, $this->propertyMocksByClass[$className] ?? [], true); + $className = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + return \in_array($variableName, $this->propertyMocksByClass[$className] ?? [], \true); } - - public function getTypeForClassAndVariable(Class_ $class, string $variable): string + public function getTypeForClassAndVariable(\PhpParser\Node\Stmt\Class_ $class, string $variable) : string { $className = $this->nodeNameResolver->getName($class); - - if (! isset($this->mocksWithsTypes[$className][$variable])) { - throw new ShouldNotHappenException(); + if (!isset($this->mocksWithsTypes[$className][$variable])) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - return $this->mocksWithsTypes[$className][$variable]; } - - public function addPropertyMock(string $class, string $property): void + public function addPropertyMock(string $class, string $property) : void { $this->propertyMocksByClass[$class][] = $property; } - - private function addMockFromParam(Param $param): void + private function addMockFromParam(\PhpParser\Node\Param $param) : void { $variable = $this->nodeNameResolver->getName($param->var); - /** @var string $class */ - $class = $param->getAttribute(AttributeKey::CLASS_NAME); - - $classMethod = $param->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { - throw new ShouldNotHappenException(); + $class = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + $classMethod = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $methodName = $this->nodeNameResolver->getName($classMethod); $this->mocks[$class][$variable][] = $methodName; - if ($param->type === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $paramType = (string) ($param->type->getAttribute(AttributeKey::ORIGINAL_NAME) ?: $param->type); + $paramType = (string) ($param->type->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NAME) ?: $param->type); $this->mocksWithsTypes[$class][$variable] = $paramType; } } diff --git a/rules/PhpSpecToPHPUnit/Rector/AbstractPhpSpecToPHPUnitRector.php b/rules/PhpSpecToPHPUnit/Rector/AbstractPhpSpecToPHPUnitRector.php index 2cbe2d65af8..2ed1e8b1598 100644 --- a/rules/PhpSpecToPHPUnit/Rector/AbstractPhpSpecToPHPUnitRector.php +++ b/rules/PhpSpecToPHPUnit/Rector/AbstractPhpSpecToPHPUnitRector.php @@ -1,7 +1,6 @@ getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { - return false; + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { + return \false; } - - return $this->isObjectType($classLike, new ObjectType('PhpSpec\ObjectBehavior')); + return $this->isObjectType($classLike, new \PHPStan\Type\ObjectType('PhpSpec\\ObjectBehavior')); } } diff --git a/rules/PhpSpecToPHPUnit/Rector/ClassMethod/PhpSpecMethodToPHPUnitMethodRector.php b/rules/PhpSpecToPHPUnit/Rector/ClassMethod/PhpSpecMethodToPHPUnitMethodRector.php index c5473ff1890..e8c5bc4bcf3 100644 --- a/rules/PhpSpecToPHPUnit/Rector/ClassMethod/PhpSpecMethodToPHPUnitMethodRector.php +++ b/rules/PhpSpecToPHPUnit/Rector/ClassMethod/PhpSpecMethodToPHPUnitMethodRector.php @@ -1,10 +1,9 @@ phpSpecRenaming = $phpSpecRenaming; $this->phpUnitTypeDeclarationDecorator = $phpUnitTypeDeclarationDecorator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isInPhpSpecBehavior($node)) { + if (!$this->isInPhpSpecBehavior($node)) { return null; } - if ($this->isName($node, 'letGo')) { - $node->name = new Identifier(MethodName::TEAR_DOWN); + $node->name = new \PhpParser\Node\Identifier(\Rector\Core\ValueObject\MethodName::TEAR_DOWN); $this->visibilityManipulator->makeProtected($node); $this->phpUnitTypeDeclarationDecorator->decorate($node); } elseif ($this->isName($node, 'let')) { - $node->name = new Identifier(MethodName::SET_UP); + $node->name = new \PhpParser\Node\Identifier(\Rector\Core\ValueObject\MethodName::SET_UP); $this->visibilityManipulator->makeProtected($node); $this->phpUnitTypeDeclarationDecorator->decorate($node); } else { $this->processTestMethod($node); } - return $node; } - - private function processTestMethod(ClassMethod $classMethod): void + private function processTestMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { // special case, @see https://johannespichler.com/writing-custom-phpspec-matchers/ if ($this->isName($classMethod, 'getMatchers')) { return; } - // change name to phpunit test case format $this->phpSpecRenaming->renameMethod($classMethod); - // reorder instantiation + expected exception $previousStmt = null; foreach ((array) $classMethod->stmts as $key => $stmt) { - if ($previousStmt && - Strings::contains($this->print($stmt), 'duringInstantiation') && - Strings::contains($this->print($previousStmt), 'beConstructedThrough') - ) { + if ($previousStmt && \RectorPrefix20210509\Nette\Utils\Strings::contains($this->print($stmt), 'duringInstantiation') && \RectorPrefix20210509\Nette\Utils\Strings::contains($this->print($previousStmt), 'beConstructedThrough')) { $classMethod->stmts[$key - 1] = $stmt; $classMethod->stmts[$key] = $previousStmt; } - $previousStmt = $stmt; } } diff --git a/rules/PhpSpecToPHPUnit/Rector/Class_/AddMockPropertiesRector.php b/rules/PhpSpecToPHPUnit/Rector/Class_/AddMockPropertiesRector.php index 3485504df74..5f198988e60 100644 --- a/rules/PhpSpecToPHPUnit/Rector/Class_/AddMockPropertiesRector.php +++ b/rules/PhpSpecToPHPUnit/Rector/Class_/AddMockPropertiesRector.php @@ -1,7 +1,6 @@ phpSpecMockCollector = $phpSpecMockCollector; $this->classInsertManipulator = $classInsertManipulator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isInPhpSpecBehavior($node)) { + if (!$this->isInPhpSpecBehavior($node)) { return null; } - $classMocks = $this->phpSpecMockCollector->resolveClassMocksFromParam($node); - /** @var string $class */ - $class = $node->getAttribute(AttributeKey::CLASS_NAME); - + $class = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); foreach ($classMocks as $name => $methods) { - if ((is_countable($methods) ? count($methods) : 0) <= 1) { + if ((\is_countable($methods) ? \count($methods) : 0) <= 1) { continue; } - // non-ctor used mocks are probably local only - if (! in_array('let', $methods, true)) { + if (!\in_array('let', $methods, \true)) { continue; } - $this->phpSpecMockCollector->addPropertyMock($class, $name); - $variableType = $this->phpSpecMockCollector->getTypeForClassAndVariable($node, $name); - - $unionType = new UnionType([ - new ObjectType($variableType), - new ObjectType('PHPUnit\Framework\MockObject\MockObject'), - ]); - + $unionType = new \PHPStan\Type\UnionType([new \PHPStan\Type\ObjectType($variableType), new \PHPStan\Type\ObjectType('PHPUnit\\Framework\\MockObject\\MockObject')]); $this->classInsertManipulator->addPropertyToClass($node, $name, $unionType); } - return null; } } diff --git a/rules/PhpSpecToPHPUnit/Rector/Class_/PhpSpecClassToPHPUnitClassRector.php b/rules/PhpSpecToPHPUnit/Rector/Class_/PhpSpecClassToPHPUnitClassRector.php index 0fe07a7b721..bfa2be79c51 100644 --- a/rules/PhpSpecToPHPUnit/Rector/Class_/PhpSpecClassToPHPUnitClassRector.php +++ b/rules/PhpSpecToPHPUnit/Rector/Class_/PhpSpecClassToPHPUnitClassRector.php @@ -1,7 +1,6 @@ phpSpecRenaming = $phpSpecRenaming; $this->letManipulator = $letManipulator; $this->classInsertManipulator = $classInsertManipulator; $this->setUpClassMethodFactory = $setUpClassMethodFactory; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isInPhpSpecBehavior($node)) { + if (!$this->isInPhpSpecBehavior($node)) { return null; } - // 1. change namespace name to PHPUnit-like $this->phpSpecRenaming->renameNamespace($node); - $propertyName = $this->phpSpecRenaming->resolveObjectPropertyName($node); - $this->phpSpecRenaming->renameClass($node); $this->phpSpecRenaming->renameExtends($node); - $testedClass = $this->phpSpecRenaming->resolveTestedClass($node); - - $this->testedObjectType = new ObjectType($testedClass); + $this->testedObjectType = new \PHPStan\Type\ObjectType($testedClass); $this->classInsertManipulator->addPropertyToClass($node, $propertyName, $this->testedObjectType); $classMethod = $node->getMethod('let'); - // add let if missing - if (! $classMethod instanceof ClassMethod) { - if (! $this->letManipulator->isLetNeededInClass($node)) { + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + if (!$this->letManipulator->isLetNeededInClass($node)) { return null; } - $letClassMethod = $this->createLetClassMethod($propertyName); $this->classInsertManipulator->addAsFirstMethod($node, $letClassMethod); } - return $this->removeSelfTypeMethod($node); } - - private function createLetClassMethod(string $propertyName): ClassMethod + private function createLetClassMethod(string $propertyName) : \PhpParser\Node\Stmt\ClassMethod { - $propertyFetch = new PropertyFetch(new Variable('this'), $propertyName); - + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $propertyName); $testedObjectType = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($this->testedObjectType); - if (! $testedObjectType instanceof Name) { - throw new ShouldNotHappenException(); + if (!$testedObjectType instanceof \PhpParser\Node\Name) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $new = new New_($testedObjectType); - - $assign = new Assign($propertyFetch, $new); - + $new = new \PhpParser\Node\Expr\New_($testedObjectType); + $assign = new \PhpParser\Node\Expr\Assign($propertyFetch, $new); return $this->setUpClassMethodFactory->createSetUpMethod([$assign]); } - /** * This is already checked on construction of object */ - private function removeSelfTypeMethod(Class_ $class): Class_ + private function removeSelfTypeMethod(\PhpParser\Node\Stmt\Class_ $class) : \PhpParser\Node\Stmt\Class_ { foreach ($class->getMethods() as $classMethod) { $classMethodStmts = (array) $classMethod->stmts; - if (count($classMethodStmts) !== 1) { + if (\count($classMethodStmts) !== 1) { continue; } - $innerClassMethodStmt = $this->resolveFirstNonExpressionStmt($classMethodStmts); - if (! $innerClassMethodStmt instanceof MethodCall) { + if (!$innerClassMethodStmt instanceof \PhpParser\Node\Expr\MethodCall) { continue; } - - if (! $this->isName($innerClassMethodStmt->name, 'shouldHaveType')) { + if (!$this->isName($innerClassMethodStmt->name, 'shouldHaveType')) { continue; } - // not the tested type - if (! $this->valueResolver->isValue( - $innerClassMethodStmt->args[0]->value, - $this->testedObjectType->getClassName() - )) { + if (!$this->valueResolver->isValue($innerClassMethodStmt->args[0]->value, $this->testedObjectType->getClassName())) { continue; } - // remove it $this->removeNodeFromStatements($class, $classMethod); } - return $class; } - /** * @param Stmt[] $stmts */ - private function resolveFirstNonExpressionStmt(array $stmts): ?Node + private function resolveFirstNonExpressionStmt(array $stmts) : ?\PhpParser\Node { - if (! isset($stmts[0])) { + if (!isset($stmts[0])) { return null; } - $firstStmt = $stmts[0]; - if ($firstStmt instanceof Expression) { + if ($firstStmt instanceof \PhpParser\Node\Stmt\Expression) { return $firstStmt->expr; } - return $firstStmt; } } diff --git a/rules/PhpSpecToPHPUnit/Rector/Class_/RenameSpecFileToTestFileRector.php b/rules/PhpSpecToPHPUnit/Rector/Class_/RenameSpecFileToTestFileRector.php index d117d24daa5..36e017c239a 100644 --- a/rules/PhpSpecToPHPUnit/Rector/Class_/RenameSpecFileToTestFileRector.php +++ b/rules/PhpSpecToPHPUnit/Rector/Class_/RenameSpecFileToTestFileRector.php @@ -1,91 +1,71 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $smartFileInfo = $this->file->getSmartFileInfo(); $oldPathname = $smartFileInfo->getPathname(); - // ends with Spec.php - if (! Strings::match($oldPathname, self::SPEC_SUFFIX_REGEX)) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($oldPathname, self::SPEC_SUFFIX_REGEX)) { return null; } - $this->removedAndAddedFilesCollector->removeFile($smartFileInfo); - $newPathName = $this->createPathName($oldPathname); - $addedFileWithContent = new AddedFileWithContent($newPathName, $smartFileInfo->getContents()); - + $addedFileWithContent = new \Rector\FileSystemRector\ValueObject\AddedFileWithContent($newPathName, $smartFileInfo->getContents()); $this->removedAndAddedFilesCollector->addAddedFile($addedFileWithContent); - return null; } - - private function createPathName(string $oldRealPath): string + private function createPathName(string $oldRealPath) : string { // suffix - $newRealPath = Strings::replace($oldRealPath, self::SPEC_SUFFIX_REGEX, 'Test.php'); - + $newRealPath = \RectorPrefix20210509\Nette\Utils\Strings::replace($oldRealPath, self::SPEC_SUFFIX_REGEX, 'Test.php'); // directory - return Strings::replace($newRealPath, self::SPEC_REGEX, '/tests/'); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($newRealPath, self::SPEC_REGEX, '/tests/'); } } diff --git a/rules/PhpSpecToPHPUnit/Rector/MethodCall/PhpSpecMocksToPHPUnitMocksRector.php b/rules/PhpSpecToPHPUnit/Rector/MethodCall/PhpSpecMocksToPHPUnitMocksRector.php index 79142766f64..2dd8af05017 100644 --- a/rules/PhpSpecToPHPUnit/Rector/MethodCall/PhpSpecMocksToPHPUnitMocksRector.php +++ b/rules/PhpSpecToPHPUnit/Rector/MethodCall/PhpSpecMocksToPHPUnitMocksRector.php @@ -1,7 +1,6 @@ phpSpecMockCollector = $phpSpecMockCollector; $this->typeAnalyzer = $typeAnalyzer; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, MethodCall::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\MethodCall::class]; } - /** * @param ClassMethod|MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isInPhpSpecBehavior($node)) { + if (!$this->isInPhpSpecBehavior($node)) { return null; } - - if ($node instanceof ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { // public = tests, protected = internal, private = own (no framework magic) if ($node->isPrivate()) { return null; } - $this->processMethodParamsToMocks($node); - return $node; } - return $this->processMethodCall($node); } - - private function processMethodParamsToMocks(ClassMethod $classMethod): void + private function processMethodParamsToMocks(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { // remove params and turn them to instances $assigns = []; foreach ($classMethod->params as $param) { - if (! $param->type instanceof Name) { - throw new ShouldNotHappenException(); + if (!$param->type instanceof \PhpParser\Node\Name) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $createMockCall = $this->createCreateMockCall($param, $param->type); if ($createMockCall !== null) { $assigns[] = $createMockCall; } } - // remove all params $classMethod->params = []; - - $classMethod->stmts = array_merge($assigns, (array) $classMethod->stmts); + $classMethod->stmts = \array_merge($assigns, (array) $classMethod->stmts); } - - private function processMethodCall(MethodCall $methodCall): ?MethodCall + private function processMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node\Expr\MethodCall { if ($this->isName($methodCall->name, 'shouldBeCalled')) { - if (! $methodCall->var instanceof MethodCall) { - throw new ShouldNotHappenException(); + if (!$methodCall->var instanceof \PhpParser\Node\Expr\MethodCall) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $mockMethodName = $this->getName($methodCall->var->name); if ($mockMethodName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $expectedArg = $methodCall->var->args[0]->value ?? null; - - $methodCall->var->name = new Identifier('expects'); + $methodCall->var->name = new \PhpParser\Node\Identifier('expects'); $thisOnceMethodCall = $this->nodeFactory->createLocalMethodCall('atLeastOnce'); - $methodCall->var->args = [new Arg($thisOnceMethodCall)]; - - $methodCall->name = new Identifier('method'); - $methodCall->args = [new Arg(new String_($mockMethodName))]; - + $methodCall->var->args = [new \PhpParser\Node\Arg($thisOnceMethodCall)]; + $methodCall->name = new \PhpParser\Node\Identifier('method'); + $methodCall->args = [new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_($mockMethodName))]; if ($expectedArg !== null) { return $this->appendWithMethodCall($methodCall, $expectedArg); } - return $methodCall; } - return null; } - /** * Variable or property fetch, based on number of present params in whole class */ - private function createCreateMockCall(Param $param, Name $name): ?Expression + private function createCreateMockCall(\PhpParser\Node\Param $param, \PhpParser\Node\Name $name) : ?\PhpParser\Node\Stmt\Expression { /** @var Class_ $classLike */ - $classLike = $param->getAttribute(AttributeKey::CLASS_NODE); - + $classLike = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); $classMocks = $this->phpSpecMockCollector->resolveClassMocksFromParam($classLike); - $variable = $this->getName($param->var); - - $classMethod = $param->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { - throw new ShouldNotHappenException(); + $classMethod = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $methodName = $this->nodeNameResolver->getName($classMethod); $methodsWithWThisMock = $classMocks[$variable]; - - if ($param->var instanceof Error) { + if ($param->var instanceof \PhpParser\Node\Expr\Error) { return null; } - // single use: "$mock = $this->createMock()" - if (! $this->phpSpecMockCollector->isVariableMockInProperty($param->var)) { + if (!$this->phpSpecMockCollector->isVariableMockInProperty($param->var)) { return $this->createNewMockVariableAssign($param, $name); } - - $reversedMethodsWithThisMock = array_flip($methodsWithWThisMock); - + $reversedMethodsWithThisMock = \array_flip($methodsWithWThisMock); // first use of many: "$this->mock = $this->createMock()" if ($reversedMethodsWithThisMock[$methodName] === 0) { return $this->createPropertyFetchMockVariableAssign($param, $name); } - return null; } - - private function appendWithMethodCall(MethodCall $methodCall, Expr $expr): MethodCall + private function appendWithMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\MethodCall { - $withMethodCall = new MethodCall($methodCall, 'with'); - - if ($expr instanceof StaticCall) { + $withMethodCall = new \PhpParser\Node\Expr\MethodCall($methodCall, 'with'); + if ($expr instanceof \PhpParser\Node\Expr\StaticCall) { if ($this->isName($expr->class, '*Argument')) { if ($this->isName($expr->name, 'any')) { // no added value having this method return $methodCall; } - if ($this->isName($expr->name, 'type')) { $expr = $this->createIsTypeOrIsInstanceOf($expr); } } } else { $newExpr = $this->nodeFactory->createLocalMethodCall('equalTo'); - $newExpr->args = [new Arg($expr)]; + $newExpr->args = [new \PhpParser\Node\Arg($expr)]; $expr = $newExpr; } - - $withMethodCall->args = [new Arg($expr)]; - + $withMethodCall->args = [new \PhpParser\Node\Arg($expr)]; return $withMethodCall; } - - private function createNewMockVariableAssign(Param $param, Name $name): Expression + private function createNewMockVariableAssign(\PhpParser\Node\Param $param, \PhpParser\Node\Name $name) : \PhpParser\Node\Stmt\Expression { $methodCall = $this->nodeFactory->createLocalMethodCall('createMock'); - $methodCall->args[] = new Arg(new ClassConstFetch($name, 'class')); - - $assign = new Assign($param->var, $methodCall); - $assignExpression = new Expression($assign); - + $methodCall->args[] = new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\ClassConstFetch($name, 'class')); + $assign = new \PhpParser\Node\Expr\Assign($param->var, $methodCall); + $assignExpression = new \PhpParser\Node\Stmt\Expression($assign); // add @var doc comment $varDoc = $this->createMockVarDoc($param, $name); - $assignExpression->setDocComment(new Doc($varDoc)); - + $assignExpression->setDocComment(new \PhpParser\Comment\Doc($varDoc)); return $assignExpression; } - - private function createPropertyFetchMockVariableAssign(Param $param, Name $name): Expression + private function createPropertyFetchMockVariableAssign(\PhpParser\Node\Param $param, \PhpParser\Node\Name $name) : \PhpParser\Node\Stmt\Expression { $variable = $this->getName($param->var); if ($variable === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $propertyFetch = new PropertyFetch(new Variable('this'), $variable); - + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $variable); $methodCall = $this->nodeFactory->createLocalMethodCall('createMock'); - $methodCall->args[] = new Arg(new ClassConstFetch($name, 'class')); - - $assign = new Assign($propertyFetch, $methodCall); - - return new Expression($assign); + $methodCall->args[] = new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\ClassConstFetch($name, 'class')); + $assign = new \PhpParser\Node\Expr\Assign($propertyFetch, $methodCall); + return new \PhpParser\Node\Stmt\Expression($assign); } - - private function createIsTypeOrIsInstanceOf(StaticCall $staticCall): MethodCall + private function createIsTypeOrIsInstanceOf(\PhpParser\Node\Expr\StaticCall $staticCall) : \PhpParser\Node\Expr\MethodCall { $type = $this->valueResolver->getValue($staticCall->args[0]->value); - $name = $this->typeAnalyzer->isPhpReservedType($type) ? 'isType' : 'isInstanceOf'; - return $this->nodeFactory->createLocalMethodCall($name, $staticCall->args); } - - private function createMockVarDoc(Param $param, Name $name): string + private function createMockVarDoc(\PhpParser\Node\Param $param, \PhpParser\Node\Name $name) : string { - $paramType = (string) ($name->getAttribute(AttributeKey::ORIGINAL_NAME) ?: $name); + $paramType = (string) ($name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NAME) ?: $name); $variableName = $this->getName($param->var); - if ($variableName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - return sprintf( - '/** @var %s|\%s $%s */', - $paramType, - 'PHPUnit\Framework\MockObject\MockObject', - $variableName - ); + return \sprintf('/** @var %s|\\%s $%s */', $paramType, 'PHPUnit\\Framework\\MockObject\\MockObject', $variableName); } } diff --git a/rules/PhpSpecToPHPUnit/Rector/MethodCall/PhpSpecPromisesToPHPUnitAssertRector.php b/rules/PhpSpecToPHPUnit/Rector/MethodCall/PhpSpecPromisesToPHPUnitAssertRector.php index 508363eabf0..b3427f05bad 100644 --- a/rules/PhpSpecToPHPUnit/Rector/MethodCall/PhpSpecPromisesToPHPUnitAssertRector.php +++ b/rules/PhpSpecToPHPUnit/Rector/MethodCall/PhpSpecPromisesToPHPUnitAssertRector.php @@ -1,7 +1,6 @@ ['shouldBeFinite', 'shouldNotBeFinite'], 'assertInfinite' => ['shouldBeInfinite', 'shouldNotBeInfinite'], ]; - /** * @var string */ private const THIS = 'this'; - /** * @var string */ private $testedClass; - /** * @var bool */ - private $isPrepared = false; - + private $isPrepared = \false; /** * @var string[] */ private $matchersKeys = []; - /** * @var PropertyFetch */ private $testedObjectPropertyFetch; - /** * @var PhpSpecRenaming */ private $phpSpecRenaming; - /** * @var MatchersManipulator */ private $matchersManipulator; - /** * @var AssertMethodCallFactory */ private $assertMethodCallFactory; - /** * @var BeConstructedWithAssignFactory */ private $beConstructedWithAssignFactory; - /** * @var DuringMethodCallFactory */ private $duringMethodCallFactory; - - public function __construct( - MatchersManipulator $matchersManipulator, - PhpSpecRenaming $phpSpecRenaming, - AssertMethodCallFactory $assertMethodCallFactory, - BeConstructedWithAssignFactory $beConstructedWithAssignFactory, - DuringMethodCallFactory $duringMethodCallFactory - ) { + public function __construct(\Rector\PhpSpecToPHPUnit\MatchersManipulator $matchersManipulator, \Rector\PhpSpecToPHPUnit\Naming\PhpSpecRenaming $phpSpecRenaming, \Rector\PhpSpecToPHPUnit\NodeFactory\AssertMethodCallFactory $assertMethodCallFactory, \Rector\PhpSpecToPHPUnit\NodeFactory\BeConstructedWithAssignFactory $beConstructedWithAssignFactory, \Rector\PhpSpecToPHPUnit\NodeFactory\DuringMethodCallFactory $duringMethodCallFactory) + { $this->phpSpecRenaming = $phpSpecRenaming; $this->matchersManipulator = $matchersManipulator; $this->assertMethodCallFactory = $assertMethodCallFactory; $this->beConstructedWithAssignFactory = $beConstructedWithAssignFactory; $this->duringMethodCallFactory = $duringMethodCallFactory; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $this->isPrepared = false; + $this->isPrepared = \false; $this->matchersKeys = []; - - if (! $this->isInPhpSpecBehavior($node)) { + if (!$this->isInPhpSpecBehavior($node)) { return null; } - if ($this->isName($node->name, 'getWrappedObject')) { return $node->var; } - if ($this->isName($node->name, 'during')) { return $this->duringMethodCallFactory->create($node, $this->testedObjectPropertyFetch); } - if ($this->isName($node->name, 'duringInstantiation')) { return $this->processDuringInstantiation($node); } - if ($this->isName($node->name, 'getMatchers')) { return null; } - $this->prepareMethodCall($node); - if ($this->isName($node->name, 'beConstructed*')) { - return $this->beConstructedWithAssignFactory->create( - $node, - $this->testedClass, - $this->testedObjectPropertyFetch - ); + return $this->beConstructedWithAssignFactory->create($node, $this->testedClass, $this->testedObjectPropertyFetch); } - $this->processMatchersKeys($node); - foreach (self::NEW_METHOD_TO_OLD_METHODS as $newMethod => $oldMethods) { - if (! $this->isNames($node->name, $oldMethods)) { + if (!$this->isNames($node->name, $oldMethods)) { continue; } - - return $this->assertMethodCallFactory->createAssertMethod( - $newMethod, - $node->var, - $node->args[0]->value ?? null, - $this->testedObjectPropertyFetch - ); + return $this->assertMethodCallFactory->createAssertMethod($newMethod, $node->var, $node->args[0]->value ?? null, $this->testedObjectPropertyFetch); } - if ($this->shouldSkip($node)) { return null; } - if ($this->isName($node->name, 'clone')) { - return new Clone_($this->testedObjectPropertyFetch); + return new \PhpParser\Node\Expr\Clone_($this->testedObjectPropertyFetch); } - $methodName = $this->getName($node->name); if ($methodName === null) { return null; } - /** @var Class_ $classLike */ - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); $classMethod = $classLike->getMethod($methodName); // it's a method call, skip if ($classMethod !== null) { return null; } - $node->var = $this->testedObjectPropertyFetch; - return $node; } - - private function processDuringInstantiation(MethodCall $methodCall): MethodCall + private function processDuringInstantiation(\PhpParser\Node\Expr\MethodCall $methodCall) : \PhpParser\Node\Expr\MethodCall { /** @var MethodCall $parentMethodCall */ $parentMethodCall = $methodCall->var; - $parentMethodCall->name = new Identifier('expectException'); - + $parentMethodCall->name = new \PhpParser\Node\Identifier('expectException'); return $parentMethodCall; } - - private function prepareMethodCall(MethodCall $methodCall): void + private function prepareMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : void { if ($this->isPrepared) { return; } - /** @var Class_ $classLike */ - $classLike = $methodCall->getAttribute(AttributeKey::CLASS_NODE); - + $classLike = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); $this->matchersKeys = $this->matchersManipulator->resolveMatcherNamesFromClass($classLike); $this->testedClass = $this->phpSpecRenaming->resolveTestedClass($methodCall); $this->testedObjectPropertyFetch = $this->createTestedObjectPropertyFetch($classLike); - - $this->isPrepared = true; + $this->isPrepared = \true; } - /** * @changelog https://johannespichler.com/writing-custom-phpspec-matchers/ */ - private function processMatchersKeys(MethodCall $methodCall): void + private function processMatchersKeys(\PhpParser\Node\Expr\MethodCall $methodCall) : void { foreach ($this->matchersKeys as $matcherKey) { - if (! $this->isName($methodCall->name, 'should' . ucfirst($matcherKey))) { + if (!$this->isName($methodCall->name, 'should' . \ucfirst($matcherKey))) { continue; } - - if (! $methodCall->var instanceof MethodCall) { + if (!$methodCall->var instanceof \PhpParser\Node\Expr\MethodCall) { continue; } - // 1. assign callable to variable $thisGetMatchers = $this->nodeFactory->createMethodCall(self::THIS, 'getMatchers'); - $arrayDimFetch = new ArrayDimFetch($thisGetMatchers, new String_($matcherKey)); - $matcherCallableVariable = new Variable('matcherCallable'); - $assign = new Assign($matcherCallableVariable, $arrayDimFetch); - + $arrayDimFetch = new \PhpParser\Node\Expr\ArrayDimFetch($thisGetMatchers, new \PhpParser\Node\Scalar\String_($matcherKey)); + $matcherCallableVariable = new \PhpParser\Node\Expr\Variable('matcherCallable'); + $assign = new \PhpParser\Node\Expr\Assign($matcherCallableVariable, $arrayDimFetch); // 2. call it on result - $funcCall = new FuncCall($matcherCallableVariable); + $funcCall = new \PhpParser\Node\Expr\FuncCall($matcherCallableVariable); $funcCall->args = $methodCall->args; - $methodCall->name = $methodCall->var->name; $methodCall->var = $this->testedObjectPropertyFetch; $methodCall->args = []; - $funcCall->args[] = new Arg($methodCall); - + $funcCall->args[] = new \PhpParser\Node\Arg($methodCall); $this->addNodesAfterNode([$assign, $funcCall], $methodCall); - $this->removeNode($methodCall); - return; } } - - private function shouldSkip(MethodCall $methodCall): bool + private function shouldSkip(\PhpParser\Node\Expr\MethodCall $methodCall) : bool { - if (! $methodCall->var instanceof Variable) { - return true; + if (!$methodCall->var instanceof \PhpParser\Node\Expr\Variable) { + return \true; } - - if (! $this->nodeNameResolver->isName($methodCall->var, self::THIS)) { - return true; + if (!$this->nodeNameResolver->isName($methodCall->var, self::THIS)) { + return \true; } - // skip "createMock" method return $this->isName($methodCall->name, 'createMock'); } - - private function createTestedObjectPropertyFetch(Class_ $class): PropertyFetch + private function createTestedObjectPropertyFetch(\PhpParser\Node\Stmt\Class_ $class) : \PhpParser\Node\Expr\PropertyFetch { $propertyName = $this->phpSpecRenaming->resolveObjectPropertyName($class); - - return new PropertyFetch(new Variable(self::THIS), $propertyName); + return new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable(self::THIS), $propertyName); } } diff --git a/rules/PhpSpecToPHPUnit/Rector/Variable/MockVariableToPropertyFetchRector.php b/rules/PhpSpecToPHPUnit/Rector/Variable/MockVariableToPropertyFetchRector.php index 6b50ec4da46..1645d06d8e9 100644 --- a/rules/PhpSpecToPHPUnit/Rector/Variable/MockVariableToPropertyFetchRector.php +++ b/rules/PhpSpecToPHPUnit/Rector/Variable/MockVariableToPropertyFetchRector.php @@ -1,7 +1,6 @@ call() * ↓ @@ -17,42 +15,36 @@ use Rector\PhpSpecToPHPUnit\Rector\AbstractPhpSpecToPHPUnitRector; * * @see \Rector\Tests\PhpSpecToPHPUnit\Rector\Variable\PhpSpecToPHPUnitRector\PhpSpecToPHPUnitRectorTest */ -final class MockVariableToPropertyFetchRector extends AbstractPhpSpecToPHPUnitRector +final class MockVariableToPropertyFetchRector extends \Rector\PhpSpecToPHPUnit\Rector\AbstractPhpSpecToPHPUnitRector { /** * @var PhpSpecMockCollector */ private $phpSpecMockCollector; - - public function __construct(PhpSpecMockCollector $phpSpecMockCollector) + public function __construct(\Rector\PhpSpecToPHPUnit\PhpSpecMockCollector $phpSpecMockCollector) { $this->phpSpecMockCollector = $phpSpecMockCollector; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Variable::class]; + return [\PhpParser\Node\Expr\Variable::class]; } - /** * @param Variable $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isInPhpSpecBehavior($node)) { + if (!$this->isInPhpSpecBehavior($node)) { return null; } - - if (! $this->phpSpecMockCollector->isVariableMockInProperty($node)) { + if (!$this->phpSpecMockCollector->isVariableMockInProperty($node)) { return null; } - /** @var string $variableName */ $variableName = $this->getName($node); - - return new PropertyFetch(new Variable('this'), $variableName); + return new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $variableName); } } diff --git a/rules/Privatization/Naming/ConstantNaming.php b/rules/Privatization/Naming/ConstantNaming.php index 2aba3d5a2bd..f0311335aa2 100644 --- a/rules/Privatization/Naming/ConstantNaming.php +++ b/rules/Privatization/Naming/ConstantNaming.php @@ -1,31 +1,25 @@ nodeNameResolver = $nodeNameResolver; } - - public function createFromProperty(PropertyProperty $propertyProperty): string + public function createFromProperty(\PhpParser\Node\Stmt\PropertyProperty $propertyProperty) : string { $propertyName = $this->nodeNameResolver->getName($propertyProperty); - - $stringy = new Stringy($propertyName); - return (string) $stringy->underscored() - ->toUpperCase(); + $stringy = new \RectorPrefix20210509\Stringy\Stringy($propertyName); + return (string) $stringy->underscored()->toUpperCase(); } } diff --git a/rules/Privatization/NodeAnalyzer/EventSubscriberMethodNamesResolver.php b/rules/Privatization/NodeAnalyzer/EventSubscriberMethodNamesResolver.php index ba4b5e0f5ce..289410cc501 100644 --- a/rules/Privatization/NodeAnalyzer/EventSubscriberMethodNamesResolver.php +++ b/rules/Privatization/NodeAnalyzer/EventSubscriberMethodNamesResolver.php @@ -1,48 +1,38 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - /** * @return string[] */ - public function resolveFromClassMethod(ClassMethod $classMethod): array + public function resolveFromClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $methodNames = []; - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $classMethod->stmts, - function (Node $node) use (&$methodNames) { - if (! $node instanceof ArrayItem) { - return null; - } - - if (! $node->value instanceof String_) { - return null; - } - - $methodNames[] = $node->value->value; + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->stmts, function (\PhpParser\Node $node) use(&$methodNames) { + if (!$node instanceof \PhpParser\Node\Expr\ArrayItem) { + return null; } - ); - + if (!$node->value instanceof \PhpParser\Node\Scalar\String_) { + return null; + } + $methodNames[] = $node->value->value; + }); return $methodNames; } } diff --git a/rules/Privatization/NodeAnalyzer/PropertyFetchByMethodAnalyzer.php b/rules/Privatization/NodeAnalyzer/PropertyFetchByMethodAnalyzer.php index 62d066491a9..53276e664b6 100644 --- a/rules/Privatization/NodeAnalyzer/PropertyFetchByMethodAnalyzer.php +++ b/rules/Privatization/NodeAnalyzer/PropertyFetchByMethodAnalyzer.php @@ -1,7 +1,6 @@ > */ - private const SCOPE_CHANGING_NODE_TYPES = [Do_::class, While_::class, If_::class, Else_::class]; - + private const SCOPE_CHANGING_NODE_TYPES = [\PhpParser\Node\Stmt\Do_::class, \PhpParser\Node\Stmt\While_::class, \PhpParser\Node\Stmt\If_::class, \PhpParser\Node\Stmt\Else_::class]; /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var PropertyFetchAnalyzer */ private $propertyFetchAnalyzer; - /** * @var SimpleCallableNodeTraverser */ private $simpleCallableNodeTraverser; - - public function __construct( - NodeNameResolver $nodeNameResolver, - PropertyFetchAnalyzer $propertyFetchAnalyzer, - SimpleCallableNodeTraverser $simpleCallableNodeTraverser - ) { + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\Core\NodeAnalyzer\PropertyFetchAnalyzer $propertyFetchAnalyzer, \RectorPrefix20210509\Symplify\Astral\NodeTraverser\SimpleCallableNodeTraverser $simpleCallableNodeTraverser) + { $this->nodeNameResolver = $nodeNameResolver; $this->propertyFetchAnalyzer = $propertyFetchAnalyzer; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - /** * @param string[] $propertyNames * @return array */ - public function collectPropertyFetchByMethods(Class_ $class, array $propertyNames): array + public function collectPropertyFetchByMethods(\PhpParser\Node\Stmt\Class_ $class, array $propertyNames) : array { $propertyUsageByMethods = []; - foreach ($propertyNames as $propertyName) { foreach ($class->getMethods() as $classMethod) { // assigned in constructor injection → skip - if ($this->nodeNameResolver->isName($classMethod, MethodName::CONSTRUCT)) { + if ($this->nodeNameResolver->isName($classMethod, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { return []; } - - if (! $this->propertyFetchAnalyzer->containsLocalPropertyFetchName($classMethod, $propertyName)) { + if (!$this->propertyFetchAnalyzer->containsLocalPropertyFetchName($classMethod, $propertyName)) { continue; } - if ($this->isPropertyChangingInMultipleMethodCalls($classMethod, $propertyName)) { continue; } - $classMethodName = $this->nodeNameResolver->getName($classMethod); $propertyUsageByMethods[$propertyName][] = $classMethodName; } } - return $propertyUsageByMethods; } - /** * Covers https://github.com/rectorphp/rector/pull/2558#discussion_r363036110 */ - private function isPropertyChangingInMultipleMethodCalls(ClassMethod $classMethod, string $propertyName): bool + private function isPropertyChangingInMultipleMethodCalls(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $propertyName) : bool { - $isPropertyChanging = false; - $isPropertyReadInIf = false; - $isIfFollowedByAssign = false; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $classMethod->getStmts(), - function (Node $node) use ( - &$isPropertyChanging, - $propertyName, - &$isPropertyReadInIf, - &$isIfFollowedByAssign - ): ?int { - if ($isPropertyReadInIf) { - if (! $this->propertyFetchAnalyzer->isLocalPropertyOfNames($node, [$propertyName])) { - return null; - } - - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Assign && $parentNode->var === $node) { - $isIfFollowedByAssign = true; - } - } - - if (! $this->isScopeChangingNode($node)) { + $isPropertyChanging = \false; + $isPropertyReadInIf = \false; + $isIfFollowedByAssign = \false; + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->getStmts(), function (\PhpParser\Node $node) use(&$isPropertyChanging, $propertyName, &$isPropertyReadInIf, &$isIfFollowedByAssign) : ?int { + if ($isPropertyReadInIf) { + if (!$this->propertyFetchAnalyzer->isLocalPropertyOfNames($node, [$propertyName])) { return null; } - - if ($node instanceof If_) { - $isPropertyReadInIf = $this->refactorIf($node, $propertyName); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\Assign && $parentNode->var === $node) { + $isIfFollowedByAssign = \true; } - - $isPropertyChanging = $this->isPropertyChanging($node, $propertyName); - if (! $isPropertyChanging) { - return null; - } - - return NodeTraverser::STOP_TRAVERSAL; } - ); - + if (!$this->isScopeChangingNode($node)) { + return null; + } + if ($node instanceof \PhpParser\Node\Stmt\If_) { + $isPropertyReadInIf = $this->refactorIf($node, $propertyName); + } + $isPropertyChanging = $this->isPropertyChanging($node, $propertyName); + if (!$isPropertyChanging) { + return null; + } + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; + }); return $isPropertyChanging || $isIfFollowedByAssign || $isPropertyReadInIf; } - - private function isScopeChangingNode(Node $node): bool + private function isScopeChangingNode(\PhpParser\Node $node) : bool { foreach (self::SCOPE_CHANGING_NODE_TYPES as $type) { - if (is_a($node, $type, true)) { - return true; + if (\is_a($node, $type, \true)) { + return \true; } } - - return false; + return \false; } - - private function refactorIf(If_ $if, string $privatePropertyName): ?bool + private function refactorIf(\PhpParser\Node\Stmt\If_ $if, string $privatePropertyName) : ?bool { - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($if->cond, function (Node $node) use ( - $privatePropertyName, - &$isPropertyReadInIf - ): ?int { - if (! $this->propertyFetchAnalyzer->isLocalPropertyOfNames($node, [$privatePropertyName])) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($if->cond, function (\PhpParser\Node $node) use($privatePropertyName, &$isPropertyReadInIf) : ?int { + if (!$this->propertyFetchAnalyzer->isLocalPropertyOfNames($node, [$privatePropertyName])) { return null; } - - $isPropertyReadInIf = true; - - return NodeTraverser::STOP_TRAVERSAL; + $isPropertyReadInIf = \true; + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; }); - return $isPropertyReadInIf; } - - private function isPropertyChanging(Node $node, string $privatePropertyName): bool + private function isPropertyChanging(\PhpParser\Node $node, string $privatePropertyName) : bool { - $isPropertyChanging = false; + $isPropertyChanging = \false; // here cannot be any property assign - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($node, function (Node $node) use ( - &$isPropertyChanging, - $privatePropertyName - ): ?int { - if (! $node instanceof Assign) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($node, function (\PhpParser\Node $node) use(&$isPropertyChanging, $privatePropertyName) : ?int { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $node->var instanceof PropertyFetch) { + if (!$node->var instanceof \PhpParser\Node\Expr\PropertyFetch) { return null; } - - if (! $this->nodeNameResolver->isName($node->var->name, $privatePropertyName)) { + if (!$this->nodeNameResolver->isName($node->var->name, $privatePropertyName)) { return null; } - - $isPropertyChanging = true; - - return NodeTraverser::STOP_TRAVERSAL; + $isPropertyChanging = \true; + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; }); - return $isPropertyChanging; } } diff --git a/rules/Privatization/NodeFactory/ClassConstantFactory.php b/rules/Privatization/NodeFactory/ClassConstantFactory.php index f98fea079d2..3e7169119c2 100644 --- a/rules/Privatization/NodeFactory/ClassConstantFactory.php +++ b/rules/Privatization/NodeFactory/ClassConstantFactory.php @@ -1,7 +1,6 @@ constantNaming = $constantNaming; $this->phpDocInfoFactory = $phpDocInfoFactory; } - - public function createFromProperty(Property $property): ClassConst + public function createFromProperty(\PhpParser\Node\Stmt\Property $property) : \PhpParser\Node\Stmt\ClassConst { $propertyProperty = $property->props[0]; - $constantName = $this->constantNaming->createFromProperty($propertyProperty); - /** @var Expr $defaultValue */ $defaultValue = $propertyProperty->default; - $const = new Const_($constantName, $defaultValue); - - $classConst = new ClassConst([$const]); - $classConst->flags = $property->flags & ~ Class_::MODIFIER_STATIC; - + $const = new \PhpParser\Node\Const_($constantName, $defaultValue); + $classConst = new \PhpParser\Node\Stmt\ClassConst([$const]); + $classConst->flags = $property->flags & ~\PhpParser\Node\Stmt\Class_::MODIFIER_STATIC; $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); $phpDocInfo->markAsChanged(); - - $classConst->setAttribute(AttributeKey::PHP_DOC_INFO, $phpDocInfo); - + $classConst->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, $phpDocInfo); return $classConst; } } diff --git a/rules/Privatization/NodeFactory/ClassConstantFetchValueFactory.php b/rules/Privatization/NodeFactory/ClassConstantFetchValueFactory.php index f8022f4cfad..8f8eb0c14f2 100644 --- a/rules/Privatization/NodeFactory/ClassConstantFetchValueFactory.php +++ b/rules/Privatization/NodeFactory/ClassConstantFetchValueFactory.php @@ -1,7 +1,6 @@ valueResolver = $valueResolver; $this->nodeFactory = $nodeFactory; $this->classConstantsResolver = $classConstantsResolver; } - /** * @param class-string $classWithConstants */ - public function create(Expr $expr, string $classWithConstants): ?ClassConstFetch + public function create(\PhpParser\Node\Expr $expr, string $classWithConstants) : ?\PhpParser\Node\Expr\ClassConstFetch { $value = $this->valueResolver->getValue($expr); if ($value === null) { return null; } - $constantNamesToValues = $this->classConstantsResolver->getClassConstantNamesToValues($classWithConstants); foreach ($constantNamesToValues as $constantName => $constantValue) { if ($constantValue !== $value) { continue; } - return $this->nodeFactory->createClassConstFetch($classWithConstants, $constantName); } - return null; } } diff --git a/rules/Privatization/NodeManipulator/VisibilityManipulator.php b/rules/Privatization/NodeManipulator/VisibilityManipulator.php index d0d0799bb4e..1dc355f8a49 100644 --- a/rules/Privatization/NodeManipulator/VisibilityManipulator.php +++ b/rules/Privatization/NodeManipulator/VisibilityManipulator.php @@ -1,7 +1,6 @@ > */ - private const ALLOWED_NODE_TYPES = [ClassMethod::class, Property::class, ClassConst::class, Class_::class]; - + private const ALLOWED_NODE_TYPES = [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Property::class, \PhpParser\Node\Stmt\ClassConst::class, \PhpParser\Node\Stmt\Class_::class]; /** * @param ClassMethod|Property|ClassConst $node */ - public function makeStatic(Node $node): void + public function makeStatic(\PhpParser\Node $node) : void { - $this->addVisibilityFlag($node, Visibility::STATIC); + $this->addVisibilityFlag($node, \Rector\Core\ValueObject\Visibility::STATIC); } - /** * @param ClassMethod|Class_ $node */ - public function makeAbstract(Node $node): void + public function makeAbstract(\PhpParser\Node $node) : void { - $this->addVisibilityFlag($node, Visibility::ABSTRACT); + $this->addVisibilityFlag($node, \Rector\Core\ValueObject\Visibility::ABSTRACT); } - /** * @param ClassMethod|Property $node */ - public function makeNonStatic(Node $node): void + public function makeNonStatic(\PhpParser\Node $node) : void { - if (! $node->isStatic()) { + if (!$node->isStatic()) { return; } - - $node->flags -= Class_::MODIFIER_STATIC; + $node->flags -= \PhpParser\Node\Stmt\Class_::MODIFIER_STATIC; } - /** * @param Class_|ClassMethod $node */ - public function makeFinal(Node $node): void + public function makeFinal(\PhpParser\Node $node) : void { - $this->addVisibilityFlag($node, Visibility::FINAL); + $this->addVisibilityFlag($node, \Rector\Core\ValueObject\Visibility::FINAL); } - /** * @param Class_|ClassMethod $node */ - public function makeNonFinal(Node $node): void + public function makeNonFinal(\PhpParser\Node $node) : void { - if (! $node->isFinal()) { + if (!$node->isFinal()) { return; } - - $node->flags -= Class_::MODIFIER_FINAL; + $node->flags -= \PhpParser\Node\Stmt\Class_::MODIFIER_FINAL; } - /** * This way "abstract", "static", "final" are kept * * @param ClassMethod|Property|ClassConst $node */ - public function removeVisibility(Node $node): void + public function removeVisibility(\PhpParser\Node $node) : void { $this->ensureIsClassMethodOrProperty($node, __METHOD__); - // no modifier if ($node->flags === 0) { return; } - if ($node->isPublic()) { - $node->flags -= Class_::MODIFIER_PUBLIC; + $node->flags -= \PhpParser\Node\Stmt\Class_::MODIFIER_PUBLIC; } - if ($node->isProtected()) { - $node->flags -= Class_::MODIFIER_PROTECTED; + $node->flags -= \PhpParser\Node\Stmt\Class_::MODIFIER_PROTECTED; } - if ($node->isPrivate()) { - $node->flags -= Class_::MODIFIER_PRIVATE; + $node->flags -= \PhpParser\Node\Stmt\Class_::MODIFIER_PRIVATE; } } - /** * @param ClassMethod|Property|ClassConst $node */ - public function changeNodeVisibility(Node $node, int $visibility): void + public function changeNodeVisibility(\PhpParser\Node $node, int $visibility) : void { - Assert::oneOf($visibility, [ - Visibility::PUBLIC, - Visibility::PROTECTED, - Visibility::PRIVATE, - Visibility::STATIC, - Visibility::ABSTRACT, - Visibility::FINAL, - ]); - + \RectorPrefix20210509\Webmozart\Assert\Assert::oneOf($visibility, [\Rector\Core\ValueObject\Visibility::PUBLIC, \Rector\Core\ValueObject\Visibility::PROTECTED, \Rector\Core\ValueObject\Visibility::PRIVATE, \Rector\Core\ValueObject\Visibility::STATIC, \Rector\Core\ValueObject\Visibility::ABSTRACT, \Rector\Core\ValueObject\Visibility::FINAL]); $this->replaceVisibilityFlag($node, $visibility); } - /** * @param ClassMethod|Property|ClassConst $node */ - public function makePublic(Node $node): void + public function makePublic(\PhpParser\Node $node) : void { - $this->replaceVisibilityFlag($node, Visibility::PUBLIC); + $this->replaceVisibilityFlag($node, \Rector\Core\ValueObject\Visibility::PUBLIC); } - /** * @param ClassMethod|Property|ClassConst $node */ - public function makeProtected(Node $node): void + public function makeProtected(\PhpParser\Node $node) : void { - $this->replaceVisibilityFlag($node, Visibility::PROTECTED); + $this->replaceVisibilityFlag($node, \Rector\Core\ValueObject\Visibility::PROTECTED); } - /** * @param ClassMethod|Property|ClassConst $node */ - public function makePrivate(Node $node): void + public function makePrivate(\PhpParser\Node $node) : void { - $this->replaceVisibilityFlag($node, Visibility::PRIVATE); + $this->replaceVisibilityFlag($node, \Rector\Core\ValueObject\Visibility::PRIVATE); } - - public function removeFinal(Class_ $class): void + public function removeFinal(\PhpParser\Node\Stmt\Class_ $class) : void { - $class->flags -= Class_::MODIFIER_FINAL; + $class->flags -= \PhpParser\Node\Stmt\Class_::MODIFIER_FINAL; } - /** * @param Class_|ClassMethod|Property|ClassConst $node */ - private function addVisibilityFlag(Node $node, int $visibility): void + private function addVisibilityFlag(\PhpParser\Node $node, int $visibility) : void { $this->ensureIsClassMethodOrProperty($node, __METHOD__); $node->flags |= $visibility; } - - private function ensureIsClassMethodOrProperty(Node $node, string $location): void + private function ensureIsClassMethodOrProperty(\PhpParser\Node $node, string $location) : void { foreach (self::ALLOWED_NODE_TYPES as $allowedNodeType) { - if (is_a($node, $allowedNodeType, true)) { + if (\is_a($node, $allowedNodeType, \true)) { return; } } - - throw new InvalidNodeTypeException(sprintf( - '"%s" only accepts "%s" types. "%s" given.', - $location, - implode('", "', self::ALLOWED_NODE_TYPES), - get_class($node) - )); + throw new \Rector\Core\Exception\InvalidNodeTypeException(\sprintf('"%s" only accepts "%s" types. "%s" given.', $location, \implode('", "', self::ALLOWED_NODE_TYPES), \get_class($node))); } - /** * @param ClassMethod|Property|ClassConst $node */ - private function replaceVisibilityFlag(Node $node, int $visibility): void + private function replaceVisibilityFlag(\PhpParser\Node $node, int $visibility) : void { - $isStatic = $node instanceof ClassMethod && $node->isStatic(); + $isStatic = $node instanceof \PhpParser\Node\Stmt\ClassMethod && $node->isStatic(); if ($isStatic) { $this->removeVisibility($node); } - - if ($visibility !== Visibility::STATIC && $visibility !== Visibility::ABSTRACT && $visibility !== Visibility::FINAL) { + if ($visibility !== \Rector\Core\ValueObject\Visibility::STATIC && $visibility !== \Rector\Core\ValueObject\Visibility::ABSTRACT && $visibility !== \Rector\Core\ValueObject\Visibility::FINAL) { $this->removeVisibility($node); } - $this->addVisibilityFlag($node, $visibility); - if ($isStatic) { $this->makeStatic($node); } diff --git a/rules/Privatization/NodeReplacer/PropertyFetchWithConstFetchReplacer.php b/rules/Privatization/NodeReplacer/PropertyFetchWithConstFetchReplacer.php index 97c719f5dd4..20f69062054 100644 --- a/rules/Privatization/NodeReplacer/PropertyFetchWithConstFetchReplacer.php +++ b/rules/Privatization/NodeReplacer/PropertyFetchWithConstFetchReplacer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->propertyFetchAnalyzer = $propertyFetchAnalyzer; $this->constantNaming = $constantNaming; $this->nodeFactory = $nodeFactory; } - - public function replace(Class_ $class, Property $property): void + public function replace(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt\Property $property) : void { $propertyProperty = $property->props[0]; - $propertyName = $this->nodeNameResolver->getName($property); $constantName = $this->constantNaming->createFromProperty($propertyProperty); - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($class, function (Node $node) use ( - $propertyName, - $constantName - ): ?ClassConstFetch { - if (! $this->propertyFetchAnalyzer->isLocalPropertyFetch($node)) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($class, function (\PhpParser\Node $node) use($propertyName, $constantName) : ?ClassConstFetch { + if (!$this->propertyFetchAnalyzer->isLocalPropertyFetch($node)) { return null; } - /** @var PropertyFetch|StaticPropertyFetch $node */ - if (! $this->nodeNameResolver->isName($node->name, $propertyName)) { + if (!$this->nodeNameResolver->isName($node->name, $propertyName)) { return null; } - // replace with constant fetch return $this->nodeFactory->createSelfFetchConstant($constantName, $node); }); diff --git a/rules/Privatization/NodeReplacer/PropertyFetchWithVariableReplacer.php b/rules/Privatization/NodeReplacer/PropertyFetchWithVariableReplacer.php index dd46023aab6..5d931df3ff3 100644 --- a/rules/Privatization/NodeReplacer/PropertyFetchWithVariableReplacer.php +++ b/rules/Privatization/NodeReplacer/PropertyFetchWithVariableReplacer.php @@ -1,7 +1,6 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeNameResolver = $nodeNameResolver; } - /** * @param array $methodsByPropertyName */ - public function replacePropertyFetchesByVariable(Class_ $class, array $methodsByPropertyName): void + public function replacePropertyFetchesByVariable(\PhpParser\Node\Stmt\Class_ $class, array $methodsByPropertyName) : void { foreach ($methodsByPropertyName as $propertyName => $methodNames) { $methodName = $methodNames[0]; $classMethod = $class->getMethod($methodName); - if (! $classMethod instanceof ClassMethod) { + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { continue; } - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $classMethod->getStmts(), - function (Node $node) use ($propertyName): ?Variable { - if (! $node instanceof PropertyFetch) { - return null; - } - - if (! $this->nodeNameResolver->isName($node, $propertyName)) { - return null; - } - - return new Variable($propertyName); + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->getStmts(), function (\PhpParser\Node $node) use($propertyName) : ?Variable { + if (!$node instanceof \PhpParser\Node\Expr\PropertyFetch) { + return null; } - ); + if (!$this->nodeNameResolver->isName($node, $propertyName)) { + return null; + } + return new \PhpParser\Node\Expr\Variable($propertyName); + }); } } } diff --git a/rules/Privatization/Rector/ClassMethod/ChangeGlobalVariablesToPropertiesRector.php b/rules/Privatization/Rector/ClassMethod/ChangeGlobalVariablesToPropertiesRector.php index 0f734926133..35b53ded2ad 100644 --- a/rules/Privatization/Rector/ClassMethod/ChangeGlobalVariablesToPropertiesRector.php +++ b/rules/Privatization/Rector/ClassMethod/ChangeGlobalVariablesToPropertiesRector.php @@ -1,7 +1,6 @@ propertyToAddCollector = $propertyToAddCollector; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change global $variables to private properties', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change global $variables to private properties', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function go() @@ -61,8 +52,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { private $variable; @@ -77,86 +67,68 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - $this->collectGlobalVariableNamesAndRefactorToPropertyFetch($node); - if ($this->globalVariableNames === []) { return null; } - foreach ($this->globalVariableNames as $globalVariableName) { $this->propertyToAddCollector->addPropertyWithoutConstructorToClass($globalVariableName, null, $classLike); } - return $node; } - - private function collectGlobalVariableNamesAndRefactorToPropertyFetch(ClassMethod $classMethod): void + private function collectGlobalVariableNamesAndRefactorToPropertyFetch(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { $this->globalVariableNames = []; - - $this->traverseNodesWithCallable($classMethod, function (Node $node): ?PropertyFetch { - if ($node instanceof Global_) { + $this->traverseNodesWithCallable($classMethod, function (\PhpParser\Node $node) : ?PropertyFetch { + if ($node instanceof \PhpParser\Node\Stmt\Global_) { $this->refactorGlobal($node); return null; } - - if ($node instanceof Variable) { + if ($node instanceof \PhpParser\Node\Expr\Variable) { return $this->refactorGlobalVariable($node); } - return null; }); } - - private function refactorGlobal(Global_ $global): void + private function refactorGlobal(\PhpParser\Node\Stmt\Global_ $global) : void { foreach ($global->vars as $var) { $varName = $this->getName($var); if ($varName === null) { return; } - $this->globalVariableNames[] = $varName; } - $this->removeNode($global); } - - private function refactorGlobalVariable(Variable $variable): ?PropertyFetch + private function refactorGlobalVariable(\PhpParser\Node\Expr\Variable $variable) : ?\PhpParser\Node\Expr\PropertyFetch { - if (! $this->isNames($variable, $this->globalVariableNames)) { + if (!$this->isNames($variable, $this->globalVariableNames)) { return null; } - // replace with property fetch $variableName = $this->getName($variable); if ($variableName === null) { return null; } - return $this->nodeFactory->createPropertyFetch('this', $variableName); } } diff --git a/rules/Privatization/Rector/ClassMethod/PrivatizeFinalClassMethodRector.php b/rules/Privatization/Rector/ClassMethod/PrivatizeFinalClassMethodRector.php index bffd6b2ab5b..e3aa053513d 100644 --- a/rules/Privatization/Rector/ClassMethod/PrivatizeFinalClassMethodRector.php +++ b/rules/Privatization/Rector/ClassMethod/PrivatizeFinalClassMethodRector.php @@ -1,7 +1,6 @@ classMethodVisibilityGuard = $classMethodVisibilityGuard; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change protected class method to private if possible', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change protected class method to private if possible', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { protected function someMethod() @@ -43,8 +35,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { private function someMethod() @@ -52,61 +43,48 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - - if (! $classReflection->isFinal()) { + if (!$classReflection->isFinal()) { return null; } - if ($this->shouldSkipClassMethod($node)) { return null; } - if ($this->classMethodVisibilityGuard->isClassMethodVisibilityGuardedByParent($node, $classReflection)) { return null; } - if ($this->classMethodVisibilityGuard->isClassMethodVisibilityGuardedByTrait($node, $classReflection)) { return null; } - $this->visibilityManipulator->makePrivate($node); - return $node; } - - private function shouldSkipClassMethod(ClassMethod $classMethod): bool + private function shouldSkipClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { if ($this->isName($classMethod, 'createComponent*')) { - return true; + return \true; } - - return ! $classMethod->isProtected(); + return !$classMethod->isProtected(); } } diff --git a/rules/Privatization/Rector/Class_/ChangeLocalPropertyToVariableRector.php b/rules/Privatization/Rector/Class_/ChangeLocalPropertyToVariableRector.php index 05334126657..f494e163b70 100644 --- a/rules/Privatization/Rector/Class_/ChangeLocalPropertyToVariableRector.php +++ b/rules/Privatization/Rector/Class_/ChangeLocalPropertyToVariableRector.php @@ -1,7 +1,6 @@ classManipulator = $classManipulator; $this->propertyFetchWithVariableReplacer = $propertyFetchWithVariableReplacer; $this->propertyFetchByMethodAnalyzer = $propertyFetchByMethodAnalyzer; $this->classAnalyzer = $classAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change local property used in single method to local variable', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change local property used in single method to local variable', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private $count; @@ -68,8 +53,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -79,58 +63,43 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->classAnalyzer->isAnonymousClass($node)) { return null; } - $privatePropertyNames = $this->classManipulator->getPrivatePropertyNames($node); - - $propertyUsageByMethods = $this->propertyFetchByMethodAnalyzer->collectPropertyFetchByMethods( - $node, - $privatePropertyNames - ); + $propertyUsageByMethods = $this->propertyFetchByMethodAnalyzer->collectPropertyFetchByMethods($node, $privatePropertyNames); if ($propertyUsageByMethods === []) { return null; } - foreach ($propertyUsageByMethods as $propertyName => $methodNames) { - if (count($methodNames) === 1) { + if (\count($methodNames) === 1) { continue; } - unset($propertyUsageByMethods[$propertyName]); } - $this->propertyFetchWithVariableReplacer->replacePropertyFetchesByVariable($node, $propertyUsageByMethods); - // remove properties foreach ($node->getProperties() as $property) { - $classMethodNames = array_keys($propertyUsageByMethods); - if (! $this->isNames($property, $classMethodNames)) { + $classMethodNames = \array_keys($propertyUsageByMethods); + if (!$this->isNames($property, $classMethodNames)) { continue; } - $this->removeNode($property); } - return $node; } } diff --git a/rules/Privatization/Rector/Class_/ChangeReadOnlyVariableWithDefaultValueToConstantRector.php b/rules/Privatization/Rector/Class_/ChangeReadOnlyVariableWithDefaultValueToConstantRector.php index eea37ebf30f..5c52cc624ed 100644 --- a/rules/Privatization/Rector/Class_/ChangeReadOnlyVariableWithDefaultValueToConstantRector.php +++ b/rules/Privatization/Rector/Class_/ChangeReadOnlyVariableWithDefaultValueToConstantRector.php @@ -1,7 +1,6 @@ classMethodAssignManipulator = $classMethodAssignManipulator; $this->varAnnotationManipulator = $varAnnotationManipulator; $this->propertyToAddCollector = $propertyToAddCollector; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change variable with read only status with default value to constant', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change variable with read only status with default value to constant', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -76,8 +63,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -95,206 +81,156 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $readOnlyVariableAssigns = $this->collectReadOnlyVariableAssigns($node); $readOnlyVariableAssigns = $this->filterOutUniqueNames($readOnlyVariableAssigns); - if ($readOnlyVariableAssigns === []) { return null; } - foreach ($readOnlyVariableAssigns as $readOnlyVariableAssign) { - $classMethod = $readOnlyVariableAssign->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { - throw new ShouldNotHappenException(); + $classMethod = $readOnlyVariableAssign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $methodName = $this->getName($classMethod); $classMethod = $node->getMethod($methodName); - if (! $classMethod instanceof ClassMethod) { - throw new ShouldNotHappenException(); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $this->refactorClassMethod($classMethod, $node, $readOnlyVariableAssigns); } - return $node; } - /** * @return Assign[] */ - private function collectReadOnlyVariableAssigns(Class_ $class): array + private function collectReadOnlyVariableAssigns(\PhpParser\Node\Stmt\Class_ $class) : array { $readOnlyVariables = []; - foreach ($class->getMethods() as $classMethod) { if ($this->isFoundByRefParam($classMethod)) { return []; } - - $readOnlyVariableAssignScalarVariables = $this->classMethodAssignManipulator->collectReadyOnlyAssignScalarVariables( - $classMethod - ); - $readOnlyVariables = array_merge($readOnlyVariables, $readOnlyVariableAssignScalarVariables); + $readOnlyVariableAssignScalarVariables = $this->classMethodAssignManipulator->collectReadyOnlyAssignScalarVariables($classMethod); + $readOnlyVariables = \array_merge($readOnlyVariables, $readOnlyVariableAssignScalarVariables); } - return $readOnlyVariables; } - /** * @param Assign[] $assigns * @return Assign[] */ - private function filterOutUniqueNames(array $assigns): array + private function filterOutUniqueNames(array $assigns) : array { $assignsByName = $this->collectAssignsByName($assigns); $assignsWithUniqueName = []; foreach ($assignsByName as $assigns) { - $count = count($assigns); + $count = \count($assigns); if ($count > 1) { continue; } - - $assignsWithUniqueName = array_merge($assignsWithUniqueName, $assigns); + $assignsWithUniqueName = \array_merge($assignsWithUniqueName, $assigns); } - return $assignsWithUniqueName; } - /** * @param Assign[] $assigns * @return array */ - private function collectAssignsByName(array $assigns): array + private function collectAssignsByName(array $assigns) : array { $assignsByName = []; foreach ($assigns as $assign) { /** @var string $variableName */ $variableName = $this->getName($assign->var); - $assignsByName[$variableName][] = $assign; } - return $assignsByName; } - /** * @param Assign[] $readOnlyVariableAssigns */ - private function refactorClassMethod(ClassMethod $classMethod, Class_ $class, array $readOnlyVariableAssigns): void + private function refactorClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Stmt\Class_ $class, array $readOnlyVariableAssigns) : void { foreach ($readOnlyVariableAssigns as $readOnlyVariableAssign) { $this->removeNode($readOnlyVariableAssign); - /** @var Variable|ClassConstFetch $variable */ $variable = $readOnlyVariableAssign->var; // already overridden - if (! $variable instanceof Variable) { + if (!$variable instanceof \PhpParser\Node\Expr\Variable) { continue; } - $classConst = $this->createPrivateClassConst($variable, $readOnlyVariableAssign->expr); - // replace $variable usage in the code with constant $this->propertyToAddCollector->addConstantToClass($class, $classConst); - $variableName = $this->getName($variable); if ($variableName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $this->replaceVariableWithClassConstFetch($classMethod, $variableName, $classConst); } } - - private function isFoundByRefParam(ClassMethod $classMethod): bool + private function isFoundByRefParam(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { $params = $classMethod->getParams(); foreach ($params as $param) { if ($param->byRef) { - return true; + return \true; } } - - return false; + return \false; } - - private function createPrivateClassConst(Variable $variable, Expr $expr): ClassConst + private function createPrivateClassConst(\PhpParser\Node\Expr\Variable $variable, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Stmt\ClassConst { $constantName = $this->createConstantNameFromVariable($variable); - - $const = new Const_($constantName, $expr); - - $classConst = new ClassConst([$const]); - $classConst->flags = Class_::MODIFIER_PRIVATE; - + $const = new \PhpParser\Node\Const_($constantName, $expr); + $classConst = new \PhpParser\Node\Stmt\ClassConst([$const]); + $classConst->flags = \PhpParser\Node\Stmt\Class_::MODIFIER_PRIVATE; $this->mirrorComments($classConst, $variable); - $constantType = $this->getStaticType($classConst->consts[0]->value); $this->varAnnotationManipulator->decorateNodeWithType($classConst, $constantType); - return $classConst; } - - private function replaceVariableWithClassConstFetch( - ClassMethod $classMethod, - string $variableName, - ClassConst $classConst - ): void { + private function replaceVariableWithClassConstFetch(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $variableName, \PhpParser\Node\Stmt\ClassConst $classConst) : void + { $constantName = $this->getName($classConst); if ($constantName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $this->traverseNodesWithCallable($classMethod, function (Node $node) use ( - $variableName, - $constantName - ): ?ClassConstFetch { - if (! $node instanceof Variable) { + $this->traverseNodesWithCallable($classMethod, function (\PhpParser\Node $node) use($variableName, $constantName) : ?ClassConstFetch { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { return null; } - - if (! $this->nodeNameResolver->isName($node, $variableName)) { + if (!$this->nodeNameResolver->isName($node, $variableName)) { return null; } - // replace with constant fetch - $classConstFetch = new ClassConstFetch(new Name('self'), new Identifier($constantName)); - + $classConstFetch = new \PhpParser\Node\Expr\ClassConstFetch(new \PhpParser\Node\Name('self'), new \PhpParser\Node\Identifier($constantName)); // needed later - $classConstFetch->setAttribute(AttributeKey::CLASS_NAME, $node->getAttribute(AttributeKey::CLASS_NAME)); - + $classConstFetch->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME, $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME)); return $classConstFetch; }); } - - private function createConstantNameFromVariable(Variable $variable): string + private function createConstantNameFromVariable(\PhpParser\Node\Expr\Variable $variable) : string { $variableName = $this->getName($variable); if ($variableName === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $stringy = new Stringy($variableName); - return (string) $stringy->underscored() - ->toUpperCase(); + $stringy = new \RectorPrefix20210509\Stringy\Stringy($variableName); + return (string) $stringy->underscored()->toUpperCase(); } } diff --git a/rules/Privatization/Rector/Class_/FinalizeClassesWithoutChildrenRector.php b/rules/Privatization/Rector/Class_/FinalizeClassesWithoutChildrenRector.php index 9e81926edf5..3904a7a7ecd 100644 --- a/rules/Privatization/Rector/Class_/FinalizeClassesWithoutChildrenRector.php +++ b/rules/Privatization/Rector/Class_/FinalizeClassesWithoutChildrenRector.php @@ -1,7 +1,6 @@ classAnalyzer = $classAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Finalize every class that has no children', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Finalize every class that has no children', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class FirstClass { } @@ -43,8 +37,7 @@ class ThirdClass extends SecondClass { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class FirstClass { } @@ -57,46 +50,37 @@ final class ThirdClass extends SecondClass { } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->isFinal()) { return null; } - if ($node->isAbstract()) { return null; } - if ($this->classAnalyzer->isAnonymousClass($node)) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - if ($phpDocInfo->hasByAnnotationClasses(['Doctrine\ORM\Mapping\Entity', 'Doctrine\ORM\Mapping\Embeddable'])) { + if ($phpDocInfo->hasByAnnotationClasses(['Doctrine\\ORM\\Mapping\\Entity', 'Doctrine\\ORM\\Mapping\\Embeddable'])) { return null; } - if ($this->nodeRepository->hasClassChildren($node)) { return null; } - $this->visibilityManipulator->makeFinal($node); - return $node; } } diff --git a/rules/Privatization/Rector/Class_/RepeatedLiteralToClassConstantRector.php b/rules/Privatization/Rector/Class_/RepeatedLiteralToClassConstantRector.php index f33b64abf3a..232586ce944 100644 --- a/rules/Privatization/Rector/Class_/RepeatedLiteralToClassConstantRector.php +++ b/rules/Privatization/Rector/Class_/RepeatedLiteralToClassConstantRector.php @@ -1,10 +1,9 @@ classInsertManipulator = $classInsertManipulator; $this->scopeAwareNodeFinder = $scopeAwareNodeFinder; $this->reservedKeywordAnalyzer = $reservedKeywordAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replace repeated strings with constant', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replace repeated strings with constant', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($key, $items) @@ -89,8 +73,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -105,180 +88,136 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { // skip tests, where string values are often used as fixtures if ($this->isName($node, '*Test')) { return null; } - /** @var String_[] $strings */ - $strings = $this->betterNodeFinder->findInstanceOf($node, String_::class); - + $strings = $this->betterNodeFinder->findInstanceOf($node, \PhpParser\Node\Scalar\String_::class); $stringsToReplace = $this->resolveStringsToReplace($strings); if ($stringsToReplace === []) { return null; } - $this->replaceStringsWithClassConstReferences($node, $stringsToReplace); $this->addClassConsts($stringsToReplace, $node); - return $node; } - /** * @param String_[] $strings * @return string[] */ - private function resolveStringsToReplace(array $strings): array + private function resolveStringsToReplace(array $strings) : array { $stringsByValue = []; foreach ($strings as $string) { if ($this->shouldSkipString($string)) { continue; } - $stringsByValue[$string->value][] = $string; } - $stringsToReplace = []; - foreach ($stringsByValue as $value => $strings) { - if (count($strings) < self::MINIMAL_VALUE_OCCURRENCE) { + if (\count($strings) < self::MINIMAL_VALUE_OCCURRENCE) { continue; } - $stringsToReplace[] = $value; } - return $stringsToReplace; } - /** * @param string[] $stringsToReplace */ - private function replaceStringsWithClassConstReferences(Class_ $class, array $stringsToReplace): void + private function replaceStringsWithClassConstReferences(\PhpParser\Node\Stmt\Class_ $class, array $stringsToReplace) : void { - $this->traverseNodesWithCallable($class, function (Node $node) use ($stringsToReplace): ?ClassConstFetch { - if (! $node instanceof String_) { + $this->traverseNodesWithCallable($class, function (\PhpParser\Node $node) use($stringsToReplace) : ?ClassConstFetch { + if (!$node instanceof \PhpParser\Node\Scalar\String_) { return null; } - - if (! $this->valueResolver->isValues($node, $stringsToReplace)) { + if (!$this->valueResolver->isValues($node, $stringsToReplace)) { return null; } - $constantName = $this->createConstName($node->value); return $this->nodeFactory->createSelfFetchConstant($constantName, $node); }); } - /** * @param string[] $stringsToReplace */ - private function addClassConsts(array $stringsToReplace, Class_ $class): void + private function addClassConsts(array $stringsToReplace, \PhpParser\Node\Stmt\Class_ $class) : void { foreach ($stringsToReplace as $stringToReplace) { $constantName = $this->createConstName($stringToReplace); - - $classConst = $this->nodeFactory->createPrivateClassConst( - $constantName, - new String_($stringToReplace) - ); - + $classConst = $this->nodeFactory->createPrivateClassConst($constantName, new \PhpParser\Node\Scalar\String_($stringToReplace)); $this->classInsertManipulator->addConstantToClass($class, $stringToReplace, $classConst); } } - - private function shouldSkipString(String_ $string): bool + private function shouldSkipString(\PhpParser\Node\Scalar\String_ $string) : bool { $value = $string->value; - // value is too short - if (strlen($value) < 2) { - return true; + if (\strlen($value) < 2) { + return \true; } - if ($this->reservedKeywordAnalyzer->isReserved($value)) { - return true; + return \true; } - if ($this->isNativeConstantResemblingValue($value)) { - return true; + return \true; } - // is replaceable value? - $matches = Strings::match($value, '#(?<' . self::VALUE . '>[\w\-\/\\_]+)#'); - if (! isset($matches[self::VALUE])) { - return true; + $matches = \RectorPrefix20210509\Nette\Utils\Strings::match($value, '#(?<' . self::VALUE . '>[\\w\\-\\/\\_]+)#'); + if (!isset($matches[self::VALUE])) { + return \true; } - // skip values in another constants - $parentConst = $this->scopeAwareNodeFinder->findParentType($string, [ClassConst::class]); + $parentConst = $this->scopeAwareNodeFinder->findParentType($string, [\PhpParser\Node\Stmt\ClassConst::class]); if ($parentConst !== null) { - return true; + return \true; } - return $matches[self::VALUE] !== $string->value; } - - private function createConstName(string $value): string + private function createConstName(string $value) : string { // replace slashes and dashes - $value = Strings::replace($value, self::SLASH_AND_DASH_REGEX, self::UNDERSCORE); - + $value = \RectorPrefix20210509\Nette\Utils\Strings::replace($value, self::SLASH_AND_DASH_REGEX, self::UNDERSCORE); // find beginning numbers $beginningNumbers = ''; - - $matches = Strings::match($value, '#(?<' . self::NUMBERS . '>[0-9]*)(?<' . self::VALUE . '>.*)#'); - + $matches = \RectorPrefix20210509\Nette\Utils\Strings::match($value, '#(?<' . self::NUMBERS . '>[0-9]*)(?<' . self::VALUE . '>.*)#'); if (isset($matches[self::NUMBERS])) { $beginningNumbers = $matches[self::NUMBERS]; } - if (isset($matches[self::VALUE])) { $value = $matches[self::VALUE]; } - // convert camelcase parts to underscore - $parts = explode(self::UNDERSCORE, $value); - - $parts = array_map( - function (string $value): string { - return StaticRectorStrings::camelCaseToUnderscore($value); - }, - $parts - ); - + $parts = \explode(self::UNDERSCORE, $value); + $parts = \array_map(function (string $value) : string { + return \Rector\Core\Util\StaticRectorStrings::camelCaseToUnderscore($value); + }, $parts); // apply "CONST" prefix if constant beginning with number if ($beginningNumbers !== '') { - $parts = array_merge(['CONST', $beginningNumbers], $parts); + $parts = \array_merge(['CONST', $beginningNumbers], $parts); } - - $value = implode(self::UNDERSCORE, $parts); - - return strtoupper(Strings::replace($value, '#_+#', self::UNDERSCORE)); + $value = \implode(self::UNDERSCORE, $parts); + return \strtoupper(\RectorPrefix20210509\Nette\Utils\Strings::replace($value, '#_+#', self::UNDERSCORE)); } - - private function isNativeConstantResemblingValue(string $value): bool + private function isNativeConstantResemblingValue(string $value) : bool { - $loweredValue = strtolower($value); - - return in_array($loweredValue, ['true', 'false', 'bool', 'null'], true); + $loweredValue = \strtolower($value); + return \in_array($loweredValue, ['true', 'false', 'bool', 'null'], \true); } } diff --git a/rules/Privatization/Rector/MethodCall/PrivatizeLocalGetterToPropertyRector.php b/rules/Privatization/Rector/MethodCall/PrivatizeLocalGetterToPropertyRector.php index c0a1d0c82fd..1d4b32b9d31 100644 --- a/rules/Privatization/Rector/MethodCall/PrivatizeLocalGetterToPropertyRector.php +++ b/rules/Privatization/Rector/MethodCall/PrivatizeLocalGetterToPropertyRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->var instanceof Variable) { + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - - if (! $this->nodeNameResolver->isName($node->var, 'this')) { + if (!$this->nodeNameResolver->isName($node->var, 'this')) { return null; } - - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - $methodName = $this->getName($node->name); if ($methodName === null) { return null; } - $classMethod = $classLike->getMethod($methodName); - if (! $classMethod instanceof ClassMethod) { + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - return $this->matchLocalPropertyFetchInGetterMethod($classMethod); } - - private function matchLocalPropertyFetchInGetterMethod(ClassMethod $classMethod): ?PropertyFetch + private function matchLocalPropertyFetchInGetterMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PhpParser\Node\Expr\PropertyFetch { $stmts = (array) $classMethod->stmts; - if (count($stmts) !== 1) { + if (\count($stmts) !== 1) { return null; } - $onlyStmt = $stmts[0] ?? null; - if (! $onlyStmt instanceof Return_) { + if (!$onlyStmt instanceof \PhpParser\Node\Stmt\Return_) { return null; } - $returnedExpr = $onlyStmt->expr; - if (! $returnedExpr instanceof PropertyFetch) { + if (!$returnedExpr instanceof \PhpParser\Node\Expr\PropertyFetch) { return null; } - return $returnedExpr; } } diff --git a/rules/Privatization/Rector/MethodCall/ReplaceStringWithClassConstantRector.php b/rules/Privatization/Rector/MethodCall/ReplaceStringWithClassConstantRector.php index a4aec9c93c3..e263f202309 100644 --- a/rules/Privatization/Rector/MethodCall/ReplaceStringWithClassConstantRector.php +++ b/rules/Privatization/Rector/MethodCall/ReplaceStringWithClassConstantRector.php @@ -1,7 +1,6 @@ classConstantFetchValueFactory = $classConstantFetchValueFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replace string values in specific method call by constant of provided class', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replace string values in specific method call by constant of provided class', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -53,8 +45,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -63,90 +54,63 @@ class SomeClass } } CODE_SAMPLE -, - [ - self::REPLACE_STRING_WITH_CLASS_CONSTANT => [ - new ReplaceStringWithClassConstant('SomeClass', 'call', 0, 'Placeholder'), - ], - ] - ), - ]); +, [self::REPLACE_STRING_WITH_CLASS_CONSTANT => [new \Rector\Privatization\ValueObject\ReplaceStringWithClassConstant('SomeClass', 'call', 0, 'Placeholder')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->args === []) { return null; } - - $hasChanged = false; - + $hasChanged = \false; foreach ($this->replaceStringWithClassConstants as $replaceStringWithClassConstant) { $desiredArg = $this->matchArg($node, $replaceStringWithClassConstant); - if (! $desiredArg instanceof Arg) { + if (!$desiredArg instanceof \PhpParser\Node\Arg) { continue; } - - $classConstFetch = $this->classConstantFetchValueFactory->create( - $desiredArg->value, - $replaceStringWithClassConstant->getClassWithConstants() - ); - - if (! $classConstFetch instanceof ClassConstFetch) { + $classConstFetch = $this->classConstantFetchValueFactory->create($desiredArg->value, $replaceStringWithClassConstant->getClassWithConstants()); + if (!$classConstFetch instanceof \PhpParser\Node\Expr\ClassConstFetch) { continue; } - $desiredArg->value = $classConstFetch; - $hasChanged = true; + $hasChanged = \true; } - if ($hasChanged) { return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->replaceStringWithClassConstants = $configuration[self::REPLACE_STRING_WITH_CLASS_CONSTANT] ?? []; } - - private function matchArg( - MethodCall $methodCall, - ReplaceStringWithClassConstant $replaceStringWithClassConstant - ): ?Arg { - if (! $this->isObjectType($methodCall->var, $replaceStringWithClassConstant->getObjectType())) { + private function matchArg(\PhpParser\Node\Expr\MethodCall $methodCall, \Rector\Privatization\ValueObject\ReplaceStringWithClassConstant $replaceStringWithClassConstant) : ?\PhpParser\Node\Arg + { + if (!$this->isObjectType($methodCall->var, $replaceStringWithClassConstant->getObjectType())) { return null; } - - if (! $this->isName($methodCall->name, $replaceStringWithClassConstant->getMethod())) { + if (!$this->isName($methodCall->name, $replaceStringWithClassConstant->getMethod())) { return null; } - $desiredArg = $methodCall->args[$replaceStringWithClassConstant->getArgPosition()] ?? null; - if (! $desiredArg instanceof Arg) { + if (!$desiredArg instanceof \PhpParser\Node\Arg) { return null; } - - if ($desiredArg->value instanceof ClassConstFetch) { + if ($desiredArg->value instanceof \PhpParser\Node\Expr\ClassConstFetch) { return null; } - return $desiredArg; } } diff --git a/rules/Privatization/Rector/Property/ChangeReadOnlyPropertyWithDefaultValueToConstantRector.php b/rules/Privatization/Rector/Property/ChangeReadOnlyPropertyWithDefaultValueToConstantRector.php index fab23b5e01c..9a5d7cdbbe2 100644 --- a/rules/Privatization/Rector/Property/ChangeReadOnlyPropertyWithDefaultValueToConstantRector.php +++ b/rules/Privatization/Rector/Property/ChangeReadOnlyPropertyWithDefaultValueToConstantRector.php @@ -1,7 +1,6 @@ propertyManipulator = $propertyManipulator; $this->classConstantFactory = $classConstantFactory; $this->propertyFetchWithConstFetchReplacer = $propertyFetchWithConstFetchReplacer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change property with read only status with default value to constant', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change property with read only status with default value to constant', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -72,8 +59,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -92,63 +78,50 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var PropertyProperty $onlyProperty */ $onlyProperty = $node->props[0]; - // we need default value if ($onlyProperty->default === null) { return null; } - - if (! $node->isPrivate()) { + if (!$node->isPrivate()) { return null; } - // is property read only? if ($this->propertyManipulator->isPropertyChangeable($node)) { return null; } - /** @var Class_ $classLike */ - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); $this->propertyFetchWithConstFetchReplacer->replace($classLike, $node); - return $this->classConstantFactory->createFromProperty($node); } - - private function shouldSkip(Property $property): bool + private function shouldSkip(\PhpParser\Node\Stmt\Property $property) : bool { - if (count($property->props) !== 1) { - return true; + if (\count($property->props) !== 1) { + return \true; } - - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return true; + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \true; } - - return $this->isObjectType($classLike, new ObjectType('PHP_CodeSniffer\Sniffs\Sniff')); + return $this->isObjectType($classLike, new \PHPStan\Type\ObjectType('PHP_CodeSniffer\\Sniffs\\Sniff')); } } diff --git a/rules/Privatization/Rector/Property/PrivatizeFinalClassPropertyRector.php b/rules/Privatization/Rector/Property/PrivatizeFinalClassPropertyRector.php index 1591a554f97..5d614ccd313 100644 --- a/rules/Privatization/Rector/Property/PrivatizeFinalClassPropertyRector.php +++ b/rules/Privatization/Rector/Property/PrivatizeFinalClassPropertyRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - - if (! $classLike->isFinal()) { + if (!$classLike->isFinal()) { return null; } - if ($this->shouldSkipProperty($node)) { return null; } - if ($classLike->extends === null) { $this->visibilityManipulator->makePrivate($node); return $node; } - if ($this->isPropertyVisibilityGuardedByParent($node, $classLike)) { return null; } - $this->visibilityManipulator->makePrivate($node); - return $node; } - - private function shouldSkipProperty(Property $property): bool + private function shouldSkipProperty(\PhpParser\Node\Stmt\Property $property) : bool { - if (count($property->props) !== 1) { - return true; + if (\count($property->props) !== 1) { + return \true; } - - return ! $property->isProtected(); + return !$property->isProtected(); } - - private function isPropertyVisibilityGuardedByParent(Property $property, Class_ $class): bool + private function isPropertyVisibilityGuardedByParent(\PhpParser\Node\Stmt\Property $property, \PhpParser\Node\Stmt\Class_ $class) : bool { if ($class->extends === null) { - return false; + return \false; } - /** @var Scope $scope */ - $scope = $property->getAttribute(AttributeKey::SCOPE); - + $scope = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); /** @var ClassReflection $classReflection */ $classReflection = $scope->getClassReflection(); - $propertyName = $this->getName($property); - foreach ($classReflection->getParents() as $parentClassReflection) { if ($parentClassReflection->hasProperty($propertyName)) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/Privatization/Rector/Property/PrivatizeLocalPropertyToPrivatePropertyRector.php b/rules/Privatization/Rector/Property/PrivatizeLocalPropertyToPrivatePropertyRector.php index c4aa8847dd7..81b63480a71 100644 --- a/rules/Privatization/Rector/Property/PrivatizeLocalPropertyToPrivatePropertyRector.php +++ b/rules/Privatization/Rector/Property/PrivatizeLocalPropertyToPrivatePropertyRector.php @@ -1,7 +1,6 @@ propertyVisibilityVendorLockResolver = $propertyVisibilityVendorLockResolver; - - $this->excludedObjectTypes = [ - new ObjectType('PHPUnit\Framework\TestCase'), - new ObjectType('PHP_CodeSniffer\Sniffs\Sniff'), - ]; + $this->excludedObjectTypes = [new \PHPStan\Type\ObjectType('PHPUnit\\Framework\\TestCase'), new \PHPStan\Type\ObjectType('PHP_CodeSniffer\\Sniffs\\Sniff')]; $this->classAnalyzer = $classAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Privatize local-only property to private property', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Privatize local-only property to private property', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public $value; @@ -75,8 +60,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { private $value; @@ -87,104 +71,81 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - $propertyFetches = $this->nodeRepository->findPropertyFetchesByProperty($node); - $usedPropertyFetchClassNames = []; foreach ($propertyFetches as $propertyFetch) { - $usedPropertyFetchClassNames[] = $propertyFetch->getAttribute(AttributeKey::CLASS_NAME); + $usedPropertyFetchClassNames[] = $propertyFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); } - - $usedPropertyFetchClassNames = array_unique($usedPropertyFetchClassNames); - - $propertyClassName = $node->getAttribute(AttributeKey::CLASS_NAME); - + $usedPropertyFetchClassNames = \array_unique($usedPropertyFetchClassNames); + $propertyClassName = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); // has external usage if ($usedPropertyFetchClassNames !== [] && [$propertyClassName] !== $usedPropertyFetchClassNames) { return null; } - $this->visibilityManipulator->makePrivate($node); - return $node; } - - private function shouldSkip(Property $property): bool + private function shouldSkip(\PhpParser\Node\Stmt\Property $property) : bool { - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { - return true; + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { + return \true; } - if ($this->shouldSkipClass($classLike)) { - return true; + return \true; } - if ($this->shouldSkipProperty($property)) { - return true; + return \true; } - // is parent required property? skip it if ($this->propertyVisibilityVendorLockResolver->isParentLockedProperty($property)) { - return true; + return \true; } - if ($this->propertyVisibilityVendorLockResolver->isChildLockedProperty($property)) { - return true; + return \true; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); return $phpDocInfo->hasByNames(self::TAGS_REQUIRING_PUBLIC_PROPERTY); } - - private function shouldSkipClass(ClassLike $classLike): bool + private function shouldSkipClass(\PhpParser\Node\Stmt\ClassLike $classLike) : bool { - if (! $classLike instanceof Class_) { - return true; + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \true; } - if ($this->classAnalyzer->isAnonymousClass($classLike)) { - return true; + return \true; } - if ($this->nodeTypeResolver->isObjectTypes($classLike, $this->excludedObjectTypes)) { - return true; + return \true; } - - if (! $classLike->isAbstract()) { - return false; + if (!$classLike->isAbstract()) { + return \false; } - return $this->isOpenSourceProjectType(); } - - private function shouldSkipProperty(Property $property): bool + private function shouldSkipProperty(\PhpParser\Node\Stmt\Property $property) : bool { // already private if ($property->isPrivate()) { - return true; + return \true; } - // skip for now return $property->isStatic(); } diff --git a/rules/Privatization/Reflection/ClassConstantsResolver.php b/rules/Privatization/Reflection/ClassConstantsResolver.php index 5a1c0cb64db..88854e709c4 100644 --- a/rules/Privatization/Reflection/ClassConstantsResolver.php +++ b/rules/Privatization/Reflection/ClassConstantsResolver.php @@ -1,47 +1,38 @@ > */ private $cachedConstantNamesToValues = []; - /** * @var ReflectionProvider */ private $reflectionProvider; - - public function __construct(ReflectionProvider $reflectionProvider) + public function __construct(\PHPStan\Reflection\ReflectionProvider $reflectionProvider) { $this->reflectionProvider = $reflectionProvider; } - /** * @return array */ - public function getClassConstantNamesToValues(string $classWithConstants): array + public function getClassConstantNamesToValues(string $classWithConstants) : array { if (isset($this->cachedConstantNamesToValues[$classWithConstants])) { return $this->cachedConstantNamesToValues[$classWithConstants]; } - - if (! $this->reflectionProvider->hasClass($classWithConstants)) { + if (!$this->reflectionProvider->hasClass($classWithConstants)) { return []; } - $classReflection = $this->reflectionProvider->getClass($classWithConstants); $reflectionClass = $classReflection->getNativeReflection(); - $constantNamesToValues = $reflectionClass->getConstants(); $this->cachedConstantNamesToValues = $constantNamesToValues; - return $constantNamesToValues; } } diff --git a/rules/Privatization/TypeManipulator/NormalizeTypeToRespectArrayScalarType.php b/rules/Privatization/TypeManipulator/NormalizeTypeToRespectArrayScalarType.php index 606fab94efd..5b3f05e4f9c 100644 --- a/rules/Privatization/TypeManipulator/NormalizeTypeToRespectArrayScalarType.php +++ b/rules/Privatization/TypeManipulator/NormalizeTypeToRespectArrayScalarType.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; } - - public function normalizeToArray(Type $type, ?Node $returnNode): Type + public function normalizeToArray(\PHPStan\Type\Type $type, ?\PhpParser\Node $returnNode) : \PHPStan\Type\Type { if ($returnNode === null) { return $type; } - - if (! $this->nodeNameResolver->isName($returnNode, 'array')) { + if (!$this->nodeNameResolver->isName($returnNode, 'array')) { return $type; } - - if ($type instanceof UnionType) { + if ($type instanceof \PHPStan\Type\UnionType) { return $this->normalizeUnionType($type); } - - if ($type instanceof MixedType) { - return new ArrayType($type, $type); + if ($type instanceof \PHPStan\Type\MixedType) { + return new \PHPStan\Type\ArrayType($type, $type); } - return $type; } - - private function normalizeUnionType(UnionType $unionType): UnionType + private function normalizeUnionType(\PHPStan\Type\UnionType $unionType) : \PHPStan\Type\UnionType { $normalizedTypes = []; foreach ($unionType->getTypes() as $unionedType) { - if ($unionedType instanceof MixedType) { - $normalizedTypes[] = new ArrayType($unionedType, $unionedType); + if ($unionedType instanceof \PHPStan\Type\MixedType) { + $normalizedTypes[] = new \PHPStan\Type\ArrayType($unionedType, $unionedType); continue; } - $normalizedTypes[] = $unionedType; } - if ($unionType->getTypes() === $normalizedTypes) { return $unionType; } - - return new UnionType($normalizedTypes); + return new \PHPStan\Type\UnionType($normalizedTypes); } } diff --git a/rules/Privatization/ValueObject/ConstantVisibility.php b/rules/Privatization/ValueObject/ConstantVisibility.php index d7401a8d74b..c7ae7375081 100644 --- a/rules/Privatization/ValueObject/ConstantVisibility.php +++ b/rules/Privatization/ValueObject/ConstantVisibility.php @@ -1,7 +1,6 @@ isPublic = $isPublic; $this->isProtected = $isProtected; $this->isPrivate = $isPrivate; } - - public function isPublic(): bool + public function isPublic() : bool { return $this->isPublic; } - - public function isProtected(): bool + public function isProtected() : bool { return $this->isProtected; } - - public function isPrivate(): bool + public function isPrivate() : bool { return $this->isPrivate; } diff --git a/rules/Privatization/ValueObject/ReplaceStringWithClassConstant.php b/rules/Privatization/ValueObject/ReplaceStringWithClassConstant.php index 08282786f5d..a05e1bb62a3 100644 --- a/rules/Privatization/ValueObject/ReplaceStringWithClassConstant.php +++ b/rules/Privatization/ValueObject/ReplaceStringWithClassConstant.php @@ -1,33 +1,27 @@ classWithConstants = $classWithConstants; $this->argPosition = $argPosition; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } - /** * @return class-string */ - public function getClassWithConstants(): string + public function getClassWithConstants() : string { return $this->classWithConstants; } - - public function getArgPosition(): int + public function getArgPosition() : int { return $this->argPosition; } diff --git a/rules/Privatization/VisibilityGuard/ClassMethodVisibilityGuard.php b/rules/Privatization/VisibilityGuard/ClassMethodVisibilityGuard.php index 03f15cd5b5c..6dc2b34e7a3 100644 --- a/rules/Privatization/VisibilityGuard/ClassMethodVisibilityGuard.php +++ b/rules/Privatization/VisibilityGuard/ClassMethodVisibilityGuard.php @@ -1,73 +1,55 @@ nodeNameResolver = $nodeNameResolver; } - - public function isClassMethodVisibilityGuardedByParent( - ClassMethod $classMethod, - ClassReflection $classReflection - ): bool { + public function isClassMethodVisibilityGuardedByParent(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Reflection\ClassReflection $classReflection) : bool + { $methodName = $this->nodeNameResolver->getName($classMethod); - /** @var ClassReflection[] $parentClassReflections */ - $parentClassReflections = array_merge($classReflection->getParents(), $classReflection->getInterfaces()); - + $parentClassReflections = \array_merge($classReflection->getParents(), $classReflection->getInterfaces()); foreach ($parentClassReflections as $parentClassReflection) { if ($parentClassReflection->hasMethod($methodName)) { - return true; + return \true; } } - - return false; + return \false; } - - public function isClassMethodVisibilityGuardedByTrait( - ClassMethod $classMethod, - ClassReflection $classReflection - ): bool { + public function isClassMethodVisibilityGuardedByTrait(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Reflection\ClassReflection $classReflection) : bool + { $parentTraitReflections = $this->getLocalAndParentTraitReflections($classReflection); - $methodName = $this->nodeNameResolver->getName($classMethod); - foreach ($parentTraitReflections as $parentTraitReflection) { if ($parentTraitReflection->hasMethod($methodName)) { - return true; + return \true; } } - - return false; + return \false; } - /** * @return ClassReflection[] */ - private function getLocalAndParentTraitReflections(ClassReflection $classReflection): array + private function getLocalAndParentTraitReflections(\PHPStan\Reflection\ClassReflection $classReflection) : array { $traitReflections = $classReflection->getTraits(); - foreach ($classReflection->getParents() as $parentClassReflection) { foreach ($parentClassReflection->getTraits() as $parentTraitReflection) { $traitReflections[] = $parentTraitReflection; } } - return $traitReflections; } } diff --git a/rules/Removing/NodeManipulator/ComplexNodeRemover.php b/rules/Removing/NodeManipulator/ComplexNodeRemover.php index f4708d55e2a..4d1d3e32835 100644 --- a/rules/Removing/NodeManipulator/ComplexNodeRemover.php +++ b/rules/Removing/NodeManipulator/ComplexNodeRemover.php @@ -1,7 +1,6 @@ classMethodRemover = $classMethodRemover; $this->assignRemover = $assignRemover; $this->propertyFetchFinder = $propertyFetchFinder; @@ -85,140 +67,109 @@ final class ComplexNodeRemover $this->nodesToRemoveCollector = $nodesToRemoveCollector; $this->nodeComparator = $nodeComparator; } - - public function removeClassMethodAndUsages(ClassMethod $classMethod): void + public function removeClassMethodAndUsages(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { $this->classMethodRemover->removeClassMethodAndUsages($classMethod); } - /** * @param string[] $classMethodNamesToSkip */ - public function removePropertyAndUsages(Property $property, array $classMethodNamesToSkip = []): void + public function removePropertyAndUsages(\PhpParser\Node\Stmt\Property $property, array $classMethodNamesToSkip = []) : void { - $shouldKeepProperty = false; - + $shouldKeepProperty = \false; $propertyFetches = $this->propertyFetchFinder->findPrivatePropertyFetches($property); - foreach ($propertyFetches as $propertyFetch) { if ($this->shouldSkipPropertyForClassMethod($propertyFetch, $classMethodNamesToSkip)) { - $shouldKeepProperty = true; + $shouldKeepProperty = \true; continue; } - // remove assigns $assign = $this->resolveAssign($propertyFetch); $this->assignRemover->removeAssignNode($assign); - $this->removeConstructorDependency($assign); } - if ($shouldKeepProperty) { return; } - // remove __construct param - /** @var Property $property */ $this->nodeRemover->removeNode($property); - foreach ($property->props as $prop) { - if (! $this->nodesToRemoveCollector->isNodeRemoved($prop)) { + if (!$this->nodesToRemoveCollector->isNodeRemoved($prop)) { // if the property has at least one node left -> return return; } } - $this->nodeRemover->removeNode($property); } - /** * @param StaticPropertyFetch|PropertyFetch $expr * @param string[] $classMethodNamesToSkip */ - private function shouldSkipPropertyForClassMethod(Expr $expr, array $classMethodNamesToSkip): bool + private function shouldSkipPropertyForClassMethod(\PhpParser\Node\Expr $expr, array $classMethodNamesToSkip) : bool { - $classMethodNode = $expr->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethodNode instanceof ClassMethod) { - return false; + $classMethodNode = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethodNode instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - $classMethodName = $this->nodeNameResolver->getName($classMethodNode); - return in_array($classMethodName, $classMethodNamesToSkip, true); + return \in_array($classMethodName, $classMethodNamesToSkip, \true); } - /** * @param PropertyFetch|StaticPropertyFetch $expr */ - private function resolveAssign(Expr $expr): Assign + private function resolveAssign(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\Assign { - $assign = $expr->getAttribute(AttributeKey::PARENT_NODE); - - while ($assign !== null && ! $assign instanceof Assign) { - $assign = $assign->getAttribute(AttributeKey::PARENT_NODE); + $assign = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + while ($assign !== null && !$assign instanceof \PhpParser\Node\Expr\Assign) { + $assign = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); } - - if (! $assign instanceof Assign) { - throw new ShouldNotHappenException("Can't handle this situation"); + if (!$assign instanceof \PhpParser\Node\Expr\Assign) { + throw new \Rector\Core\Exception\ShouldNotHappenException("Can't handle this situation"); } - return $assign; } - - private function removeConstructorDependency(Assign $assign): void + private function removeConstructorDependency(\PhpParser\Node\Expr\Assign $assign) : void { - $classMethod = $assign->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { + $classMethod = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - - if (! $this->nodeNameResolver->isName($classMethod, MethodName::CONSTRUCT)) { + if (!$this->nodeNameResolver->isName($classMethod, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { return; } - - $class = $assign->getAttribute(AttributeKey::CLASS_NODE); - if (! $class instanceof Class_) { + $class = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$class instanceof \PhpParser\Node\Stmt\Class_) { return; } - - $constructClassMethod = $class->getMethod(MethodName::CONSTRUCT); - if (! $constructClassMethod instanceof ClassMethod) { + $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - foreach ($constructClassMethod->getParams() as $param) { - $variable = $this->betterNodeFinder->findFirst((array) $constructClassMethod->stmts, function (Node $node) use ( - $param - ): bool { + $variable = $this->betterNodeFinder->findFirst((array) $constructClassMethod->stmts, function (\PhpParser\Node $node) use($param) : bool { return $this->nodeComparator->areNodesEqual($param->var, $node); }); - - if (! $variable instanceof Node) { + if (!$variable instanceof \PhpParser\Node) { continue; } - if ($this->isExpressionVariableNotAssign($variable)) { continue; } - - if (! $this->nodeComparator->areNodesEqual($param->var, $assign->expr)) { + if (!$this->nodeComparator->areNodesEqual($param->var, $assign->expr)) { continue; } - $this->nodeRemover->removeNode($param); } } - - private function isExpressionVariableNotAssign(Node $node): bool + private function isExpressionVariableNotAssign(\PhpParser\Node $node) : bool { if ($node !== null) { - $expressionVariable = $node->getAttribute(AttributeKey::PARENT_NODE); - - if (! $expressionVariable instanceof Assign) { - return true; + $expressionVariable = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$expressionVariable instanceof \PhpParser\Node\Expr\Assign) { + return \true; } } - - return false; + return \false; } } diff --git a/rules/Removing/Rector/ClassMethod/ArgumentRemoverRector.php b/rules/Removing/Rector/ClassMethod/ArgumentRemoverRector.php index 250c0c67c3e..2fa9f11bacf 100644 --- a/rules/Removing/Rector/ClassMethod/ArgumentRemoverRector.php +++ b/rules/Removing/Rector/ClassMethod/ArgumentRemoverRector.php @@ -1,7 +1,6 @@ someMethod(true); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someObject = new SomeClass; $someObject->someMethod();' CODE_SAMPLE - , - [ - self::REMOVED_ARGUMENTS => [new ArgumentRemover('ExampleClass', 'someMethod', 0, 'true')], - ] - ), - ] - ); +, [self::REMOVED_ARGUMENTS => [new \Rector\Removing\ValueObject\ArgumentRemover('ExampleClass', 'someMethod', 0, 'true')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class, StaticCall::class, ClassMethod::class]; + return [\PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param MethodCall|StaticCall|ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->removedArguments as $removedArgument) { - if (! $this->nodeTypeResolver->isMethodStaticCallOrClassMethodObjectType( - $node, - $removedArgument->getObjectType() - )) { + if (!$this->nodeTypeResolver->isMethodStaticCallOrClassMethodObjectType($node, $removedArgument->getObjectType())) { continue; } - - if (! $this->isName($node->name, $removedArgument->getMethod())) { + if (!$this->isName($node->name, $removedArgument->getMethod())) { continue; } - $this->processPosition($node, $removedArgument); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $removedArguments = $configuration[self::REMOVED_ARGUMENTS] ?? []; - Assert::allIsInstanceOf($removedArguments, ArgumentRemover::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($removedArguments, \Rector\Removing\ValueObject\ArgumentRemover::class); $this->removedArguments = $removedArguments; } - /** * @param ClassMethod|StaticCall|MethodCall $node */ - private function processPosition(Node $node, ArgumentRemover $argumentRemover): void + private function processPosition(\PhpParser\Node $node, \Rector\Removing\ValueObject\ArgumentRemover $argumentRemover) : void { if ($argumentRemover->getValue() === null) { - if ($node instanceof MethodCall || $node instanceof StaticCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall || $node instanceof \PhpParser\Node\Expr\StaticCall) { $this->nodeRemover->removeArg($node, $argumentRemover->getPosition()); } else { $this->nodeRemover->removeParam($node, $argumentRemover->getPosition()); } - return; } - $match = $argumentRemover->getValue(); if (isset($match['name'])) { $this->removeByName($node, $argumentRemover->getPosition(), $match['name']); return; } - // only argument specific value can be removed - if ($node instanceof ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - - if (! isset($node->args[$argumentRemover->getPosition()])) { + if (!isset($node->args[$argumentRemover->getPosition()])) { return; } - if ($this->isArgumentValueMatch($node->args[$argumentRemover->getPosition()], $match)) { $this->nodeRemover->removeArg($node, $argumentRemover->getPosition()); } } - /** * @param ClassMethod|StaticCall|MethodCall $node */ - private function removeByName(Node $node, int $position, string $name): void + private function removeByName(\PhpParser\Node $node, int $position, string $name) : void { - if ($node instanceof MethodCall || $node instanceof StaticCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall || $node instanceof \PhpParser\Node\Expr\StaticCall) { if (isset($node->args[$position]) && $this->isName($node->args[$position], $name)) { $this->nodeRemover->removeArg($node, $position); } - return; } - - if (! (isset($node->params[$position]) && $this->isName($node->params[$position], $name))) { + if (!(isset($node->params[$position]) && $this->isName($node->params[$position], $name))) { return; } - $this->nodeRemover->removeParam($node, $position); } - /** * @param mixed[] $values */ - private function isArgumentValueMatch(Arg $arg, array $values): bool + private function isArgumentValueMatch(\PhpParser\Node\Arg $arg, array $values) : bool { $nodeValue = $this->valueResolver->getValue($arg->value); - return in_array($nodeValue, $values, true); + return \in_array($nodeValue, $values, \true); } } diff --git a/rules/Removing/Rector/Class_/RemoveInterfacesRector.php b/rules/Removing/Rector/Class_/RemoveInterfacesRector.php index d82f2f45cb4..b1cd4fc85f3 100644 --- a/rules/Removing/Rector/Class_/RemoveInterfacesRector.php +++ b/rules/Removing/Rector/Class_/RemoveInterfacesRector.php @@ -1,7 +1,6 @@ ['SomeInterface'], - ] - ), - ]); +, [self::INTERFACES_TO_REMOVE => ['SomeInterface']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->implements === []) { return null; } - foreach ($node->implements as $key => $implement) { if ($this->isNames($implement, $this->interfacesToRemove)) { unset($node->implements[$key]); } } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->interfacesToRemove = $configuration[self::INTERFACES_TO_REMOVE] ?? []; } diff --git a/rules/Removing/Rector/Class_/RemoveParentRector.php b/rules/Removing/Rector/Class_/RemoveParentRector.php index df4d381d514..ebf5067295e 100644 --- a/rules/Removing/Rector/Class_/RemoveParentRector.php +++ b/rules/Removing/Rector/Class_/RemoveParentRector.php @@ -1,7 +1,6 @@ parentClassScopeResolver = $parentClassScopeResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Removes extends class by name', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Removes extends class by name', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' final class SomeClass extends SomeParentClass { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { } CODE_SAMPLE - , - [ - self::PARENT_TYPES_TO_REMOVE => ['SomeParentClass'], - ] - ), - ]); +, [self::PARENT_TYPES_TO_REMOVE => ['SomeParentClass']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $parentClassName = $this->parentClassScopeResolver->resolveParentClassName($node); if ($parentClassName === null) { return null; } - foreach ($this->parentClassesToRemove as $parentClassToRemove) { if ($parentClassName !== $parentClassToRemove) { continue; } - // remove parent class $node->extends = null; - return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->parentClassesToRemove = $configuration[self::PARENT_TYPES_TO_REMOVE] ?? []; } diff --git a/rules/Removing/Rector/Class_/RemoveTraitRector.php b/rules/Removing/Rector/Class_/RemoveTraitRector.php index e010141591b..cf2058f21da 100644 --- a/rules/Removing/Rector/Class_/RemoveTraitRector.php +++ b/rules/Removing/Rector/Class_/RemoveTraitRector.php @@ -1,7 +1,6 @@ classManipulator = $classManipulator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Remove specific traits from code', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove specific traits from code', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { use SomeTrait; } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { } CODE_SAMPLE -, - [ - self::TRAITS_TO_REMOVE => ['TraitNameToRemove'], - ] - ), - ]); +, [self::TRAITS_TO_REMOVE => ['TraitNameToRemove']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class, Trait_::class]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Stmt\Trait_::class]; } - /** * @param Class_|Trait_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $usedTraits = $this->classManipulator->getUsedTraits($node); if ($usedTraits === []) { return null; } - - $this->classHasChanged = false; + $this->classHasChanged = \false; $this->removeTraits($usedTraits); - // invoke re-print if ($this->classHasChanged) { - $node->setAttribute(AttributeKey::ORIGINAL_NODE, null); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->traitsToRemove = $configuration[self::TRAITS_TO_REMOVE] ?? []; } - /** * @param Name[] $usedTraits */ - private function removeTraits(array $usedTraits): void + private function removeTraits(array $usedTraits) : void { foreach ($usedTraits as $usedTrait) { foreach ($this->traitsToRemove as $traitToRemove) { - if (! $this->isName($usedTrait, $traitToRemove)) { + if (!$this->isName($usedTrait, $traitToRemove)) { continue; } - $this->removeNode($usedTrait); - $this->classHasChanged = true; + $this->classHasChanged = \true; continue 2; } } diff --git a/rules/Removing/Rector/FuncCall/RemoveFuncCallArgRector.php b/rules/Removing/Rector/FuncCall/RemoveFuncCallArgRector.php index 91cd4cb73fb..3b4662f17b5 100644 --- a/rules/Removing/Rector/FuncCall/RemoveFuncCallArgRector.php +++ b/rules/Removing/Rector/FuncCall/RemoveFuncCallArgRector.php @@ -1,7 +1,6 @@ [new RemoveFuncCallArg('remove_last_arg', 1)], - ] - ), - ]); +, [self::REMOVED_FUNCTION_ARGUMENTS => [new \Rector\Removing\ValueObject\RemoveFuncCallArg('remove_last_arg', 1)]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node->name instanceof Expr) { + if ($node->name instanceof \PhpParser\Node\Expr) { return null; } - foreach ($this->removedFunctionArguments as $removedFunctionArgument) { - if (! $this->isName($node->name, $removedFunctionArgument->getFunction())) { + if (!$this->isName($node->name, $removedFunctionArgument->getFunction())) { continue; } - - foreach (array_keys($node->args) as $position) { + foreach (\array_keys($node->args) as $position) { if ($removedFunctionArgument->getArgumentPosition() !== $position) { continue; } - $this->nodeRemover->removeArg($node, $position); } } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $removedFunctionArguments = $configuration[self::REMOVED_FUNCTION_ARGUMENTS] ?? []; - Assert::allIsInstanceOf($removedFunctionArguments, RemoveFuncCallArg::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($removedFunctionArguments, \Rector\Removing\ValueObject\RemoveFuncCallArg::class); $this->removedFunctionArguments = $removedFunctionArguments; } } diff --git a/rules/Removing/Rector/FuncCall/RemoveFuncCallRector.php b/rules/Removing/Rector/FuncCall/RemoveFuncCallRector.php index 07fbec99eb9..7633efaa80f 100644 --- a/rules/Removing/Rector/FuncCall/RemoveFuncCallRector.php +++ b/rules/Removing/Rector/FuncCall/RemoveFuncCallRector.php @@ -1,7 +1,6 @@ breakingRemovalGuard = $breakingRemovalGuard; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - $configuration = [ - self::REMOVE_FUNC_CALLS => [ - new RemoveFuncCall('ini_get', [ - 1 => ['y2k_compliance'], - ]), - ], - ]; - return new RuleDefinition( - 'Remove ini_get by configuration', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + $configuration = [self::REMOVE_FUNC_CALLS => [new \Rector\Removing\ValueObject\RemoveFuncCall('ini_get', [1 => ['y2k_compliance']])]]; + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove ini_get by configuration', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' ini_get('y2k_compliance'); ini_get('keep_me'); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' ini_get('keep_me'); CODE_SAMPLE - , - $configuration - ), ] - ); +, $configuration)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->removeFuncCalls as $removeFuncCall) { - if (! $this->isName($node, $removeFuncCall->getFuncCall())) { + if (!$this->isName($node, $removeFuncCall->getFuncCall())) { continue; } - if ($removeFuncCall->getArgumentPositionAndValues() === []) { $this->removeNode($node); return null; } - $this->refactorFuncCallsWithPositions($node, $removeFuncCall); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $removeFuncCalls = $configuration[self::REMOVE_FUNC_CALLS] ?? []; - Assert::allIsInstanceOf($removeFuncCalls, RemoveFuncCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($removeFuncCalls, \Rector\Removing\ValueObject\RemoveFuncCall::class); $this->removeFuncCalls = $removeFuncCalls; } - - private function refactorFuncCallsWithPositions(FuncCall $funcCall, RemoveFuncCall $removeFuncCall): void + private function refactorFuncCallsWithPositions(\PhpParser\Node\Expr\FuncCall $funcCall, \Rector\Removing\ValueObject\RemoveFuncCall $removeFuncCall) : void { foreach ($removeFuncCall->getArgumentPositionAndValues() as $argumentPosition => $values) { - if (! $this->isArgumentPositionValueMatch($funcCall, $argumentPosition, $values)) { + if (!$this->isArgumentPositionValueMatch($funcCall, $argumentPosition, $values)) { continue; } - if ($this->breakingRemovalGuard->isLegalNodeRemoval($funcCall)) { $this->removeNode($funcCall); } } } - /** * @param mixed[] $values */ - private function isArgumentPositionValueMatch(FuncCall $funcCall, int $argumentPosition, array $values): bool + private function isArgumentPositionValueMatch(\PhpParser\Node\Expr\FuncCall $funcCall, int $argumentPosition, array $values) : bool { - if (! isset($funcCall->args[$argumentPosition])) { - return false; + if (!isset($funcCall->args[$argumentPosition])) { + return \false; } - return $this->valueResolver->isValues($funcCall->args[$argumentPosition]->value, $values); } } diff --git a/rules/Removing/ValueObject/ArgumentRemover.php b/rules/Removing/ValueObject/ArgumentRemover.php index 9cffc9be2d0..e9f2e03e6a1 100644 --- a/rules/Removing/ValueObject/ArgumentRemover.php +++ b/rules/Removing/ValueObject/ArgumentRemover.php @@ -1,33 +1,27 @@ position = $position; $this->value = $value; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } - - public function getPosition(): int + public function getPosition() : int { return $this->position; } - /** * @return mixed */ diff --git a/rules/Removing/ValueObject/RemoveFuncCall.php b/rules/Removing/ValueObject/RemoveFuncCall.php index 9853b46d819..7de81f36266 100644 --- a/rules/Removing/ValueObject/RemoveFuncCall.php +++ b/rules/Removing/ValueObject/RemoveFuncCall.php @@ -1,7 +1,6 @@ */ private $argumentPositionAndValues = []; - /** * @param array $argumentPositionAndValues */ @@ -24,16 +21,14 @@ final class RemoveFuncCall $this->funcCall = $funcCall; $this->argumentPositionAndValues = $argumentPositionAndValues; } - - public function getFuncCall(): string + public function getFuncCall() : string { return $this->funcCall; } - /** * @return array */ - public function getArgumentPositionAndValues(): array + public function getArgumentPositionAndValues() : array { return $this->argumentPositionAndValues; } diff --git a/rules/Removing/ValueObject/RemoveFuncCallArg.php b/rules/Removing/ValueObject/RemoveFuncCallArg.php index 514cb48c501..38c95ba4036 100644 --- a/rules/Removing/ValueObject/RemoveFuncCallArg.php +++ b/rules/Removing/ValueObject/RemoveFuncCallArg.php @@ -1,7 +1,6 @@ function = $function; $this->argumentPosition = $argumentPosition; } - - public function getFunction(): string + public function getFunction() : string { return $this->function; } - - public function getArgumentPosition(): int + public function getArgumentPosition() : int { return $this->argumentPosition; } diff --git a/rules/RemovingStatic/NodeAnalyzer/SetUpClassMethodUpdater.php b/rules/RemovingStatic/NodeAnalyzer/SetUpClassMethodUpdater.php index bd962f8c830..5b35957c302 100644 --- a/rules/RemovingStatic/NodeAnalyzer/SetUpClassMethodUpdater.php +++ b/rules/RemovingStatic/NodeAnalyzer/SetUpClassMethodUpdater.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; } - - public function updateSetUpMethod( - ClassMethod $setupClassMethod, - Expression $parentSetupStaticCall, - Expression $assign - ): void { + public function updateSetUpMethod(\PhpParser\Node\Stmt\ClassMethod $setupClassMethod, \PhpParser\Node\Stmt\Expression $parentSetupStaticCall, \PhpParser\Node\Stmt\Expression $assign) : void + { $parentSetUpStaticCallPosition = $this->getParentSetUpStaticCallPosition($setupClassMethod); if ($parentSetUpStaticCallPosition === null) { - $setupClassMethod->stmts = array_merge([$parentSetupStaticCall, $assign], (array) $setupClassMethod->stmts); + $setupClassMethod->stmts = \array_merge([$parentSetupStaticCall, $assign], (array) $setupClassMethod->stmts); } else { - assert($setupClassMethod->stmts !== null); - array_splice($setupClassMethod->stmts, $parentSetUpStaticCallPosition + 1, 0, [$assign]); + \assert($setupClassMethod->stmts !== null); + \array_splice($setupClassMethod->stmts, $parentSetUpStaticCallPosition + 1, 0, [$assign]); } } - - private function getParentSetUpStaticCallPosition(ClassMethod $setupClassMethod): ?int + private function getParentSetUpStaticCallPosition(\PhpParser\Node\Stmt\ClassMethod $setupClassMethod) : ?int { foreach ((array) $setupClassMethod->stmts as $position => $methodStmt) { - if ($methodStmt instanceof Expression) { + if ($methodStmt instanceof \PhpParser\Node\Stmt\Expression) { $methodStmt = $methodStmt->expr; } - - if (! $methodStmt instanceof StaticCall) { + if (!$methodStmt instanceof \PhpParser\Node\Expr\StaticCall) { continue; } - - if (! $methodStmt->class instanceof Name) { + if (!$methodStmt->class instanceof \PhpParser\Node\Name) { continue; } - - if (! $this->nodeNameResolver->isName($methodStmt->class, 'parent')) { + if (!$this->nodeNameResolver->isName($methodStmt->class, 'parent')) { continue; } - - if (! $this->nodeNameResolver->isName($methodStmt->name, MethodName::SET_UP)) { + if (!$this->nodeNameResolver->isName($methodStmt->name, \Rector\Core\ValueObject\MethodName::SET_UP)) { continue; } - return $position; } - return null; } } diff --git a/rules/RemovingStatic/NodeAnalyzer/StaticCallPresenceAnalyzer.php b/rules/RemovingStatic/NodeAnalyzer/StaticCallPresenceAnalyzer.php index f997df259a1..4338bb5cc70 100644 --- a/rules/RemovingStatic/NodeAnalyzer/StaticCallPresenceAnalyzer.php +++ b/rules/RemovingStatic/NodeAnalyzer/StaticCallPresenceAnalyzer.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeTypeResolver = $nodeTypeResolver; } - - public function hasMethodStaticCallOnType(ClassMethod $classMethod, ObjectType $objectType): bool + public function hasMethodStaticCallOnType(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Type\ObjectType $objectType) : bool { - return (bool) $this->betterNodeFinder->findFirst( - (array) $classMethod->stmts, - function (Node $node) use ($objectType): bool { - if (! $node instanceof StaticCall) { - return false; - } - - return $this->nodeTypeResolver->isObjectType($node->class, $objectType); + return (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (\PhpParser\Node $node) use($objectType) : bool { + if (!$node instanceof \PhpParser\Node\Expr\StaticCall) { + return \false; } - ); + return $this->nodeTypeResolver->isObjectType($node->class, $objectType); + }); } - - public function hasClassAnyMethodWithStaticCallOnType(Class_ $class, ObjectType $objectType): bool + public function hasClassAnyMethodWithStaticCallOnType(\PhpParser\Node\Stmt\Class_ $class, \PHPStan\Type\ObjectType $objectType) : bool { foreach ($class->getMethods() as $classMethod) { // handled else where - if ((string) $classMethod->name === MethodName::CONSTRUCT) { + if ((string) $classMethod->name === \Rector\Core\ValueObject\MethodName::CONSTRUCT) { continue; } - if ($this->hasMethodStaticCallOnType($classMethod, $objectType)) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/rules/RemovingStatic/NodeFactory/SelfContainerFactory.php b/rules/RemovingStatic/NodeFactory/SelfContainerFactory.php index b4e116b5c1e..5603e204346 100644 --- a/rules/RemovingStatic/NodeFactory/SelfContainerFactory.php +++ b/rules/RemovingStatic/NodeFactory/SelfContainerFactory.php @@ -1,7 +1,6 @@ staticTypeMapper = $staticTypeMapper; } - - public function createGetTypeMethodCall(ObjectType $objectType): MethodCall + public function createGetTypeMethodCall(\PHPStan\Type\ObjectType $objectType) : \PhpParser\Node\Expr\MethodCall { - $staticPropertyFetch = new StaticPropertyFetch(new Name('self'), 'container'); - $getMethodCall = new MethodCall($staticPropertyFetch, 'get'); - + $staticPropertyFetch = new \PhpParser\Node\Expr\StaticPropertyFetch(new \PhpParser\Node\Name('self'), 'container'); + $getMethodCall = new \PhpParser\Node\Expr\MethodCall($staticPropertyFetch, 'get'); $className = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($objectType); - if (! $className instanceof Name) { - throw new ShouldNotHappenException(); + if (!$className instanceof \PhpParser\Node\Name) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $getMethodCall->args[] = new Arg(new ClassConstFetch($className, 'class')); - + $getMethodCall->args[] = new \PhpParser\Node\Arg(new \PhpParser\Node\Expr\ClassConstFetch($className, 'class')); return $getMethodCall; } } diff --git a/rules/RemovingStatic/NodeFactory/SetUpFactory.php b/rules/RemovingStatic/NodeFactory/SetUpFactory.php index 5b7d2233d0e..a29af07a57e 100644 --- a/rules/RemovingStatic/NodeFactory/SetUpFactory.php +++ b/rules/RemovingStatic/NodeFactory/SetUpFactory.php @@ -1,28 +1,24 @@ nodeFactory = $nodeFactory; } - - public function createParentStaticCall(): Expression + public function createParentStaticCall() : \PhpParser\Node\Stmt\Expression { - $parentSetupStaticCall = $this->nodeFactory->createStaticCall('parent', MethodName::SET_UP); - return new Expression($parentSetupStaticCall); + $parentSetupStaticCall = $this->nodeFactory->createStaticCall('parent', \Rector\Core\ValueObject\MethodName::SET_UP); + return new \PhpParser\Node\Stmt\Expression($parentSetupStaticCall); } } diff --git a/rules/RemovingStatic/Printer/FactoryClassPrinter.php b/rules/RemovingStatic/Printer/FactoryClassPrinter.php index e703f9a466b..83800969522 100644 --- a/rules/RemovingStatic/Printer/FactoryClassPrinter.php +++ b/rules/RemovingStatic/Printer/FactoryClassPrinter.php @@ -1,10 +1,9 @@ nodeNameResolver = $nodeNameResolver; $this->betterStandardPrinter = $betterStandardPrinter; $this->smartFileSystem = $smartFileSystem; $this->currentFileProvider = $currentFileProvider; } - - public function printFactoryForClass(Class_ $factoryClass, Class_ $oldClass): void + public function printFactoryForClass(\PhpParser\Node\Stmt\Class_ $factoryClass, \PhpParser\Node\Stmt\Class_ $oldClass) : void { - $parentNode = $oldClass->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Namespace_) { + $parentNode = $oldClass->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Stmt\Namespace_) { $newNamespace = clone $parentNode; $newNamespace->stmts = []; $newNamespace->stmts[] = $factoryClass; @@ -59,27 +48,20 @@ final class FactoryClassPrinter } else { $nodeToPrint = $factoryClass; } - $factoryClassFilePath = $this->createFactoryClassFilePath($oldClass); $factoryClassContent = $this->betterStandardPrinter->prettyPrintFile([$nodeToPrint]); - $this->smartFileSystem->dumpFile($factoryClassFilePath, $factoryClassContent); } - - private function createFactoryClassFilePath(Class_ $oldClass): string + private function createFactoryClassFilePath(\PhpParser\Node\Stmt\Class_ $oldClass) : string { $file = $this->currentFileProvider->getFile(); - $smartFileInfo = $file->getSmartFileInfo(); - - $directoryPath = Strings::before($smartFileInfo->getRealPath(), DIRECTORY_SEPARATOR, -1); + $directoryPath = \RectorPrefix20210509\Nette\Utils\Strings::before($smartFileInfo->getRealPath(), \DIRECTORY_SEPARATOR, -1); $resolvedOldClass = $this->nodeNameResolver->getName($oldClass); if ($resolvedOldClass === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $bareClassName = Strings::after($resolvedOldClass, '\\', -1) . 'Factory.php'; - - return $directoryPath . DIRECTORY_SEPARATOR . $bareClassName; + $bareClassName = \RectorPrefix20210509\Nette\Utils\Strings::after($resolvedOldClass, '\\', -1) . 'Factory.php'; + return $directoryPath . \DIRECTORY_SEPARATOR . $bareClassName; } } diff --git a/rules/RemovingStatic/Rector/ClassMethod/LocallyCalledStaticMethodToNonStaticRector.php b/rules/RemovingStatic/Rector/ClassMethod/LocallyCalledStaticMethodToNonStaticRector.php index b5777344373..2017fbd6211 100644 --- a/rules/RemovingStatic/Rector/ClassMethod/LocallyCalledStaticMethodToNonStaticRector.php +++ b/rules/RemovingStatic/Rector/ClassMethod/LocallyCalledStaticMethodToNonStaticRector.php @@ -1,7 +1,6 @@ classMethodVisibilityGuard = $classMethodVisibilityGuard; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change static method and local-only calls to non-static', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change static method and local-only calls to non-static', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -50,9 +42,7 @@ class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -65,109 +55,87 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, StaticCall::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param ClassMethod|StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { return $this->refactorClassMethod($node); } - return $this->refactorStaticCall($node); } - - private function refactorClassMethod(ClassMethod $classMethod): ?ClassMethod + private function refactorClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PhpParser\Node\Stmt\ClassMethod { - if (! $classMethod->isStatic()) { + if (!$classMethod->isStatic()) { return null; } - - if (! $this->isClassMethodWithOnlyLocalStaticCalls($classMethod)) { + if (!$this->isClassMethodWithOnlyLocalStaticCalls($classMethod)) { return null; } - - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - if ($this->classMethodVisibilityGuard->isClassMethodVisibilityGuardedByParent($classMethod, $classReflection)) { return null; } - // change static calls to non-static ones, but only if in non-static method!!! $this->visibilityManipulator->makeNonStatic($classMethod); - return $classMethod; } - - private function refactorStaticCall(StaticCall $staticCall): ?MethodCall + private function refactorStaticCall(\PhpParser\Node\Expr\StaticCall $staticCall) : ?\PhpParser\Node\Expr\MethodCall { $classMethod = $this->nodeRepository->findClassMethodByStaticCall($staticCall); - if (! $classMethod instanceof ClassMethod) { + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - // is static call in the same as class method - if (! $this->haveSharedClass($classMethod, [$staticCall])) { + if (!$this->haveSharedClass($classMethod, [$staticCall])) { return null; } - if ($this->isInStaticClassMethod($staticCall)) { return null; } - - $thisVariable = new Variable('this'); - return new MethodCall($thisVariable, $staticCall->name, $staticCall->args); + $thisVariable = new \PhpParser\Node\Expr\Variable('this'); + return new \PhpParser\Node\Expr\MethodCall($thisVariable, $staticCall->name, $staticCall->args); } - - private function isClassMethodWithOnlyLocalStaticCalls(ClassMethod $classMethod): bool + private function isClassMethodWithOnlyLocalStaticCalls(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { $staticCalls = $this->nodeRepository->findStaticCallsByClassMethod($classMethod); - // get static staticCalls return $this->haveSharedClass($classMethod, $staticCalls); } - /** * @param Node[] $nodes */ - private function haveSharedClass(Node $mainNode, array $nodes): bool + private function haveSharedClass(\PhpParser\Node $mainNode, array $nodes) : bool { - $mainNodeClass = $mainNode->getAttribute(AttributeKey::CLASS_NAME); + $mainNodeClass = $mainNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); foreach ($nodes as $node) { - $nodeClass = $node->getAttribute(AttributeKey::CLASS_NAME); + $nodeClass = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($mainNodeClass !== $nodeClass) { - return false; + return \false; } } - - return true; + return \true; } - - private function isInStaticClassMethod(StaticCall $staticCall): bool + private function isInStaticClassMethod(\PhpParser\Node\Expr\StaticCall $staticCall) : bool { - $locationClassMethod = $staticCall->getAttribute(AttributeKey::METHOD_NODE); - if (! $locationClassMethod instanceof ClassMethod) { - return false; + $locationClassMethod = $staticCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$locationClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - return $locationClassMethod->isStatic(); } } diff --git a/rules/RemovingStatic/Rector/Class_/DesiredClassTypeToDynamicRector.php b/rules/RemovingStatic/Rector/Class_/DesiredClassTypeToDynamicRector.php index f69ee0a074b..735f2759447 100644 --- a/rules/RemovingStatic/Rector/Class_/DesiredClassTypeToDynamicRector.php +++ b/rules/RemovingStatic/Rector/Class_/DesiredClassTypeToDynamicRector.php @@ -1,7 +1,6 @@ provideArrayParameter(Option::TYPES_TO_REMOVE_STATIC_FROM); + public function __construct(\Rector\Naming\Naming\PropertyNaming $propertyNaming, \Rector\RemovingStatic\NodeAnalyzer\StaticCallPresenceAnalyzer $staticCallPresenceAnalyzer, \RectorPrefix20210509\Symplify\PackageBuilder\Parameter\ParameterProvider $parameterProvider) + { + $typesToRemoveStaticFrom = $parameterProvider->provideArrayParameter(\Rector\Core\Configuration\Option::TYPES_TO_REMOVE_STATIC_FROM); foreach ($typesToRemoveStaticFrom as $typeToRemoveStaticFrom) { - $this->staticObjectTypes[] = new ObjectType($typeToRemoveStaticFrom); + $this->staticObjectTypes[] = new \PHPStan\Type\ObjectType($typeToRemoveStaticFrom); } - $this->propertyNaming = $propertyNaming; $this->staticCallPresenceAnalyzer = $staticCallPresenceAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change full static service, to dynamic one', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change full static service, to dynamic one', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class AnotherClass { public function run() @@ -79,8 +67,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class AnotherClass { /** @@ -111,84 +98,64 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->staticObjectTypes as $staticObjectType) { // do not any dependencies to class itself if ($this->isObjectType($node, $staticObjectType)) { continue; } - $this->completeDependencyToConstructorOnly($node, $staticObjectType); - if ($this->staticCallPresenceAnalyzer->hasClassAnyMethodWithStaticCallOnType($node, $staticObjectType)) { $propertyExpectedName = $this->propertyNaming->fqnToVariableName($staticObjectType); $this->addConstructorDependencyToClass($node, $staticObjectType, $propertyExpectedName); - return $node; } } - return null; } - - private function completeDependencyToConstructorOnly(Class_ $class, ObjectType $objectType): void + private function completeDependencyToConstructorOnly(\PhpParser\Node\Stmt\Class_ $class, \PHPStan\Type\ObjectType $objectType) : void { - $constructClassMethod = $class->getMethod(MethodName::CONSTRUCT); - if (! $constructClassMethod instanceof ClassMethod) { + $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - - $hasStaticCall = $this->staticCallPresenceAnalyzer->hasMethodStaticCallOnType( - $constructClassMethod, - $objectType - ); - - if (! $hasStaticCall) { + $hasStaticCall = $this->staticCallPresenceAnalyzer->hasMethodStaticCallOnType($constructClassMethod, $objectType); + if (!$hasStaticCall) { return; } - $propertyExpectedName = $this->propertyNaming->fqnToVariableName($objectType); - if ($this->isTypeAlreadyInParamMethod($constructClassMethod, $objectType)) { return; } - $constructClassMethod->params[] = $this->createParam($propertyExpectedName, $objectType); } - - private function isTypeAlreadyInParamMethod(ClassMethod $classMethod, ObjectType $objectType): bool + private function isTypeAlreadyInParamMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Type\ObjectType $objectType) : bool { foreach ($classMethod->getParams() as $param) { if ($param->type === null) { continue; } - if ($this->isName($param->type, $objectType->getClassName())) { - return true; + return \true; } } - - return false; + return \false; } - - private function createParam(string $propertyName, ObjectType $objectType): Param + private function createParam(string $propertyName, \PHPStan\Type\ObjectType $objectType) : \PhpParser\Node\Param { - return new Param(new Variable($propertyName), null, new FullyQualified($objectType->getClassName())); + return new \PhpParser\Node\Param(new \PhpParser\Node\Expr\Variable($propertyName), null, new \PhpParser\Node\Name\FullyQualified($objectType->getClassName())); } } diff --git a/rules/RemovingStatic/Rector/Class_/NewUniqueObjectToEntityFactoryRector.php b/rules/RemovingStatic/Rector/Class_/NewUniqueObjectToEntityFactoryRector.php index 55c27c16055..a2e1a1ceae4 100644 --- a/rules/RemovingStatic/Rector/Class_/NewUniqueObjectToEntityFactoryRector.php +++ b/rules/RemovingStatic/Rector/Class_/NewUniqueObjectToEntityFactoryRector.php @@ -1,7 +1,6 @@ propertyNaming = $propertyNaming; $this->staticTypesInClassResolver = $staticTypesInClassResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Convert new X to new factories', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Convert new X to new factories', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' ['ClassName'], - ] - ), ]); +, [self::TYPES_TO_SERVICES => ['ClassName']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $this->matchedObjectTypes = []; - // collect classes with new to factory in all classes $classesUsingTypes = $this->resolveClassesUsingTypes(); - - $this->traverseNodesWithCallable($node->stmts, function (Node $node) use ( - $classesUsingTypes - ): ?MethodCall { - if (! $node instanceof New_) { + $this->traverseNodesWithCallable($node->stmts, function (\PhpParser\Node $node) use($classesUsingTypes) : ?MethodCall { + if (!$node instanceof \PhpParser\Node\Expr\New_) { return null; } - $class = $this->getName($node->class); if ($class === null) { return null; } - - if (! in_array($class, $classesUsingTypes, true)) { + if (!\in_array($class, $classesUsingTypes, \true)) { return null; } - - $objectType = new FullyQualifiedObjectType($class); + $objectType = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($class); $this->matchedObjectTypes[] = $objectType; - $propertyName = $this->propertyNaming->fqnToVariableName($objectType) . self::FACTORY; - $propertyFetch = new PropertyFetch(new Variable('this'), $propertyName); - - return new MethodCall($propertyFetch, 'create', $node->args); + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $propertyName); + return new \PhpParser\Node\Expr\MethodCall($propertyFetch, 'create', $node->args); }); - foreach ($this->matchedObjectTypes as $matchedObjectType) { $propertyName = $this->propertyNaming->fqnToVariableName($matchedObjectType) . self::FACTORY; - $propertyType = new FullyQualifiedObjectType($matchedObjectType->getClassName() . self::FACTORY); - + $propertyType = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($matchedObjectType->getClassName() . self::FACTORY); $this->addConstructorDependencyToClass($node, $propertyType, $propertyName); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $typesToServices = $configuration[self::TYPES_TO_SERVICES] ?? []; foreach ($typesToServices as $typeToService) { - $this->serviceObjectTypes[] = new ObjectType($typeToService); + $this->serviceObjectTypes[] = new \PHPStan\Type\ObjectType($typeToService); } } - /** * @return string[] */ - private function resolveClassesUsingTypes(): array + private function resolveClassesUsingTypes() : array { if ($this->classesUsingTypes !== []) { return $this->classesUsingTypes; } - // temporary $classes = $this->nodeRepository->getClasses(); if ($classes === []) { return []; } - foreach ($classes as $class) { - $hasTypes = (bool) $this->staticTypesInClassResolver->collectStaticCallTypeInClass( - $class, - $this->serviceObjectTypes - ); + $hasTypes = (bool) $this->staticTypesInClassResolver->collectStaticCallTypeInClass($class, $this->serviceObjectTypes); if ($hasTypes) { $name = $this->getName($class); if ($name === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } $this->classesUsingTypes[] = $name; } } - - $this->classesUsingTypes = array_unique($this->classesUsingTypes); - + $this->classesUsingTypes = \array_unique($this->classesUsingTypes); return $this->classesUsingTypes; } } diff --git a/rules/RemovingStatic/Rector/Class_/PHPUnitStaticToKernelTestCaseGetRector.php b/rules/RemovingStatic/Rector/Class_/PHPUnitStaticToKernelTestCaseGetRector.php index ee44c9ff4ad..7370c5daad9 100644 --- a/rules/RemovingStatic/Rector/Class_/PHPUnitStaticToKernelTestCaseGetRector.php +++ b/rules/RemovingStatic/Rector/Class_/PHPUnitStaticToKernelTestCaseGetRector.php @@ -1,7 +1,6 @@ propertyNaming = $propertyNaming; $this->classInsertManipulator = $classInsertManipulator; $this->setUpClassMethodFactory = $setUpClassMethodFactory; @@ -94,26 +77,24 @@ final class PHPUnitStaticToKernelTestCaseGetRector extends AbstractRector implem $this->selfContainerFactory = $selfContainerFactory; $this->setUpClassMethodUpdater = $setUpClassMethodUpdater; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Convert static calls in PHPUnit test cases, to get() from the container of KernelTestCase', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Convert static calls in PHPUnit test cases, to get() from the container of KernelTestCase', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' ['EntityFactory'], - ] - ), - ]); +, [self::STATIC_CLASS_TYPES => ['EntityFactory']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class, Class_::class]; + return [\PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Stmt\Class_::class]; } - /** * @param StaticCall|Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { // skip yourself $this->newPropertyObjectTypes = []; - - if ($node instanceof Class_) { + if ($node instanceof \PhpParser\Node\Stmt\Class_) { if ($this->nodeTypeResolver->isObjectTypes($node, $this->staticObjectTypes)) { return null; } - return $this->processClass($node); } - return $this->processStaticCall($node); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $staticClassTypes = $configuration[self::STATIC_CLASS_TYPES] ?? []; foreach ($staticClassTypes as $staticClassType) { - $this->staticObjectTypes[] = new ObjectType($staticClassType); + $this->staticObjectTypes[] = new \PHPStan\Type\ObjectType($staticClassType); } } - - private function processClass(Class_ $class): ?Class_ + private function processClass(\PhpParser\Node\Stmt\Class_ $class) : ?\PhpParser\Node\Stmt\Class_ { - if ($this->isObjectType($class, new ObjectType('PHPUnit\Framework\TestCase'))) { + if ($this->isObjectType($class, new \PHPStan\Type\ObjectType('PHPUnit\\Framework\\TestCase'))) { return $this->processPHPUnitClass($class); } - // add property with the object $newPropertyObjectTypes = $this->collectNewPropertyObjectTypes($class); if ($newPropertyObjectTypes === []) { return null; } - // add via constructor foreach ($newPropertyObjectTypes as $newPropertyObjectType) { $newPropertyName = $this->propertyNaming->fqnToVariableName($newPropertyObjectType); $this->addConstructorDependencyToClass($class, $newPropertyObjectType, $newPropertyName); } - return $class; } - - private function processStaticCall(StaticCall $staticCall): ?MethodCall + private function processStaticCall(\PhpParser\Node\Expr\StaticCall $staticCall) : ?\PhpParser\Node\Expr\MethodCall { - $classLike = $staticCall->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $staticCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - foreach ($this->staticObjectTypes as $staticObjectType) { - if (! $this->isObjectType($staticCall->class, $staticObjectType)) { + if (!$this->isObjectType($staticCall->class, $staticObjectType)) { continue; } - return $this->convertStaticCallToPropertyMethodCall($staticCall, $staticObjectType); } - return null; } - - private function processPHPUnitClass(Class_ $class): ?Class_ + private function processPHPUnitClass(\PhpParser\Node\Stmt\Class_ $class) : ?\PhpParser\Node\Stmt\Class_ { // add property with the object $newPropertyTypes = $this->collectNewPropertyObjectTypes($class); if ($newPropertyTypes === []) { return null; } - // add all properties to class $class = $this->addNewPropertiesToClass($class, $newPropertyTypes); - $parentSetUpStaticCallExpression = $this->setUpFactory->createParentStaticCall(); foreach ($newPropertyTypes as $newPropertyType) { // container fetch assign $assign = $this->createContainerGetTypeToPropertyAssign($newPropertyType); - - $setupClassMethod = $class->getMethod(MethodName::SET_UP); - + $setupClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::SET_UP); // get setup or create a setup add add it there if ($setupClassMethod !== null) { - $this->setUpClassMethodUpdater->updateSetUpMethod( - $setupClassMethod, - $parentSetUpStaticCallExpression, - $assign - ); + $this->setUpClassMethodUpdater->updateSetUpMethod($setupClassMethod, $parentSetUpStaticCallExpression, $assign); } else { $setUpMethod = $this->setUpClassMethodFactory->createSetUpMethod([$assign]); $this->classInsertManipulator->addAsFirstMethod($class, $setUpMethod); } } - // update parent clsas if not already - if (! $this->isObjectType($class, new ObjectType('Symfony\Bundle\FrameworkBundle\Test\KernelTestCase'))) { - $class->extends = new FullyQualified('Symfony\Bundle\FrameworkBundle\Test\KernelTestCase'); + if (!$this->isObjectType($class, new \PHPStan\Type\ObjectType('Symfony\\Bundle\\FrameworkBundle\\Test\\KernelTestCase'))) { + $class->extends = new \PhpParser\Node\Name\FullyQualified('Symfony\\Bundle\\FrameworkBundle\\Test\\KernelTestCase'); } - return $class; } - /** * @return ObjectType[] */ - private function collectNewPropertyObjectTypes(Class_ $class): array + private function collectNewPropertyObjectTypes(\PhpParser\Node\Stmt\Class_ $class) : array { $this->newPropertyObjectTypes = []; - - $this->traverseNodesWithCallable($class->stmts, function (Node $node): void { - if (! $node instanceof StaticCall) { + $this->traverseNodesWithCallable($class->stmts, function (\PhpParser\Node $node) : void { + if (!$node instanceof \PhpParser\Node\Expr\StaticCall) { return; } - foreach ($this->staticObjectTypes as $staticObjectType) { - if (! $this->isObjectType($node->class, $staticObjectType)) { + if (!$this->isObjectType($node->class, $staticObjectType)) { continue; } - $this->newPropertyObjectTypes[] = $staticObjectType; } }); - - $this->newPropertyObjectTypes = array_unique($this->newPropertyObjectTypes); - + $this->newPropertyObjectTypes = \array_unique($this->newPropertyObjectTypes); return $this->newPropertyObjectTypes; } - - private function convertStaticCallToPropertyMethodCall(StaticCall $staticCall, ObjectType $objectType): MethodCall + private function convertStaticCallToPropertyMethodCall(\PhpParser\Node\Expr\StaticCall $staticCall, \PHPStan\Type\ObjectType $objectType) : \PhpParser\Node\Expr\MethodCall { // create "$this->someService" instead $propertyName = $this->propertyNaming->fqnToVariableName($objectType); - $propertyFetch = new PropertyFetch(new Variable('this'), $propertyName); - + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $propertyName); // turn static call to method on property call - $methodCall = new MethodCall($propertyFetch, $staticCall->name); + $methodCall = new \PhpParser\Node\Expr\MethodCall($propertyFetch, $staticCall->name); $methodCall->args = $staticCall->args; - return $methodCall; } - /** * @param ObjectType[] $propertyTypes */ - private function addNewPropertiesToClass(Class_ $class, array $propertyTypes): Class_ + private function addNewPropertiesToClass(\PhpParser\Node\Stmt\Class_ $class, array $propertyTypes) : \PhpParser\Node\Stmt\Class_ { $properties = []; foreach ($propertyTypes as $propertyType) { $propertyName = $this->propertyNaming->fqnToVariableName($propertyType); $properties[] = $this->nodeFactory->createPrivatePropertyFromNameAndType($propertyName, $propertyType); } - // add property to the start of the class - $class->stmts = array_merge($properties, $class->stmts); - + $class->stmts = \array_merge($properties, $class->stmts); return $class; } - - private function createContainerGetTypeToPropertyAssign(ObjectType $objectType): Expression + private function createContainerGetTypeToPropertyAssign(\PHPStan\Type\ObjectType $objectType) : \PhpParser\Node\Stmt\Expression { $getMethodCall = $this->selfContainerFactory->createGetTypeMethodCall($objectType); - $propertyName = $this->propertyNaming->fqnToVariableName($objectType); - $propertyFetch = new PropertyFetch(new Variable('this'), $propertyName); - - $assign = new Assign($propertyFetch, $getMethodCall); - - return new Expression($assign); + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $propertyName); + $assign = new \PhpParser\Node\Expr\Assign($propertyFetch, $getMethodCall); + return new \PhpParser\Node\Stmt\Expression($assign); } } diff --git a/rules/RemovingStatic/Rector/Class_/PassFactoryToUniqueObjectRector.php b/rules/RemovingStatic/Rector/Class_/PassFactoryToUniqueObjectRector.php index 502cc26605a..84a37fa3563 100644 --- a/rules/RemovingStatic/Rector/Class_/PassFactoryToUniqueObjectRector.php +++ b/rules/RemovingStatic/Rector/Class_/PassFactoryToUniqueObjectRector.php @@ -1,7 +1,6 @@ propertyNaming = $propertyNaming; $this->uniqueObjectOrServiceDetector = $uniqueObjectOrServiceDetector; $this->uniqueObjectFactoryFactory = $uniqueObjectFactoryFactory; $this->factoryClassPrinter = $factoryClassPrinter; $this->staticTypesInClassResolver = $staticTypesInClassResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Convert new X/Static::call() to factories in entities, pass them via constructor to each other', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Convert new X/Static::call() to factories in entities, pass them via constructor to each other', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' ['StaticClass'], - ] - ), ] - ); +, [self::TYPES_TO_SERVICES => ['StaticClass']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class, StaticCall::class]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall|Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof Class_) { + if ($node instanceof \PhpParser\Node\Stmt\Class_) { return $this->refactorClass($node); } - foreach ($this->serviceObjectTypes as $serviceObjectType) { - if (! $this->isObjectType($node->class, $serviceObjectType)) { + if (!$this->isObjectType($node->class, $serviceObjectType)) { continue; } - // is this object created via new somewhere else? use factory! $variableName = $this->propertyNaming->fqnToVariableName($serviceObjectType); - $thisPropertyFetch = new PropertyFetch(new Variable('this'), $variableName); - - return new MethodCall($thisPropertyFetch, $node->name, $node->args); + $thisPropertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $variableName); + return new \PhpParser\Node\Expr\MethodCall($thisPropertyFetch, $node->name, $node->args); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $typesToServices = $configuration[self::TYPES_TO_SERVICES] ?? []; foreach ($typesToServices as $typeToService) { - $this->serviceObjectTypes[] = new ObjectType($typeToService); + $this->serviceObjectTypes[] = new \PHPStan\Type\ObjectType($typeToService); } } - - private function refactorClass(Class_ $class): Class_ + private function refactorClass(\PhpParser\Node\Stmt\Class_ $class) : \PhpParser\Node\Stmt\Class_ { - $staticTypesInClass = $this->staticTypesInClassResolver->collectStaticCallTypeInClass( - $class, - $this->serviceObjectTypes - ); - + $staticTypesInClass = $this->staticTypesInClassResolver->collectStaticCallTypeInClass($class, $this->serviceObjectTypes); foreach ($staticTypesInClass as $staticTypeInClass) { $variableName = $this->propertyNaming->fqnToVariableName($staticTypeInClass); $this->addConstructorDependencyToClass($class, $staticTypeInClass, $variableName); - // is this an object? create factory for it next to this :) if ($this->uniqueObjectOrServiceDetector->isUniqueObject()) { $factoryClass = $this->uniqueObjectFactoryFactory->createFactoryClass($class, $staticTypeInClass); - $this->factoryClassPrinter->printFactoryForClass($factoryClass, $class); } } - return $class; } } diff --git a/rules/RemovingStatic/Rector/Class_/StaticTypeToSetterInjectionRector.php b/rules/RemovingStatic/Rector/Class_/StaticTypeToSetterInjectionRector.php index 35b36f2be38..ab0d7b2da94 100644 --- a/rules/RemovingStatic/Rector/Class_/StaticTypeToSetterInjectionRector.php +++ b/rules/RemovingStatic/Rector/Class_/StaticTypeToSetterInjectionRector.php @@ -1,7 +1,6 @@ */ private $staticTypes = []; - /** * @var PropertyNaming */ private $propertyNaming; - /** * @var PhpDocTypeChanger */ private $phpDocTypeChanger; - - public function __construct(PropertyNaming $propertyNaming, PhpDocTypeChanger $phpDocTypeChanger) + public function __construct(\Rector\Naming\Naming\PropertyNaming $propertyNaming, \Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger $phpDocTypeChanger) { $this->propertyNaming = $propertyNaming; $this->phpDocTypeChanger = $phpDocTypeChanger; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { // custom made only for Elasticr - return new RuleDefinition('Changes types to setter injection', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes types to setter injection', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' someStaticClass = $someStaticClass; } - public function run() { return $this->someStaticClass->go(); } } +\class_alias('CheckoutEntityFactory', 'CheckoutEntityFactory', \false); CODE_SAMPLE - , - [ - self::STATIC_TYPES => ['SomeStaticClass'], - ] - ), - ]); +, [self::STATIC_TYPES => ['SomeStaticClass']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class, StaticCall::class]; + return [\PhpParser\Node\Stmt\Class_::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall|Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof Class_) { + if ($node instanceof \PhpParser\Node\Stmt\Class_) { return $this->processClass($node); } - foreach ($this->staticTypes as $staticType) { - $objectType = new ObjectType($staticType); - if (! $this->isObjectType($node->class, $objectType)) { + $objectType = new \PHPStan\Type\ObjectType($staticType); + if (!$this->isObjectType($node->class, $objectType)) { continue; } - $variableName = $this->propertyNaming->fqnToVariableName($objectType); - $propertyFetch = new PropertyFetch(new Variable('this'), $variableName); - - return new MethodCall($propertyFetch, $node->name, $node->args); + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $variableName); + return new \PhpParser\Node\Expr\MethodCall($propertyFetch, $node->name, $node->args); } - return null; } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->staticTypes = $configuration[self::STATIC_TYPES] ?? []; } - - private function processClass(Class_ $class): Class_ + private function processClass(\PhpParser\Node\Stmt\Class_ $class) : \PhpParser\Node\Stmt\Class_ { foreach ($this->staticTypes as $implements => $staticType) { - $objectType = new ObjectType($staticType); - - $containsEntityFactoryStaticCall = (bool) $this->betterNodeFinder->findFirst( - $class->stmts, - function (Node $node) use ($objectType): bool { - return $this->isEntityFactoryStaticCall($node, $objectType); - } - ); - - if (! $containsEntityFactoryStaticCall) { + $objectType = new \PHPStan\Type\ObjectType($staticType); + $containsEntityFactoryStaticCall = (bool) $this->betterNodeFinder->findFirst($class->stmts, function (\PhpParser\Node $node) use($objectType) : bool { + return $this->isEntityFactoryStaticCall($node, $objectType); + }); + if (!$containsEntityFactoryStaticCall) { continue; } - - if (is_string($implements)) { - $class->implements[] = new FullyQualified($implements); + if (\is_string($implements)) { + $class->implements[] = new \PhpParser\Node\Name\FullyQualified($implements); } - $variableName = $this->propertyNaming->fqnToVariableName($objectType); $setEntityFactoryMethod = $this->nodeFactory->createSetterClassMethod($variableName, $objectType); - $entityFactoryProperty = $this->nodeFactory->createPrivateProperty($variableName); - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($entityFactoryProperty); $this->phpDocTypeChanger->changeVarType($phpDocInfo, $objectType); - - $class->stmts = array_merge([$entityFactoryProperty, $setEntityFactoryMethod], $class->stmts); - + $class->stmts = \array_merge([$entityFactoryProperty, $setEntityFactoryMethod], $class->stmts); break; } - return $class; } - - private function isEntityFactoryStaticCall(Node $node, ObjectType $objectType): bool + private function isEntityFactoryStaticCall(\PhpParser\Node $node, \PHPStan\Type\ObjectType $objectType) : bool { - if (! $node instanceof StaticCall) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\StaticCall) { + return \false; } - return $this->isObjectType($node->class, $objectType); } } diff --git a/rules/RemovingStatic/Rector/Property/DesiredPropertyClassMethodTypeToDynamicRector.php b/rules/RemovingStatic/Rector/Property/DesiredPropertyClassMethodTypeToDynamicRector.php index 54449825198..3874b74cd04 100644 --- a/rules/RemovingStatic/Rector/Property/DesiredPropertyClassMethodTypeToDynamicRector.php +++ b/rules/RemovingStatic/Rector/Property/DesiredPropertyClassMethodTypeToDynamicRector.php @@ -1,7 +1,6 @@ provideArrayParameter(Option::TYPES_TO_REMOVE_STATIC_FROM); + $typesToRemoveStaticFrom = $parameterProvider->provideArrayParameter(\Rector\Core\Configuration\Option::TYPES_TO_REMOVE_STATIC_FROM); foreach ($typesToRemoveStaticFrom as $typeToRemoveStaticFrom) { - $this->staticObjectTypes[] = new ObjectType($typeToRemoveStaticFrom); + $this->staticObjectTypes[] = new \PHPStan\Type\ObjectType($typeToRemoveStaticFrom); } } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change defined static properties and methods to dynamic', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change defined static properties and methods to dynamic', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public static $name; @@ -49,8 +43,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public $name; @@ -60,47 +53,37 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return class-string[] */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class, ClassMethod::class]; + return [\PhpParser\Node\Stmt\Property::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param Property|ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { /** @var Scope $scope */ - $scope = $node->getAttribute(AttributeKey::SCOPE); - + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - - $classObjectType = new ObjectType($classReflection->getName()); - + $classObjectType = new \PHPStan\Type\ObjectType($classReflection->getName()); foreach ($this->staticObjectTypes as $staticObjectType) { - if (! $staticObjectType->isSuperTypeOf($classObjectType)->yes()) { + if (!$staticObjectType->isSuperTypeOf($classObjectType)->yes()) { continue; } - - if (! $node->isStatic()) { + if (!$node->isStatic()) { return null; } - $this->visibilityManipulator->makeNonStatic($node); - return $node; } - return null; } } diff --git a/rules/RemovingStatic/Rector/StaticCall/DesiredStaticCallTypeToDynamicRector.php b/rules/RemovingStatic/Rector/StaticCall/DesiredStaticCallTypeToDynamicRector.php index 011e7fb93b8..073288ea112 100644 --- a/rules/RemovingStatic/Rector/StaticCall/DesiredStaticCallTypeToDynamicRector.php +++ b/rules/RemovingStatic/Rector/StaticCall/DesiredStaticCallTypeToDynamicRector.php @@ -1,7 +1,6 @@ provideArrayParameter(Option::TYPES_TO_REMOVE_STATIC_FROM); + $typesToRemoveStaticFrom = $parameterProvider->provideArrayParameter(\Rector\Core\Configuration\Option::TYPES_TO_REMOVE_STATIC_FROM); foreach ($typesToRemoveStaticFrom as $typeToRemoveStaticFrom) { - $this->staticObjectTypes[] = new ObjectType($typeToRemoveStaticFrom); + $this->staticObjectTypes[] = new \PHPStan\Type\ObjectType($typeToRemoveStaticFrom); } - $this->propertyNaming = $propertyNaming; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change defined static service to dynamic one', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change defined static service to dynamic one', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -57,8 +49,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -67,51 +58,42 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->staticObjectTypes as $staticObjectType) { - if (! $this->isObjectType($node->class, $staticObjectType)) { + if (!$this->isObjectType($node->class, $staticObjectType)) { continue; } - // is the same class or external call? $className = $this->getName($node->class); if ($className === 'self') { return $this->createFromSelf($node); } - $propertyName = $this->propertyNaming->fqnToVariableName($staticObjectType); - - $classMethod = $node->getAttribute(AttributeKey::METHOD_NODE); - if ($this->nodeNameResolver->isName($classMethod, MethodName::CONSTRUCT)) { - $propertyFetch = new Variable($propertyName); + $classMethod = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if ($this->nodeNameResolver->isName($classMethod, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { + $propertyFetch = new \PhpParser\Node\Expr\Variable($propertyName); } else { - $propertyFetch = new PropertyFetch(new Variable('this'), $propertyName); + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $propertyName); } - - return new MethodCall($propertyFetch, $node->name, $node->args); + return new \PhpParser\Node\Expr\MethodCall($propertyFetch, $node->name, $node->args); } - return null; } - - private function createFromSelf(StaticCall $staticCall): MethodCall + private function createFromSelf(\PhpParser\Node\Expr\StaticCall $staticCall) : \PhpParser\Node\Expr\MethodCall { - return new MethodCall(new Variable('this'), $staticCall->name, $staticCall->args); + return new \PhpParser\Node\Expr\MethodCall(new \PhpParser\Node\Expr\Variable('this'), $staticCall->name, $staticCall->args); } } diff --git a/rules/RemovingStatic/Rector/StaticPropertyFetch/DesiredStaticPropertyFetchTypeToDynamicRector.php b/rules/RemovingStatic/Rector/StaticPropertyFetch/DesiredStaticPropertyFetchTypeToDynamicRector.php index 7b0e57725b4..d85f81e6769 100644 --- a/rules/RemovingStatic/Rector/StaticPropertyFetch/DesiredStaticPropertyFetchTypeToDynamicRector.php +++ b/rules/RemovingStatic/Rector/StaticPropertyFetch/DesiredStaticPropertyFetchTypeToDynamicRector.php @@ -1,7 +1,6 @@ provideArrayParameter(Option::TYPES_TO_REMOVE_STATIC_FROM); + $typesToRemoveStaticFrom = $parameterProvider->provideArrayParameter(\Rector\Core\Configuration\Option::TYPES_TO_REMOVE_STATIC_FROM); foreach ($typesToRemoveStaticFrom as $typeToRemoveStaticFrom) { - $this->staticObjectTypes[] = new ObjectType($typeToRemoveStaticFrom); + $this->staticObjectTypes[] = new \PHPStan\Type\ObjectType($typeToRemoveStaticFrom); } - $this->propertyNaming = $propertyNaming; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change defined static service to dynamic one', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change defined static service to dynamic one', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -58,8 +50,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -68,58 +59,46 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticPropertyFetch::class]; + return [\PhpParser\Node\Expr\StaticPropertyFetch::class]; } - /** * @param StaticPropertyFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { /** @var Scope $scope */ - $scope = $node->getAttribute(AttributeKey::SCOPE); - + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - - $classObjectType = new ObjectType($classReflection->getName()); - + $classObjectType = new \PHPStan\Type\ObjectType($classReflection->getName()); // A. remove local fetch foreach ($this->staticObjectTypes as $staticObjectType) { - if (! $staticObjectType->isSuperTypeOf($classObjectType)->yes()) { + if (!$staticObjectType->isSuperTypeOf($classObjectType)->yes()) { continue; } - - return new PropertyFetch(new Variable('this'), $node->name); + return new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $node->name); } - // B. external property fetch foreach ($this->staticObjectTypes as $staticObjectType) { - if (! $this->isObjectType($node->class, $staticObjectType)) { + if (!$this->isObjectType($node->class, $staticObjectType)) { continue; } - $propertyName = $this->propertyNaming->fqnToVariableName($staticObjectType); - /** @var Class_ $class */ - $class = $node->getAttribute(AttributeKey::CLASS_NODE); + $class = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); $this->addConstructorDependencyToClass($class, $staticObjectType, $propertyName); - - $objectPropertyFetch = new PropertyFetch(new Variable('this'), $propertyName); - return new PropertyFetch($objectPropertyFetch, $node->name); + $objectPropertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $propertyName); + return new \PhpParser\Node\Expr\PropertyFetch($objectPropertyFetch, $node->name); } - return null; } } diff --git a/rules/RemovingStatic/StaticTypesInClassResolver.php b/rules/RemovingStatic/StaticTypesInClassResolver.php index a8f42a3efb9..96daf27b118 100644 --- a/rules/RemovingStatic/StaticTypesInClassResolver.php +++ b/rules/RemovingStatic/StaticTypesInClassResolver.php @@ -1,7 +1,6 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeTypeResolver = $nodeTypeResolver; } - /** * @param ObjectType[] $objectTypes * @return ObjectType[] */ - public function collectStaticCallTypeInClass(Class_ $class, array $objectTypes): array + public function collectStaticCallTypeInClass(\PhpParser\Node\Stmt\Class_ $class, array $objectTypes) : array { $staticTypesInClass = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($class->stmts, function (Node $class) use ( - $objectTypes, - &$staticTypesInClass - ) { - if (! $class instanceof StaticCall) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($class->stmts, function (\PhpParser\Node $class) use($objectTypes, &$staticTypesInClass) { + if (!$class instanceof \PhpParser\Node\Expr\StaticCall) { return null; } - foreach ($objectTypes as $objectType) { if ($this->nodeTypeResolver->isObjectType($class->class, $objectType)) { $staticTypesInClass[] = $objectType; } } - return null; }); - return $staticTypesInClass; } } diff --git a/rules/RemovingStatic/UniqueObjectFactoryFactory.php b/rules/RemovingStatic/UniqueObjectFactoryFactory.php index c5a1c631bf9..438cf52e460 100644 --- a/rules/RemovingStatic/UniqueObjectFactoryFactory.php +++ b/rules/RemovingStatic/UniqueObjectFactoryFactory.php @@ -1,10 +1,9 @@ nodeNameResolver = $nodeNameResolver; $this->propertyNaming = $propertyNaming; $this->staticTypeMapper = $staticTypeMapper; @@ -76,136 +62,106 @@ final class UniqueObjectFactoryFactory $this->phpDocTypeChanger = $phpDocTypeChanger; $this->phpDocInfoFactory = $phpDocInfoFactory; } - - public function createFactoryClass(Class_ $class, ObjectType $objectType): Class_ + public function createFactoryClass(\PhpParser\Node\Stmt\Class_ $class, \PHPStan\Type\ObjectType $objectType) : \PhpParser\Node\Stmt\Class_ { $className = $this->nodeNameResolver->getName($class); if ($className === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $name = $className . 'Factory'; - $shortName = $this->resolveClassShortName($name); - - $factoryClassBuilder = new ClassBuilder($shortName); + $factoryClassBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\ClassBuilder($shortName); $factoryClassBuilder->makeFinal(); - $properties = $this->createPropertiesFromTypes($objectType); $factoryClassBuilder->addStmts($properties); - // constructor $constructorClassMethod = $this->createConstructMethod($objectType); $factoryClassBuilder->addStmt($constructorClassMethod); - // create $classMethod = $this->createCreateMethod($class, $className, $properties); $factoryClassBuilder->addStmt($classMethod); - return $factoryClassBuilder->getNode(); } - - private function resolveClassShortName(string $name): string + private function resolveClassShortName(string $name) : string { - if (Strings::contains($name, '\\')) { - return (string) Strings::after($name, '\\', -1); + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($name, '\\')) { + return (string) \RectorPrefix20210509\Nette\Utils\Strings::after($name, '\\', -1); } - return $name; } - /** * @return Property[] */ - private function createPropertiesFromTypes(ObjectType $objectType): array + private function createPropertiesFromTypes(\PHPStan\Type\ObjectType $objectType) : array { $properties = []; $properties[] = $this->createPropertyFromObjectType($objectType); - return $properties; } - - private function createConstructMethod(ObjectType $objectType): ClassMethod + private function createConstructMethod(\PHPStan\Type\ObjectType $objectType) : \PhpParser\Node\Stmt\ClassMethod { $propertyName = $this->propertyNaming->fqnToVariableName($objectType); - $paramBuilder = new ParamBuilder($propertyName); - + $paramBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\ParamBuilder($propertyName); $typeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($objectType); if ($typeNode !== null) { $paramBuilder->setType($typeNode); } - $params = [$paramBuilder->getNode()]; - $assigns = $this->createAssignsFromParams($params); - - $methodBuilder = new MethodBuilder(MethodName::CONSTRUCT); + $methodBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\MethodBuilder(\Rector\Core\ValueObject\MethodName::CONSTRUCT); $methodBuilder->makePublic(); $methodBuilder->addParams($params); $methodBuilder->addStmts($assigns); - return $methodBuilder->getNode(); } - /** * @param Property[] $properties */ - private function createCreateMethod(Class_ $class, string $className, array $properties): ClassMethod + private function createCreateMethod(\PhpParser\Node\Stmt\Class_ $class, string $className, array $properties) : \PhpParser\Node\Stmt\ClassMethod { - $new = new New_(new FullyQualified($className)); - - $constructClassMethod = $class->getMethod(MethodName::CONSTRUCT); + $new = new \PhpParser\Node\Expr\New_(new \PhpParser\Node\Name\FullyQualified($className)); + $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); $params = []; if ($constructClassMethod !== null) { foreach ($constructClassMethod->params as $param) { $params[] = $param; - $new->args[] = new Arg($param->var); + $new->args[] = new \PhpParser\Node\Arg($param->var); } } - foreach ($properties as $property) { $propertyName = $this->nodeNameResolver->getName($property); - $propertyFetch = new PropertyFetch(new Variable('this'), $propertyName); - $new->args[] = new Arg($propertyFetch); + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $propertyName); + $new->args[] = new \PhpParser\Node\Arg($propertyFetch); } - - $return = new Return_($new); - - $methodBuilder = new MethodBuilder('create'); - $methodBuilder->setReturnType(new FullyQualified($className)); + $return = new \PhpParser\Node\Stmt\Return_($new); + $methodBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\MethodBuilder('create'); + $methodBuilder->setReturnType(new \PhpParser\Node\Name\FullyQualified($className)); $methodBuilder->makePublic(); $methodBuilder->addStmt($return); $methodBuilder->addParams($params); - return $methodBuilder->getNode(); } - - private function createPropertyFromObjectType(ObjectType $objectType): Property + private function createPropertyFromObjectType(\PHPStan\Type\ObjectType $objectType) : \PhpParser\Node\Stmt\Property { $propertyName = $this->propertyNaming->fqnToVariableName($objectType); $property = $this->nodeFactory->createPrivateProperty($propertyName); - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); $this->phpDocTypeChanger->changeVarType($phpDocInfo, $objectType); - return $property; } - /** * @param Param[] $params * * @return Assign[] */ - private function createAssignsFromParams(array $params): array + private function createAssignsFromParams(array $params) : array { $assigns = []; - /** @var Param $param */ foreach ($params as $param) { - $propertyFetch = new PropertyFetch(new Variable('this'), $param->var->name); - $assigns[] = new Assign($propertyFetch, new Variable($param->var->name)); + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $param->var->name); + $assigns[] = new \PhpParser\Node\Expr\Assign($propertyFetch, new \PhpParser\Node\Expr\Variable($param->var->name)); } - return $assigns; } } diff --git a/rules/RemovingStatic/UniqueObjectOrServiceDetector.php b/rules/RemovingStatic/UniqueObjectOrServiceDetector.php index 9d1ddc1f9ff..db35584aac4 100644 --- a/rules/RemovingStatic/UniqueObjectOrServiceDetector.php +++ b/rules/RemovingStatic/UniqueObjectOrServiceDetector.php @@ -1,19 +1,17 @@ methodCallRenames = array_merge($this->methodCallRenames, $methodCallRenames); + $this->methodCallRenames = \array_merge($this->methodCallRenames, $methodCallRenames); } - /** * @return MethodCallRenameInterface[] */ - public function getMethodCallRenames(): array + public function getMethodCallRenames() : array { return $this->methodCallRenames; } diff --git a/rules/Renaming/Contract/MethodCallRenameInterface.php b/rules/Renaming/Contract/MethodCallRenameInterface.php index d62dc6bc794..c36c8f28dc7 100644 --- a/rules/Renaming/Contract/MethodCallRenameInterface.php +++ b/rules/Renaming/Contract/MethodCallRenameInterface.php @@ -1,16 +1,12 @@ nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->phpDocClassRenamer = $phpDocClassRenamer; @@ -113,194 +90,151 @@ final class ClassRenamer $this->nodeRemover = $nodeRemover; $this->parameterProvider = $parameterProvider; } - /** * @param array $oldToNewClasses */ - public function renameNode(Node $node, array $oldToNewClasses): ?Node + public function renameNode(\PhpParser\Node $node, array $oldToNewClasses) : ?\PhpParser\Node { $oldToNewTypes = []; foreach ($oldToNewClasses as $oldClass => $newClass) { - $oldToNewTypes[] = new OldToNewType(new ObjectType($oldClass), new FullyQualifiedObjectType($newClass)); + $oldToNewTypes[] = new \Rector\NodeTypeResolver\ValueObject\OldToNewType(new \PHPStan\Type\ObjectType($oldClass), new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($newClass)); } - $this->refactorPhpDoc($node, $oldToNewTypes, $oldToNewClasses); - - if ($node instanceof Name) { + if ($node instanceof \PhpParser\Node\Name) { return $this->refactorName($node, $oldToNewClasses); } - - if ($node instanceof Namespace_) { + if ($node instanceof \PhpParser\Node\Stmt\Namespace_) { return $this->refactorNamespace($node, $oldToNewClasses); } - - if ($node instanceof ClassLike) { + if ($node instanceof \PhpParser\Node\Stmt\ClassLike) { return $this->refactorClassLike($node, $oldToNewClasses); } - return null; } - /** * @param OldToNewType[] $oldToNewTypes * @param array $oldToNewClasses */ - private function refactorPhpDoc(Node $node, array $oldToNewTypes, array $oldToNewClasses): void + private function refactorPhpDoc(\PhpParser\Node $node, array $oldToNewTypes, array $oldToNewClasses) : void { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - if (! $phpDocInfo->hasByTypes(NodeTypes::TYPE_AWARE_NODES) && ! $phpDocInfo->hasByAnnotationClasses( - NodeTypes::TYPE_AWARE_DOCTRINE_ANNOTATION_CLASSES - )) { + if (!$phpDocInfo->hasByTypes(\Rector\BetterPhpDocParser\ValueObject\NodeTypes::TYPE_AWARE_NODES) && !$phpDocInfo->hasByAnnotationClasses(\Rector\BetterPhpDocParser\ValueObject\NodeTypes::TYPE_AWARE_DOCTRINE_ANNOTATION_CLASSES)) { return; } - $this->docBlockClassRenamer->renamePhpDocType($phpDocInfo, $oldToNewTypes); - $this->phpDocClassRenamer->changeTypeInAnnotationTypes($node, $phpDocInfo, $oldToNewClasses); } - /** * @param array $oldToNewClasses */ - private function refactorName(Name $name, array $oldToNewClasses): ?Name + private function refactorName(\PhpParser\Node\Name $name, array $oldToNewClasses) : ?\PhpParser\Node\Name { $stringName = $this->nodeNameResolver->getName($name); - $newName = $oldToNewClasses[$stringName] ?? null; - if (! $newName) { + if (!$newName) { return null; } - - if (! $this->isClassToInterfaceValidChange($name, $newName)) { + if (!$this->isClassToInterfaceValidChange($name, $newName)) { return null; } - - $parentNode = $name->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // no need to preslash "use \SomeNamespace" of imported namespace - if ($parentNode instanceof UseUse && ($parentNode->type === Use_::TYPE_NORMAL || $parentNode->type === Use_::TYPE_UNKNOWN)) { - + if ($parentNode instanceof \PhpParser\Node\Stmt\UseUse && ($parentNode->type === \PhpParser\Node\Stmt\Use_::TYPE_NORMAL || $parentNode->type === \PhpParser\Node\Stmt\Use_::TYPE_UNKNOWN)) { // no need to rename imports, they will be handled by autoimport and coding standard // also they might cause some rename return null; } - $last = $name->getLast(); - $newFullyQualified = new FullyQualified($newName); + $newFullyQualified = new \PhpParser\Node\Name\FullyQualified($newName); $newNameLastName = $newFullyQualified->getLast(); - - $importNames = $this->parameterProvider->provideBoolParameter(Option::AUTO_IMPORT_NAMES); - + $importNames = $this->parameterProvider->provideBoolParameter(\Rector\Core\Configuration\Option::AUTO_IMPORT_NAMES); if ($this->shouldRemoveUseName($last, $newNameLastName, $importNames)) { $this->removeUseName($name); } - - return new FullyQualified($newName); + return new \PhpParser\Node\Name\FullyQualified($newName); } - - private function removeUseName(Name $oldName): void + private function removeUseName(\PhpParser\Node\Name $oldName) : void { - $uses = $this->betterNodeFinder->findFirstPreviousOfNode($oldName, function (Node $node) use ($oldName): bool { - return $node instanceof UseUse && $this->nodeNameResolver->areNamesEqual($node, $oldName); + $uses = $this->betterNodeFinder->findFirstPreviousOfNode($oldName, function (\PhpParser\Node $node) use($oldName) : bool { + return $node instanceof \PhpParser\Node\Stmt\UseUse && $this->nodeNameResolver->areNamesEqual($node, $oldName); }); - - if (! $uses instanceof UseUse) { + if (!$uses instanceof \PhpParser\Node\Stmt\UseUse) { return; } - if ($uses->alias !== null) { return; } - // ios the only one? Remove whole use instead to avoid "use ;" constructions - $parentUse = $uses->getAttribute(AttributeKey::PARENT_NODE); - if ($parentUse instanceof Use_ && count($parentUse->uses) === 1) { + $parentUse = $uses->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentUse instanceof \PhpParser\Node\Stmt\Use_ && \count($parentUse->uses) === 1) { $this->nodeRemover->removeNode($parentUse); } else { $this->nodeRemover->removeNode($uses); } } - /** * @param array $oldToNewClasses */ - private function refactorNamespace(Namespace_ $namespace, array $oldToNewClasses): ?Node + private function refactorNamespace(\PhpParser\Node\Stmt\Namespace_ $namespace, array $oldToNewClasses) : ?\PhpParser\Node { $name = $this->nodeNameResolver->getName($namespace); if ($name === null) { return null; } - $classLike = $this->getClassOfNamespaceToRefactor($namespace, $oldToNewClasses); - if (! $classLike instanceof ClassLike) { + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { return null; } - $currentName = $this->nodeNameResolver->getName($classLike); $newClassFullyQualified = $oldToNewClasses[$currentName]; - if ($this->reflectionProvider->hasClass($newClassFullyQualified)) { return null; } - $newNamespace = $this->classNaming->getNamespace($newClassFullyQualified); // Renaming to class without namespace (example MyNamespace\DateTime -> DateTimeImmutable) - if (! $newNamespace) { - $classLike->name = new Identifier($newClassFullyQualified); - + if (!$newNamespace) { + $classLike->name = new \PhpParser\Node\Identifier($newClassFullyQualified); return $classLike; } - - $namespace->name = new Name($newNamespace); - + $namespace->name = new \PhpParser\Node\Name($newNamespace); return $namespace; } - /** * @param array $oldToNewClasses */ - private function refactorClassLike(ClassLike $classLike, array $oldToNewClasses): ?Node + private function refactorClassLike(\PhpParser\Node\Stmt\ClassLike $classLike, array $oldToNewClasses) : ?\PhpParser\Node { // rename interfaces $this->renameClassImplements($classLike, $oldToNewClasses); - $name = $this->nodeNameResolver->getName($classLike); if ($name === null) { return null; } - $newName = $oldToNewClasses[$name] ?? null; - if (! $newName) { + if (!$newName) { return null; } - // prevents re-iterating same class in endless loop - if (in_array($name, $this->alreadyProcessedClasses, true)) { + if (\in_array($name, $this->alreadyProcessedClasses, \true)) { return null; } - $this->alreadyProcessedClasses[] = $name; - $newName = $oldToNewClasses[$name]; $newClassNamePart = $this->nodeNameResolver->getShortName($newName); $newNamespacePart = $this->classNaming->getNamespace($newName); if ($this->isClassAboutToBeDuplicated($newName)) { return null; } - - $classLike->name = new Identifier($newClassNamePart); + $classLike->name = new \PhpParser\Node\Identifier($newClassNamePart); $classNamingGetNamespace = $this->classNaming->getNamespace($name); - // Old class did not have any namespace, we need to wrap class with Namespace_ node - if ($newNamespacePart && ! $classNamingGetNamespace) { + if ($newNamespacePart && !$classNamingGetNamespace) { $this->changeNameToFullyQualifiedName($classLike); - - $nameNode = new Name($newNamespacePart); - return new Namespace_($nameNode, [$classLike]); + $nameNode = new \PhpParser\Node\Name($newNamespacePart); + return new \PhpParser\Node\Stmt\Namespace_($nameNode, [$classLike]); } - return $classLike; } - /** * Checks validity: * @@ -313,136 +247,109 @@ final class ClassRenamer * - implements SomeInterface * - implements SomeClass */ - private function isClassToInterfaceValidChange(Name $name, string $newClassName): bool + private function isClassToInterfaceValidChange(\PhpParser\Node\Name $name, string $newClassName) : bool { - if (! $this->reflectionProvider->hasClass($newClassName)) { - return true; + if (!$this->reflectionProvider->hasClass($newClassName)) { + return \true; } - $classReflection = $this->reflectionProvider->getClass($newClassName); - // ensure new is not with interface - $parentNode = $name->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof New_ && $classReflection->isInterface()) { - return false; + $parentNode = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Expr\New_ && $classReflection->isInterface()) { + return \false; } - - if ($parentNode instanceof Class_) { + if ($parentNode instanceof \PhpParser\Node\Stmt\Class_) { return $this->isValidClassNameChange($name, $parentNode, $classReflection); } - // prevent to change to import, that already exists - if ($parentNode instanceof UseUse) { + if ($parentNode instanceof \PhpParser\Node\Stmt\UseUse) { return $this->isValidUseImportChange($newClassName, $parentNode); } - - return true; + return \true; } - /** * @param array $oldToNewClasses */ - private function getClassOfNamespaceToRefactor(Namespace_ $namespace, array $oldToNewClasses): ?ClassLike + private function getClassOfNamespaceToRefactor(\PhpParser\Node\Stmt\Namespace_ $namespace, array $oldToNewClasses) : ?\PhpParser\Node\Stmt\ClassLike { - $foundClass = $this->betterNodeFinder->findFirst($namespace, function (Node $node) use ( - $oldToNewClasses - ): bool { - if (! $node instanceof ClassLike) { - return false; + $foundClass = $this->betterNodeFinder->findFirst($namespace, function (\PhpParser\Node $node) use($oldToNewClasses) : bool { + if (!$node instanceof \PhpParser\Node\Stmt\ClassLike) { + return \false; } - $classLikeName = $this->nodeNameResolver->getName($node); - return isset($oldToNewClasses[$classLikeName]); }); - - return $foundClass instanceof ClassLike ? $foundClass : null; + return $foundClass instanceof \PhpParser\Node\Stmt\ClassLike ? $foundClass : null; } - /** * @param string[] $oldToNewClasses */ - private function renameClassImplements(ClassLike $classLike, array $oldToNewClasses): void + private function renameClassImplements(\PhpParser\Node\Stmt\ClassLike $classLike, array $oldToNewClasses) : void { - if (! $classLike instanceof Class_) { + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return; } - /** @var Scope|null $scope */ - $scope = $classLike->getAttribute(AttributeKey::SCOPE); - - $classLike->implements = array_unique($classLike->implements); + $scope = $classLike->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + $classLike->implements = \array_unique($classLike->implements); foreach ($classLike->implements as $key => $implementName) { - $virtualNode = $implementName->getAttribute(AttributeKey::VIRTUAL_NODE); - if (! $virtualNode) { + $virtualNode = $implementName->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::VIRTUAL_NODE); + if (!$virtualNode) { continue; } - - $namespaceName = $scope instanceof Scope ? $scope->getNamespace() : null; - + $namespaceName = $scope instanceof \PHPStan\Analyser\Scope ? $scope->getNamespace() : null; $fullyQualifiedName = $namespaceName . '\\' . $implementName->toString(); $newName = $oldToNewClasses[$fullyQualifiedName] ?? null; if ($newName === null) { continue; } - - $classLike->implements[$key] = new FullyQualified($newName); + $classLike->implements[$key] = new \PhpParser\Node\Name\FullyQualified($newName); } } - - private function isClassAboutToBeDuplicated(string $newName): bool + private function isClassAboutToBeDuplicated(string $newName) : bool { return $this->reflectionProvider->hasClass($newName); } - - private function changeNameToFullyQualifiedName(ClassLike $classLike): void + private function changeNameToFullyQualifiedName(\PhpParser\Node\Stmt\ClassLike $classLike) : void { - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classLike, function (Node $node) { - if (! $node instanceof FullyQualified) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classLike, function (\PhpParser\Node $node) { + if (!$node instanceof \PhpParser\Node\Name\FullyQualified) { return null; } - // invoke override - $node->setAttribute(AttributeKey::ORIGINAL_NODE, null); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); }); } - - private function isValidClassNameChange(Name $name, Class_ $class, ClassReflection $classReflection): bool + private function isValidClassNameChange(\PhpParser\Node\Name $name, \PhpParser\Node\Stmt\Class_ $class, \PHPStan\Reflection\ClassReflection $classReflection) : bool { if ($class->extends === $name) { // is class to interface? if ($classReflection->isInterface()) { - return false; + return \false; } - if ($classReflection->isFinalByKeyword()) { - return false; + return \false; } } - // is interface to class? - return ! (in_array($name, $class->implements, true) && $classReflection->isClass()); + return !(\in_array($name, $class->implements, \true) && $classReflection->isClass()); } - - private function isValidUseImportChange(string $newName, UseUse $useUse): bool + private function isValidUseImportChange(string $newName, \PhpParser\Node\Stmt\UseUse $useUse) : bool { /** @var Use_[]|null $useNodes */ - $useNodes = $useUse->getAttribute(AttributeKey::USE_NODES); + $useNodes = $useUse->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::USE_NODES); if ($useNodes === null) { - return true; + return \true; } - foreach ($useNodes as $useNode) { if ($this->nodeNameResolver->isName($useNode, $newName)) { // name already exists - return false; + return \false; } } - - return true; + return \true; } - - private function shouldRemoveUseName(string $last, string $newNameLastName, bool $importNames): bool + private function shouldRemoveUseName(string $last, string $newNameLastName, bool $importNames) : bool { return $last === $newNameLastName && $importNames; } diff --git a/rules/Renaming/NodeManipulator/IdentifierManipulator.php b/rules/Renaming/NodeManipulator/IdentifierManipulator.php index 24758b4358c..5bbd6ab7130 100644 --- a/rules/Renaming/NodeManipulator/IdentifierManipulator.php +++ b/rules/Renaming/NodeManipulator/IdentifierManipulator.php @@ -1,10 +1,9 @@ nodeNameResolver = $nodeNameResolver; } - /** * @param ClassConstFetch|MethodCall|PropertyFetch|StaticCall|ClassMethod $node * @param string[] $renameMethodMap */ - public function renameNodeWithMap(Node $node, array $renameMethodMap): void + public function renameNodeWithMap(\PhpParser\Node $node, array $renameMethodMap) : void { - Assert::isAnyOf($node, [ - ClassConstFetch::class, MethodCall::class, PropertyFetch::class, StaticCall::class, ClassMethod::class, - ]); - + \RectorPrefix20210509\Webmozart\Assert\Assert::isAnyOf($node, [\PhpParser\Node\Expr\ClassConstFetch::class, \PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\PropertyFetch::class, \PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Stmt\ClassMethod::class]); $oldNodeMethodName = $this->resolveOldMethodName($node); if ($oldNodeMethodName === null) { return; } - - $node->name = new Identifier($renameMethodMap[$oldNodeMethodName]); + $node->name = new \PhpParser\Node\Identifier($renameMethodMap[$oldNodeMethodName]); } - /** * @param ClassConstFetch|MethodCall|PropertyFetch|StaticCall|ClassMethod $node */ - public function removeSuffix(Node $node, string $suffixToRemove): void + public function removeSuffix(\PhpParser\Node $node, string $suffixToRemove) : void { - Assert::isAnyOf( - $node, - [ClassConstFetch::class, MethodCall::class, PropertyFetch::class, StaticCall::class, ClassMethod::class] - ); - + \RectorPrefix20210509\Webmozart\Assert\Assert::isAnyOf($node, [\PhpParser\Node\Expr\ClassConstFetch::class, \PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\PropertyFetch::class, \PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Stmt\ClassMethod::class]); $name = $this->nodeNameResolver->getName($node); if ($name === null) { return; } - - $newName = Strings::replace($name, sprintf('#%s$#', $suffixToRemove), ''); - - $node->name = new Identifier($newName); + $newName = \RectorPrefix20210509\Nette\Utils\Strings::replace($name, \sprintf('#%s$#', $suffixToRemove), ''); + $node->name = new \PhpParser\Node\Identifier($newName); } - /** * @param ClassConstFetch|MethodCall|PropertyFetch|StaticCall|ClassMethod $node */ - private function resolveOldMethodName(Node $node): ?string + private function resolveOldMethodName(\PhpParser\Node $node) : ?string { - if ($node instanceof StaticCall || $node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\StaticCall || $node instanceof \PhpParser\Node\Expr\MethodCall) { return $this->nodeNameResolver->getName($node->name); } - return $this->nodeNameResolver->getName($node); } } diff --git a/rules/Renaming/NodeManipulator/SwitchManipulator.php b/rules/Renaming/NodeManipulator/SwitchManipulator.php index b5e71a08e30..bcaa1f6d4c2 100644 --- a/rules/Renaming/NodeManipulator/SwitchManipulator.php +++ b/rules/Renaming/NodeManipulator/SwitchManipulator.php @@ -1,26 +1,23 @@ $node) { - if ($node instanceof Break_) { + if ($node instanceof \PhpParser\Node\Stmt\Break_) { unset($stmts[$key]); } } - return $stmts; } } diff --git a/rules/Renaming/Rector/ClassConstFetch/RenameClassConstFetchRector.php b/rules/Renaming/Rector/ClassConstFetch/RenameClassConstFetchRector.php index a1a1ec48b6b..83db266a39a 100644 --- a/rules/Renaming/Rector/ClassConstFetch/RenameClassConstFetchRector.php +++ b/rules/Renaming/Rector/ClassConstFetch/RenameClassConstFetchRector.php @@ -1,7 +1,6 @@ [ - new RenameClassConstFetch('SomeClass', 'OLD_CONSTANT', 'NEW_CONSTANT'), - new RenameClassAndConstFetch('SomeClass', 'OTHER_OLD_CONSTANT', 'DifferentClass', 'NEW_CONSTANT'), - ], - ]; - - return new RuleDefinition( - 'Replaces defined class constants in their calls.', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + $configuration = [self::CLASS_CONSTANT_RENAME => [new \Rector\Renaming\ValueObject\RenameClassConstFetch('SomeClass', 'OLD_CONSTANT', 'NEW_CONSTANT'), new \Rector\Renaming\ValueObject\RenameClassAndConstFetch('SomeClass', 'OTHER_OLD_CONSTANT', 'DifferentClass', 'NEW_CONSTANT')]]; + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces defined class constants in their calls.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' $value = SomeClass::OLD_CONSTANT; $value = SomeClass::OTHER_OLD_CONSTANT; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $value = SomeClass::NEW_CONSTANT; $value = DifferentClass::NEW_CONSTANT; CODE_SAMPLE - , - $configuration - ), - ] - ); +, $configuration)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassConstFetch::class]; + return [\PhpParser\Node\Expr\ClassConstFetch::class]; } - /** * @param ClassConstFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->renameClassConstFetches as $renameClassConstFetch) { - if (! $this->isObjectType($node->class, $renameClassConstFetch->getOldObjectType())) { + if (!$this->isObjectType($node->class, $renameClassConstFetch->getOldObjectType())) { continue; } - - if (! $this->isName($node->name, $renameClassConstFetch->getOldConstant())) { + if (!$this->isName($node->name, $renameClassConstFetch->getOldConstant())) { continue; } - - if ($renameClassConstFetch instanceof RenameClassAndConstFetch) { + if ($renameClassConstFetch instanceof \Rector\Renaming\ValueObject\RenameClassAndConstFetch) { return $this->createClassAndConstFetch($renameClassConstFetch); } - - $node->name = new Identifier($renameClassConstFetch->getNewConstant()); - + $node->name = new \PhpParser\Node\Identifier($renameClassConstFetch->getNewConstant()); return $node; } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $renameClassConstFetches = $configuration[self::CLASS_CONSTANT_RENAME] ?? []; - Assert::allIsInstanceOf($renameClassConstFetches, RenameClassConstFetchInterface::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($renameClassConstFetches, \Rector\Renaming\Contract\RenameClassConstFetchInterface::class); $this->renameClassConstFetches = $renameClassConstFetches; } - - private function createClassAndConstFetch(RenameClassAndConstFetch $renameClassAndConstFetch): ClassConstFetch + private function createClassAndConstFetch(\Rector\Renaming\ValueObject\RenameClassAndConstFetch $renameClassAndConstFetch) : \PhpParser\Node\Expr\ClassConstFetch { - return new ClassConstFetch( - new FullyQualified($renameClassAndConstFetch->getNewClass()), - new Identifier($renameClassAndConstFetch->getNewConstant()) - ); + return new \PhpParser\Node\Expr\ClassConstFetch(new \PhpParser\Node\Name\FullyQualified($renameClassAndConstFetch->getNewClass()), new \PhpParser\Node\Identifier($renameClassAndConstFetch->getNewConstant())); } } diff --git a/rules/Renaming/Rector/ClassMethod/RenameAnnotationRector.php b/rules/Renaming/Rector/ClassMethod/RenameAnnotationRector.php index 93ecd1b6070..c88dc400559 100644 --- a/rules/Renaming/Rector/ClassMethod/RenameAnnotationRector.php +++ b/rules/Renaming/Rector/ClassMethod/RenameAnnotationRector.php @@ -1,7 +1,6 @@ docBlockTagReplacer = $docBlockTagReplacer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Turns defined annotations above properties and methods to their new values.', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns defined annotations above properties and methods to their new values.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeTest extends PHPUnit\Framework\TestCase { /** @@ -59,8 +49,7 @@ class SomeTest extends PHPUnit\Framework\TestCase } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeTest extends PHPUnit\Framework\TestCase { /** @@ -71,59 +60,40 @@ class SomeTest extends PHPUnit\Framework\TestCase } } CODE_SAMPLE - , - [ - self::RENAMED_ANNOTATIONS_IN_TYPES => [ - new RenameAnnotation('PHPUnit\Framework\TestCase', 'test', 'scenario'), - ], - ] - ), - ] - ); +, [self::RENAMED_ANNOTATIONS_IN_TYPES => [new \Rector\Renaming\ValueObject\RenameAnnotation('PHPUnit\\Framework\\TestCase', 'test', 'scenario')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Property::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Property::class]; } - /** * @param ClassMethod|Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - foreach ($this->renamedAnnotations as $renamedAnnotation) { - if (! $this->isObjectType($classLike, $renamedAnnotation->getObjectType())) { + if (!$this->isObjectType($classLike, $renamedAnnotation->getObjectType())) { continue; } - - $this->docBlockTagReplacer->replaceTagByAnother( - $phpDocInfo, - $renamedAnnotation->getOldAnnotation(), - $renamedAnnotation->getNewAnnotation() - ); + $this->docBlockTagReplacer->replaceTagByAnother($phpDocInfo, $renamedAnnotation->getOldAnnotation(), $renamedAnnotation->getNewAnnotation()); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $renamedAnnotationsInTypes = $configuration[self::RENAMED_ANNOTATIONS_IN_TYPES] ?? []; - Assert::allIsInstanceOf($renamedAnnotationsInTypes, RenameAnnotation::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($renamedAnnotationsInTypes, \Rector\Renaming\ValueObject\RenameAnnotation::class); $this->renamedAnnotations = $renamedAnnotationsInTypes; } } diff --git a/rules/Renaming/Rector/ConstFetch/RenameConstantRector.php b/rules/Renaming/Rector/ConstFetch/RenameConstantRector.php index c25881d124a..236285e5095 100644 --- a/rules/Renaming/Rector/ConstFetch/RenameConstantRector.php +++ b/rules/Renaming/Rector/ConstFetch/RenameConstantRector.php @@ -1,7 +1,6 @@ */ private $oldToNewConstants = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replace constant by new ones', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replace constant by new ones', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -40,8 +34,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -50,46 +43,33 @@ final class SomeClass } } CODE_SAMPLE - , - [ - self::OLD_TO_NEW_CONSTANTS => [ - 'MYSQL_ASSOC' => 'MYSQLI_ASSOC', - 'OLD_CONSTANT' => 'NEW_CONSTANT', - ], - ] - ), - ]); +, [self::OLD_TO_NEW_CONSTANTS => ['MYSQL_ASSOC' => 'MYSQLI_ASSOC', 'OLD_CONSTANT' => 'NEW_CONSTANT']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ConstFetch::class]; + return [\PhpParser\Node\Expr\ConstFetch::class]; } - /** * @param ConstFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->oldToNewConstants as $oldConstant => $newConstant) { - if (! $this->isName($node->name, $oldConstant)) { + if (!$this->isName($node->name, $oldConstant)) { continue; } - - $node->name = new Name($newConstant); + $node->name = new \PhpParser\Node\Name($newConstant); return $node; } - return null; } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->oldToNewConstants = $configuration[self::OLD_TO_NEW_CONSTANTS] ?? []; } diff --git a/rules/Renaming/Rector/FileWithoutNamespace/PseudoNamespaceToNamespaceRector.php b/rules/Renaming/Rector/FileWithoutNamespace/PseudoNamespaceToNamespaceRector.php index cccaa1d56b4..ed8baa38a2e 100644 --- a/rules/Renaming/Rector/FileWithoutNamespace/PseudoNamespaceToNamespaceRector.php +++ b/rules/Renaming/Rector/FileWithoutNamespace/PseudoNamespaceToNamespaceRector.php @@ -1,10 +1,9 @@ phpDocTypeRenamer = $phpDocTypeRenamer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replaces defined Pseudo_Namespaces by Namespace\Ones.', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces defined Pseudo_Namespaces by Namespace\\Ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' /** @var Some_Chicken $someService */ $someService = new Some_Chicken; $someClassToKeep = new Some_Class_To_Keep; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' /** @var Some\Chicken $someService */ $someService = new Some\Chicken; $someClassToKeep = new Some_Class_To_Keep; CODE_SAMPLE - , - [ - self::NAMESPACE_PREFIXES_WITH_EXCLUDED_CLASSES => [ - new PseudoNamespaceToNamespace('Some_', ['Some_Class_To_Keep']), - ], - ] - ), - ]); +, [self::NAMESPACE_PREFIXES_WITH_EXCLUDED_CLASSES => [new \Rector\Renaming\ValueObject\PseudoNamespaceToNamespace('Some_', ['Some_Class_To_Keep'])]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { // property, method - return [FileWithoutNamespace::class, Namespace_::class]; + return [\Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace::class, \PhpParser\Node\Stmt\Namespace_::class]; } - /** * @param Namespace_|FileWithoutNamespace $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $this->newNamespace = null; - - if ($node instanceof FileWithoutNamespace) { + if ($node instanceof \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace) { $stmts = $this->refactorStmts($node->stmts); $node->stmts = $stmts; - // add a new namespace? if ($this->newNamespace) { - $namespace = new Namespace_(new Name($this->newNamespace)); + $namespace = new \PhpParser\Node\Stmt\Namespace_(new \PhpParser\Node\Name($this->newNamespace)); $namespace->stmts = $stmts; - return $namespace; } } - - if ($node instanceof Namespace_) { + if ($node instanceof \PhpParser\Node\Stmt\Namespace_) { $this->refactorStmts([$node]); return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $namespacePrefixesWithExcludedClasses = $configuration[self::NAMESPACE_PREFIXES_WITH_EXCLUDED_CLASSES] ?? []; - Assert::allIsInstanceOf($namespacePrefixesWithExcludedClasses, PseudoNamespaceToNamespace::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($namespacePrefixesWithExcludedClasses, \Rector\Renaming\ValueObject\PseudoNamespaceToNamespace::class); $this->pseudoNamespacesToNamespaces = $namespacePrefixesWithExcludedClasses; } - /** * @param Stmt[] $stmts * @return Stmt[] */ - private function refactorStmts(array $stmts): array + private function refactorStmts(array $stmts) : array { - $this->traverseNodesWithCallable($stmts, function (Node $node): ?Node { - if (! $node instanceof Name && ! $node instanceof Identifier && ! $node instanceof Property && ! $node instanceof FunctionLike) { + $this->traverseNodesWithCallable($stmts, function (\PhpParser\Node $node) : ?Node { + if (!$node instanceof \PhpParser\Node\Name && !$node instanceof \PhpParser\Node\Identifier && !$node instanceof \PhpParser\Node\Stmt\Property && !$node instanceof \PhpParser\Node\FunctionLike) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - // replace on @var/@param/@return/@throws foreach ($this->pseudoNamespacesToNamespaces as $pseudoNamespaceToNamespace) { $this->phpDocTypeRenamer->changeUnderscoreType($phpDocInfo, $node, $pseudoNamespaceToNamespace); } - // @todo - update rule to allow for bool instanceof check - if ($node instanceof Name || $node instanceof Identifier) { + if ($node instanceof \PhpParser\Node\Name || $node instanceof \PhpParser\Node\Identifier) { return $this->processNameOrIdentifier($node); } - return null; }); - return $stmts; } - /** * @param Name|Identifier $node * @return Name|Identifier */ - private function processNameOrIdentifier(Node $node): ?Node + private function processNameOrIdentifier(\PhpParser\Node $node) : ?\PhpParser\Node { // no name → skip if ($node->toString() === '') { return null; } - foreach ($this->pseudoNamespacesToNamespaces as $pseudoNamespaceToNamespace) { - if (! $this->isName($node, $pseudoNamespaceToNamespace->getNamespacePrefix() . '*')) { + if (!$this->isName($node, $pseudoNamespaceToNamespace->getNamespacePrefix() . '*')) { continue; } - $excludedClasses = $pseudoNamespaceToNamespace->getExcludedClasses(); - if (is_array($excludedClasses) && $this->isNames($node, $excludedClasses)) { + if (\is_array($excludedClasses) && $this->isNames($node, $excludedClasses)) { return null; } - - if ($node instanceof Name) { + if ($node instanceof \PhpParser\Node\Name) { return $this->processName($node); } - return $this->processIdentifier($node); } - return null; } - - private function processName(Name $name): Name + private function processName(\PhpParser\Node\Name $name) : \PhpParser\Node\Name { $nodeName = $this->getName($name); - if ($nodeName !== null) { - $name->parts = explode('_', $nodeName); + $name->parts = \explode('_', $nodeName); } - return $name; } - - private function processIdentifier(Identifier $identifier): ?Identifier + private function processIdentifier(\PhpParser\Node\Identifier $identifier) : ?\PhpParser\Node\Identifier { - $parentNode = $identifier->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Class_) { + $parentNode = $identifier->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\Stmt\Class_) { return null; } - $name = $this->getName($identifier); if ($name === null) { return null; } - /** @var string $namespaceName */ - $namespaceName = Strings::before($name, '_', -1); - + $namespaceName = \RectorPrefix20210509\Nette\Utils\Strings::before($name, '_', -1); /** @var string $lastNewNamePart */ - $lastNewNamePart = Strings::after($name, '_', -1); - - $newNamespace = Strings::replace($namespaceName, self::SPLIT_BY_UNDERSCORE_REGEX, '$1$2\\\\$4'); - + $lastNewNamePart = \RectorPrefix20210509\Nette\Utils\Strings::after($name, '_', -1); + $newNamespace = \RectorPrefix20210509\Nette\Utils\Strings::replace($namespaceName, self::SPLIT_BY_UNDERSCORE_REGEX, '$1$2\\\\$4'); if ($this->newNamespace !== null && $this->newNamespace !== $newNamespace) { - throw new ShouldNotHappenException('There cannot be 2 different namespaces in one file'); + throw new \Rector\Core\Exception\ShouldNotHappenException('There cannot be 2 different namespaces in one file'); } - $this->newNamespace = $newNamespace; $identifier->name = $lastNewNamePart; - return $identifier; } } diff --git a/rules/Renaming/Rector/FuncCall/RenameFunctionRector.php b/rules/Renaming/Rector/FuncCall/RenameFunctionRector.php index 191fb894f09..2c20554b998 100644 --- a/rules/Renaming/Rector/FuncCall/RenameFunctionRector.php +++ b/rules/Renaming/Rector/FuncCall/RenameFunctionRector.php @@ -1,10 +1,9 @@ */ private $oldFunctionToNewFunction = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turns defined function call new one.', [ - new ConfiguredCodeSample( - 'view("...", []);', - 'Laravel\Templating\render("...", []);', - [ - self::OLD_FUNCTION_TO_NEW_FUNCTION => [ - 'view' => 'Laravel\Templating\render', - ], - ] - ), - ]); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns defined function call new one.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample('view("...", []);', 'Laravel\\Templating\\render("...", []);', [self::OLD_FUNCTION_TO_NEW_FUNCTION => ['view' => 'Laravel\\Templating\\render']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->oldFunctionToNewFunction as $oldFunction => $newFunction) { - if (! $this->isName($node, $oldFunction)) { + if (!$this->isName($node, $oldFunction)) { continue; } - $node->name = $this->createName($newFunction); return $node; } - return null; } - /** * @param mixed[] $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->oldFunctionToNewFunction = $configuration[self::OLD_FUNCTION_TO_NEW_FUNCTION] ?? []; } - - private function createName(string $newFunction): Name + private function createName(string $newFunction) : \PhpParser\Node\Name { - if (Strings::contains($newFunction, '\\')) { - return new FullyQualified($newFunction); + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($newFunction, '\\')) { + return new \PhpParser\Node\Name\FullyQualified($newFunction); } - - return new Name($newFunction); + return new \PhpParser\Node\Name($newFunction); } } diff --git a/rules/Renaming/Rector/MethodCall/RenameMethodRector.php b/rules/Renaming/Rector/MethodCall/RenameMethodRector.php index f28b12637d9..2147c29e73b 100644 --- a/rules/Renaming/Rector/MethodCall/RenameMethodRector.php +++ b/rules/Renaming/Rector/MethodCall/RenameMethodRector.php @@ -1,7 +1,6 @@ classManipulator = $classManipulator; $this->methodCallRenameCollector = $methodCallRenameCollector; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turns method names to new ones.', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns method names to new ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' $someObject = new SomeExampleClass; $someObject->oldMethod(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someObject = new SomeExampleClass; $someObject->newMethod(); CODE_SAMPLE - , - [ - self::METHOD_CALL_RENAMES => [ - new MethodCallRename('SomeExampleClass', 'oldMethod', 'newMethod'), - ], - ] - ), - ]); +, [self::METHOD_CALL_RENAMES => [new \Rector\Renaming\ValueObject\MethodCallRename('SomeExampleClass', 'oldMethod', 'newMethod')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class, StaticCall::class, ClassMethod::class]; + return [\PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param MethodCall|StaticCall|ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->methodCallRenames as $methodCallRename) { - $implementsInterface = $this->classManipulator->hasParentMethodOrInterface( - $methodCallRename->getOldObjectType(), - $methodCallRename->getOldMethod() - ); + $implementsInterface = $this->classManipulator->hasParentMethodOrInterface($methodCallRename->getOldObjectType(), $methodCallRename->getOldMethod()); if ($implementsInterface) { continue; } - - if (! $this->nodeTypeResolver->isMethodStaticCallOrClassMethodObjectType( - $node, - $methodCallRename->getOldObjectType() - )) { + if (!$this->nodeTypeResolver->isMethodStaticCallOrClassMethodObjectType($node, $methodCallRename->getOldObjectType())) { continue; } - - if (! $this->isName($node->name, $methodCallRename->getOldMethod())) { + if (!$this->isName($node->name, $methodCallRename->getOldMethod())) { continue; } - if ($this->skipClassMethod($node, $methodCallRename)) { continue; } - - $node->name = new Identifier($methodCallRename->getNewMethod()); - - if ($methodCallRename instanceof MethodCallRenameWithArrayKey && ! $node instanceof ClassMethod) { - return new ArrayDimFetch($node, BuilderHelpers::normalizeValue($methodCallRename->getArrayKey())); + $node->name = new \PhpParser\Node\Identifier($methodCallRename->getNewMethod()); + if ($methodCallRename instanceof \Rector\Renaming\ValueObject\MethodCallRenameWithArrayKey && !$node instanceof \PhpParser\Node\Stmt\ClassMethod) { + return new \PhpParser\Node\Expr\ArrayDimFetch($node, \PhpParser\BuilderHelpers::normalizeValue($methodCallRename->getArrayKey())); } - return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $methodCallRenames = $configuration[self::METHOD_CALL_RENAMES] ?? []; - Assert::allIsInstanceOf($methodCallRenames, MethodCallRenameInterface::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($methodCallRenames, \Rector\Renaming\Contract\MethodCallRenameInterface::class); $this->methodCallRenames = $methodCallRenames; $this->methodCallRenameCollector->addMethodCallRenames($methodCallRenames); } - /** * @param MethodCall|StaticCall|ClassMethod $node */ - private function skipClassMethod(Node $node, MethodCallRenameInterface $methodCallRename): bool + private function skipClassMethod(\PhpParser\Node $node, \Rector\Renaming\Contract\MethodCallRenameInterface $methodCallRename) : bool { - if (! $node instanceof ClassMethod) { - return false; + if (!$node instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - if ($this->shouldSkipForAlreadyExistingClassMethod($node, $methodCallRename)) { - return true; + return \true; } - - return $this->shouldSkipForExactClassMethodForClassMethodOrTargetInvokePrivate( - $node, - $methodCallRename->getOldObjectType(), - $methodCallRename->getNewMethod() - ); + return $this->shouldSkipForExactClassMethodForClassMethodOrTargetInvokePrivate($node, $methodCallRename->getOldObjectType(), $methodCallRename->getNewMethod()); } - - private function shouldSkipForAlreadyExistingClassMethod( - ClassMethod $classMethod, - MethodCallRenameInterface $methodCallRename - ): bool { - $classLike = $classMethod->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { - return false; + private function shouldSkipForAlreadyExistingClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \Rector\Renaming\Contract\MethodCallRenameInterface $methodCallRename) : bool + { + $classLike = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { + return \false; } - return (bool) $classLike->getMethod($methodCallRename->getNewMethod()); } - - private function shouldSkipForExactClassMethodForClassMethodOrTargetInvokePrivate( - ClassMethod $classMethod, - ObjectType $objectType, - string $newMethodName - ): bool { - $className = $classMethod->getAttribute(AttributeKey::CLASS_NAME); + private function shouldSkipForExactClassMethodForClassMethodOrTargetInvokePrivate(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Type\ObjectType $objectType, string $newMethodName) : bool + { + $className = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); $methodCalls = $this->nodeRepository->findMethodCallsOnClass($className); - $name = $this->getName($classMethod->name); if (isset($methodCalls[$name])) { - return false; + return \false; } - - $classMethodClass = $classMethod->getAttribute(AttributeKey::CLASS_NAME); + $classMethodClass = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($classMethodClass === $objectType) { - return true; + return \true; } - if ($classMethod->isPublic()) { - return false; + return \false; } - $newClassMethod = clone $classMethod; - $newClassMethod->name = new Identifier($newMethodName); - + $newClassMethod->name = new \PhpParser\Node\Identifier($newMethodName); return $newClassMethod->isMagic(); } } diff --git a/rules/Renaming/Rector/Name/RenameClassRector.php b/rules/Renaming/Rector/Name/RenameClassRector.php index 1772d06d4c7..3558e7b2b6d 100644 --- a/rules/Renaming/Rector/Name/RenameClassRector.php +++ b/rules/Renaming/Rector/Name/RenameClassRector.php @@ -1,7 +1,6 @@ */ private $oldToNewClasses = []; - /** * @var ClassRenamer */ private $classRenamer; - /** * @var RenamedClassesDataCollector */ private $renamedClassesDataCollector; - - public function __construct(RenamedClassesDataCollector $renamedClassesDataCollector, ClassRenamer $classRenamer) + public function __construct(\Rector\Core\Configuration\RenamedClassesDataCollector $renamedClassesDataCollector, \Rector\Renaming\NodeManipulator\ClassRenamer $classRenamer) { $this->classRenamer = $classRenamer; $this->renamedClassesDataCollector = $renamedClassesDataCollector; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replaces defined classes by new ones.', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces defined classes by new ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' namespace App; use SomeOldClass; @@ -66,8 +57,7 @@ function someFunction(SomeOldClass $someOldClass): SomeOldClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' namespace App; use SomeNewClass; @@ -79,47 +69,28 @@ function someFunction(SomeNewClass $someOldClass): SomeNewClass } } CODE_SAMPLE - , - [ - self::OLD_TO_NEW_CLASSES => [ - 'App\SomeOldClass' => 'App\SomeNewClass', - ], - ] - ), - ]); +, [self::OLD_TO_NEW_CLASSES => ['App\\SomeOldClass' => 'App\\SomeNewClass']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ - Name::class, - Property::class, - FunctionLike::class, - Expression::class, - ClassLike::class, - Namespace_::class, - FileWithoutNamespace::class, - ]; + return [\PhpParser\Node\Name::class, \PhpParser\Node\Stmt\Property::class, \PhpParser\Node\FunctionLike::class, \PhpParser\Node\Stmt\Expression::class, \PhpParser\Node\Stmt\ClassLike::class, \PhpParser\Node\Stmt\Namespace_::class, \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace::class]; } - /** * @param FunctionLike|Name|ClassLike|Expression|Namespace_|Property|FileWithoutNamespace $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { return $this->classRenamer->renameNode($node, $this->oldToNewClasses); } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $oldToNewClasses = $configuration[self::OLD_TO_NEW_CLASSES] ?? []; - $this->renamedClassesDataCollector->addOldToNewClasses($oldToNewClasses); $this->oldToNewClasses = $this->renamedClassesDataCollector->getOldToNewClasses(); } diff --git a/rules/Renaming/Rector/Namespace_/RenameNamespaceRector.php b/rules/Renaming/Rector/Namespace_/RenameNamespaceRector.php index 7fd4f47907b..d6372b4720f 100644 --- a/rules/Renaming/Rector/Namespace_/RenameNamespaceRector.php +++ b/rules/Renaming/Rector/Namespace_/RenameNamespaceRector.php @@ -1,10 +1,9 @@ */ private $oldToNewNamespaces = []; - /** * @var NamespaceMatcher */ private $namespaceMatcher; - - public function __construct(NamespaceMatcher $namespaceMatcher) + public function __construct(\Rector\Naming\NamespaceMatcher $namespaceMatcher) { $this->namespaceMatcher = $namespaceMatcher; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replaces old namespace by new one.', [ - new ConfiguredCodeSample( - '$someObject = new SomeOldNamespace\SomeClass;', - '$someObject = new SomeNewNamespace\SomeClass;', - [ - self::OLD_TO_NEW_NAMESPACES => [ - 'SomeOldNamespace' => 'SomeNewNamespace', - ], - ] - ), - ]); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces old namespace by new one.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample('$someObject = new SomeOldNamespace\\SomeClass;', '$someObject = new SomeNewNamespace\\SomeClass;', [self::OLD_TO_NEW_NAMESPACES => ['SomeOldNamespace' => 'SomeNewNamespace']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Namespace_::class, Use_::class, Name::class]; + return [\PhpParser\Node\Stmt\Namespace_::class, \PhpParser\Node\Stmt\Use_::class, \PhpParser\Node\Name::class]; } - /** * @param Namespace_|Use_|Name $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $name = $this->getName($node); if ($name === null) { return null; } - $renamedNamespaceValueObject = $this->namespaceMatcher->matchRenamedNamespace($name, $this->oldToNewNamespaces); - if (! $renamedNamespaceValueObject instanceof RenamedNamespace) { + if (!$renamedNamespaceValueObject instanceof \Rector\Renaming\ValueObject\RenamedNamespace) { return null; } - if ($this->isClassFullyQualifiedName($node)) { return null; } - - if ($node instanceof Namespace_) { + if ($node instanceof \PhpParser\Node\Stmt\Namespace_) { $newName = $renamedNamespaceValueObject->getNameInNewNamespace(); - $node->name = new Name($newName); - + $node->name = new \PhpParser\Node\Name($newName); return $node; } - - if ($node instanceof Use_) { + if ($node instanceof \PhpParser\Node\Stmt\Use_) { $newName = $renamedNamespaceValueObject->getNameInNewNamespace(); - $node->uses[0]->name = new Name($newName); - + $node->uses[0]->name = new \PhpParser\Node\Name($newName); return $node; } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); // already resolved above - if ($parent instanceof Namespace_) { + if ($parent instanceof \PhpParser\Node\Stmt\Namespace_) { return null; } - - if ($parent instanceof UseUse && $parent->type === Use_::TYPE_UNKNOWN) { + if ($parent instanceof \PhpParser\Node\Stmt\UseUse && $parent->type === \PhpParser\Node\Stmt\Use_::TYPE_UNKNOWN) { return null; } - - $newName = $this->isPartialNamespace($node) ? $this->resolvePartialNewName( - $node, - $renamedNamespaceValueObject - ) : $renamedNamespaceValueObject->getNameInNewNamespace(); - - return new FullyQualified($newName); + $newName = $this->isPartialNamespace($node) ? $this->resolvePartialNewName($node, $renamedNamespaceValueObject) : $renamedNamespaceValueObject->getNameInNewNamespace(); + return new \PhpParser\Node\Name\FullyQualified($newName); } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->oldToNewNamespaces = $configuration[self::OLD_TO_NEW_NAMESPACES] ?? []; } - /** * Checks for "new \ClassNoNamespace;" * This should be skipped, not a namespace. */ - private function isClassFullyQualifiedName(Node $node): bool + private function isClassFullyQualifiedName(\PhpParser\Node $node) : bool { - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Node) { - return false; + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node) { + return \false; } - - if (! $parentNode instanceof New_) { - return false; + if (!$parentNode instanceof \PhpParser\Node\Expr\New_) { + return \false; } - /** @var FullyQualified $fullyQualifiedNode */ $fullyQualifiedNode = $parentNode->class; - $newClassName = $fullyQualifiedNode->toString(); - - return array_key_exists($newClassName, $this->oldToNewNamespaces); + return \array_key_exists($newClassName, $this->oldToNewNamespaces); } - - private function isPartialNamespace(Name $name): bool + private function isPartialNamespace(\PhpParser\Node\Name $name) : bool { - $resolvedName = $name->getAttribute(AttributeKey::RESOLVED_NAME); - if (! $resolvedName instanceof Name) { - return false; + $resolvedName = $name->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::RESOLVED_NAME); + if (!$resolvedName instanceof \PhpParser\Node\Name) { + return \false; } - - if ($resolvedName instanceof FullyQualified) { - return ! $this->isName($name, $resolvedName->toString()); + if ($resolvedName instanceof \PhpParser\Node\Name\FullyQualified) { + return !$this->isName($name, $resolvedName->toString()); } - - return false; + return \false; } - - private function resolvePartialNewName(Name $name, RenamedNamespace $renamedNamespace): string + private function resolvePartialNewName(\PhpParser\Node\Name $name, \Rector\Renaming\ValueObject\RenamedNamespace $renamedNamespace) : string { $nameInNewNamespace = $renamedNamespace->getNameInNewNamespace(); - // first dummy implementation - improve - $cutOffFromTheLeft = Strings::length($nameInNewNamespace) - Strings::length($name->toString()); - - return Strings::substring($nameInNewNamespace, $cutOffFromTheLeft); + $cutOffFromTheLeft = \RectorPrefix20210509\Nette\Utils\Strings::length($nameInNewNamespace) - \RectorPrefix20210509\Nette\Utils\Strings::length($name->toString()); + return \RectorPrefix20210509\Nette\Utils\Strings::substring($nameInNewNamespace, $cutOffFromTheLeft); } } diff --git a/rules/Renaming/Rector/PropertyFetch/RenamePropertyRector.php b/rules/Renaming/Rector/PropertyFetch/RenamePropertyRector.php index f27d14fc229..ad5f931eaa5 100644 --- a/rules/Renaming/Rector/PropertyFetch/RenamePropertyRector.php +++ b/rules/Renaming/Rector/PropertyFetch/RenamePropertyRector.php @@ -1,7 +1,6 @@ someOldProperty;', - '$someObject->someNewProperty;', - [ - self::RENAMED_PROPERTIES => [ - new RenameProperty('SomeClass', 'someOldProperty', 'someNewProperty'), - ], - ] - ), - ]); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces defined old properties by new ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample('$someObject->someOldProperty;', '$someObject->someNewProperty;', [self::RENAMED_PROPERTIES => [new \Rector\Renaming\ValueObject\RenameProperty('SomeClass', 'someOldProperty', 'someNewProperty')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [PropertyFetch::class]; + return [\PhpParser\Node\Expr\PropertyFetch::class]; } - /** * @param PropertyFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->renamedProperties as $renamedProperty) { - if (! $this->isObjectType($node->var, $renamedProperty->getObjectType())) { + if (!$this->isObjectType($node->var, $renamedProperty->getObjectType())) { continue; } - - if (! $this->isName($node, $renamedProperty->getOldProperty())) { + if (!$this->isName($node, $renamedProperty->getOldProperty())) { continue; } - - $node->name = new Identifier($renamedProperty->getNewProperty()); + $node->name = new \PhpParser\Node\Identifier($renamedProperty->getNewProperty()); return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $renamedProperties = $configuration[self::RENAMED_PROPERTIES] ?? []; - Assert::allIsInstanceOf($renamedProperties, RenameProperty::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($renamedProperties, \Rector\Renaming\ValueObject\RenameProperty::class); $this->renamedProperties = $renamedProperties; } } diff --git a/rules/Renaming/Rector/StaticCall/RenameStaticMethodRector.php b/rules/Renaming/Rector/StaticCall/RenameStaticMethodRector.php index cf8aec80719..68e68669d25 100644 --- a/rules/Renaming/Rector/StaticCall/RenameStaticMethodRector.php +++ b/rules/Renaming/Rector/StaticCall/RenameStaticMethodRector.php @@ -1,7 +1,6 @@ [ - new RenameStaticMethod(self::SOME_CLASS, 'oldMethod', 'AnotherExampleClass', 'newStaticMethod'), - ], - ]; - - $renameMethodConfiguration = [ - self::OLD_TO_NEW_METHODS_BY_CLASSES => [ - new RenameStaticMethod(self::SOME_CLASS, 'oldMethod', self::SOME_CLASS, 'newStaticMethod'), - ], - ]; - - return new RuleDefinition('Turns method names to new ones.', [ - new ConfiguredCodeSample( - 'SomeClass::oldStaticMethod();', - 'AnotherExampleClass::newStaticMethod();', - $renameClassConfiguration - ), - new ConfiguredCodeSample( - 'SomeClass::oldStaticMethod();', - 'SomeClass::newStaticMethod();', - $renameMethodConfiguration - ), - ]); + $renameClassConfiguration = [self::OLD_TO_NEW_METHODS_BY_CLASSES => [new \Rector\Renaming\ValueObject\RenameStaticMethod(self::SOME_CLASS, 'oldMethod', 'AnotherExampleClass', 'newStaticMethod')]]; + $renameMethodConfiguration = [self::OLD_TO_NEW_METHODS_BY_CLASSES => [new \Rector\Renaming\ValueObject\RenameStaticMethod(self::SOME_CLASS, 'oldMethod', self::SOME_CLASS, 'newStaticMethod')]]; + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns method names to new ones.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample('SomeClass::oldStaticMethod();', 'AnotherExampleClass::newStaticMethod();', $renameClassConfiguration), new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample('SomeClass::oldStaticMethod();', 'SomeClass::newStaticMethod();', $renameMethodConfiguration)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->staticMethodRenames as $staticMethodRename) { - if (! $this->isObjectType($node->class, $staticMethodRename->getOldObjectType())) { + if (!$this->isObjectType($node->class, $staticMethodRename->getOldObjectType())) { continue; } - - if (! $this->isName($node->name, $staticMethodRename->getOldMethod())) { + if (!$this->isName($node->name, $staticMethodRename->getOldMethod())) { continue; } - return $this->rename($node, $staticMethodRename); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $oldToNewMethodsByClasses = $configuration[self::OLD_TO_NEW_METHODS_BY_CLASSES]; - Assert::allIsInstanceOf($oldToNewMethodsByClasses, RenameStaticMethod::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($oldToNewMethodsByClasses, \Rector\Renaming\ValueObject\RenameStaticMethod::class); $this->staticMethodRenames = $oldToNewMethodsByClasses; } - - private function rename(StaticCall $staticCall, RenameStaticMethod $renameStaticMethod): StaticCall + private function rename(\PhpParser\Node\Expr\StaticCall $staticCall, \Rector\Renaming\ValueObject\RenameStaticMethod $renameStaticMethod) : \PhpParser\Node\Expr\StaticCall { - $staticCall->name = new Identifier($renameStaticMethod->getNewMethod()); - + $staticCall->name = new \PhpParser\Node\Identifier($renameStaticMethod->getNewMethod()); if ($renameStaticMethod->hasClassChanged()) { - $staticCall->class = new FullyQualified($renameStaticMethod->getNewClass()); + $staticCall->class = new \PhpParser\Node\Name\FullyQualified($renameStaticMethod->getNewClass()); } - return $staticCall; } } diff --git a/rules/Renaming/Rector/String_/RenameStringRector.php b/rules/Renaming/Rector/String_/RenameStringRector.php index 5097ef6f0c2..092f3481913 100644 --- a/rules/Renaming/Rector/String_/RenameStringRector.php +++ b/rules/Renaming/Rector/String_/RenameStringRector.php @@ -1,7 +1,6 @@ [ - 'ROLE_PREVIOUS_ADMIN' => 'IS_IMPERSONATOR', - ], - ] - ), - ]); +, [self::STRING_CHANGES => ['ROLE_PREVIOUS_ADMIN' => 'IS_IMPERSONATOR']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [String_::class]; + return [\PhpParser\Node\Scalar\String_::class]; } - /** * @param String_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->stringChanges as $oldValue => $newValue) { - if (! $this->valueResolver->isValue($node, $oldValue)) { + if (!$this->valueResolver->isValue($node, $oldValue)) { continue; } - - return new String_($newValue); + return new \PhpParser\Node\Scalar\String_($newValue); } - return null; } - /** * @param mixed[] $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->stringChanges = $configuration[self::STRING_CHANGES] ?? []; } diff --git a/rules/Renaming/ValueObject/MethodCallRename.php b/rules/Renaming/ValueObject/MethodCallRename.php index 6dff7da0157..ddab7195bfd 100644 --- a/rules/Renaming/ValueObject/MethodCallRename.php +++ b/rules/Renaming/ValueObject/MethodCallRename.php @@ -1,47 +1,39 @@ oldClass = $oldClass; $this->oldMethod = $oldMethod; $this->newMethod = $newMethod; } - - public function getOldObjectType(): ObjectType + public function getOldObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->oldClass); + return new \PHPStan\Type\ObjectType($this->oldClass); } - - public function getOldMethod(): string + public function getOldMethod() : string { return $this->oldMethod; } - - public function getNewMethod(): string + public function getNewMethod() : string { return $this->newMethod; } diff --git a/rules/Renaming/ValueObject/MethodCallRenameWithArrayKey.php b/rules/Renaming/ValueObject/MethodCallRenameWithArrayKey.php index c6862efeab9..51578df5eaa 100644 --- a/rules/Renaming/ValueObject/MethodCallRenameWithArrayKey.php +++ b/rules/Renaming/ValueObject/MethodCallRenameWithArrayKey.php @@ -1,34 +1,28 @@ newMethod = $newMethod; $this->arrayKey = $arrayKey; } - - public function getOldObjectType(): ObjectType + public function getOldObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->oldClass); + return new \PHPStan\Type\ObjectType($this->oldClass); } - - public function getOldMethod(): string + public function getOldMethod() : string { return $this->oldMethod; } - - public function getNewMethod(): string + public function getNewMethod() : string { return $this->newMethod; } - /** * @return mixed */ diff --git a/rules/Renaming/ValueObject/PseudoNamespaceToNamespace.php b/rules/Renaming/ValueObject/PseudoNamespaceToNamespace.php index a01f8275c28..f6492c88d96 100644 --- a/rules/Renaming/ValueObject/PseudoNamespaceToNamespace.php +++ b/rules/Renaming/ValueObject/PseudoNamespaceToNamespace.php @@ -1,7 +1,6 @@ namespacePrefix = $namespacePrefix; $this->excludedClasses = $excludedClasses; } - - public function getNamespacePrefix(): string + public function getNamespacePrefix() : string { return $this->namespacePrefix; } - /** * @return string[] */ - public function getExcludedClasses(): array + public function getExcludedClasses() : array { return $this->excludedClasses; } diff --git a/rules/Renaming/ValueObject/RenameAnnotation.php b/rules/Renaming/ValueObject/RenameAnnotation.php index 7ec0c47d647..cd990eb96cf 100644 --- a/rules/Renaming/ValueObject/RenameAnnotation.php +++ b/rules/Renaming/ValueObject/RenameAnnotation.php @@ -1,46 +1,38 @@ type = $type; $this->oldAnnotation = $oldAnnotation; $this->newAnnotation = $newAnnotation; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->type); + return new \PHPStan\Type\ObjectType($this->type); } - - public function getOldAnnotation(): string + public function getOldAnnotation() : string { return $this->oldAnnotation; } - - public function getNewAnnotation(): string + public function getNewAnnotation() : string { return $this->newAnnotation; } diff --git a/rules/Renaming/ValueObject/RenameClassAndConstFetch.php b/rules/Renaming/ValueObject/RenameClassAndConstFetch.php index 1f9bc30b00d..7902701ac6d 100644 --- a/rules/Renaming/ValueObject/RenameClassAndConstFetch.php +++ b/rules/Renaming/ValueObject/RenameClassAndConstFetch.php @@ -1,34 +1,28 @@ oldClass = $oldClass; @@ -36,23 +30,19 @@ final class RenameClassAndConstFetch implements RenameClassConstFetchInterface $this->newConstant = $newConstant; $this->newClass = $newClass; } - - public function getOldObjectType(): ObjectType + public function getOldObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->oldClass); + return new \PHPStan\Type\ObjectType($this->oldClass); } - - public function getOldConstant(): string + public function getOldConstant() : string { return $this->oldConstant; } - - public function getNewConstant(): string + public function getNewConstant() : string { return $this->newConstant; } - - public function getNewClass(): string + public function getNewClass() : string { return $this->newClass; } diff --git a/rules/Renaming/ValueObject/RenameClassConstFetch.php b/rules/Renaming/ValueObject/RenameClassConstFetch.php index 8e3235bbb83..2fd513b7f24 100644 --- a/rules/Renaming/ValueObject/RenameClassConstFetch.php +++ b/rules/Renaming/ValueObject/RenameClassConstFetch.php @@ -1,47 +1,39 @@ oldClass = $oldClass; $this->oldConstant = $oldConstant; $this->newConstant = $newConstant; } - - public function getOldObjectType(): ObjectType + public function getOldObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->oldClass); + return new \PHPStan\Type\ObjectType($this->oldClass); } - - public function getOldConstant(): string + public function getOldConstant() : string { return $this->oldConstant; } - - public function getNewConstant(): string + public function getNewConstant() : string { return $this->newConstant; } diff --git a/rules/Renaming/ValueObject/RenameProperty.php b/rules/Renaming/ValueObject/RenameProperty.php index 676299b77da..65de153075a 100644 --- a/rules/Renaming/ValueObject/RenameProperty.php +++ b/rules/Renaming/ValueObject/RenameProperty.php @@ -1,46 +1,38 @@ type = $type; $this->oldProperty = $oldProperty; $this->newProperty = $newProperty; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->type); + return new \PHPStan\Type\ObjectType($this->type); } - - public function getOldProperty(): string + public function getOldProperty() : string { return $this->oldProperty; } - - public function getNewProperty(): string + public function getNewProperty() : string { return $this->newProperty; } diff --git a/rules/Renaming/ValueObject/RenameStaticMethod.php b/rules/Renaming/ValueObject/RenameStaticMethod.php index 8b30f406dce..2ad802ce1ee 100644 --- a/rules/Renaming/ValueObject/RenameStaticMethod.php +++ b/rules/Renaming/ValueObject/RenameStaticMethod.php @@ -1,33 +1,27 @@ oldClass = $oldClass; @@ -35,28 +29,23 @@ final class RenameStaticMethod $this->newClass = $newClass; $this->newMethod = $newMethod; } - - public function getOldObjectType(): ObjectType + public function getOldObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->oldClass); + return new \PHPStan\Type\ObjectType($this->oldClass); } - - public function getOldMethod(): string + public function getOldMethod() : string { return $this->oldMethod; } - - public function getNewClass(): string + public function getNewClass() : string { return $this->newClass; } - - public function getNewMethod(): string + public function getNewMethod() : string { return $this->newMethod; } - - public function hasClassChanged(): bool + public function hasClassChanged() : bool { return $this->oldClass !== $this->newClass; } diff --git a/rules/Renaming/ValueObject/RenamedNamespace.php b/rules/Renaming/ValueObject/RenamedNamespace.php index c4416e6df60..f2aa3dbad52 100644 --- a/rules/Renaming/ValueObject/RenamedNamespace.php +++ b/rules/Renaming/ValueObject/RenamedNamespace.php @@ -1,7 +1,6 @@ currentName = $currentNamespaceName; $this->oldNamespace = $oldNamespace; $this->newNamespace = $newNamespace; } - - public function getNameInNewNamespace(): string + public function getNameInNewNamespace() : string { - return str_replace($this->oldNamespace, $this->newNamespace, $this->currentName); + return \str_replace($this->oldNamespace, $this->newNamespace, $this->currentName); } } diff --git a/rules/Restoration/Rector/ClassConstFetch/MissingClassConstantReferenceToStringRector.php b/rules/Restoration/Rector/ClassConstFetch/MissingClassConstantReferenceToStringRector.php index d29ce7a4613..1d5d8d21eda 100644 --- a/rules/Restoration/Rector/ClassConstFetch/MissingClassConstantReferenceToStringRector.php +++ b/rules/Restoration/Rector/ClassConstFetch/MissingClassConstantReferenceToStringRector.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Convert missing class reference to string', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Convert missing class reference to string', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -40,8 +34,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -50,36 +43,30 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassConstFetch::class]; + return [\PhpParser\Node\Expr\ClassConstFetch::class]; } - /** * @param ClassConstFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isName($node->name, 'class')) { + if (!$this->isName($node->name, 'class')) { return null; } - $referencedClass = $this->getName($node->class); if ($referencedClass === null) { return null; } - if ($this->reflectionProvider->hasClass($referencedClass)) { return null; } - - return new String_($referencedClass); + return new \PhpParser\Node\Scalar\String_($referencedClass); } } diff --git a/rules/Restoration/Rector/ClassLike/UpdateFileNameByClassNameFileSystemRector.php b/rules/Restoration/Rector/ClassLike/UpdateFileNameByClassNameFileSystemRector.php index 14821917856..a5c84ecf6dc 100644 --- a/rules/Restoration/Rector/ClassLike/UpdateFileNameByClassNameFileSystemRector.php +++ b/rules/Restoration/Rector/ClassLike/UpdateFileNameByClassNameFileSystemRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassLike::class]; + return [\PhpParser\Node\Stmt\ClassLike::class]; } - /** * @param ClassLike $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $className = $this->getName($node); if ($className === null) { return null; } - $classShortName = $this->nodeNameResolver->getShortName($className); - $smartFileInfo = $this->file->getSmartFileInfo(); - // matches if ($classShortName === $smartFileInfo->getBasenameWithoutSuffix()) { return null; } - // no match → rename file - $newFileLocation = $smartFileInfo->getPath() . DIRECTORY_SEPARATOR . $classShortName . '.php'; - - $addedFileWithContent = new AddedFileWithContent($newFileLocation, $smartFileInfo->getContents()); + $newFileLocation = $smartFileInfo->getPath() . \DIRECTORY_SEPARATOR . $classShortName . '.php'; + $addedFileWithContent = new \Rector\FileSystemRector\ValueObject\AddedFileWithContent($newFileLocation, $smartFileInfo->getContents()); $this->removedAndAddedFilesCollector->removeFile($smartFileInfo); - $this->removedAndAddedFilesCollector->addAddedFile($addedFileWithContent); - return null; } } diff --git a/rules/Restoration/Rector/ClassMethod/InferParamFromClassMethodReturnRector.php b/rules/Restoration/Rector/ClassMethod/InferParamFromClassMethodReturnRector.php index 66a6431e5c5..2c23bf6e44a 100644 --- a/rules/Restoration/Rector/ClassMethod/InferParamFromClassMethodReturnRector.php +++ b/rules/Restoration/Rector/ClassMethod/InferParamFromClassMethodReturnRector.php @@ -1,7 +1,6 @@ returnTypeInferer = $returnTypeInferer; $this->constantReturnToParamTypeConverter = $constantReturnToParamTypeConverter; $this->phpDocTypeChanger = $phpDocTypeChanger; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change @param doc based on another method return type', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change @param doc based on another method return type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function getNodeTypes(): array @@ -81,8 +68,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function getNodeTypes(): array @@ -98,106 +84,77 @@ class SomeClass } } CODE_SAMPLE -, - [ - self::INFER_PARAMS_FROM_CLASS_METHOD_RETURNS => [ - new InferParamFromClassMethodReturn('SomeClass', 'process', 'getNodeTypes'), - ], - ] - ), - ]); +, [self::INFER_PARAMS_FROM_CLASS_METHOD_RETURNS => [new \Rector\Restoration\ValueObject\InferParamFromClassMethodReturn('SomeClass', 'process', 'getNodeTypes')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { // must be exactly 1 param - if (count($node->params) !== 1) { + if (\count($node->params) !== 1) { return null; } - $firstParam = $node->params[0]; $paramName = $this->getName($firstParam); - foreach ($this->inferParamFromClassMethodReturn as $singleInferParamFromClassMethodReturn) { $returnClassMethod = $this->matchReturnClassMethod($node, $singleInferParamFromClassMethodReturn); - if (! $returnClassMethod instanceof ClassMethod) { + if (!$returnClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { continue; } - $returnType = $this->returnTypeInferer->inferFunctionLike($returnClassMethod); - $currentPhpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - $paramType = $this->constantReturnToParamTypeConverter->convert($returnType); - if ($paramType instanceof MixedType) { + if ($paramType instanceof \PHPStan\Type\MixedType) { continue; } - if ($this->isParamDocTypeEqualToPhpType($firstParam, $paramType)) { return null; } - $this->phpDocTypeChanger->changeParamType($currentPhpDocInfo, $paramType, $firstParam, $paramName); - return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $inferParamsFromClassMethodReturns = $configuration[self::INFER_PARAMS_FROM_CLASS_METHOD_RETURNS] ?? []; - Assert::allIsInstanceOf($inferParamsFromClassMethodReturns, InferParamFromClassMethodReturn::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($inferParamsFromClassMethodReturns, \Rector\Restoration\ValueObject\InferParamFromClassMethodReturn::class); $this->inferParamFromClassMethodReturn = $inferParamsFromClassMethodReturns; } - - private function matchReturnClassMethod( - ClassMethod $classMethod, - InferParamFromClassMethodReturn $inferParamFromClassMethodReturn - ): ?ClassMethod { - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + private function matchReturnClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \Rector\Restoration\ValueObject\InferParamFromClassMethodReturn $inferParamFromClassMethodReturn) : ?\PhpParser\Node\Stmt\ClassMethod + { + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - - if (! $classReflection->isSubclassOf($inferParamFromClassMethodReturn->getClass())) { + if (!$classReflection->isSubclassOf($inferParamFromClassMethodReturn->getClass())) { return null; } - - if (! $this->isName($classMethod->name, $inferParamFromClassMethodReturn->getParamMethod())) { + if (!$this->isName($classMethod->name, $inferParamFromClassMethodReturn->getParamMethod())) { return null; } - - $classLike = $classMethod->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - return $classLike->getMethod($inferParamFromClassMethodReturn->getReturnMethod()); } - - private function isParamDocTypeEqualToPhpType(Param $param, Type $paramType): bool + private function isParamDocTypeEqualToPhpType(\PhpParser\Node\Param $param, \PHPStan\Type\Type $paramType) : bool { $currentParamType = $this->nodeTypeResolver->getStaticType($param); return $currentParamType->equals($paramType); diff --git a/rules/Restoration/Rector/Class_/RemoveFinalFromEntityRector.php b/rules/Restoration/Rector/Class_/RemoveFinalFromEntityRector.php index b334a6395ec..d2a816a0eeb 100644 --- a/rules/Restoration/Rector/Class_/RemoveFinalFromEntityRector.php +++ b/rules/Restoration/Rector/Class_/RemoveFinalFromEntityRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - if (! $phpDocInfo->hasByAnnotationClasses(['Doctrine\ORM\Mapping\Entity', 'Doctrine\ORM\Mapping\Embeddable'])) { + if (!$phpDocInfo->hasByAnnotationClasses(['Doctrine\\ORM\\Mapping\\Entity', 'Doctrine\\ORM\\Mapping\\Embeddable'])) { return null; } - - if (! $node->isFinal()) { + if (!$node->isFinal()) { return null; } - $this->visibilityManipulator->removeFinal($node); - return $node; } } diff --git a/rules/Restoration/Rector/Namespace_/CompleteImportForPartialAnnotationRector.php b/rules/Restoration/Rector/Namespace_/CompleteImportForPartialAnnotationRector.php index 0da5c458f10..e306e000cd6 100644 --- a/rules/Restoration/Rector/Namespace_/CompleteImportForPartialAnnotationRector.php +++ b/rules/Restoration/Rector/Namespace_/CompleteImportForPartialAnnotationRector.php @@ -1,10 +1,9 @@ [ - new CompleteImportForPartialAnnotation('Doctrine\ORM\Mapping', 'ORM'), - ], - ] - ), - ]); +, [self::USE_IMPORTS_TO_RESTORE => [new \Rector\Restoration\ValueObject\CompleteImportForPartialAnnotation('Doctrine\\ORM\\Mapping', 'ORM')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Namespace_::class]; + return [\PhpParser\Node\Stmt\Namespace_::class]; } - /** * @param Namespace_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $class = $this->betterNodeFinder->findFirstInstanceOf($node->stmts, Class_::class); - if (! $class instanceof Class_) { + $class = $this->betterNodeFinder->findFirstInstanceOf($node->stmts, \PhpParser\Node\Stmt\Class_::class); + if (!$class instanceof \PhpParser\Node\Stmt\Class_) { return null; } - foreach ($this->useImportsToRestore as $useImportToRestore) { - $annotationToSeek = '#\*\s+\@' . $useImportToRestore->getAlias() . '#'; - if (! Strings::match($this->print($class), $annotationToSeek)) { + $annotationToSeek = '#\\*\\s+\\@' . $useImportToRestore->getAlias() . '#'; + if (!\RectorPrefix20210509\Nette\Utils\Strings::match($this->print($class), $annotationToSeek)) { continue; } - $node = $this->addImportToNamespaceIfMissing($node, $useImportToRestore); } - return $node; } - /** * @param CompleteImportForPartialAnnotation[][] $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { - $default = [ - new CompleteImportForPartialAnnotation('Doctrine\ORM\Mapping', 'ORM'), - new CompleteImportForPartialAnnotation('Symfony\Component\Validator\Constraints', 'Assert'), - new CompleteImportForPartialAnnotation('JMS\Serializer\Annotation', 'Serializer'), - ]; - - $this->useImportsToRestore = array_merge($configuration[self::USE_IMPORTS_TO_RESTORE] ?? [], $default); + $default = [new \Rector\Restoration\ValueObject\CompleteImportForPartialAnnotation('Doctrine\\ORM\\Mapping', 'ORM'), new \Rector\Restoration\ValueObject\CompleteImportForPartialAnnotation('Symfony\\Component\\Validator\\Constraints', 'Assert'), new \Rector\Restoration\ValueObject\CompleteImportForPartialAnnotation('JMS\\Serializer\\Annotation', 'Serializer')]; + $this->useImportsToRestore = \array_merge($configuration[self::USE_IMPORTS_TO_RESTORE] ?? [], $default); } - - private function addImportToNamespaceIfMissing( - Namespace_ $namespace, - CompleteImportForPartialAnnotation $completeImportForPartialAnnotation - ): Namespace_ { + private function addImportToNamespaceIfMissing(\PhpParser\Node\Stmt\Namespace_ $namespace, \Rector\Restoration\ValueObject\CompleteImportForPartialAnnotation $completeImportForPartialAnnotation) : \PhpParser\Node\Stmt\Namespace_ + { foreach ($namespace->stmts as $stmt) { - if (! $stmt instanceof Use_) { + if (!$stmt instanceof \PhpParser\Node\Stmt\Use_) { continue; } - $useUse = $stmt->uses[0]; // already there - if (! $this->isName($useUse->name, $completeImportForPartialAnnotation->getUse())) { + if (!$this->isName($useUse->name, $completeImportForPartialAnnotation->getUse())) { continue; } if ((string) $useUse->alias !== $completeImportForPartialAnnotation->getAlias()) { @@ -131,24 +102,17 @@ CODE_SAMPLE } return $namespace; } - return $this->addImportToNamespace($namespace, $completeImportForPartialAnnotation); } - - private function addImportToNamespace( - Namespace_ $namespace, - CompleteImportForPartialAnnotation $completeImportForPartialAnnotation - ): Namespace_ { - $useBuilder = new UseBuilder($completeImportForPartialAnnotation->getUse()); + private function addImportToNamespace(\PhpParser\Node\Stmt\Namespace_ $namespace, \Rector\Restoration\ValueObject\CompleteImportForPartialAnnotation $completeImportForPartialAnnotation) : \PhpParser\Node\Stmt\Namespace_ + { + $useBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\UseBuilder($completeImportForPartialAnnotation->getUse()); if ($completeImportForPartialAnnotation->getAlias() !== '') { $useBuilder->as($completeImportForPartialAnnotation->getAlias()); } - /** @var Stmt $use */ $use = $useBuilder->getNode(); - - $namespace->stmts = array_merge([$use], $namespace->stmts); - + $namespace->stmts = \array_merge([$use], $namespace->stmts); return $namespace; } } diff --git a/rules/Restoration/Rector/New_/CompleteMissingDependencyInNewRector.php b/rules/Restoration/Rector/New_/CompleteMissingDependencyInNewRector.php index 5b0addd3095..2a797254e62 100644 --- a/rules/Restoration/Rector/New_/CompleteMissingDependencyInNewRector.php +++ b/rules/Restoration/Rector/New_/CompleteMissingDependencyInNewRector.php @@ -1,7 +1,6 @@ */ private $classToInstantiateByType = []; - /** * @var ReflectionProvider */ private $reflectionProvider; - - public function __construct(ReflectionProvider $reflectionProvider) + public function __construct(\PHPStan\Reflection\ReflectionProvider $reflectionProvider) { $this->reflectionProvider = $reflectionProvider; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Complete missing constructor dependency instance by type', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Complete missing constructor dependency instance by type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -63,8 +55,7 @@ class RandomValueObject } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -80,97 +71,74 @@ class RandomValueObject } } CODE_SAMPLE - , - [ - self::CLASS_TO_INSTANTIATE_BY_TYPE => [ - 'RandomDependency' => 'RandomDependency', - ], - ] - ), - ]); +, [self::CLASS_TO_INSTANTIATE_BY_TYPE => ['RandomDependency' => 'RandomDependency']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [New_::class]; + return [\PhpParser\Node\Expr\New_::class]; } - /** * @param New_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipNew($node)) { return null; } - /** @var ReflectionMethod $constructorMethodReflection */ $constructorMethodReflection = $this->getNewNodeClassConstructorMethodReflection($node); - foreach ($constructorMethodReflection->getParameters() as $position => $reflectionParameter) { // argument is already set if (isset($node->args[$position])) { continue; } - $classToInstantiate = $this->resolveClassToInstantiateByParameterReflection($reflectionParameter); if ($classToInstantiate === null) { continue; } - - $new = new New_(new FullyQualified($classToInstantiate)); - $node->args[$position] = new Arg($new); + $new = new \PhpParser\Node\Expr\New_(new \PhpParser\Node\Name\FullyQualified($classToInstantiate)); + $node->args[$position] = new \PhpParser\Node\Arg($new); } - return $node; } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->classToInstantiateByType = $configuration[self::CLASS_TO_INSTANTIATE_BY_TYPE] ?? []; } - - private function shouldSkipNew(New_ $new): bool + private function shouldSkipNew(\PhpParser\Node\Expr\New_ $new) : bool { $constructorMethodReflection = $this->getNewNodeClassConstructorMethodReflection($new); - if (! $constructorMethodReflection instanceof ReflectionMethod) { - return true; + if (!$constructorMethodReflection instanceof \ReflectionMethod) { + return \true; } - - return $constructorMethodReflection->getNumberOfRequiredParameters() <= count($new->args); + return $constructorMethodReflection->getNumberOfRequiredParameters() <= \count($new->args); } - - private function getNewNodeClassConstructorMethodReflection(New_ $new): ?ReflectionMethod + private function getNewNodeClassConstructorMethodReflection(\PhpParser\Node\Expr\New_ $new) : ?\ReflectionMethod { $className = $this->getName($new->class); if ($className === null) { return null; } - - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return null; } - $classReflection = $this->reflectionProvider->getClass($className); $reflectionClass = $classReflection->getNativeReflection(); return $reflectionClass->getConstructor(); } - - private function resolveClassToInstantiateByParameterReflection(ReflectionParameter $reflectionParameter): ?string + private function resolveClassToInstantiateByParameterReflection(\ReflectionParameter $reflectionParameter) : ?string { $reflectionType = $reflectionParameter->getType(); - if (! $reflectionType instanceof ReflectionType) { + if (!$reflectionType instanceof \ReflectionType) { return null; } - $requiredType = (string) $reflectionType; - return $this->classToInstantiateByType[$requiredType] ?? null; } } diff --git a/rules/Restoration/Rector/Property/MakeTypedPropertyNullableIfCheckedRector.php b/rules/Restoration/Rector/Property/MakeTypedPropertyNullableIfCheckedRector.php index 890fd4e639d..cf706e948e0 100644 --- a/rules/Restoration/Rector/Property/MakeTypedPropertyNullableIfCheckedRector.php +++ b/rules/Restoration/Rector/Property/MakeTypedPropertyNullableIfCheckedRector.php @@ -1,7 +1,6 @@ > */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipProperty($node)) { return null; } - /** @var PropertyProperty $onlyProperty */ $onlyProperty = $node->props[0]; - $isPropretyNullChecked = $this->isPropertyNullChecked($onlyProperty); - if (! $isPropretyNullChecked) { + if (!$isPropretyNullChecked) { return null; } - $currentPropertyType = $node->type; if ($currentPropertyType === null) { return null; } - - $node->type = new NullableType($currentPropertyType); + $node->type = new \PhpParser\Node\NullableType($currentPropertyType); $onlyProperty->default = $this->nodeFactory->createNull(); - return $node; } - - private function shouldSkipProperty(Property $property): bool + private function shouldSkipProperty(\PhpParser\Node\Stmt\Property $property) : bool { - if (count($property->props) !== 1) { - return true; + if (\count($property->props) !== 1) { + return \true; } - if ($property->type === null) { - return true; + return \true; } - - return $property->type instanceof NullableType; + return $property->type instanceof \PhpParser\Node\NullableType; } - - private function isPropertyNullChecked(PropertyProperty $onlyPropertyProperty): bool + private function isPropertyNullChecked(\PhpParser\Node\Stmt\PropertyProperty $onlyPropertyProperty) : bool { - $classLike = $onlyPropertyProperty->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return false; + $classLike = $onlyPropertyProperty->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } - if ($this->isIdenticalOrNotIdenticalToNull($classLike, $onlyPropertyProperty)) { - return true; + return \true; } - return $this->isBooleanNot($classLike, $onlyPropertyProperty); } - - private function isIdenticalOrNotIdenticalToNull(Class_ $class, PropertyProperty $onlyPropertyProperty): bool + private function isIdenticalOrNotIdenticalToNull(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt\PropertyProperty $onlyPropertyProperty) : bool { - $isIdenticalOrNotIdenticalToNull = false; - - $this->traverseNodesWithCallable($class->stmts, function (Node $node) use ( - $onlyPropertyProperty, - &$isIdenticalOrNotIdenticalToNull - ) { + $isIdenticalOrNotIdenticalToNull = \false; + $this->traverseNodesWithCallable($class->stmts, function (\PhpParser\Node $node) use($onlyPropertyProperty, &$isIdenticalOrNotIdenticalToNull) { $matchedPropertyFetchName = $this->matchPropertyFetchNameComparedToNull($node); if ($matchedPropertyFetchName === null) { return null; } - - if (! $this->isName($onlyPropertyProperty, $matchedPropertyFetchName)) { + if (!$this->isName($onlyPropertyProperty, $matchedPropertyFetchName)) { return null; } - - $isIdenticalOrNotIdenticalToNull = true; + $isIdenticalOrNotIdenticalToNull = \true; }); - return $isIdenticalOrNotIdenticalToNull; } - - private function isBooleanNot(Class_ $class, PropertyProperty $onlyPropertyProperty): bool + private function isBooleanNot(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt\PropertyProperty $onlyPropertyProperty) : bool { - $isBooleanNot = false; - - $this->traverseNodesWithCallable($class->stmts, function (Node $node) use ( - $onlyPropertyProperty, - &$isBooleanNot - ) { - if (! $node instanceof BooleanNot) { + $isBooleanNot = \false; + $this->traverseNodesWithCallable($class->stmts, function (\PhpParser\Node $node) use($onlyPropertyProperty, &$isBooleanNot) { + if (!$node instanceof \PhpParser\Node\Expr\BooleanNot) { return null; } - - if (! $node->expr instanceof PropertyFetch) { + if (!$node->expr instanceof \PhpParser\Node\Expr\PropertyFetch) { return null; } - - if (! $this->isName($node->expr->var, 'this')) { + if (!$this->isName($node->expr->var, 'this')) { return null; } - - if (! $this->nodeNameResolver->areNamesEqual($onlyPropertyProperty, $node->expr->name)) { + if (!$this->nodeNameResolver->areNamesEqual($onlyPropertyProperty, $node->expr->name)) { return null; } - - $isBooleanNot = true; + $isBooleanNot = \true; }); - return $isBooleanNot; } - /** * Matches: * $this-> === null * null === $this-> */ - private function matchPropertyFetchNameComparedToNull(Node $node): ?string + private function matchPropertyFetchNameComparedToNull(\PhpParser\Node $node) : ?string { - if (! $node instanceof Identical && ! $node instanceof NotIdentical) { + if (!$node instanceof \PhpParser\Node\Expr\BinaryOp\Identical && !$node instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical) { return null; } - - if ($node->left instanceof PropertyFetch && $this->valueResolver->isNull($node->right)) { + if ($node->left instanceof \PhpParser\Node\Expr\PropertyFetch && $this->valueResolver->isNull($node->right)) { $propertyFetch = $node->left; - } elseif ($node->right instanceof PropertyFetch && $this->valueResolver->isNull($node->left)) { + } elseif ($node->right instanceof \PhpParser\Node\Expr\PropertyFetch && $this->valueResolver->isNull($node->left)) { $propertyFetch = $node->right; } else { return null; } - - if (! $this->isName($propertyFetch->var, 'this')) { + if (!$this->isName($propertyFetch->var, 'this')) { return null; } - return $this->getName($propertyFetch->name); } } diff --git a/rules/Restoration/Type/ConstantReturnToParamTypeConverter.php b/rules/Restoration/Type/ConstantReturnToParamTypeConverter.php index 8a5abc45c80..863cbc46313 100644 --- a/rules/Restoration/Type/ConstantReturnToParamTypeConverter.php +++ b/rules/Restoration/Type/ConstantReturnToParamTypeConverter.php @@ -1,7 +1,6 @@ typeFactory = $typeFactory; } - - public function convert(Type $type): Type + public function convert(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - if ($type instanceof UnionType) { - $flattenReturnTypes = TypeUtils::flattenTypes($type); + if ($type instanceof \PHPStan\Type\UnionType) { + $flattenReturnTypes = \PHPStan\Type\TypeUtils::flattenTypes($type); $unionedTypes = []; foreach ($flattenReturnTypes as $flattenReturnType) { - if ($flattenReturnType instanceof ArrayType) { + if ($flattenReturnType instanceof \PHPStan\Type\ArrayType) { $unionedTypes[] = $flattenReturnType->getItemType(); } } - $resolvedTypes = []; foreach ($unionedTypes as $unionedType) { $resolvedTypes[] = $this->convert($unionedType); } - - return new UnionType($resolvedTypes); + return new \PHPStan\Type\UnionType($resolvedTypes); } - - if ($type instanceof ConstantStringType) { + if ($type instanceof \PHPStan\Type\Constant\ConstantStringType) { return $this->unwrapConstantTypeToObjectType($type); } - - if ($type instanceof ArrayType) { + if ($type instanceof \PHPStan\Type\ArrayType) { return $this->unwrapConstantTypeToObjectType($type); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - private function unwrapConstantTypeToObjectType(Type $type): Type + private function unwrapConstantTypeToObjectType(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - if ($type instanceof ArrayType) { + if ($type instanceof \PHPStan\Type\ArrayType) { return $this->unwrapConstantTypeToObjectType($type->getItemType()); } - - if ($type instanceof ConstantStringType) { - return new ObjectType($type->getValue()); + if ($type instanceof \PHPStan\Type\Constant\ConstantStringType) { + return new \PHPStan\Type\ObjectType($type->getValue()); } - - if ($type instanceof GenericClassStringType && $type->getGenericType() instanceof ObjectType) { + if ($type instanceof \PHPStan\Type\Generic\GenericClassStringType && $type->getGenericType() instanceof \PHPStan\Type\ObjectType) { return $type->getGenericType(); } - - if ($type instanceof UnionType) { + if ($type instanceof \PHPStan\Type\UnionType) { return $this->unwrapUnionType($type); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - private function unwrapUnionType(UnionType $unionType): Type + private function unwrapUnionType(\PHPStan\Type\UnionType $unionType) : \PHPStan\Type\Type { $types = []; foreach ($unionType->getTypes() as $unionedType) { @@ -86,7 +71,6 @@ final class ConstantReturnToParamTypeConverter $types[] = $unionType; } } - return $this->typeFactory->createMixedPassedOrUnionType($types); } } diff --git a/rules/Restoration/ValueObject/CompleteImportForPartialAnnotation.php b/rules/Restoration/ValueObject/CompleteImportForPartialAnnotation.php index 0b92576ad5c..6481701976f 100644 --- a/rules/Restoration/ValueObject/CompleteImportForPartialAnnotation.php +++ b/rules/Restoration/ValueObject/CompleteImportForPartialAnnotation.php @@ -1,7 +1,6 @@ use = $use; $this->alias = $alias; } - - public function getUse(): string + public function getUse() : string { return $this->use; } - - public function getAlias(): string + public function getAlias() : string { return $this->alias; } diff --git a/rules/Restoration/ValueObject/InferParamFromClassMethodReturn.php b/rules/Restoration/ValueObject/InferParamFromClassMethodReturn.php index 04f457bd2da..aa94d19e08b 100644 --- a/rules/Restoration/ValueObject/InferParamFromClassMethodReturn.php +++ b/rules/Restoration/ValueObject/InferParamFromClassMethodReturn.php @@ -1,7 +1,6 @@ class = $class; $this->paramMethod = $paramMethod; $this->returnMethod = $returnMethod; } - - public function getClass(): string + public function getClass() : string { return $this->class; } - - public function getParamMethod(): string + public function getParamMethod() : string { return $this->paramMethod; } - - public function getReturnMethod(): string + public function getReturnMethod() : string { return $this->returnMethod; } diff --git a/rules/Transform/Naming/FullyQualifiedNameResolver.php b/rules/Transform/Naming/FullyQualifiedNameResolver.php index 241541659ac..687b91b529e 100644 --- a/rules/Transform/Naming/FullyQualifiedNameResolver.php +++ b/rules/Transform/Naming/FullyQualifiedNameResolver.php @@ -1,47 +1,40 @@ betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; } - /** * @param Node[] $nodes */ - public function resolveFullyQualifiedName(array $nodes, string $shortClassName): string + public function resolveFullyQualifiedName(array $nodes, string $shortClassName) : string { - $namespace = $this->betterNodeFinder->findFirstInstanceOf($nodes, Namespace_::class); - if (! $namespace instanceof Namespace_) { + $namespace = $this->betterNodeFinder->findFirstInstanceOf($nodes, \PhpParser\Node\Stmt\Namespace_::class); + if (!$namespace instanceof \PhpParser\Node\Stmt\Namespace_) { return $shortClassName; } - $namespaceName = $this->nodeNameResolver->getName($namespace); if ($namespaceName === null) { return $shortClassName; } - return $namespaceName . '\\' . $shortClassName; } } diff --git a/rules/Transform/NodeAnalyzer/FuncCallStaticCallToMethodCallAnalyzer.php b/rules/Transform/NodeAnalyzer/FuncCallStaticCallToMethodCallAnalyzer.php index 8c60fab7bec..09b6d48284d 100644 --- a/rules/Transform/NodeAnalyzer/FuncCallStaticCallToMethodCallAnalyzer.php +++ b/rules/Transform/NodeAnalyzer/FuncCallStaticCallToMethodCallAnalyzer.php @@ -1,7 +1,6 @@ typeProvidingExprFromClassResolver = $typeProvidingExprFromClassResolver; $this->propertyNaming = $propertyNaming; $this->nodeNameResolver = $nodeNameResolver; @@ -67,42 +53,30 @@ final class FuncCallStaticCallToMethodCallAnalyzer $this->propertyFetchFactory = $propertyFetchFactory; $this->propertyAdder = $propertyAdder; } - /** * @param ClassMethod|Function_ $functionLike * @return MethodCall|PropertyFetch|Variable */ - public function matchTypeProvidingExpr(Class_ $class, FunctionLike $functionLike, ObjectType $objectType): Expr + public function matchTypeProvidingExpr(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\FunctionLike $functionLike, \PHPStan\Type\ObjectType $objectType) : \PhpParser\Node\Expr { - $expr = $this->typeProvidingExprFromClassResolver->resolveTypeProvidingExprFromClass( - $class, - $functionLike, - $objectType - ); + $expr = $this->typeProvidingExprFromClassResolver->resolveTypeProvidingExprFromClass($class, $functionLike, $objectType); if ($expr !== null) { - if ($expr instanceof Variable) { + if ($expr instanceof \PhpParser\Node\Expr\Variable) { $this->addClassMethodParamForVariable($expr, $objectType, $functionLike); } - return $expr; } - $propertyName = $this->propertyNaming->fqnToVariableName($objectType); $this->propertyAdder->addConstructorDependencyToClass($class, $objectType, $propertyName); return $this->propertyFetchFactory->createFromType($objectType); } - /** * @param ClassMethod|Function_ $functionLike */ - private function addClassMethodParamForVariable( - Variable $variable, - ObjectType $objectType, - FunctionLike $functionLike - ): void { + private function addClassMethodParamForVariable(\PhpParser\Node\Expr\Variable $variable, \PHPStan\Type\ObjectType $objectType, \PhpParser\Node\FunctionLike $functionLike) : void + { /** @var string $variableName */ $variableName = $this->nodeNameResolver->getName($variable); - // add variable to __construct as dependency $functionLike->params[] = $this->nodeFactory->createParamFromNameAndType($variableName, $objectType); } diff --git a/rules/Transform/NodeAnalyzer/SingletonClassMethodAnalyzer.php b/rules/Transform/NodeAnalyzer/SingletonClassMethodAnalyzer.php index 4ffcb43a9da..074f931e338 100644 --- a/rules/Transform/NodeAnalyzer/SingletonClassMethodAnalyzer.php +++ b/rules/Transform/NodeAnalyzer/SingletonClassMethodAnalyzer.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->valueResolver = $valueResolver; $this->nodeComparator = $nodeComparator; } - /** * Match this code: * if (null === static::$instance) { @@ -55,78 +46,62 @@ final class SingletonClassMethodAnalyzer * * Matches "static::$instance" on success */ - public function matchStaticPropertyFetch(ClassMethod $classMethod): ?StaticPropertyFetch + public function matchStaticPropertyFetch(\PhpParser\Node\Stmt\ClassMethod $classMethod) : ?\PhpParser\Node\Expr\StaticPropertyFetch { $stmts = (array) $classMethod->stmts; - if (count($stmts) !== 2) { + if (\count($stmts) !== 2) { return null; } - $firstStmt = $stmts[0] ?? null; - if (! $firstStmt instanceof If_) { + if (!$firstStmt instanceof \PhpParser\Node\Stmt\If_) { return null; } - $staticPropertyFetch = $this->matchStaticPropertyFetchInIfCond($firstStmt->cond); - - if (count($firstStmt->stmts) !== 1) { + if (\count($firstStmt->stmts) !== 1) { return null; } - - if (! $firstStmt->stmts[0] instanceof Expression) { + if (!$firstStmt->stmts[0] instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $stmt = $firstStmt->stmts[0]->expr; - // create self and assign to static property - if (! $stmt instanceof Assign) { + if (!$stmt instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $this->nodeComparator->areNodesEqual($staticPropertyFetch, $stmt->var)) { + if (!$this->nodeComparator->areNodesEqual($staticPropertyFetch, $stmt->var)) { return null; } - - if (! $stmt->expr instanceof New_) { + if (!$stmt->expr instanceof \PhpParser\Node\Expr\New_) { return null; } - /** @var string $class */ - $class = $classMethod->getAttribute(AttributeKey::CLASS_NAME); - + $class = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); // the "self" class is created - if (! $this->nodeTypeResolver->isObjectType($stmt->expr->class, new ObjectType($class))) { + if (!$this->nodeTypeResolver->isObjectType($stmt->expr->class, new \PHPStan\Type\ObjectType($class))) { return null; } - /** @var StaticPropertyFetch $staticPropertyFetch */ return $staticPropertyFetch; } - - private function matchStaticPropertyFetchInIfCond(Expr $expr): ?StaticPropertyFetch + private function matchStaticPropertyFetchInIfCond(\PhpParser\Node\Expr $expr) : ?\PhpParser\Node\Expr\StaticPropertyFetch { // matching: "self::$static === null" - if ($expr instanceof Identical) { - if ($this->valueResolver->isNull($expr->left) && $expr->right instanceof StaticPropertyFetch) { + if ($expr instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { + if ($this->valueResolver->isNull($expr->left) && $expr->right instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { return $expr->right; } - - if ($this->valueResolver->isNull($expr->right) && $expr->left instanceof StaticPropertyFetch) { + if ($this->valueResolver->isNull($expr->right) && $expr->left instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { return $expr->left; } } - // matching: "! self::$static" - if (! $expr instanceof BooleanNot) { + if (!$expr instanceof \PhpParser\Node\Expr\BooleanNot) { return null; } - $negatedExpr = $expr->expr; - if (! $negatedExpr instanceof StaticPropertyFetch) { + if (!$negatedExpr instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { return null; } - return $negatedExpr; } } diff --git a/rules/Transform/NodeFactory/ClassMethodFactory.php b/rules/Transform/NodeFactory/ClassMethodFactory.php index 44d68f1b591..903a0455b38 100644 --- a/rules/Transform/NodeFactory/ClassMethodFactory.php +++ b/rules/Transform/NodeFactory/ClassMethodFactory.php @@ -1,22 +1,19 @@ makePublic(); $methodBuilder->makeStatic(); $methodBuilder->addStmts($function->stmts); - return $methodBuilder->getNode(); } } diff --git a/rules/Transform/NodeFactory/PropertyFetchFactory.php b/rules/Transform/NodeFactory/PropertyFetchFactory.php index e084ce9d8f0..5f5b5aa55a1 100644 --- a/rules/Transform/NodeFactory/PropertyFetchFactory.php +++ b/rules/Transform/NodeFactory/PropertyFetchFactory.php @@ -1,31 +1,26 @@ propertyNaming = $propertyNaming; } - - public function createFromType(ObjectType $objectType): PropertyFetch + public function createFromType(\PHPStan\Type\ObjectType $objectType) : \PhpParser\Node\Expr\PropertyFetch { - $thisVariable = new Variable('this'); + $thisVariable = new \PhpParser\Node\Expr\Variable('this'); $propertyName = $this->propertyNaming->fqnToVariableName($objectType->getClassName()); - - return new PropertyFetch($thisVariable, $propertyName); + return new \PhpParser\Node\Expr\PropertyFetch($thisVariable, $propertyName); } } diff --git a/rules/Transform/NodeFactory/ProvideConfigFilePathClassMethodFactory.php b/rules/Transform/NodeFactory/ProvideConfigFilePathClassMethodFactory.php index 54ed2060f41..f92ba2a70c2 100644 --- a/rules/Transform/NodeFactory/ProvideConfigFilePathClassMethodFactory.php +++ b/rules/Transform/NodeFactory/ProvideConfigFilePathClassMethodFactory.php @@ -1,7 +1,6 @@ nodeFactory = $nodeFactory; } - - public function create(): ClassMethod + public function create() : \PhpParser\Node\Stmt\ClassMethod { $classMethod = $this->nodeFactory->createPublicMethod('provideConfigFilePath'); - $classMethod->returnType = new Identifier('string'); - - $concat = new Concat(new Dir(), new String_('/config/configured_rule.php')); - $return = new Return_($concat); - + $classMethod->returnType = new \PhpParser\Node\Identifier('string'); + $concat = new \PhpParser\Node\Expr\BinaryOp\Concat(new \PhpParser\Node\Scalar\MagicConst\Dir(), new \PhpParser\Node\Scalar\String_('/config/configured_rule.php')); + $return = new \PhpParser\Node\Stmt\Return_($concat); $classMethod->stmts[] = $return; - return $classMethod; } } diff --git a/rules/Transform/NodeFactory/StaticMethodClassFactory.php b/rules/Transform/NodeFactory/StaticMethodClassFactory.php index d2a1fccee16..36d47eb17a0 100644 --- a/rules/Transform/NodeFactory/StaticMethodClassFactory.php +++ b/rules/Transform/NodeFactory/StaticMethodClassFactory.php @@ -1,50 +1,42 @@ classMethodFactory = $classMethodFactory; $this->classNaming = $classNaming; } - /** * @param Function_[] $functions */ - public function createStaticMethodClass(string $shortClassName, array $functions): Class_ + public function createStaticMethodClass(string $shortClassName, array $functions) : \PhpParser\Node\Stmt\Class_ { - $classBuilder = new ClassBuilder($shortClassName); + $classBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\ClassBuilder($shortClassName); $classBuilder->makeFinal(); - foreach ($functions as $function) { $staticClassMethod = $this->createStaticMethod($function); $classBuilder->addStmt($staticClassMethod); } - return $classBuilder->getNode(); } - - private function createStaticMethod(Function_ $function): ClassMethod + private function createStaticMethod(\PhpParser\Node\Stmt\Function_ $function) : \PhpParser\Node\Stmt\ClassMethod { $methodName = $this->classNaming->createMethodNameFromFunction($function); return $this->classMethodFactory->createClassMethodFromFunction($methodName, $function); diff --git a/rules/Transform/NodeFactory/UnwrapClosureFactory.php b/rules/Transform/NodeFactory/UnwrapClosureFactory.php index a8e2c97666f..cc6d75777ad 100644 --- a/rules/Transform/NodeFactory/UnwrapClosureFactory.php +++ b/rules/Transform/NodeFactory/UnwrapClosureFactory.php @@ -1,7 +1,6 @@ value; - - if ($argValue instanceof Closure) { + if ($argValue instanceof \PhpParser\Node\Expr\Closure) { $unwrappedNodes = $argValue->getStmts(); - - $lastStmtKey = array_key_last($argValue->stmts); + \end($argValue->stmts); + $lastStmtKey = \key($argValue->stmts); $lastStmt = $argValue->stmts[$lastStmtKey]; - - if ($lastStmt instanceof Return_ && $lastStmt->expr !== null) { + if ($lastStmt instanceof \PhpParser\Node\Stmt\Return_ && $lastStmt->expr !== null) { unset($unwrappedNodes[$lastStmtKey]); - $unwrappedNodes[] = new Assign($resultVariable, $lastStmt->expr); + $unwrappedNodes[] = new \PhpParser\Node\Expr\Assign($resultVariable, $lastStmt->expr); } - return $unwrappedNodes; } - - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } } diff --git a/rules/Transform/NodeTypeAnalyzer/TypeProvidingExprFromClassResolver.php b/rules/Transform/NodeTypeAnalyzer/TypeProvidingExprFromClassResolver.php index a85d9fde64c..b74996af026 100644 --- a/rules/Transform/NodeTypeAnalyzer/TypeProvidingExprFromClassResolver.php +++ b/rules/Transform/NodeTypeAnalyzer/TypeProvidingExprFromClassResolver.php @@ -1,7 +1,6 @@ typeUnwrapper = $typeUnwrapper; $this->reflectionProvider = $reflectionProvider; $this->nodeNameResolver = $nodeNameResolver; $this->propertyNaming = $propertyNaming; } - /** * @param ClassMethod|Function_ $functionLike * @return MethodCall|PropertyFetch|Variable|null */ - public function resolveTypeProvidingExprFromClass( - Class_ $class, - FunctionLike $functionLike, - ObjectType $objectType - ): ?Expr { - $className = $class->getAttribute(AttributeKey::CLASS_NAME); + public function resolveTypeProvidingExprFromClass(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\FunctionLike $functionLike, \PHPStan\Type\ObjectType $objectType) : ?\PhpParser\Node\Expr + { + $className = $class->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === null) { return null; } - // A. match a method $classReflection = $this->reflectionProvider->getClass($className); $methodCallProvidingType = $this->resolveMethodCallProvidingType($classReflection, $objectType); if ($methodCallProvidingType !== null) { return $methodCallProvidingType; } - // B. match existing property - $scope = $class->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $class->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $propertyFetch = $this->resolvePropertyFetchProvidingType($classReflection, $scope, $objectType); if ($propertyFetch !== null) { return $propertyFetch; } - // C. param in constructor? return $this->resolveConstructorParamProvidingType($functionLike, $objectType); } - - private function resolveMethodCallProvidingType( - ClassReflection $classReflection, - ObjectType $objectType - ): ?MethodCall { + private function resolveMethodCallProvidingType(\PHPStan\Reflection\ClassReflection $classReflection, \PHPStan\Type\ObjectType $objectType) : ?\PhpParser\Node\Expr\MethodCall + { foreach ($classReflection->getNativeMethods() as $methodReflection) { - $functionVariant = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants()); + $functionVariant = \PHPStan\Reflection\ParametersAcceptorSelector::selectSingle($methodReflection->getVariants()); $returnType = $functionVariant->getReturnType(); - - if (! $this->isMatchingType($returnType, $objectType)) { + if (!$this->isMatchingType($returnType, $objectType)) { continue; } - - $thisVariable = new Variable('this'); - return new MethodCall($thisVariable, $methodReflection->getName()); + $thisVariable = new \PhpParser\Node\Expr\Variable('this'); + return new \PhpParser\Node\Expr\MethodCall($thisVariable, $methodReflection->getName()); } - return null; } - - private function resolvePropertyFetchProvidingType( - ClassReflection $classReflection, - Scope $scope, - ObjectType $objectType - ): ?PropertyFetch { + private function resolvePropertyFetchProvidingType(\PHPStan\Reflection\ClassReflection $classReflection, \PHPStan\Analyser\Scope $scope, \PHPStan\Type\ObjectType $objectType) : ?\PhpParser\Node\Expr\PropertyFetch + { $reflectionClass = $classReflection->getNativeReflection(); - foreach ($reflectionClass->getProperties() as $reflectionProperty) { /** @var PhpPropertyReflection $phpPropertyReflection */ $phpPropertyReflection = $classReflection->getProperty($reflectionProperty->getName(), $scope); - $readableType = $phpPropertyReflection->getReadableType(); - if (! $this->isMatchingType($readableType, $objectType)) { + if (!$this->isMatchingType($readableType, $objectType)) { continue; } - - return new PropertyFetch(new Variable('this'), $reflectionProperty->getName()); + return new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $reflectionProperty->getName()); } - return null; } - - private function resolveConstructorParamProvidingType(FunctionLike $functionLike, ObjectType $objectType): ?Variable + private function resolveConstructorParamProvidingType(\PhpParser\Node\FunctionLike $functionLike, \PHPStan\Type\ObjectType $objectType) : ?\PhpParser\Node\Expr\Variable { - if (! $functionLike instanceof ClassMethod) { + if (!$functionLike instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - - if (! $this->nodeNameResolver->isName($functionLike, MethodName::CONSTRUCT)) { + if (!$this->nodeNameResolver->isName($functionLike, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { return null; } - $variableName = $this->propertyNaming->fqnToVariableName($objectType); - return new Variable($variableName); + return new \PhpParser\Node\Expr\Variable($variableName); } - - private function isMatchingType(Type $readableType, ObjectType $objectType): bool + private function isMatchingType(\PHPStan\Type\Type $readableType, \PHPStan\Type\ObjectType $objectType) : bool { - if ($readableType instanceof MixedType) { - return false; + if ($readableType instanceof \PHPStan\Type\MixedType) { + return \false; } - $readableType = $this->typeUnwrapper->unwrapNullableType($readableType); - - if (! $readableType instanceof TypeWithClassName) { - return false; + if (!$readableType instanceof \PHPStan\Type\TypeWithClassName) { + return \false; } - return $readableType->equals($objectType); } } diff --git a/rules/Transform/Rector/Assign/DimFetchAssignToMethodCallRector.php b/rules/Transform/Rector/Assign/DimFetchAssignToMethodCallRector.php index 29bb8e40077..b2cda3b7c52 100644 --- a/rules/Transform/Rector/Assign/DimFetchAssignToMethodCallRector.php +++ b/rules/Transform/Rector/Assign/DimFetchAssignToMethodCallRector.php @@ -1,7 +1,6 @@ addMethod(...)', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change magic array access add to $list[], to explicit $list->addMethod(...)', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' use Nette\Application\Routers\Route; use Nette\Application\Routers\RouteList; @@ -51,8 +43,7 @@ class RouterFactory } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use Nette\Application\Routers\RouteList; class RouterFactory @@ -64,76 +55,54 @@ class RouterFactory } } CODE_SAMPLE -, - [ - self::DIM_FETCH_ASSIGN_TO_METHOD_CALL => [ - new DimFetchAssignToMethodCall( - 'Nette\Application\Routers\RouteList', - 'Nette\Application\Routers\Route', - 'addRoute' - ), - ], - ] - ), - ] - ); +, [self::DIM_FETCH_ASSIGN_TO_METHOD_CALL => [new \Rector\Transform\ValueObject\DimFetchAssignToMethodCall('Nette\\Application\\Routers\\RouteList', 'Nette\\Application\\Routers\\Route', 'addRoute')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->var instanceof ArrayDimFetch) { + if (!$node->var instanceof \PhpParser\Node\Expr\ArrayDimFetch) { return null; } - $arrayDimFetch = $node->var; - if (! $arrayDimFetch->var instanceof Variable) { + if (!$arrayDimFetch->var instanceof \PhpParser\Node\Expr\Variable) { return null; } - - if (! $node->expr instanceof New_) { + if (!$node->expr instanceof \PhpParser\Node\Expr\New_) { return null; } - $dimFetchAssignToMethodCall = $this->findDimFetchAssignToMethodCall($node); - if (! $dimFetchAssignToMethodCall instanceof DimFetchAssignToMethodCall) { + if (!$dimFetchAssignToMethodCall instanceof \Rector\Transform\ValueObject\DimFetchAssignToMethodCall) { return null; } - - return new MethodCall($arrayDimFetch->var, $dimFetchAssignToMethodCall->getAddMethod(), $node->expr->args); + return new \PhpParser\Node\Expr\MethodCall($arrayDimFetch->var, $dimFetchAssignToMethodCall->getAddMethod(), $node->expr->args); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $dimFetchAssignToMethodCalls = $configuration[self::DIM_FETCH_ASSIGN_TO_METHOD_CALL] ?? []; - Assert::allIsInstanceOf($dimFetchAssignToMethodCalls, DimFetchAssignToMethodCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($dimFetchAssignToMethodCalls, \Rector\Transform\ValueObject\DimFetchAssignToMethodCall::class); $this->dimFetchAssignToMethodCalls = $dimFetchAssignToMethodCalls; } - - private function findDimFetchAssignToMethodCall(Assign $assign): ?DimFetchAssignToMethodCall + private function findDimFetchAssignToMethodCall(\PhpParser\Node\Expr\Assign $assign) : ?\Rector\Transform\ValueObject\DimFetchAssignToMethodCall { /** @var ArrayDimFetch $arrayDimFetch */ $arrayDimFetch = $assign->var; - foreach ($this->dimFetchAssignToMethodCalls as $dimFetchAssignToMethodCall) { - if (! $this->isObjectType($arrayDimFetch->var, $dimFetchAssignToMethodCall->getListObjectType())) { + if (!$this->isObjectType($arrayDimFetch->var, $dimFetchAssignToMethodCall->getListObjectType())) { continue; } - - if (! $this->isObjectType($assign->expr, $dimFetchAssignToMethodCall->getItemObjectType())) { + if (!$this->isObjectType($assign->expr, $dimFetchAssignToMethodCall->getItemObjectType())) { continue; } return $dimFetchAssignToMethodCall; diff --git a/rules/Transform/Rector/Assign/GetAndSetToMethodCallRector.php b/rules/Transform/Rector/Assign/GetAndSetToMethodCallRector.php index cda0def6b3c..18ab145f22b 100644 --- a/rules/Transform/Rector/Assign/GetAndSetToMethodCallRector.php +++ b/rules/Transform/Rector/Assign/GetAndSetToMethodCallRector.php @@ -1,7 +1,6 @@ propertyFetchAnalyzer = $propertyFetchAnalyzer; $this->magicPropertyFetchAnalyzer = $magicPropertyFetchAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turns defined `__get`/`__set` to specific method calls.', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns defined `__get`/`__set` to specific method calls.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' $container = new SomeContainer; $container->someService = $someService; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $container = new SomeContainer; $container->setService("someService", $someService); CODE_SAMPLE - , - [ - self::TYPE_TO_METHOD_CALLS => [ - new GetAndSetToMethodCall('SomeContainer', 'addService', 'getService'), - ], - ] - ), - ]); +, [self::TYPE_TO_METHOD_CALLS => [new \Rector\Transform\ValueObject\GetAndSetToMethodCall('SomeContainer', 'addService', 'getService')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class, PropertyFetch::class]; + return [\PhpParser\Node\Expr\Assign::class, \PhpParser\Node\Expr\PropertyFetch::class]; } - /** * @param Assign|PropertyFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof Assign) { - if ($node->var instanceof PropertyFetch) { + if ($node instanceof \PhpParser\Node\Expr\Assign) { + if ($node->var instanceof \PhpParser\Node\Expr\PropertyFetch) { return $this->processMagicSet($node->expr, $node->var); } - return null; } - return $this->processPropertyFetch($node); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $getAndSetToMethodCalls = $configuration[self::TYPE_TO_METHOD_CALLS] ?? []; - Assert::allIsAOf($getAndSetToMethodCalls, GetAndSetToMethodCall::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsAOf($getAndSetToMethodCalls, \Rector\Transform\ValueObject\GetAndSetToMethodCall::class); $this->getAndSetToMethodCalls = $getAndSetToMethodCalls; } - - private function processMagicSet(Expr $expr, PropertyFetch $propertyFetch): ?Node + private function processMagicSet(\PhpParser\Node\Expr $expr, \PhpParser\Node\Expr\PropertyFetch $propertyFetch) : ?\PhpParser\Node { foreach ($this->getAndSetToMethodCalls as $getAndSetToMethodCall) { $objectType = $getAndSetToMethodCall->getObjectType(); if ($this->shouldSkipPropertyFetch($propertyFetch, $objectType)) { continue; } - - return $this->createMethodCallNodeFromAssignNode( - $propertyFetch, - $expr, - $getAndSetToMethodCall->getSetMethod() - ); + return $this->createMethodCallNodeFromAssignNode($propertyFetch, $expr, $getAndSetToMethodCall->getSetMethod()); } - return null; } - - private function processPropertyFetch(PropertyFetch $propertyFetch): ?MethodCall + private function processPropertyFetch(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : ?\PhpParser\Node\Expr\MethodCall { - $parentNode = $propertyFetch->getAttribute(AttributeKey::PARENT_NODE); - + $parentNode = $propertyFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); foreach ($this->getAndSetToMethodCalls as $getAndSetToMethodCall) { if ($this->shouldSkipPropertyFetch($propertyFetch, $getAndSetToMethodCall->getObjectType())) { continue; } - // setter, skip - if (! $parentNode instanceof Assign) { - return $this->createMethodCallNodeFromPropertyFetchNode( - $propertyFetch, - $getAndSetToMethodCall->getGetMethod() - ); + if (!$parentNode instanceof \PhpParser\Node\Expr\Assign) { + return $this->createMethodCallNodeFromPropertyFetchNode($propertyFetch, $getAndSetToMethodCall->getGetMethod()); } - if ($parentNode->var !== $propertyFetch) { - return $this->createMethodCallNodeFromPropertyFetchNode( - $propertyFetch, - $getAndSetToMethodCall->getGetMethod() - ); + return $this->createMethodCallNodeFromPropertyFetchNode($propertyFetch, $getAndSetToMethodCall->getGetMethod()); } } - return null; } - - private function shouldSkipPropertyFetch(PropertyFetch $propertyFetch, ObjectType $objectType): bool + private function shouldSkipPropertyFetch(\PhpParser\Node\Expr\PropertyFetch $propertyFetch, \PHPStan\Type\ObjectType $objectType) : bool { - if (! $this->isObjectType($propertyFetch->var, $objectType)) { - return true; + if (!$this->isObjectType($propertyFetch->var, $objectType)) { + return \true; } - - if (! $this->magicPropertyFetchAnalyzer->isMagicOnType($propertyFetch, $objectType)) { - return true; + if (!$this->magicPropertyFetchAnalyzer->isMagicOnType($propertyFetch, $objectType)) { + return \true; } - return $this->propertyFetchAnalyzer->isPropertyToSelf($propertyFetch); } - - private function createMethodCallNodeFromAssignNode( - PropertyFetch $propertyFetch, - Expr $expr, - string $method - ): MethodCall { + private function createMethodCallNodeFromAssignNode(\PhpParser\Node\Expr\PropertyFetch $propertyFetch, \PhpParser\Node\Expr $expr, string $method) : \PhpParser\Node\Expr\MethodCall + { $propertyName = $this->getName($propertyFetch->name); return $this->nodeFactory->createMethodCall($propertyFetch->var, $method, [$propertyName, $expr]); } - - private function createMethodCallNodeFromPropertyFetchNode( - PropertyFetch $propertyFetch, - string $method - ): MethodCall { + private function createMethodCallNodeFromPropertyFetchNode(\PhpParser\Node\Expr\PropertyFetch $propertyFetch, string $method) : \PhpParser\Node\Expr\MethodCall + { /** @var Variable $variableNode */ $variableNode = $propertyFetch->var; - return $this->nodeFactory->createMethodCall($variableNode, $method, [$this->getName($propertyFetch)]); } } diff --git a/rules/Transform/Rector/Assign/PropertyAssignToMethodCallRector.php b/rules/Transform/Rector/Assign/PropertyAssignToMethodCallRector.php index e3a50e3d87c..2be06566964 100644 --- a/rules/Transform/Rector/Assign/PropertyAssignToMethodCallRector.php +++ b/rules/Transform/Rector/Assign/PropertyAssignToMethodCallRector.php @@ -1,7 +1,6 @@ oldProperty = false; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someObject = new SomeClass; $someObject->newMethodCall(false); CODE_SAMPLE - , - [ - self::PROPERTY_ASSIGNS_TO_METHODS_CALLS => [ - new PropertyAssignToMethodCall('SomeClass', 'oldProperty', 'newMethodCall'), - ], - ] - ), - ]); +, [self::PROPERTY_ASSIGNS_TO_METHODS_CALLS => [new \Rector\Transform\ValueObject\PropertyAssignToMethodCall('SomeClass', 'oldProperty', 'newMethodCall')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->var instanceof PropertyFetch) { + if (!$node->var instanceof \PhpParser\Node\Expr\PropertyFetch) { return null; } - $propertyFetchNode = $node->var; - /** @var Variable $propertyNode */ $propertyNode = $propertyFetchNode->var; - foreach ($this->propertyAssignsToMethodCalls as $propertyAssignToMethodCall) { - if (! $this->isObjectType($propertyFetchNode->var, $propertyAssignToMethodCall->getObjectType())) { + if (!$this->isObjectType($propertyFetchNode->var, $propertyAssignToMethodCall->getObjectType())) { continue; } - - if (! $this->isName($propertyFetchNode, $propertyAssignToMethodCall->getOldPropertyName())) { + if (!$this->isName($propertyFetchNode, $propertyAssignToMethodCall->getOldPropertyName())) { continue; } - - return $this->nodeFactory->createMethodCall( - $propertyNode, - $propertyAssignToMethodCall->getNewMethodName(), - [$node->expr] - ); + return $this->nodeFactory->createMethodCall($propertyNode, $propertyAssignToMethodCall->getNewMethodName(), [$node->expr]); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $propertyAssignsToMethodCalls = $configuration[self::PROPERTY_ASSIGNS_TO_METHODS_CALLS] ?? []; - Assert::allIsInstanceOf($propertyAssignsToMethodCalls, PropertyAssignToMethodCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($propertyAssignsToMethodCalls, \Rector\Transform\ValueObject\PropertyAssignToMethodCall::class); $this->propertyAssignsToMethodCalls = $propertyAssignsToMethodCalls; } } diff --git a/rules/Transform/Rector/Assign/PropertyFetchToMethodCallRector.php b/rules/Transform/Rector/Assign/PropertyFetchToMethodCallRector.php index 5a18ceb2625..ac4f0cac0e5 100644 --- a/rules/Transform/Rector/Assign/PropertyFetchToMethodCallRector.php +++ b/rules/Transform/Rector/Assign/PropertyFetchToMethodCallRector.php @@ -1,7 +1,6 @@ [ - new PropertyFetchToMethodCall('SomeObject', 'property', 'getProperty', 'setProperty'), - ], - ]; - - $secondConfiguration = [ - self::PROPERTIES_TO_METHOD_CALLS => [ - new PropertyFetchToMethodCall('SomeObject', 'property', 'getConfig', null, ['someArg']), - ], - ]; - return new RuleDefinition('Replaces properties assign calls be defined methods.', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + $firstConfiguration = [self::PROPERTIES_TO_METHOD_CALLS => [new \Rector\Transform\ValueObject\PropertyFetchToMethodCall('SomeObject', 'property', 'getProperty', 'setProperty')]]; + $secondConfiguration = [self::PROPERTIES_TO_METHOD_CALLS => [new \Rector\Transform\ValueObject\PropertyFetchToMethodCall('SomeObject', 'property', 'getConfig', null, ['someArg'])]]; + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces properties assign calls be defined methods.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' $result = $object->property; $object->property = $value; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $result = $object->getProperty(); $object->setProperty($value); CODE_SAMPLE - , - $firstConfiguration - ), - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' +, $firstConfiguration), new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' $result = $object->property; CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $result = $object->getProperty('someArg'); CODE_SAMPLE - , - $secondConfiguration - ), - ]); +, $secondConfiguration)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Assign::class]; + return [\PhpParser\Node\Expr\Assign::class]; } - /** * @param Assign $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node->var instanceof PropertyFetch) { + if ($node->var instanceof \PhpParser\Node\Expr\PropertyFetch) { return $this->processSetter($node); } - - if ($node->expr instanceof PropertyFetch) { + if ($node->expr instanceof \PhpParser\Node\Expr\PropertyFetch) { return $this->processGetter($node); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $propertiesToMethodCalls = $configuration[self::PROPERTIES_TO_METHOD_CALLS] ?? []; - Assert::allIsInstanceOf($propertiesToMethodCalls, PropertyFetchToMethodCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($propertiesToMethodCalls, \Rector\Transform\ValueObject\PropertyFetchToMethodCall::class); $this->propertiesToMethodCalls = $propertiesToMethodCalls; } - - private function processSetter(Assign $assign): ?Node + private function processSetter(\PhpParser\Node\Expr\Assign $assign) : ?\PhpParser\Node { /** @var PropertyFetch $propertyFetchNode */ $propertyFetchNode = $assign->var; - $propertyToMethodCall = $this->matchPropertyFetchCandidate($propertyFetchNode); - if (! $propertyToMethodCall instanceof PropertyFetchToMethodCall) { + if (!$propertyToMethodCall instanceof \Rector\Transform\ValueObject\PropertyFetchToMethodCall) { return null; } - if ($propertyToMethodCall->getNewSetMethod() === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $args = $this->nodeFactory->createArgs([$assign->expr]); - /** @var Variable $variable */ $variable = $propertyFetchNode->var; - return $this->nodeFactory->createMethodCall($variable, $propertyToMethodCall->getNewSetMethod(), $args); } - - private function processGetter(Assign $assign): ?Node + private function processGetter(\PhpParser\Node\Expr\Assign $assign) : ?\PhpParser\Node { /** @var PropertyFetch $propertyFetchNode */ $propertyFetchNode = $assign->expr; - $propertyToMethodCall = $this->matchPropertyFetchCandidate($propertyFetchNode); - if (! $propertyToMethodCall instanceof PropertyFetchToMethodCall) { + if (!$propertyToMethodCall instanceof \Rector\Transform\ValueObject\PropertyFetchToMethodCall) { return null; } - // simple method name if ($propertyToMethodCall->getNewGetMethod() !== '') { - $assign->expr = $this->nodeFactory->createMethodCall( - $propertyFetchNode->var, - $propertyToMethodCall->getNewGetMethod() - ); - + $assign->expr = $this->nodeFactory->createMethodCall($propertyFetchNode->var, $propertyToMethodCall->getNewGetMethod()); if ($propertyToMethodCall->getNewGetArguments() !== []) { $args = $this->nodeFactory->createArgs($propertyToMethodCall->getNewGetArguments()); $assign->expr->args = $args; } - return $assign; } - return $assign; } - - private function matchPropertyFetchCandidate(PropertyFetch $propertyFetch): ?PropertyFetchToMethodCall + private function matchPropertyFetchCandidate(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : ?\Rector\Transform\ValueObject\PropertyFetchToMethodCall { foreach ($this->propertiesToMethodCalls as $propertyToMethodCall) { - if (! $this->isObjectType($propertyFetch->var, $propertyToMethodCall->getOldObjectType())) { + if (!$this->isObjectType($propertyFetch->var, $propertyToMethodCall->getOldObjectType())) { continue; } - - if (! $this->isName($propertyFetch, $propertyToMethodCall->getOldProperty())) { + if (!$this->isName($propertyFetch, $propertyToMethodCall->getOldProperty())) { continue; } - return $propertyToMethodCall; } - return null; } } diff --git a/rules/Transform/Rector/ClassConstFetch/ClassConstFetchToValueRector.php b/rules/Transform/Rector/ClassConstFetch/ClassConstFetchToValueRector.php index e10118e09bc..e9725ea4690 100644 --- a/rules/Transform/Rector/ClassConstFetch/ClassConstFetchToValueRector.php +++ b/rules/Transform/Rector/ClassConstFetch/ClassConstFetchToValueRector.php @@ -1,7 +1,6 @@ [ - new ClassConstFetchToValue('Nette\Configurator', 'DEVELOPMENT', 'development'), - new ClassConstFetchToValue('Nette\Configurator', 'PRODUCTION', 'production'), - ], - ]; - - return new RuleDefinition('Replaces constant by value', [ - new ConfiguredCodeSample( - '$value === Nette\Configurator::DEVELOPMENT', - '$value === "development"', - $configuration - ), - ]); + $configuration = [self::CLASS_CONST_FETCHES_TO_VALUES => [new \Rector\Transform\ValueObject\ClassConstFetchToValue('Nette\\Configurator', 'DEVELOPMENT', 'development'), new \Rector\Transform\ValueObject\ClassConstFetchToValue('Nette\\Configurator', 'PRODUCTION', 'production')]]; + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces constant by value', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample('$value === Nette\\Configurator::DEVELOPMENT', '$value === "development"', $configuration)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassConstFetch::class]; + return [\PhpParser\Node\Expr\ClassConstFetch::class]; } - /** * @param ClassConstFetch $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->classConstFetchesToValues as $classConstFetchToValue) { - if (! $this->isObjectType($node->class, $classConstFetchToValue->getObjectType())) { + if (!$this->isObjectType($node->class, $classConstFetchToValue->getObjectType())) { continue; } - - if (! $this->isName($node->name, $classConstFetchToValue->getConstant())) { + if (!$this->isName($node->name, $classConstFetchToValue->getConstant())) { continue; } - - return BuilderHelpers::normalizeValue($classConstFetchToValue->getValue()); + return \PhpParser\BuilderHelpers::normalizeValue($classConstFetchToValue->getValue()); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $classConstFetchesToValues = $configuration[self::CLASS_CONST_FETCHES_TO_VALUES] ?? []; - Assert::allIsInstanceOf($classConstFetchesToValues, ClassConstFetchToValue::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($classConstFetchesToValues, \Rector\Transform\ValueObject\ClassConstFetchToValue::class); $this->classConstFetchesToValues = $classConstFetchesToValues; } } diff --git a/rules/Transform/Rector/ClassMethod/SingleToManyMethodRector.php b/rules/Transform/Rector/ClassMethod/SingleToManyMethodRector.php index 1c3285837ef..b3c4a9ddb37 100644 --- a/rules/Transform/Rector/ClassMethod/SingleToManyMethodRector.php +++ b/rules/Transform/Rector/ClassMethod/SingleToManyMethodRector.php @@ -1,7 +1,6 @@ phpDocTypeChanger = $phpDocTypeChanger; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change method that returns single value to multiple values', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change method that returns single value to multiple values', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function getNode(): string @@ -59,8 +51,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -72,86 +63,66 @@ class SomeClass } } CODE_SAMPLE - , - [ - self::SINGLES_TO_MANY_METHODS => [new SingleToManyMethod('SomeClass', 'getNode', 'getNodes')], - ] - ), - ]); +, [self::SINGLES_TO_MANY_METHODS => [new \Rector\Transform\ValueObject\SingleToManyMethod('SomeClass', 'getNode', 'getNodes')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { return null; } - foreach ($this->singleToManyMethods as $singleToManyMethod) { - if (! $this->isObjectType($classLike, $singleToManyMethod->getObjectType())) { + if (!$this->isObjectType($classLike, $singleToManyMethod->getObjectType())) { continue; } - - if (! $this->isName($node, $singleToManyMethod->getSingleMethodName())) { + if (!$this->isName($node, $singleToManyMethod->getSingleMethodName())) { continue; } - - $node->name = new Identifier($singleToManyMethod->getManyMethodName()); + $node->name = new \PhpParser\Node\Identifier($singleToManyMethod->getManyMethodName()); $this->keepOldReturnTypeInDocBlock($node); - - $node->returnType = new Identifier('array'); + $node->returnType = new \PhpParser\Node\Identifier('array'); $this->wrapReturnValueToArray($node); - return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $singleToManyMethods = $configuration[self::SINGLES_TO_MANY_METHODS] ?? []; - Assert::allIsInstanceOf($singleToManyMethods, SingleToManyMethod::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($singleToManyMethods, \Rector\Transform\ValueObject\SingleToManyMethod::class); $this->singleToManyMethods = $singleToManyMethods; } - - private function keepOldReturnTypeInDocBlock(ClassMethod $classMethod): void + private function keepOldReturnTypeInDocBlock(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { // keep old return type in the docblock $oldReturnType = $classMethod->returnType; if ($oldReturnType === null) { return; } - $staticType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($oldReturnType); - $arrayType = new ArrayType(new MixedType(), $staticType); - + $arrayType = new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), $staticType); $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); $this->phpDocTypeChanger->changeReturnType($phpDocInfo, $arrayType); } - - private function wrapReturnValueToArray(ClassMethod $classMethod): void + private function wrapReturnValueToArray(\PhpParser\Node\Stmt\ClassMethod $classMethod) : void { - $this->traverseNodesWithCallable((array) $classMethod->stmts, function (Node $node) { - if (! $node instanceof Return_) { + $this->traverseNodesWithCallable((array) $classMethod->stmts, function (\PhpParser\Node $node) { + if (!$node instanceof \PhpParser\Node\Stmt\Return_) { return null; } - $node->expr = $this->nodeFactory->createArray([$node->expr]); return null; }); diff --git a/rules/Transform/Rector/ClassMethod/WrapReturnRector.php b/rules/Transform/Rector/ClassMethod/WrapReturnRector.php index 8985301d3c0..cac12472fab 100644 --- a/rules/Transform/Rector/ClassMethod/WrapReturnRector.php +++ b/rules/Transform/Rector/ClassMethod/WrapReturnRector.php @@ -1,7 +1,6 @@ [new WrapReturn('SomeClass', 'getItem', true)], - ] - ), - ]); +, [self::TYPE_METHOD_WRAPS => [new \Rector\Transform\ValueObject\WrapReturn('SomeClass', 'getItem', \true)]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->typeMethodWraps as $typeMethodWrap) { - if (! $this->isObjectType($node, $typeMethodWrap->getObjectType())) { + if (!$this->isObjectType($node, $typeMethodWrap->getObjectType())) { continue; } - - if (! $this->isName($node, $typeMethodWrap->getMethod())) { + if (!$this->isName($node, $typeMethodWrap->getMethod())) { continue; } - - if (! $node->stmts) { + if (!$node->stmts) { continue; } - return $this->wrap($node, $typeMethodWrap->isArrayWrap()); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $typeMethodWraps = $configuration[self::TYPE_METHOD_WRAPS] ?? []; - Assert::allIsInstanceOf($typeMethodWraps, WrapReturn::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($typeMethodWraps, \Rector\Transform\ValueObject\WrapReturn::class); $this->typeMethodWraps = $typeMethodWraps; } - - private function wrap(ClassMethod $classMethod, bool $isArrayWrap): ?ClassMethod + private function wrap(\PhpParser\Node\Stmt\ClassMethod $classMethod, bool $isArrayWrap) : ?\PhpParser\Node\Stmt\ClassMethod { - if (! is_iterable($classMethod->stmts)) { + if (!\is_iterable($classMethod->stmts)) { return null; } - foreach ($classMethod->stmts as $key => $stmt) { - if ($stmt instanceof Return_ && $stmt->expr !== null) { - if ($isArrayWrap && ! $stmt->expr instanceof Array_) { - $stmt->expr = new Array_([new ArrayItem($stmt->expr)]); + if ($stmt instanceof \PhpParser\Node\Stmt\Return_ && $stmt->expr !== null) { + if ($isArrayWrap && !$stmt->expr instanceof \PhpParser\Node\Expr\Array_) { + $stmt->expr = new \PhpParser\Node\Expr\Array_([new \PhpParser\Node\Expr\ArrayItem($stmt->expr)]); } - $classMethod->stmts[$key] = $stmt; } } - return $classMethod; } } diff --git a/rules/Transform/Rector/Class_/AddInterfaceByParentRector.php b/rules/Transform/Rector/Class_/AddInterfaceByParentRector.php index 786cbea8f9e..d863920129c 100644 --- a/rules/Transform/Rector/Class_/AddInterfaceByParentRector.php +++ b/rules/Transform/Rector/Class_/AddInterfaceByParentRector.php @@ -1,7 +1,6 @@ */ private $interfaceByParent = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add interface by parent', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add interface by parent', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass extends SomeParent { } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass extends SomeParent implements SomeInterface { } CODE_SAMPLE - , - [ - self::INTERFACE_BY_PARENT => [ - 'SomeParent' => 'SomeInterface', - ], - ] - ), - ]); +, [self::INTERFACE_BY_PARENT => ['SomeParent' => 'SomeInterface']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { /** @var Scope $scope */ - $scope = $node->getAttribute(AttributeKey::SCOPE); - + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - $parentClassReflection = $classReflection->getParentClass(); - if (! $parentClassReflection) { + if (!$parentClassReflection) { return null; } - foreach ($this->interfaceByParent as $parentName => $interfaceName) { if ($parentName !== $parentClassReflection->getName()) { continue; } - foreach ($node->implements as $implement) { if ($this->isName($implement, $interfaceName)) { continue 2; } } - - $node->implements[] = new FullyQualified($interfaceName); + $node->implements[] = new \PhpParser\Node\Name\FullyQualified($interfaceName); } - return $node; } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->interfaceByParent = $configuration[self::INTERFACE_BY_PARENT] ?? []; } diff --git a/rules/Transform/Rector/Class_/AddInterfaceByTraitRector.php b/rules/Transform/Rector/Class_/AddInterfaceByTraitRector.php index 39877ff1c3a..53901ff153d 100644 --- a/rules/Transform/Rector/Class_/AddInterfaceByTraitRector.php +++ b/rules/Transform/Rector/Class_/AddInterfaceByTraitRector.php @@ -1,7 +1,6 @@ */ private $interfaceByTrait = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add interface by used trait', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add interface by used trait', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { use SomeTrait; } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass implements SomeInterface { use SomeTrait; } CODE_SAMPLE - , - [ - self::INTERFACE_BY_TRAIT => [ - 'SomeTrait' => 'SomeInterface', - ], - ] - ), - ]); +, [self::INTERFACE_BY_TRAIT => ['SomeTrait' => 'SomeInterface']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { /** @var Scope $scope */ - $scope = $node->getAttribute(AttributeKey::SCOPE); + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { return null; } - foreach ($this->interfaceByTrait as $traitName => $interfaceName) { - if (! $classReflection->hasTraitUse($traitName)) { + if (!$classReflection->hasTraitUse($traitName)) { continue; } - foreach ($node->implements as $implement) { if ($this->isName($implement, $interfaceName)) { continue 2; } } - - $node->implements[] = new FullyQualified($interfaceName); + $node->implements[] = new \PhpParser\Node\Name\FullyQualified($interfaceName); } - return $node; } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->interfaceByTrait = $configuration[self::INTERFACE_BY_TRAIT] ?? []; } diff --git a/rules/Transform/Rector/Class_/ChangeSingletonToServiceRector.php b/rules/Transform/Rector/Class_/ChangeSingletonToServiceRector.php index 1fdb48f339a..64656e6bda6 100644 --- a/rules/Transform/Rector/Class_/ChangeSingletonToServiceRector.php +++ b/rules/Transform/Rector/Class_/ChangeSingletonToServiceRector.php @@ -1,7 +1,6 @@ singletonClassMethodAnalyzer = $singletonClassMethodAnalyzer; $this->classAnalyzer = $classAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change singleton class to normal class that can be registered as a service', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change singleton class to normal class that can be registered as a service', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private static $instance; @@ -66,8 +55,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function __construct() @@ -75,78 +63,60 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->classAnalyzer->isAnonymousClass($node)) { return null; } - $propertyAndClassMethodName = $this->matchStaticPropertyFetchAndGetSingletonMethodName($node); - if (! $propertyAndClassMethodName instanceof PropertyAndClassMethodName) { + if (!$propertyAndClassMethodName instanceof \Rector\Transform\ValueObject\PropertyAndClassMethodName) { return null; } - return $this->refactorClassStmts($node, $propertyAndClassMethodName); } - - private function matchStaticPropertyFetchAndGetSingletonMethodName(Class_ $class): ?PropertyAndClassMethodName + private function matchStaticPropertyFetchAndGetSingletonMethodName(\PhpParser\Node\Stmt\Class_ $class) : ?\Rector\Transform\ValueObject\PropertyAndClassMethodName { foreach ($class->getMethods() as $classMethod) { - if (! $classMethod->isStatic()) { + if (!$classMethod->isStatic()) { continue; } - $staticPropertyFetch = $this->singletonClassMethodAnalyzer->matchStaticPropertyFetch($classMethod); - if (! $staticPropertyFetch instanceof StaticPropertyFetch) { + if (!$staticPropertyFetch instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { return null; } - /** @var string $propertyName */ $propertyName = $this->getName($staticPropertyFetch); - /** @var string $classMethodName */ $classMethodName = $this->getName($classMethod); - - return new PropertyAndClassMethodName($propertyName, $classMethodName); + return new \Rector\Transform\ValueObject\PropertyAndClassMethodName($propertyName, $classMethodName); } - return null; } - - private function refactorClassStmts( - Class_ $class, - PropertyAndClassMethodName $propertyAndClassMethodName - ): Class_ { + private function refactorClassStmts(\PhpParser\Node\Stmt\Class_ $class, \Rector\Transform\ValueObject\PropertyAndClassMethodName $propertyAndClassMethodName) : \PhpParser\Node\Stmt\Class_ + { foreach ($class->getMethods() as $classMethod) { if ($this->isName($classMethod, $propertyAndClassMethodName->getClassMethodName())) { $this->removeNodeFromStatements($class, $classMethod); continue; } - - if (! $this->isNames($classMethod, [MethodName::CONSTRUCT, MethodName::CLONE, '__wakeup'])) { + if (!$this->isNames($classMethod, [\Rector\Core\ValueObject\MethodName::CONSTRUCT, \Rector\Core\ValueObject\MethodName::CLONE, '__wakeup'])) { continue; } - if ($classMethod->isPublic()) { continue; } - // remove non-public empty if ($classMethod->stmts === []) { $this->removeNodeFromStatements($class, $classMethod); @@ -154,19 +124,15 @@ CODE_SAMPLE $this->visibilityManipulator->makePublic($classMethod); } } - $this->removePropertyByName($class, $propertyAndClassMethodName->getPropertyName()); - return $class; } - - private function removePropertyByName(Class_ $class, string $propertyName): void + private function removePropertyByName(\PhpParser\Node\Stmt\Class_ $class, string $propertyName) : void { foreach ($class->getProperties() as $property) { - if (! $this->isName($property, $propertyName)) { + if (!$this->isName($property, $propertyName)) { continue; } - $this->removeNodeFromStatements($class, $property); } } diff --git a/rules/Transform/Rector/Class_/MergeInterfacesRector.php b/rules/Transform/Rector/Class_/MergeInterfacesRector.php index 6305873fe54..af895acc881 100644 --- a/rules/Transform/Rector/Class_/MergeInterfacesRector.php +++ b/rules/Transform/Rector/Class_/MergeInterfacesRector.php @@ -1,7 +1,6 @@ */ private $oldToNewInterfaces = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Merges old interface to a new one, that already has its methods', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Merges old interface to a new one, that already has its methods', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass implements SomeInterface, SomeOldInterface { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass implements SomeInterface { } CODE_SAMPLE - , - [ - self::OLD_TO_NEW_INTERFACES => [ - 'SomeOldInterface' => 'SomeInterface', - ], - ] - ), - ]); +, [self::OLD_TO_NEW_INTERFACES => ['SomeOldInterface' => 'SomeInterface']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->implements === []) { return null; } - foreach ($node->implements as $key => $implement) { - $oldInterfaces = array_keys($this->oldToNewInterfaces); - if (! $this->isNames($implement, $oldInterfaces)) { + $oldInterfaces = \array_keys($this->oldToNewInterfaces); + if (!$this->isNames($implement, $oldInterfaces)) { continue; } - $interface = $this->getName($implement); - $node->implements[$key] = new Name($this->oldToNewInterfaces[$interface]); + $node->implements[$key] = new \PhpParser\Node\Name($this->oldToNewInterfaces[$interface]); } - $this->makeImplementsUnique($node); - return $node; } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->oldToNewInterfaces = $configuration[self::OLD_TO_NEW_INTERFACES] ?? []; } - - private function makeImplementsUnique(Class_ $class): void + private function makeImplementsUnique(\PhpParser\Node\Stmt\Class_ $class) : void { $alreadyAddedNames = []; foreach ($class->implements as $key => $name) { $fqnName = $this->getName($name); - if (in_array($fqnName, $alreadyAddedNames, true)) { + if (\in_array($fqnName, $alreadyAddedNames, \true)) { $this->nodeRemover->removeImplements($class, $key); continue; } - $alreadyAddedNames[] = $fqnName; } } diff --git a/rules/Transform/Rector/Class_/ParentClassToTraitsRector.php b/rules/Transform/Rector/Class_/ParentClassToTraitsRector.php index 9a1198f6ee7..a366deb75cc 100644 --- a/rules/Transform/Rector/Class_/ParentClassToTraitsRector.php +++ b/rules/Transform/Rector/Class_/ParentClassToTraitsRector.php @@ -1,7 +1,6 @@ classInsertManipulator = $classInsertManipulator; $this->classAnalyzer = $classAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replaces parent class to specific traits', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces parent class to specific traits', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass extends Nette\Object { } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { use Nette\SmartObject; } CODE_SAMPLE - , - [ - self::PARENT_CLASS_TO_TRAITS => [ - 'Nette\Object' => ['Nette\SmartObject'], - ], - ] - ), - ]); +, [self::PARENT_CLASS_TO_TRAITS => ['Nette\\Object' => ['Nette\\SmartObject']]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Class_::class]; + return [\PhpParser\Node\Stmt\Class_::class]; } - /** * @param Class_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->extends === null) { return null; } - if ($this->classAnalyzer->isAnonymousClass($node)) { return null; } - foreach ($this->parentClassToTraits as $parentClassToTrait) { - if (! $this->isObjectType($node, $parentClassToTrait->getParentObjectType())) { + if (!$this->isObjectType($node, $parentClassToTrait->getParentObjectType())) { continue; } - foreach ($parentClassToTrait->getTraitNames() as $traitName) { $this->classInsertManipulator->addAsFirstTrait($node, $traitName); } - $this->removeParentClass($node); - return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $parentClassToTraits = $configuration[self::PARENT_CLASS_TO_TRAITS] ?? []; - Assert::allIsInstanceOf($parentClassToTraits, ParentClassToTraits::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($parentClassToTraits, \Rector\Transform\ValueObject\ParentClassToTraits::class); $this->parentClassToTraits = $parentClassToTraits; } - - private function removeParentClass(Class_ $class): void + private function removeParentClass(\PhpParser\Node\Stmt\Class_ $class) : void { $class->extends = null; } diff --git a/rules/Transform/Rector/Expression/MethodCallToReturnRector.php b/rules/Transform/Rector/Expression/MethodCallToReturnRector.php index df5d334bb2f..80dcad41518 100644 --- a/rules/Transform/Rector/Expression/MethodCallToReturnRector.php +++ b/rules/Transform/Rector/Expression/MethodCallToReturnRector.php @@ -1,7 +1,6 @@ [ - 'SomeClass' => ['deny'], - ], - ] - ), - ]); +, [self::METHOD_CALL_WRAPS => ['SomeClass' => ['deny']]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Expression::class]; + return [\PhpParser\Node\Stmt\Expression::class]; } - /** * @param Expression $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $node->expr instanceof MethodCall) { + if (!$node->expr instanceof \PhpParser\Node\Expr\MethodCall) { return null; } - $methodCall = $node->expr; - return $this->refactorMethodCall($methodCall); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $methodCallWraps = $configuration[self::METHOD_CALL_WRAPS] ?? []; - Assert::allIsInstanceOf($methodCallWraps, MethodCallToReturn::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($methodCallWraps, \Rector\Transform\ValueObject\MethodCallToReturn::class); $this->methodCallWraps = $methodCallWraps; } - - private function refactorMethodCall(MethodCall $methodCall): ?Node + private function refactorMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node { - $parent = $methodCall->getAttribute(AttributeKey::PARENT_NODE); - + $parent = $methodCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); foreach ($this->methodCallWraps as $methodCallWrap) { - if (! $this->isObjectType($methodCall->var, $methodCallWrap->getObjectType())) { + if (!$this->isObjectType($methodCall->var, $methodCallWrap->getObjectType())) { continue; } - - if (! $this->isName($methodCall->name, $methodCallWrap->getMethod())) { + if (!$this->isName($methodCall->name, $methodCallWrap->getMethod())) { continue; } - // already wrapped - if ($parent instanceof Return_) { + if ($parent instanceof \PhpParser\Node\Stmt\Return_) { continue; } - - return new Return_($methodCall); + return new \PhpParser\Node\Stmt\Return_($methodCall); } - return null; } } diff --git a/rules/Transform/Rector/FileWithoutNamespace/FunctionToStaticMethodRector.php b/rules/Transform/Rector/FileWithoutNamespace/FunctionToStaticMethodRector.php index 10cb1d43a29..64104b5becd 100644 --- a/rules/Transform/Rector/FileWithoutNamespace/FunctionToStaticMethodRector.php +++ b/rules/Transform/Rector/FileWithoutNamespace/FunctionToStaticMethodRector.php @@ -1,7 +1,6 @@ classNaming = $classNaming; $this->staticMethodClassFactory = $staticMethodClassFactory; $this->fullyQualifiedNameResolver = $fullyQualifiedNameResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change functions to static calls, so composer can autoload them', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change functions to static calls, so composer can autoload them', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' function some_function() { } some_function('lol'); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeUtilsClass { public static function someFunction() @@ -76,129 +62,97 @@ class SomeUtilsClass SomeUtilsClass::someFunction('lol'); CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FileWithoutNamespace::class, Namespace_::class]; + return [\Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace::class, \PhpParser\Node\Stmt\Namespace_::class]; } - /** * @param FileWithoutNamespace|Namespace_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { /** @var Function_[] $functions */ - $functions = $this->betterNodeFinder->findInstanceOf($node, Function_::class); + $functions = $this->betterNodeFinder->findInstanceOf($node, \PhpParser\Node\Stmt\Function_::class); if ($functions === []) { return null; } - $smartFileInfo = $this->file->getSmartFileInfo(); - $shortClassName = $this->classNaming->getNameFromFileInfo($smartFileInfo); $class = $this->staticMethodClassFactory->createStaticMethodClass($shortClassName, $functions); - $stmts = $node->stmts; $this->removeNodes($functions); - // replace function calls with class static call $functionsToStaticCalls = $this->resolveFunctionsToStaticCalls($stmts, $shortClassName, $functions); $node->stmts = $this->replaceFuncCallsWithStaticCalls($stmts, $functionsToStaticCalls); - $this->printStaticMethodClass($smartFileInfo, $shortClassName, $node, $class); - return $node; } - /** * @param Node[] $stmts * @param Function_[] $functions * @return FunctionToStaticCall[] */ - private function resolveFunctionsToStaticCalls(array $stmts, string $shortClassName, array $functions): array + private function resolveFunctionsToStaticCalls(array $stmts, string $shortClassName, array $functions) : array { $functionsToStaticCalls = []; - $className = $this->fullyQualifiedNameResolver->resolveFullyQualifiedName($stmts, $shortClassName); foreach ($functions as $function) { $functionName = $this->getName($function); if ($functionName === null) { continue; } - $methodName = $this->classNaming->createMethodNameFromFunction($function); - $functionsToStaticCalls[] = new FunctionToStaticCall($functionName, $className, $methodName); + $functionsToStaticCalls[] = new \Rector\Transform\ValueObject\FunctionToStaticCall($functionName, $className, $methodName); } - return $functionsToStaticCalls; } - /** * @param Node[] $stmts * @param FunctionToStaticCall[] $functionsToStaticCalls * @return Node[] */ - private function replaceFuncCallsWithStaticCalls(array $stmts, array $functionsToStaticCalls): array + private function replaceFuncCallsWithStaticCalls(array $stmts, array $functionsToStaticCalls) : array { - $this->traverseNodesWithCallable($stmts, function (Node $node) use ($functionsToStaticCalls): ?StaticCall { - if (! $node instanceof FuncCall) { + $this->traverseNodesWithCallable($stmts, function (\PhpParser\Node $node) use($functionsToStaticCalls) : ?StaticCall { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { return null; } - foreach ($functionsToStaticCalls as $functionToStaticCall) { - if (! $this->isName($node, $functionToStaticCall->getFunction())) { + if (!$this->isName($node, $functionToStaticCall->getFunction())) { continue; } - - $staticCall = $this->nodeFactory->createStaticCall( - $functionToStaticCall->getClass(), - $functionToStaticCall->getMethod() - ); + $staticCall = $this->nodeFactory->createStaticCall($functionToStaticCall->getClass(), $functionToStaticCall->getMethod()); $staticCall->args = $node->args; - return $staticCall; } - return null; }); - return $stmts; } - /** * @param Namespace_|FileWithoutNamespace $node */ - private function printStaticMethodClass( - SmartFileInfo $smartFileInfo, - string $shortClassName, - Node $node, - Class_ $class - ): void { - $classFileDestination = $smartFileInfo->getPath() . DIRECTORY_SEPARATOR . $shortClassName . '.php'; - + private function printStaticMethodClass(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo, string $shortClassName, \PhpParser\Node $node, \PhpParser\Node\Stmt\Class_ $class) : void + { + $classFileDestination = $smartFileInfo->getPath() . \DIRECTORY_SEPARATOR . $shortClassName . '.php'; $nodesToPrint = [$this->resolveNodeToPrint($node, $class)]; - - $addedFileWithNodes = new AddedFileWithNodes($classFileDestination, $nodesToPrint); + $addedFileWithNodes = new \Rector\FileSystemRector\ValueObject\AddedFileWithNodes($classFileDestination, $nodesToPrint); $this->removedAndAddedFilesCollector->addAddedFile($addedFileWithNodes); } - /** * @param Namespace_|FileWithoutNamespace $node * @return Namespace_|Class_ */ - private function resolveNodeToPrint(Node $node, Class_ $class): Stmt + private function resolveNodeToPrint(\PhpParser\Node $node, \PhpParser\Node\Stmt\Class_ $class) : \PhpParser\Node\Stmt { - if ($node instanceof Namespace_) { - return new Namespace_($node->name, [$class]); + if ($node instanceof \PhpParser\Node\Stmt\Namespace_) { + return new \PhpParser\Node\Stmt\Namespace_($node->name, [$class]); } - return $class; } } diff --git a/rules/Transform/Rector/FuncCall/ArgumentFuncCallToMethodCallRector.php b/rules/Transform/Rector/FuncCall/ArgumentFuncCallToMethodCallRector.php index 958024540a7..6914d3eaaae 100644 --- a/rules/Transform/Rector/FuncCall/ArgumentFuncCallToMethodCallRector.php +++ b/rules/Transform/Rector/FuncCall/ArgumentFuncCallToMethodCallRector.php @@ -1,7 +1,6 @@ propertyNaming = $propertyNaming; $this->arrayTypeAnalyzer = $arrayTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Move help facade-like function calls to constructor injection', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Move help facade-like function calls to constructor injection', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeController { public function action() @@ -80,8 +69,7 @@ class SomeController } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeController { /** @@ -101,185 +89,128 @@ class SomeController } } CODE_SAMPLE - , - [ - self::FUNCTIONS_TO_METHOD_CALLS => [ - new ArgumentFuncCallToMethodCall('view', 'Illuminate\Contracts\View\Factory', 'make'), - ], - ] - ), - ]); +, [self::FUNCTIONS_TO_METHOD_CALLS => [new \Rector\Transform\ValueObject\ArgumentFuncCallToMethodCall('view', 'Illuminate\\Contracts\\View\\Factory', 'make')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkipFuncCall($node)) { return null; } - /** @var Class_ $classLike */ - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); foreach ($this->argumentFuncCallToMethodCalls as $argumentFuncCallToMethodCall) { - if (! $this->isName($node, $argumentFuncCallToMethodCall->getFunction())) { + if (!$this->isName($node, $argumentFuncCallToMethodCall->getFunction())) { continue; } - return $this->refactorFuncCallToMethodCall($argumentFuncCallToMethodCall, $classLike, $node); } - foreach ($this->arrayFunctionsToMethodCalls as $arrayFunctionToMethodCall) { - if (! $this->isName($node, $arrayFunctionToMethodCall->getFunction())) { + if (!$this->isName($node, $arrayFunctionToMethodCall->getFunction())) { continue; } - return $this->refactorArrayFunctionToMethodCall($arrayFunctionToMethodCall, $node, $classLike); } - return null; } - /** * @param mixed[] $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $functionToMethodCalls = $configuration[self::FUNCTIONS_TO_METHOD_CALLS] ?? []; - Assert::allIsInstanceOf($functionToMethodCalls, ArgumentFuncCallToMethodCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($functionToMethodCalls, \Rector\Transform\ValueObject\ArgumentFuncCallToMethodCall::class); $this->argumentFuncCallToMethodCalls = $functionToMethodCalls; - $arrayFunctionsToMethodCalls = $configuration[self::ARRAY_FUNCTIONS_TO_METHOD_CALLS] ?? []; - Assert::allIsInstanceOf($arrayFunctionsToMethodCalls, ArrayFuncCallToMethodCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($arrayFunctionsToMethodCalls, \Rector\Transform\ValueObject\ArrayFuncCallToMethodCall::class); $this->arrayFunctionsToMethodCalls = $arrayFunctionsToMethodCalls; } - - private function shouldSkipFuncCall(FuncCall $funcCall): bool + private function shouldSkipFuncCall(\PhpParser\Node\Expr\FuncCall $funcCall) : bool { // we can inject only in injectable class method context // we can inject only in injectable class method context /** @var ClassMethod|null $classMethod */ - $classMethod = $funcCall->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { - return true; + $classMethod = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \true; } - return $classMethod->isStatic(); } - /** * @return PropertyFetch|MethodCall */ - private function refactorFuncCallToMethodCall( - ArgumentFuncCallToMethodCall $argumentFuncCallToMethodCall, - Class_ $class, - FuncCall $funcCall - ): ?Node { - $fullyQualifiedObjectType = new FullyQualifiedObjectType($argumentFuncCallToMethodCall->getClass()); + private function refactorFuncCallToMethodCall(\Rector\Transform\ValueObject\ArgumentFuncCallToMethodCall $argumentFuncCallToMethodCall, \PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node + { + $fullyQualifiedObjectType = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($argumentFuncCallToMethodCall->getClass()); $expectedName = $this->propertyNaming->getExpectedNameFromType($fullyQualifiedObjectType); - - if (! $expectedName instanceof ExpectedName) { - throw new ShouldNotHappenException(); + if (!$expectedName instanceof \Rector\Naming\ValueObject\ExpectedName) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $this->addConstructorDependencyToClass($class, $fullyQualifiedObjectType, $expectedName->getName()); - $propertyFetchNode = $this->nodeFactory->createPropertyFetch('this', $expectedName->getName()); - if ($funcCall->args === []) { return $this->refactorEmptyFuncCallArgs($argumentFuncCallToMethodCall, $propertyFetchNode); } - if ($this->isFunctionToMethodCallWithArgs($funcCall, $argumentFuncCallToMethodCall)) { $methodName = $argumentFuncCallToMethodCall->getMethodIfArgs(); - if (! is_string($methodName)) { - throw new ShouldNotHappenException(); + if (!\is_string($methodName)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - return new MethodCall($propertyFetchNode, $methodName, $funcCall->args); + return new \PhpParser\Node\Expr\MethodCall($propertyFetchNode, $methodName, $funcCall->args); } - return null; } - /** * @return PropertyFetch|MethodCall|null */ - private function refactorArrayFunctionToMethodCall( - ArrayFuncCallToMethodCall $arrayFuncCallToMethodCall, - FuncCall $funcCall, - Class_ $class - ): ?Node { + private function refactorArrayFunctionToMethodCall(\Rector\Transform\ValueObject\ArrayFuncCallToMethodCall $arrayFuncCallToMethodCall, \PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Stmt\Class_ $class) : ?\PhpParser\Node + { $propertyName = $this->propertyNaming->fqnToVariableName($arrayFuncCallToMethodCall->getClass()); $propertyFetch = $this->nodeFactory->createPropertyFetch('this', $propertyName); - - $fullyQualifiedObjectType = new FullyQualifiedObjectType($arrayFuncCallToMethodCall->getClass()); - + $fullyQualifiedObjectType = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($arrayFuncCallToMethodCall->getClass()); $this->addConstructorDependencyToClass($class, $fullyQualifiedObjectType, $propertyName); - - return $this->createMethodCallArrayFunctionToMethodCall( - $funcCall, - $arrayFuncCallToMethodCall, - $propertyFetch - ); + return $this->createMethodCallArrayFunctionToMethodCall($funcCall, $arrayFuncCallToMethodCall, $propertyFetch); } - /** * @return PropertyFetch|MethodCall */ - private function refactorEmptyFuncCallArgs( - ArgumentFuncCallToMethodCall $argumentFuncCallToMethodCall, - PropertyFetch $propertyFetch - ): Expr { + private function refactorEmptyFuncCallArgs(\Rector\Transform\ValueObject\ArgumentFuncCallToMethodCall $argumentFuncCallToMethodCall, \PhpParser\Node\Expr\PropertyFetch $propertyFetch) : \PhpParser\Node\Expr + { if ($argumentFuncCallToMethodCall->getMethodIfNoArgs()) { $methodName = $argumentFuncCallToMethodCall->getMethodIfNoArgs(); - if (! is_string($methodName)) { - throw new ShouldNotHappenException(); + if (!\is_string($methodName)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - return new MethodCall($propertyFetch, $methodName); + return new \PhpParser\Node\Expr\MethodCall($propertyFetch, $methodName); } - return $propertyFetch; } - - private function isFunctionToMethodCallWithArgs( - FuncCall $funcCall, - ArgumentFuncCallToMethodCall $argumentFuncCallToMethodCall - ): bool { + private function isFunctionToMethodCallWithArgs(\PhpParser\Node\Expr\FuncCall $funcCall, \Rector\Transform\ValueObject\ArgumentFuncCallToMethodCall $argumentFuncCallToMethodCall) : bool + { if ($argumentFuncCallToMethodCall->getMethodIfArgs() === null) { - return false; + return \false; } - - return count($funcCall->args) >= 1; + return \count($funcCall->args) >= 1; } - /** * @return PropertyFetch|MethodCall|null */ - private function createMethodCallArrayFunctionToMethodCall( - FuncCall $funcCall, - ArrayFuncCallToMethodCall $arrayFuncCallToMethodCall, - PropertyFetch $propertyFetch - ): ?Node { + private function createMethodCallArrayFunctionToMethodCall(\PhpParser\Node\Expr\FuncCall $funcCall, \Rector\Transform\ValueObject\ArrayFuncCallToMethodCall $arrayFuncCallToMethodCall, \PhpParser\Node\Expr\PropertyFetch $propertyFetch) : ?\PhpParser\Node + { if ($funcCall->args === []) { return $propertyFetch; } - - if ($arrayFuncCallToMethodCall->getArrayMethod() && $this->arrayTypeAnalyzer->isArrayType( - $funcCall->args[0]->value - )) { - return new MethodCall($propertyFetch, $arrayFuncCallToMethodCall->getArrayMethod(), $funcCall->args); + if ($arrayFuncCallToMethodCall->getArrayMethod() && $this->arrayTypeAnalyzer->isArrayType($funcCall->args[0]->value)) { + return new \PhpParser\Node\Expr\MethodCall($propertyFetch, $arrayFuncCallToMethodCall->getArrayMethod(), $funcCall->args); } if ($arrayFuncCallToMethodCall->getNonArrayMethod() === '') { return null; @@ -287,6 +218,6 @@ CODE_SAMPLE if ($this->arrayTypeAnalyzer->isArrayType($funcCall->args[0]->value)) { return null; } - return new MethodCall($propertyFetch, $arrayFuncCallToMethodCall->getNonArrayMethod(), $funcCall->args); + return new \PhpParser\Node\Expr\MethodCall($propertyFetch, $arrayFuncCallToMethodCall->getNonArrayMethod(), $funcCall->args); } } diff --git a/rules/Transform/Rector/FuncCall/FuncCallToConstFetchRector.php b/rules/Transform/Rector/FuncCall/FuncCallToConstFetchRector.php index 51b4f2c70e1..505b8e38669 100644 --- a/rules/Transform/Rector/FuncCall/FuncCallToConstFetchRector.php +++ b/rules/Transform/Rector/FuncCall/FuncCallToConstFetchRector.php @@ -1,7 +1,6 @@ [ - 'php_sapi_name' => 'PHP_SAPI', - ], - ] - ), - - ]); +, [self::FUNCTIONS_TO_CONSTANTS => ['php_sapi_name' => 'PHP_SAPI']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $functionName = $this->getName($node); - if (! $functionName) { + if (!$functionName) { return null; } - if (! array_key_exists($functionName, $this->functionsToConstants)) { + if (!\array_key_exists($functionName, $this->functionsToConstants)) { return null; } - - return new ConstFetch(new Name($this->functionsToConstants[$functionName])); + return new \PhpParser\Node\Expr\ConstFetch(new \PhpParser\Node\Name($this->functionsToConstants[$functionName])); } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->functionsToConstants = $configuration[self::FUNCTIONS_TO_CONSTANTS] ?? []; } diff --git a/rules/Transform/Rector/FuncCall/FuncCallToMethodCallRector.php b/rules/Transform/Rector/FuncCall/FuncCallToMethodCallRector.php index ed5950b92ac..347e3ca8ec0 100644 --- a/rules/Transform/Rector/FuncCall/FuncCallToMethodCallRector.php +++ b/rules/Transform/Rector/FuncCall/FuncCallToMethodCallRector.php @@ -1,7 +1,6 @@ funcCallStaticCallToMethodCallAnalyzer = $funcCallStaticCallToMethodCallAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turns defined function calls to local method calls.', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns defined function calls to local method calls.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -55,8 +47,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -75,71 +66,47 @@ class SomeClass } } CODE_SAMPLE - , - [ - self::FUNC_CALL_TO_CLASS_METHOD_CALL => [ - new FuncCallToMethodCall('view', 'Namespaced\SomeRenderer', 'render'), - ], - ] - ), - ]); +, [self::FUNC_CALL_TO_CLASS_METHOD_CALL => [new \Rector\Transform\ValueObject\FuncCallToMethodCall('view', 'Namespaced\\SomeRenderer', 'render')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - - $classMethod = $node->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { + $classMethod = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - if ($classMethod->isStatic()) { return null; } - foreach ($this->funcNameToMethodCallNames as $funcNameToMethodCallName) { - if (! $this->isName($node->name, $funcNameToMethodCallName->getOldFuncName())) { + if (!$this->isName($node->name, $funcNameToMethodCallName->getOldFuncName())) { continue; } - - $expr = $this->funcCallStaticCallToMethodCallAnalyzer->matchTypeProvidingExpr( - $classLike, - $classMethod, - $funcNameToMethodCallName->getNewObjectType() - ); - return $this->nodeFactory->createMethodCall( - $expr, - $funcNameToMethodCallName->getNewMethodName(), - $node->args - ); + $expr = $this->funcCallStaticCallToMethodCallAnalyzer->matchTypeProvidingExpr($classLike, $classMethod, $funcNameToMethodCallName->getNewObjectType()); + return $this->nodeFactory->createMethodCall($expr, $funcNameToMethodCallName->getNewMethodName(), $node->args); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $funcCallsToClassMethodCalls = $configuration[self::FUNC_CALL_TO_CLASS_METHOD_CALL] ?? []; - Assert::allIsInstanceOf($funcCallsToClassMethodCalls, FuncCallToMethodCall::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($funcCallsToClassMethodCalls, \Rector\Transform\ValueObject\FuncCallToMethodCall::class); $this->funcNameToMethodCallNames = $funcCallsToClassMethodCalls; } } diff --git a/rules/Transform/Rector/FuncCall/FuncCallToNewRector.php b/rules/Transform/Rector/FuncCall/FuncCallToNewRector.php index d2e222e3e09..794bbf0cae8 100644 --- a/rules/Transform/Rector/FuncCall/FuncCallToNewRector.php +++ b/rules/Transform/Rector/FuncCall/FuncCallToNewRector.php @@ -1,7 +1,6 @@ [ - 'collection' => ['Collection'], - ], - ] - ), - ]); +, [self::FUNCTIONS_TO_NEWS => ['collection' => ['Collection']]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->functionToNew as $function => $new) { - if (! $this->isName($node, $function)) { + if (!$this->isName($node, $function)) { continue; } - - return new New_(new FullyQualified($new), $node->args); + return new \PhpParser\Node\Expr\New_(new \PhpParser\Node\Name\FullyQualified($new), $node->args); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->functionToNew = $configuration[self::FUNCTIONS_TO_NEWS] ?? []; } diff --git a/rules/Transform/Rector/FuncCall/FuncCallToStaticCallRector.php b/rules/Transform/Rector/FuncCall/FuncCallToStaticCallRector.php index b47fb37d36a..21b48c84b00 100644 --- a/rules/Transform/Rector/FuncCall/FuncCallToStaticCallRector.php +++ b/rules/Transform/Rector/FuncCall/FuncCallToStaticCallRector.php @@ -1,7 +1,6 @@ [ - new FuncCallToStaticCall('view', 'SomeStaticClass', 'render'), - ], - ] - ), - ]); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns defined function call to static method call.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample('view("...", []);', 'SomeClass::render("...", []);', [self::FUNC_CALLS_TO_STATIC_CALLS => [new \Rector\Transform\ValueObject\FuncCallToStaticCall('view', 'SomeStaticClass', 'render')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [FuncCall::class]; + return [\PhpParser\Node\Expr\FuncCall::class]; } - /** * @param FuncCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->funcCallsToStaticCalls as $funcCallToStaticCall) { - if (! $this->isName($node, $funcCallToStaticCall->getOldFuncName())) { + if (!$this->isName($node, $funcCallToStaticCall->getOldFuncName())) { continue; } - - return $this->nodeFactory->createStaticCall( - $funcCallToStaticCall->getNewClassName(), - $funcCallToStaticCall->getNewMethodName(), - $node->args - ); + return $this->nodeFactory->createStaticCall($funcCallToStaticCall->getNewClassName(), $funcCallToStaticCall->getNewMethodName(), $node->args); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $funcCallsToStaticCalls = $configuration[self::FUNC_CALLS_TO_STATIC_CALLS] ?? []; - Assert::allIsInstanceOf($funcCallsToStaticCalls, FuncCallToStaticCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($funcCallsToStaticCalls, \Rector\Transform\ValueObject\FuncCallToStaticCall::class); $this->funcCallsToStaticCalls = $funcCallsToStaticCalls; } } diff --git a/rules/Transform/Rector/Isset_/UnsetAndIssetToMethodCallRector.php b/rules/Transform/Rector/Isset_/UnsetAndIssetToMethodCallRector.php index f27d31bc0f9..2b333e845c3 100644 --- a/rules/Transform/Rector/Isset_/UnsetAndIssetToMethodCallRector.php +++ b/rules/Transform/Rector/Isset_/UnsetAndIssetToMethodCallRector.php @@ -1,7 +1,6 @@ hasService("someKey"); $container->removeService("someKey"); CODE_SAMPLE - , - [ - self::ISSET_UNSET_TO_METHOD_CALL => [$unsetAndIssetToMethodCall], - ] - ), - ]); +, [self::ISSET_UNSET_TO_METHOD_CALL => [$unsetAndIssetToMethodCall]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Isset_::class, Unset_::class]; + return [\PhpParser\Node\Expr\Isset_::class, \PhpParser\Node\Stmt\Unset_::class]; } - /** * @param Isset_|Unset_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($node->vars as $arrayDimFetch) { - if (! $arrayDimFetch instanceof ArrayDimFetch) { + if (!$arrayDimFetch instanceof \PhpParser\Node\Expr\ArrayDimFetch) { continue; } - foreach ($this->issetUnsetToMethodCalls as $issetUnsetToMethodCall) { - if (! $this->isObjectType($arrayDimFetch->var, $issetUnsetToMethodCall->getObjectType())) { + if (!$this->isObjectType($arrayDimFetch->var, $issetUnsetToMethodCall->getObjectType())) { continue; } - $newNode = $this->processArrayDimFetchNode($node, $arrayDimFetch, $issetUnsetToMethodCall); if ($newNode !== null) { return $newNode; } } } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $issetUnsetToMethodCalls = $configuration[self::ISSET_UNSET_TO_METHOD_CALL] ?? []; - Assert::allIsInstanceOf($issetUnsetToMethodCalls, UnsetAndIssetToMethodCall::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($issetUnsetToMethodCalls, \Rector\Transform\ValueObject\UnsetAndIssetToMethodCall::class); $this->issetUnsetToMethodCalls = $issetUnsetToMethodCalls; } - - private function processArrayDimFetchNode( - Node $node, - ArrayDimFetch $arrayDimFetch, - UnsetAndIssetToMethodCall $unsetAndIssetToMethodCall - ): ?Node { - if ($node instanceof Isset_) { + private function processArrayDimFetchNode(\PhpParser\Node $node, \PhpParser\Node\Expr\ArrayDimFetch $arrayDimFetch, \Rector\Transform\ValueObject\UnsetAndIssetToMethodCall $unsetAndIssetToMethodCall) : ?\PhpParser\Node + { + if ($node instanceof \PhpParser\Node\Expr\Isset_) { if ($unsetAndIssetToMethodCall->getIssetMethodCall() === '') { return null; } - - return $this->nodeFactory->createMethodCall( - $arrayDimFetch->var, - $unsetAndIssetToMethodCall->getIssetMethodCall(), - [$arrayDimFetch->dim] - ); + return $this->nodeFactory->createMethodCall($arrayDimFetch->var, $unsetAndIssetToMethodCall->getIssetMethodCall(), [$arrayDimFetch->dim]); } - - if ($node instanceof Unset_) { + if ($node instanceof \PhpParser\Node\Stmt\Unset_) { if ($unsetAndIssetToMethodCall->getUnsedMethodCall() === '') { return null; } - - return $this->nodeFactory->createMethodCall( - $arrayDimFetch->var, - $unsetAndIssetToMethodCall->getUnsedMethodCall(), - [$arrayDimFetch->dim] - ); + return $this->nodeFactory->createMethodCall($arrayDimFetch->var, $unsetAndIssetToMethodCall->getUnsedMethodCall(), [$arrayDimFetch->dim]); } - return null; } } diff --git a/rules/Transform/Rector/MethodCall/CallableInMethodCallToVariableRector.php b/rules/Transform/Rector/MethodCall/CallableInMethodCallToVariableRector.php index f5fccab3ef4..fd38ca17312 100644 --- a/rules/Transform/Rector/MethodCall/CallableInMethodCallToVariableRector.php +++ b/rules/Transform/Rector/MethodCall/CallableInMethodCallToVariableRector.php @@ -1,7 +1,6 @@ unwrapClosureFactory = $unwrapClosureFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change a callable in method call to standalone variable assign', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change a callable in method call to standalone variable assign', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -59,8 +51,7 @@ final class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -71,66 +62,48 @@ final class SomeClass } } CODE_SAMPLE -, - [ - self::CALLABLE_IN_METHOD_CALL_TO_VARIABLE => [ - new CallableInMethodCallToVariable('Nette\Caching\Cache', 'save', 1), - ], - ] - ), - ]); +, [self::CALLABLE_IN_METHOD_CALL_TO_VARIABLE => [new \Rector\Transform\ValueObject\CallableInMethodCallToVariable('Nette\\Caching\\Cache', 'save', 1)]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node * @return Node|Node[]|null */ - public function refactor(Node $node) + public function refactor(\PhpParser\Node $node) { foreach ($this->callableInMethodCallToVariable as $singleCallableInMethodCallToVariable) { - if (! $this->isObjectType($node->var, $singleCallableInMethodCallToVariable->getObjectType())) { + if (!$this->isObjectType($node->var, $singleCallableInMethodCallToVariable->getObjectType())) { continue; } - - if (! isset($node->args[$singleCallableInMethodCallToVariable->getArgumentPosition()])) { + if (!isset($node->args[$singleCallableInMethodCallToVariable->getArgumentPosition()])) { continue; } - $arg = $node->args[$singleCallableInMethodCallToVariable->getArgumentPosition()]; $argValueType = $this->getStaticType($arg->value); - if (! $argValueType instanceof ClosureType) { + if (!$argValueType instanceof \PHPStan\Type\ClosureType) { continue; } - - $resultVariable = new Variable('result'); - + $resultVariable = new \PhpParser\Node\Expr\Variable('result'); $unwrappedNodes = $this->unwrapClosureFactory->createAssign($resultVariable, $arg); - $arg->value = $resultVariable; $this->addNodesBeforeNode($unwrappedNodes, $node); - return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $callableInMethodCallToVariable = $configuration[self::CALLABLE_IN_METHOD_CALL_TO_VARIABLE] ?? []; - Assert::allIsInstanceOf($callableInMethodCallToVariable, CallableInMethodCallToVariable::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($callableInMethodCallToVariable, \Rector\Transform\ValueObject\CallableInMethodCallToVariable::class); $this->callableInMethodCallToVariable = $callableInMethodCallToVariable; } } diff --git a/rules/Transform/Rector/MethodCall/MethodCallToAnotherMethodCallWithArgumentsRector.php b/rules/Transform/Rector/MethodCall/MethodCallToAnotherMethodCallWithArgumentsRector.php index 2157fc08f40..b961ae30d42 100644 --- a/rules/Transform/Rector/MethodCall/MethodCallToAnotherMethodCallWithArgumentsRector.php +++ b/rules/Transform/Rector/MethodCall/MethodCallToAnotherMethodCallWithArgumentsRector.php @@ -1,7 +1,6 @@ setInject(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $serviceDefinition = new Nette\DI\ServiceDefinition; $serviceDefinition->addTag('inject'); CODE_SAMPLE - , - [ - self::METHOD_CALL_RENAMES_WITH_ADDED_ARGUMENTS => [ - new MethodCallRenameWithArrayKey('Nette\DI\ServiceDefinition', 'setInject', 'addTag', 'inject'), - ], - ] - ), - ]); +, [self::METHOD_CALL_RENAMES_WITH_ADDED_ARGUMENTS => [new \Rector\Renaming\ValueObject\MethodCallRenameWithArrayKey('Nette\\DI\\ServiceDefinition', 'setInject', 'addTag', 'inject')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->methodCallRenamesWithAddedArguments as $methodCallRenameWithAddedArgument) { - if (! $this->isObjectType($node->var, $methodCallRenameWithAddedArgument->getObjectType())) { + if (!$this->isObjectType($node->var, $methodCallRenameWithAddedArgument->getObjectType())) { continue; } - - if (! $this->isName($node->name, $methodCallRenameWithAddedArgument->getOldMethod())) { + if (!$this->isName($node->name, $methodCallRenameWithAddedArgument->getOldMethod())) { continue; } - - $node->name = new Identifier($methodCallRenameWithAddedArgument->getNewMethod()); + $node->name = new \PhpParser\Node\Identifier($methodCallRenameWithAddedArgument->getNewMethod()); $node->args = $this->nodeFactory->createArgs($methodCallRenameWithAddedArgument->getNewArguments()); - return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $methodCallRenamesWithAddedArguments = $configuration[self::METHOD_CALL_RENAMES_WITH_ADDED_ARGUMENTS] ?? []; - Assert::allIsInstanceOf( - $methodCallRenamesWithAddedArguments, - MethodCallToAnotherMethodCallWithArguments::class - ); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($methodCallRenamesWithAddedArguments, \Rector\Transform\ValueObject\MethodCallToAnotherMethodCallWithArguments::class); $this->methodCallRenamesWithAddedArguments = $methodCallRenamesWithAddedArguments; } } diff --git a/rules/Transform/Rector/MethodCall/MethodCallToPropertyFetchRector.php b/rules/Transform/Rector/MethodCall/MethodCallToPropertyFetchRector.php index 573add67485..99640472677 100644 --- a/rules/Transform/Rector/MethodCall/MethodCallToPropertyFetchRector.php +++ b/rules/Transform/Rector/MethodCall/MethodCallToPropertyFetchRector.php @@ -1,7 +1,6 @@ */ private $methodCallToPropertyFetchCollection = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turns method call "$this->something()" to property fetch "$this->something"', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns method call "$this->something()" to property fetch "$this->something"', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -40,8 +34,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run() @@ -50,44 +43,32 @@ class SomeClass } } CODE_SAMPLE - , - [ - self::METHOD_CALL_TO_PROPERTY_FETCHES => [ - 'someMethod' => 'someProperty', - ], - ] - ), - ]); +, [self::METHOD_CALL_TO_PROPERTY_FETCHES => ['someMethod' => 'someProperty']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->methodCallToPropertyFetchCollection as $methodName => $propertyName) { - if (! $this->isName($node->name, $methodName)) { + if (!$this->isName($node->name, $methodName)) { continue; } - return $this->nodeFactory->createPropertyFetch('this', $propertyName); } - return null; } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->methodCallToPropertyFetchCollection = $configuration[self::METHOD_CALL_TO_PROPERTY_FETCHES] ?? []; } diff --git a/rules/Transform/Rector/MethodCall/MethodCallToStaticCallRector.php b/rules/Transform/Rector/MethodCall/MethodCallToStaticCallRector.php index 9ab91dafe30..9dbcd249f3e 100644 --- a/rules/Transform/Rector/MethodCall/MethodCallToStaticCallRector.php +++ b/rules/Transform/Rector/MethodCall/MethodCallToStaticCallRector.php @@ -1,7 +1,6 @@ [ - new MethodCallToStaticCall('AnotherDependency', 'process', 'StaticCaller', 'anotherMethod'), - ], - ] - ), - ]); +, [self::METHOD_CALLS_TO_STATIC_CALLS => [new \Rector\Transform\ValueObject\MethodCallToStaticCall('AnotherDependency', 'process', 'StaticCaller', 'anotherMethod')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->methodCallsToStaticCalls as $methodCallToStaticCall) { - if (! $this->isObjectType($node->var, $methodCallToStaticCall->getOldObjectType())) { + if (!$this->isObjectType($node->var, $methodCallToStaticCall->getOldObjectType())) { continue; } - - if (! $this->isName($node->name, $methodCallToStaticCall->getOldMethod())) { + if (!$this->isName($node->name, $methodCallToStaticCall->getOldMethod())) { continue; } - - return $this->nodeFactory->createStaticCall( - $methodCallToStaticCall->getNewClass(), - $methodCallToStaticCall->getNewMethod(), - $node->args - ); + return $this->nodeFactory->createStaticCall($methodCallToStaticCall->getNewClass(), $methodCallToStaticCall->getNewMethod(), $node->args); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $methodCallsToStaticCalls = $configuration[self::METHOD_CALLS_TO_STATIC_CALLS] ?? []; - Assert::allIsInstanceOf($methodCallsToStaticCalls, MethodCallToStaticCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($methodCallsToStaticCalls, \Rector\Transform\ValueObject\MethodCallToStaticCall::class); $this->methodCallsToStaticCalls = $methodCallsToStaticCalls; } } diff --git a/rules/Transform/Rector/MethodCall/ReplaceParentCallByPropertyCallRector.php b/rules/Transform/Rector/MethodCall/ReplaceParentCallByPropertyCallRector.php index 50c0a9b1722..04a6813a1ea 100644 --- a/rules/Transform/Rector/MethodCall/ReplaceParentCallByPropertyCallRector.php +++ b/rules/Transform/Rector/MethodCall/ReplaceParentCallByPropertyCallRector.php @@ -1,7 +1,6 @@ [ - new ReplaceParentCallByPropertyCall('SomeTypeToReplace', 'someMethodCall', 'someProperty'), - ], - ] - ), - ] - ); +, [self::PARENT_CALLS_TO_PROPERTIES => [new \Rector\Transform\ValueObject\ReplaceParentCallByPropertyCall('SomeTypeToReplace', 'someMethodCall', 'someProperty')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->parentCallToProperties as $parentCallToProperty) { - if (! $this->isObjectType($node->var, $parentCallToProperty->getObjectType())) { + if (!$this->isObjectType($node->var, $parentCallToProperty->getObjectType())) { continue; } - - if (! $this->isName($node->name, $parentCallToProperty->getMethod())) { + if (!$this->isName($node->name, $parentCallToProperty->getMethod())) { continue; } - $node->var = $this->nodeFactory->createPropertyFetch('this', $parentCallToProperty->getProperty()); return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->parentCallToProperties = $configuration[self::PARENT_CALLS_TO_PROPERTIES] ?? []; } diff --git a/rules/Transform/Rector/MethodCall/ServiceGetterToConstructorInjectionRector.php b/rules/Transform/Rector/MethodCall/ServiceGetterToConstructorInjectionRector.php index bee88d8e111..1db24e732d6 100644 --- a/rules/Transform/Rector/MethodCall/ServiceGetterToConstructorInjectionRector.php +++ b/rules/Transform/Rector/MethodCall/ServiceGetterToConstructorInjectionRector.php @@ -1,7 +1,6 @@ propertyNaming = $propertyNaming; $this->classAnalyzer = $classAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Get service call to constructor injection', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Get service call to constructor injection', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' final class SomeClass { /** @@ -95,8 +86,7 @@ class FirstService } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { /** @@ -122,67 +112,49 @@ final class SomeClass } } CODE_SAMPLE - , - [ - self::METHOD_CALL_TO_SERVICES => [ - new ServiceGetterToConstructorInjection('FirstService', 'getAnotherService', 'AnotherService'), - ], - ] - ), - ]); +, [self::METHOD_CALL_TO_SERVICES => [new \Rector\Transform\ValueObject\ServiceGetterToConstructorInjection('FirstService', 'getAnotherService', 'AnotherService')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { return null; } - if ($this->classAnalyzer->isAnonymousClass($classLike)) { return null; } - foreach ($this->methodCallToServices as $methodCallToService) { - if (! $this->isObjectType($node->var, $methodCallToService->getOldObjectType())) { + if (!$this->isObjectType($node->var, $methodCallToService->getOldObjectType())) { continue; } - - if (! $this->isName($node->name, $methodCallToService->getOldMethod())) { + if (!$this->isName($node->name, $methodCallToService->getOldMethod())) { continue; } - - $serviceObjectType = new ObjectType($methodCallToService->getServiceType()); - + $serviceObjectType = new \PHPStan\Type\ObjectType($methodCallToService->getServiceType()); $propertyName = $this->propertyNaming->fqnToVariableName($serviceObjectType); - /** @var Class_ $classLike */ $this->addConstructorDependencyToClass($classLike, $serviceObjectType, $propertyName); - - return new PropertyFetch(new Variable('this'), new Identifier($propertyName)); + return new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), new \PhpParser\Node\Identifier($propertyName)); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $methodCallToServices = $configuration[self::METHOD_CALL_TO_SERVICES] ?? []; - Assert::allIsInstanceOf($methodCallToServices, ServiceGetterToConstructorInjection::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($methodCallToServices, \Rector\Transform\ValueObject\ServiceGetterToConstructorInjection::class); $this->methodCallToServices = $methodCallToServices; } } diff --git a/rules/Transform/Rector/MethodCall/VariableMethodCallToServiceCallRector.php b/rules/Transform/Rector/MethodCall/VariableMethodCallToServiceCallRector.php index 801558a178e..8e274d2c1c4 100644 --- a/rules/Transform/Rector/MethodCall/VariableMethodCallToServiceCallRector.php +++ b/rules/Transform/Rector/MethodCall/VariableMethodCallToServiceCallRector.php @@ -1,7 +1,6 @@ propertyNaming = $propertyNaming; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replace variable method call to a service one', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replace variable method call to a service one', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' use PhpParser\Node; class SomeClass @@ -59,8 +51,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory; use PhpParser\Node; @@ -76,95 +67,62 @@ class SomeClass } } CODE_SAMPLE - , - [ - self::VARIABLE_METHOD_CALLS_TO_SERVICE_CALLS => [ - new VariableMethodCallToServiceCall( - 'PhpParser\Node', - 'getAttribute', - 'php_doc_info', - 'Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory', - 'createFromNodeOrEmpty' - ), - ], - ] - ), - ]); +, [self::VARIABLE_METHOD_CALLS_TO_SERVICE_CALLS => [new \Rector\Transform\ValueObject\VariableMethodCallToServiceCall('PhpParser\\Node', 'getAttribute', 'php_doc_info', 'Rector\\BetterPhpDocParser\\PhpDocInfo\\PhpDocInfoFactory', 'createFromNodeOrEmpty')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class]; } - /** * @param MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->variableMethodCallsToServiceCalls as $variableMethodCallToServiceCall) { - if (! $node->var instanceof Variable) { + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { continue; } - - if (! $this->isObjectType($node->var, $variableMethodCallToServiceCall->getVariableObjectType())) { + if (!$this->isObjectType($node->var, $variableMethodCallToServiceCall->getVariableObjectType())) { continue; } - - if (! $this->isName($node->name, $variableMethodCallToServiceCall->getMethodName())) { + if (!$this->isName($node->name, $variableMethodCallToServiceCall->getMethodName())) { continue; } - $firstArgValue = $node->args[0]->value; - if (! $this->valueResolver->isValue( - $firstArgValue, - $variableMethodCallToServiceCall->getArgumentValue() - )) { + if (!$this->valueResolver->isValue($firstArgValue, $variableMethodCallToServiceCall->getArgumentValue())) { continue; } - - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { continue; } - - $serviceObjectType = new ObjectType($variableMethodCallToServiceCall->getServiceType()); - + $serviceObjectType = new \PHPStan\Type\ObjectType($variableMethodCallToServiceCall->getServiceType()); $this->addConstructorDependency($serviceObjectType, $classLike); - return $this->createServiceMethodCall( - $serviceObjectType, - $variableMethodCallToServiceCall->getServiceMethodName(), - $node - ); + return $this->createServiceMethodCall($serviceObjectType, $variableMethodCallToServiceCall->getServiceMethodName(), $node); } - return null; } - /** * @param mixed[] $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->variableMethodCallsToServiceCalls = $configuration[self::VARIABLE_METHOD_CALLS_TO_SERVICE_CALLS] ?? []; } - - private function addConstructorDependency(ObjectType $objectType, Class_ $class): void + private function addConstructorDependency(\PHPStan\Type\ObjectType $objectType, \PhpParser\Node\Stmt\Class_ $class) : void { $propertyName = $this->propertyNaming->fqnToVariableName($objectType); $this->addConstructorDependencyToClass($class, $objectType, $propertyName); } - - private function createServiceMethodCall(ObjectType $objectType, string $methodName, MethodCall $node): MethodCall + private function createServiceMethodCall(\PHPStan\Type\ObjectType $objectType, string $methodName, \PhpParser\Node\Expr\MethodCall $node) : \PhpParser\Node\Expr\MethodCall { $propertyName = $this->propertyNaming->fqnToVariableName($objectType); - $propertyFetch = new PropertyFetch(new Variable('this'), $propertyName); - $methodCall = new MethodCall($propertyFetch, $methodName); - $methodCall->args[] = new Arg($node->var); - + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $propertyName); + $methodCall = new \PhpParser\Node\Expr\MethodCall($propertyFetch, $methodName); + $methodCall->args[] = new \PhpParser\Node\Arg($node->var); return $methodCall; } } diff --git a/rules/Transform/Rector/New_/NewArgToMethodCallRector.php b/rules/Transform/Rector/New_/NewArgToMethodCallRector.php index 185ed074da1..1828764e3a7 100644 --- a/rules/Transform/Rector/New_/NewArgToMethodCallRector.php +++ b/rules/Transform/Rector/New_/NewArgToMethodCallRector.php @@ -1,7 +1,6 @@ [new NewArgToMethodCall('Dotenv', true, 'usePutenv')], - ] - ), - ]); +, [self::NEW_ARGS_TO_METHOD_CALLS => [new \Rector\Transform\ValueObject\NewArgToMethodCall('Dotenv', \true, 'usePutenv')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [New_::class]; + return [\PhpParser\Node\Expr\New_::class]; } - /** * @param New_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->newArgsToMethodCalls as $newArgToMethodCall) { - if (! $this->isObjectType($node->class, $newArgToMethodCall->getObjectType())) { + if (!$this->isObjectType($node->class, $newArgToMethodCall->getObjectType())) { continue; } - - if (! isset($node->args[0])) { + if (!isset($node->args[0])) { return null; } - $firstArgValue = $node->args[0]->value; - if (! $this->valueResolver->isValue($firstArgValue, $newArgToMethodCall->getValue())) { + if (!$this->valueResolver->isValue($firstArgValue, $newArgToMethodCall->getValue())) { continue; } - unset($node->args[0]); - - return new MethodCall($node, 'usePutenv'); + return new \PhpParser\Node\Expr\MethodCall($node, 'usePutenv'); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $newArgsToMethodCalls = $configuration[self::NEW_ARGS_TO_METHOD_CALLS] ?? []; - Assert::allIsInstanceOf($newArgsToMethodCalls, NewArgToMethodCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($newArgsToMethodCalls, \Rector\Transform\ValueObject\NewArgToMethodCall::class); $this->newArgsToMethodCalls = $newArgsToMethodCalls; } } diff --git a/rules/Transform/Rector/New_/NewToConstructorInjectionRector.php b/rules/Transform/Rector/New_/NewToConstructorInjectionRector.php index d12560bc356..fa29b71c7f3 100644 --- a/rules/Transform/Rector/New_/NewToConstructorInjectionRector.php +++ b/rules/Transform/Rector/New_/NewToConstructorInjectionRector.php @@ -1,7 +1,6 @@ propertyFetchFactory = $propertyFetchFactory; $this->propertyNaming = $propertyNaming; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change defined new type to constructor injection', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change defined new type to constructor injection', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() @@ -65,8 +56,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -85,112 +75,85 @@ class SomeClass } } CODE_SAMPLE - , - [ - self::TYPES_TO_CONSTRUCTOR_INJECTION => ['Validator'], - ] - ), - ]); +, [self::TYPES_TO_CONSTRUCTOR_INJECTION => ['Validator']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [New_::class, Assign::class, MethodCall::class]; + return [\PhpParser\Node\Expr\New_::class, \PhpParser\Node\Expr\Assign::class, \PhpParser\Node\Expr\MethodCall::class]; } - /** * @param New_|Assign|MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { return $this->refactorMethodCall($node); } - - if ($node instanceof Assign) { + if ($node instanceof \PhpParser\Node\Expr\Assign) { $this->refactorAssign($node); } - - if ($node instanceof New_) { + if ($node instanceof \PhpParser\Node\Expr\New_) { $this->refactorNew($node); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $typesToConstructorInjections = $configuration[self::TYPES_TO_CONSTRUCTOR_INJECTION] ?? []; foreach ($typesToConstructorInjections as $typeToConstructorInjection) { - $this->constructorInjectionObjectTypes[] = new ObjectType($typeToConstructorInjection); + $this->constructorInjectionObjectTypes[] = new \PHPStan\Type\ObjectType($typeToConstructorInjection); } } - - private function refactorMethodCall(MethodCall $methodCall): ?MethodCall + private function refactorMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node\Expr\MethodCall { foreach ($this->constructorInjectionObjectTypes as $constructorInjectionObjectType) { - if (! $methodCall->var instanceof Variable) { + if (!$methodCall->var instanceof \PhpParser\Node\Expr\Variable) { continue; } - - if (! $this->isObjectType($methodCall->var, $constructorInjectionObjectType)) { + if (!$this->isObjectType($methodCall->var, $constructorInjectionObjectType)) { continue; } - - if (! $this->nodeTypeResolver->isObjectType($methodCall->var, $constructorInjectionObjectType)) { + if (!$this->nodeTypeResolver->isObjectType($methodCall->var, $constructorInjectionObjectType)) { continue; } - $methodCall->var = $this->propertyFetchFactory->createFromType($constructorInjectionObjectType); return $methodCall; } - return null; } - - private function refactorAssign(Assign $assign): void + private function refactorAssign(\PhpParser\Node\Expr\Assign $assign) : void { - if (! $assign->expr instanceof New_) { + if (!$assign->expr instanceof \PhpParser\Node\Expr\New_) { return; } - foreach ($this->constructorInjectionObjectTypes as $constructorInjectionObjectType) { - if (! $this->isObjectType($assign->expr, $constructorInjectionObjectType)) { + if (!$this->isObjectType($assign->expr, $constructorInjectionObjectType)) { continue; } - $this->removeNode($assign); } } - - private function refactorNew(New_ $new): void + private function refactorNew(\PhpParser\Node\Expr\New_ $new) : void { foreach ($this->constructorInjectionObjectTypes as $constructorInjectionObjectType) { - if (! $this->isObjectType($new->class, $constructorInjectionObjectType)) { + if (!$this->isObjectType($new->class, $constructorInjectionObjectType)) { continue; } - - $classLike = $new->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $new->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { continue; } - $expectedPropertyName = $this->propertyNaming->getExpectedNameFromType($constructorInjectionObjectType); - if (! $expectedPropertyName instanceof ExpectedName) { + if (!$expectedPropertyName instanceof \Rector\Naming\ValueObject\ExpectedName) { continue; } - - $this->addConstructorDependencyToClass( - $classLike, - $constructorInjectionObjectType, - $expectedPropertyName->getName() - ); + $this->addConstructorDependencyToClass($classLike, $constructorInjectionObjectType, $expectedPropertyName->getName()); } } } diff --git a/rules/Transform/Rector/New_/NewToMethodCallRector.php b/rules/Transform/Rector/New_/NewToMethodCallRector.php index 72f90a4c834..50dda4f9c30 100644 --- a/rules/Transform/Rector/New_/NewToMethodCallRector.php +++ b/rules/Transform/Rector/New_/NewToMethodCallRector.php @@ -1,7 +1,6 @@ classNaming = $classNaming; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Replaces creating object instances with "new" keyword with factory method.', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces creating object instances with "new" keyword with factory method.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function example() { @@ -57,8 +49,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -71,86 +62,60 @@ class SomeClass } } CODE_SAMPLE - , - [ - self::NEWS_TO_METHOD_CALLS => [new NewToMethodCall('MyClass', 'MyClassFactory', 'create')], - ] - ), - ]); +, [self::NEWS_TO_METHOD_CALLS => [new \Rector\Transform\ValueObject\NewToMethodCall('MyClass', 'MyClassFactory', 'create')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [New_::class]; + return [\PhpParser\Node\Expr\New_::class]; } - /** * @param New_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->newsToMethodCalls as $newsToMethodCall) { - if (! $this->isObjectType($node, $newsToMethodCall->getNewObjectType())) { + if (!$this->isObjectType($node, $newsToMethodCall->getNewObjectType())) { continue; } - $serviceObjectType = $newsToMethodCall->getServiceObjectType(); - $className = $node->getAttribute(AttributeKey::CLASS_NAME); + $className = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); if ($className === $serviceObjectType->getClassName()) { continue; } - /** @var Class_ $classNode */ - $classNode = $node->getAttribute(AttributeKey::CLASS_NODE); - - $propertyName = $this->getExistingFactoryPropertyName( - $classNode, - $newsToMethodCall->getServiceObjectType() - ); - + $classNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + $propertyName = $this->getExistingFactoryPropertyName($classNode, $newsToMethodCall->getServiceObjectType()); if ($propertyName === null) { $serviceObjectType = $newsToMethodCall->getServiceObjectType(); $propertyName = $this->classNaming->getShortName($serviceObjectType->getClassName()); - $propertyName = lcfirst($propertyName); - - $this->addConstructorDependencyToClass( - $classNode, - $newsToMethodCall->getServiceObjectType(), - $propertyName - ); + $propertyName = \lcfirst($propertyName); + $this->addConstructorDependencyToClass($classNode, $newsToMethodCall->getServiceObjectType(), $propertyName); } - - $propertyFetch = new PropertyFetch(new Variable('this'), $propertyName); - - return new MethodCall($propertyFetch, $newsToMethodCall->getServiceMethod(), $node->args); + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable('this'), $propertyName); + return new \PhpParser\Node\Expr\MethodCall($propertyFetch, $newsToMethodCall->getServiceMethod(), $node->args); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $newsToMethodCalls = $configuration[self::NEWS_TO_METHOD_CALLS] ?? []; - Assert::allIsInstanceOf($newsToMethodCalls, NewToMethodCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($newsToMethodCalls, \Rector\Transform\ValueObject\NewToMethodCall::class); $this->newsToMethodCalls = $newsToMethodCalls; } - - private function getExistingFactoryPropertyName(Class_ $class, ObjectType $factoryObjectType): ?string + private function getExistingFactoryPropertyName(\PhpParser\Node\Stmt\Class_ $class, \PHPStan\Type\ObjectType $factoryObjectType) : ?string { foreach ($class->getProperties() as $property) { - if (! $this->isObjectType($property, $factoryObjectType)) { + if (!$this->isObjectType($property, $factoryObjectType)) { continue; } - return $this->getName($property); } - return null; } } diff --git a/rules/Transform/Rector/New_/NewToStaticCallRector.php b/rules/Transform/Rector/New_/NewToStaticCallRector.php index 246a6e51567..d5a69d201f1 100644 --- a/rules/Transform/Rector/New_/NewToStaticCallRector.php +++ b/rules/Transform/Rector/New_/NewToStaticCallRector.php @@ -1,7 +1,6 @@ [new NewToStaticCall('Cookie', 'Cookie', 'create')], - ] - ), - ]); +, [self::TYPE_TO_STATIC_CALLS => [new \Rector\Transform\ValueObject\NewToStaticCall('Cookie', 'Cookie', 'create')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [New_::class]; + return [\PhpParser\Node\Expr\New_::class]; } - /** * @param New_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->typeToStaticCalls as $typeToStaticCall) { - if (! $this->isObjectType($node->class, $typeToStaticCall->getObjectType())) { + if (!$this->isObjectType($node->class, $typeToStaticCall->getObjectType())) { continue; } - - return $this->nodeFactory->createStaticCall( - $typeToStaticCall->getStaticCallClass(), - $typeToStaticCall->getStaticCallMethod(), - $node->args - ); + return $this->nodeFactory->createStaticCall($typeToStaticCall->getStaticCallClass(), $typeToStaticCall->getStaticCallMethod(), $node->args); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $typeToStaticCalls = $configuration[self::TYPE_TO_STATIC_CALLS] ?? []; - Assert::allIsInstanceOf($typeToStaticCalls, NewToStaticCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($typeToStaticCalls, \Rector\Transform\ValueObject\NewToStaticCall::class); $this->typeToStaticCalls = $typeToStaticCalls; } } diff --git a/rules/Transform/Rector/StaticCall/StaticCallToFuncCallRector.php b/rules/Transform/Rector/StaticCall/StaticCallToFuncCallRector.php index 55d36a5b09e..c7ccc0d7e94 100644 --- a/rules/Transform/Rector/StaticCall/StaticCallToFuncCallRector.php +++ b/rules/Transform/Rector/StaticCall/StaticCallToFuncCallRector.php @@ -1,7 +1,6 @@ staticCallsToFunctions = $staticCallToFunctions; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turns static call to function call.', [ - new ConfiguredCodeSample( - 'OldClass::oldMethod("args");', - 'new_function("args");', - [ - self::STATIC_CALLS_TO_FUNCTIONS => [ - new StaticCallToFuncCall('OldClass', 'oldMethod', 'new_function'), - ], - ] - ), - ]); + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns static call to function call.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample('OldClass::oldMethod("args");', 'new_function("args");', [self::STATIC_CALLS_TO_FUNCTIONS => [new \Rector\Transform\ValueObject\StaticCallToFuncCall('OldClass', 'oldMethod', 'new_function')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->staticCallsToFunctions as $staticCallToFunction) { - if (! $this->isObjectType($node->class, $staticCallToFunction->getObjectType())) { + if (!$this->isObjectType($node->class, $staticCallToFunction->getObjectType())) { continue; } - - if (! $this->isName($node->name, $staticCallToFunction->getMethod())) { + if (!$this->isName($node->name, $staticCallToFunction->getMethod())) { continue; } - - return new FuncCall(new FullyQualified($staticCallToFunction->getFunction()), $node->args); + return new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name\FullyQualified($staticCallToFunction->getFunction()), $node->args); } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $staticCallsToFunctions = $configuration[self::STATIC_CALLS_TO_FUNCTIONS] ?? []; - Assert::allIsInstanceOf($staticCallsToFunctions, StaticCallToFuncCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($staticCallsToFunctions, \Rector\Transform\ValueObject\StaticCallToFuncCall::class); $this->staticCallsToFunctions = $staticCallsToFunctions; } } diff --git a/rules/Transform/Rector/StaticCall/StaticCallToMethodCallRector.php b/rules/Transform/Rector/StaticCall/StaticCallToMethodCallRector.php index 5f8419d3012..79077e7990f 100644 --- a/rules/Transform/Rector/StaticCall/StaticCallToMethodCallRector.php +++ b/rules/Transform/Rector/StaticCall/StaticCallToMethodCallRector.php @@ -1,7 +1,6 @@ funcCallStaticCallToMethodCallAnalyzer = $funcCallStaticCallToMethodCallAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change static call to service method via constructor injection', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change static call to service method via constructor injection', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' use Nette\Utils\FileSystem; class SomeClass @@ -62,8 +54,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' use Symplify\SmartFileSystem\SmartFileSystem; class SomeClass @@ -84,90 +75,60 @@ class SomeClass } } CODE_SAMPLE - , - [ - self::STATIC_CALLS_TO_METHOD_CALLS => [ - new StaticCallToMethodCall( - 'Nette\Utils\FileSystem', - 'write', - 'Symplify\SmartFileSystem\SmartFileSystem', - 'dumpFile' - ), - ], - ] - ), - ]); +, [self::STATIC_CALLS_TO_METHOD_CALLS => [new \Rector\Transform\ValueObject\StaticCallToMethodCall('Nette\\Utils\\FileSystem', 'write', 'Symplify\\SmartFileSystem\\SmartFileSystem', 'dumpFile')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - - $classMethod = $node->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { + $classMethod = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - foreach ($this->staticCallsToMethodCalls as $staticCallToMethodCall) { - if (! $staticCallToMethodCall->isStaticCallMatch($node)) { + if (!$staticCallToMethodCall->isStaticCallMatch($node)) { continue; } - if ($classMethod->isStatic()) { return $this->refactorToInstanceCall($node, $staticCallToMethodCall); } - - $expr = $this->funcCallStaticCallToMethodCallAnalyzer->matchTypeProvidingExpr( - $classLike, - $classMethod, - $staticCallToMethodCall->getClassObjectType() - ); - + $expr = $this->funcCallStaticCallToMethodCallAnalyzer->matchTypeProvidingExpr($classLike, $classMethod, $staticCallToMethodCall->getClassObjectType()); if ($staticCallToMethodCall->getMethodName() === '*') { $methodName = $this->getName($node->name); } else { $methodName = $staticCallToMethodCall->getMethodName(); } - - if (! is_string($methodName)) { - throw new ShouldNotHappenException(); + if (!\is_string($methodName)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - return new MethodCall($expr, $methodName, $node->args); + return new \PhpParser\Node\Expr\MethodCall($expr, $methodName, $node->args); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $staticCallsToMethodCalls = $configuration[self::STATIC_CALLS_TO_METHOD_CALLS] ?? []; - Assert::allIsInstanceOf($staticCallsToMethodCalls, StaticCallToMethodCall::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($staticCallsToMethodCalls, \Rector\Transform\ValueObject\StaticCallToMethodCall::class); $this->staticCallsToMethodCalls = $staticCallsToMethodCalls; } - - private function refactorToInstanceCall( - StaticCall $staticCall, - StaticCallToMethodCall $staticCallToMethodCall - ): MethodCall { - $new = new New_(new FullyQualified($staticCallToMethodCall->getClassType())); - return new MethodCall($new, $staticCallToMethodCall->getMethodName(), $staticCall->args); + private function refactorToInstanceCall(\PhpParser\Node\Expr\StaticCall $staticCall, \Rector\Transform\ValueObject\StaticCallToMethodCall $staticCallToMethodCall) : \PhpParser\Node\Expr\MethodCall + { + $new = new \PhpParser\Node\Expr\New_(new \PhpParser\Node\Name\FullyQualified($staticCallToMethodCall->getClassType())); + return new \PhpParser\Node\Expr\MethodCall($new, $staticCallToMethodCall->getMethodName(), $staticCall->args); } } diff --git a/rules/Transform/Rector/StaticCall/StaticCallToNewRector.php b/rules/Transform/Rector/StaticCall/StaticCallToNewRector.php index 6155f3882c0..f2c0e49f6c6 100644 --- a/rules/Transform/Rector/StaticCall/StaticCallToNewRector.php +++ b/rules/Transform/Rector/StaticCall/StaticCallToNewRector.php @@ -1,7 +1,6 @@ [new StaticCallToNew('JsonResponse', 'create')], - ] - ), - ]); +, [self::STATIC_CALLS_TO_NEWS => [new \Rector\Transform\ValueObject\StaticCallToNew('JsonResponse', 'create')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [StaticCall::class]; + return [\PhpParser\Node\Expr\StaticCall::class]; } - /** * @param Node\Expr\StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->staticCallsToNews as $staticCallToNews) { - if (! $this->isName($node->class, $staticCallToNews->getClass())) { + if (!$this->isName($node->class, $staticCallToNews->getClass())) { continue; } - - if (! $this->isName($node->name, $staticCallToNews->getMethod())) { + if (!$this->isName($node->name, $staticCallToNews->getMethod())) { continue; } - $class = $this->getName($node->class); if ($class === null) { continue; } - - return new New_(new FullyQualified($class)); + return new \PhpParser\Node\Expr\New_(new \PhpParser\Node\Name\FullyQualified($class)); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $staticCallsToNews = $configuration[self::STATIC_CALLS_TO_NEWS] ?? []; $this->staticCallsToNews = $staticCallsToNews; diff --git a/rules/Transform/Rector/String_/StringToClassConstantRector.php b/rules/Transform/Rector/String_/StringToClassConstantRector.php index d911353ad50..aff2ba9a8e1 100644 --- a/rules/Transform/Rector/String_/StringToClassConstantRector.php +++ b/rules/Transform/Rector/String_/StringToClassConstantRector.php @@ -1,7 +1,6 @@ [ - new StringToClassConstant('compiler.post_dump', 'Yet\AnotherClass', 'CONSTANT'), - ], - ] - ), - ]); +, [self::STRINGS_TO_CLASS_CONSTANTS => [new \Rector\Transform\ValueObject\StringToClassConstant('compiler.post_dump', 'Yet\\AnotherClass', 'CONSTANT')]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [String_::class]; + return [\PhpParser\Node\Scalar\String_::class]; } - /** * @param String_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->stringsToClassConstants as $stringToClassConstant) { - if (! $this->valueResolver->isValue($node, $stringToClassConstant->getString())) { + if (!$this->valueResolver->isValue($node, $stringToClassConstant->getString())) { continue; } - - return $this->nodeFactory->createClassConstFetch( - $stringToClassConstant->getClass(), - $stringToClassConstant->getConstant() - ); + return $this->nodeFactory->createClassConstFetch($stringToClassConstant->getClass(), $stringToClassConstant->getConstant()); } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $stringToClassConstants = $configuration[self::STRINGS_TO_CLASS_CONSTANTS] ?? []; - Assert::allIsInstanceOf($stringToClassConstants, StringToClassConstant::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($stringToClassConstants, \Rector\Transform\ValueObject\StringToClassConstant::class); $this->stringsToClassConstants = $stringToClassConstants; } } diff --git a/rules/Transform/Rector/String_/ToStringToMethodCallRector.php b/rules/Transform/Rector/String_/ToStringToMethodCallRector.php index 28869a50e70..e8c77e818b7 100644 --- a/rules/Transform/Rector/String_/ToStringToMethodCallRector.php +++ b/rules/Transform/Rector/String_/ToStringToMethodCallRector.php @@ -1,7 +1,6 @@ */ private $methodNamesByType = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Turns defined code uses of "__toString()" method to specific method calls.', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Turns defined code uses of "__toString()" method to specific method calls.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' $someValue = new SomeObject; $result = (string) $someValue; $result = $someValue->__toString(); CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' $someValue = new SomeObject; $result = $someValue->getPath(); $result = $someValue->getPath(); CODE_SAMPLE - , - [ - self::METHOD_NAMES_BY_TYPE => [ - 'SomeObject' => 'getPath', - ], - ] - ), - ]); +, [self::METHOD_NAMES_BY_TYPE => ['SomeObject' => 'getPath']])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [String_::class, MethodCall::class]; + return [\PhpParser\Node\Expr\Cast\String_::class, \PhpParser\Node\Expr\MethodCall::class]; } - /** * @param String_|MethodCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if ($node instanceof String_) { + if ($node instanceof \PhpParser\Node\Expr\Cast\String_) { return $this->processStringNode($node); } - return $this->processMethodCall($node); } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->methodNamesByType = $configuration[self::METHOD_NAMES_BY_TYPE] ?? []; } - - private function processStringNode(String_ $string): ?Node + private function processStringNode(\PhpParser\Node\Expr\Cast\String_ $string) : ?\PhpParser\Node { foreach ($this->methodNamesByType as $type => $methodName) { - if (! $this->isObjectType($string->expr, new ObjectType($type))) { + if (!$this->isObjectType($string->expr, new \PHPStan\Type\ObjectType($type))) { continue; } - return $this->nodeFactory->createMethodCall($string->expr, $methodName); } - return null; } - - private function processMethodCall(MethodCall $methodCall): ?Node + private function processMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node { foreach ($this->methodNamesByType as $type => $methodName) { - if (! $this->isObjectType($methodCall->var, new ObjectType($type))) { + if (!$this->isObjectType($methodCall->var, new \PHPStan\Type\ObjectType($type))) { continue; } - - if (! $this->isName($methodCall->name, '__toString')) { + if (!$this->isName($methodCall->name, '__toString')) { continue; } - - $methodCall->name = new Identifier($methodName); - + $methodCall->name = new \PhpParser\Node\Identifier($methodName); return $methodCall; } - return null; } } diff --git a/rules/Transform/ValueObject/ArgumentFuncCallToMethodCall.php b/rules/Transform/ValueObject/ArgumentFuncCallToMethodCall.php index 64479a53432..948357e9567 100644 --- a/rules/Transform/ValueObject/ArgumentFuncCallToMethodCall.php +++ b/rules/Transform/ValueObject/ArgumentFuncCallToMethodCall.php @@ -1,7 +1,6 @@ function = $function; $this->class = $class; $this->methodIfArgs = $methodIfArgs; $this->methodIfNoArgs = $methodIfNoArgs; } - - public function getFunction(): string + public function getFunction() : string { return $this->function; } - - public function getClass(): string + public function getClass() : string { return $this->class; } - - public function getMethodIfNoArgs(): ?string + public function getMethodIfNoArgs() : ?string { return $this->methodIfNoArgs; } - - public function getMethodIfArgs(): ?string + public function getMethodIfArgs() : ?string { return $this->methodIfArgs; } diff --git a/rules/Transform/ValueObject/ArrayFuncCallToMethodCall.php b/rules/Transform/ValueObject/ArrayFuncCallToMethodCall.php index dbcd60ce9aa..0f823c2facc 100644 --- a/rules/Transform/ValueObject/ArrayFuncCallToMethodCall.php +++ b/rules/Transform/ValueObject/ArrayFuncCallToMethodCall.php @@ -1,7 +1,6 @@ function = $function; @@ -33,23 +28,19 @@ final class ArrayFuncCallToMethodCall $this->arrayMethod = $arrayMethod; $this->nonArrayMethod = $nonArrayMethod; } - - public function getFunction(): string + public function getFunction() : string { return $this->function; } - - public function getClass(): string + public function getClass() : string { return $this->class; } - - public function getArrayMethod(): string + public function getArrayMethod() : string { return $this->arrayMethod; } - - public function getNonArrayMethod(): string + public function getNonArrayMethod() : string { return $this->nonArrayMethod; } diff --git a/rules/Transform/ValueObject/CallableInMethodCallToVariable.php b/rules/Transform/ValueObject/CallableInMethodCallToVariable.php index 7f3eed1189d..47fa9e10206 100644 --- a/rules/Transform/ValueObject/CallableInMethodCallToVariable.php +++ b/rules/Transform/ValueObject/CallableInMethodCallToVariable.php @@ -1,46 +1,38 @@ classType = $classType; $this->methodName = $methodName; $this->argumentPosition = $argumentPosition; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->classType); + return new \PHPStan\Type\ObjectType($this->classType); } - - public function getMethodName(): string + public function getMethodName() : string { return $this->methodName; } - - public function getArgumentPosition(): int + public function getArgumentPosition() : int { return $this->argumentPosition; } diff --git a/rules/Transform/ValueObject/ClassConstFetchToValue.php b/rules/Transform/ValueObject/ClassConstFetchToValue.php index 4cdde7db8c3..490fdbaa817 100644 --- a/rules/Transform/ValueObject/ClassConstFetchToValue.php +++ b/rules/Transform/ValueObject/ClassConstFetchToValue.php @@ -1,28 +1,23 @@ constant = $constant; $this->value = $value; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getConstant(): string + public function getConstant() : string { return $this->constant; } - /** * @return mixed */ diff --git a/rules/Transform/ValueObject/DimFetchAssignToMethodCall.php b/rules/Transform/ValueObject/DimFetchAssignToMethodCall.php index 52668427eef..3fe57865605 100644 --- a/rules/Transform/ValueObject/DimFetchAssignToMethodCall.php +++ b/rules/Transform/ValueObject/DimFetchAssignToMethodCall.php @@ -1,46 +1,38 @@ listClass = $listClass; $this->itemClass = $itemClass; $this->addMethod = $addMethod; } - - public function getListObjectType(): ObjectType + public function getListObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->listClass); + return new \PHPStan\Type\ObjectType($this->listClass); } - - public function getItemObjectType(): ObjectType + public function getItemObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->itemClass); + return new \PHPStan\Type\ObjectType($this->itemClass); } - - public function getAddMethod(): string + public function getAddMethod() : string { return $this->addMethod; } diff --git a/rules/Transform/ValueObject/FuncCallToMethodCall.php b/rules/Transform/ValueObject/FuncCallToMethodCall.php index 2378cc13c09..34fae9c68af 100644 --- a/rules/Transform/ValueObject/FuncCallToMethodCall.php +++ b/rules/Transform/ValueObject/FuncCallToMethodCall.php @@ -1,46 +1,38 @@ oldFuncName = $oldFuncName; $this->newClassName = $newClassName; $this->newMethodName = $newMethodName; } - - public function getOldFuncName(): string + public function getOldFuncName() : string { return $this->oldFuncName; } - - public function getNewObjectType(): ObjectType + public function getNewObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->newClassName); + return new \PHPStan\Type\ObjectType($this->newClassName); } - - public function getNewMethodName(): string + public function getNewMethodName() : string { return $this->newMethodName; } diff --git a/rules/Transform/ValueObject/FuncCallToStaticCall.php b/rules/Transform/ValueObject/FuncCallToStaticCall.php index 10add504273..86d3cd17aac 100644 --- a/rules/Transform/ValueObject/FuncCallToStaticCall.php +++ b/rules/Transform/ValueObject/FuncCallToStaticCall.php @@ -1,7 +1,6 @@ oldFuncName = $oldFuncName; $this->newClassName = $newClassName; $this->newMethodName = $newMethodName; } - - public function getOldFuncName(): string + public function getOldFuncName() : string { return $this->oldFuncName; } - - public function getNewClassName(): string + public function getNewClassName() : string { return $this->newClassName; } - - public function getNewMethodName(): string + public function getNewMethodName() : string { return $this->newMethodName; } diff --git a/rules/Transform/ValueObject/FunctionToStaticCall.php b/rules/Transform/ValueObject/FunctionToStaticCall.php index aa07ce06d8a..f103a35530f 100644 --- a/rules/Transform/ValueObject/FunctionToStaticCall.php +++ b/rules/Transform/ValueObject/FunctionToStaticCall.php @@ -1,7 +1,6 @@ class = $class; $this->method = $method; $this->function = $function; } - - public function getClass(): string + public function getClass() : string { return $this->class; } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } - - public function getFunction(): string + public function getFunction() : string { return $this->function; } diff --git a/rules/Transform/ValueObject/GetAndSetToMethodCall.php b/rules/Transform/ValueObject/GetAndSetToMethodCall.php index 575c6090637..dce875b261d 100644 --- a/rules/Transform/ValueObject/GetAndSetToMethodCall.php +++ b/rules/Transform/ValueObject/GetAndSetToMethodCall.php @@ -1,28 +1,23 @@ getMethod = $getMethod; $this->setMethod = $setMethod; } - - public function getGetMethod(): string + public function getGetMethod() : string { return $this->getMethod; } - - public function getSetMethod(): string + public function getSetMethod() : string { return $this->setMethod; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->classType); + return new \PHPStan\Type\ObjectType($this->classType); } } diff --git a/rules/Transform/ValueObject/MethodCallToAnotherMethodCallWithArguments.php b/rules/Transform/ValueObject/MethodCallToAnotherMethodCallWithArguments.php index 5f02d4d3f00..230061406ee 100644 --- a/rules/Transform/ValueObject/MethodCallToAnotherMethodCallWithArguments.php +++ b/rules/Transform/ValueObject/MethodCallToAnotherMethodCallWithArguments.php @@ -1,33 +1,27 @@ newMethod = $newMethod; $this->newArguments = $newArguments; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->type); + return new \PHPStan\Type\ObjectType($this->type); } - - public function getOldMethod(): string + public function getOldMethod() : string { return $this->oldMethod; } - - public function getNewMethod(): string + public function getNewMethod() : string { return $this->newMethod; } - /** * @return mixed[] */ - public function getNewArguments(): array + public function getNewArguments() : array { return $this->newArguments; } diff --git a/rules/Transform/ValueObject/MethodCallToReturn.php b/rules/Transform/ValueObject/MethodCallToReturn.php index 0808de78cd9..9179920c2f9 100644 --- a/rules/Transform/ValueObject/MethodCallToReturn.php +++ b/rules/Transform/ValueObject/MethodCallToReturn.php @@ -1,35 +1,29 @@ class = $class; $this->method = $method; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } diff --git a/rules/Transform/ValueObject/MethodCallToStaticCall.php b/rules/Transform/ValueObject/MethodCallToStaticCall.php index fe8f869e414..7e6438df34c 100644 --- a/rules/Transform/ValueObject/MethodCallToStaticCall.php +++ b/rules/Transform/ValueObject/MethodCallToStaticCall.php @@ -1,33 +1,27 @@ oldClass = $oldClass; @@ -35,23 +29,19 @@ final class MethodCallToStaticCall $this->newClass = $newClass; $this->newMethod = $newMethod; } - - public function getOldObjectType(): ObjectType + public function getOldObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->oldClass); + return new \PHPStan\Type\ObjectType($this->oldClass); } - - public function getOldMethod(): string + public function getOldMethod() : string { return $this->oldMethod; } - - public function getNewClass(): string + public function getNewClass() : string { return $this->newClass; } - - public function getNewMethod(): string + public function getNewMethod() : string { return $this->newMethod; } diff --git a/rules/Transform/ValueObject/NewArgToMethodCall.php b/rules/Transform/ValueObject/NewArgToMethodCall.php index f81cdbb2115..864a51b6b14 100644 --- a/rules/Transform/ValueObject/NewArgToMethodCall.php +++ b/rules/Transform/ValueObject/NewArgToMethodCall.php @@ -1,28 +1,23 @@ value = $value; $this->methodCall = $methodCall; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->type); + return new \PHPStan\Type\ObjectType($this->type); } - /** * @return mixed */ @@ -45,8 +38,7 @@ final class NewArgToMethodCall { return $this->value; } - - public function getMethodCall(): string + public function getMethodCall() : string { return $this->methodCall; } diff --git a/rules/Transform/ValueObject/NewToMethodCall.php b/rules/Transform/ValueObject/NewToMethodCall.php index bd2ccf9243d..9799747daff 100644 --- a/rules/Transform/ValueObject/NewToMethodCall.php +++ b/rules/Transform/ValueObject/NewToMethodCall.php @@ -1,46 +1,38 @@ newType = $newType; $this->serviceType = $serviceType; $this->serviceMethod = $serviceMethod; } - - public function getNewObjectType(): ObjectType + public function getNewObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->newType); + return new \PHPStan\Type\ObjectType($this->newType); } - - public function getServiceObjectType(): ObjectType + public function getServiceObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->serviceType); + return new \PHPStan\Type\ObjectType($this->serviceType); } - - public function getServiceMethod(): string + public function getServiceMethod() : string { return $this->serviceMethod; } diff --git a/rules/Transform/ValueObject/NewToStaticCall.php b/rules/Transform/ValueObject/NewToStaticCall.php index c5e10c08145..67bfe4f9398 100644 --- a/rules/Transform/ValueObject/NewToStaticCall.php +++ b/rules/Transform/ValueObject/NewToStaticCall.php @@ -1,46 +1,38 @@ type = $type; $this->staticCallClass = $staticCallClass; $this->staticCallMethod = $staticCallMethod; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->type); + return new \PHPStan\Type\ObjectType($this->type); } - - public function getStaticCallClass(): string + public function getStaticCallClass() : string { return $this->staticCallClass; } - - public function getStaticCallMethod(): string + public function getStaticCallMethod() : string { return $this->staticCallMethod; } diff --git a/rules/Transform/ValueObject/ParentClassToTraits.php b/rules/Transform/ValueObject/ParentClassToTraits.php index 4558871b537..b863e3e6310 100644 --- a/rules/Transform/ValueObject/ParentClassToTraits.php +++ b/rules/Transform/ValueObject/ParentClassToTraits.php @@ -1,23 +1,19 @@ parentType = $parentType; $this->traitNames = $traitNames; } - - public function getParentObjectType(): ObjectType + public function getParentObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->parentType); + return new \PHPStan\Type\ObjectType($this->parentType); } - /** * @return string[] */ - public function getTraitNames(): array + public function getTraitNames() : array { // keep the Trait order the way it is in config - return array_reverse($this->traitNames); + return \array_reverse($this->traitNames); } } diff --git a/rules/Transform/ValueObject/PropertyAndClassMethodName.php b/rules/Transform/ValueObject/PropertyAndClassMethodName.php index 30cac474eef..9b9360e38c7 100644 --- a/rules/Transform/ValueObject/PropertyAndClassMethodName.php +++ b/rules/Transform/ValueObject/PropertyAndClassMethodName.php @@ -1,7 +1,6 @@ propertyName = $propertyName; $this->classMethodName = $classMethodName; } - - public function getPropertyName(): string + public function getPropertyName() : string { return $this->propertyName; } - - public function getClassMethodName(): string + public function getClassMethodName() : string { return $this->classMethodName; } diff --git a/rules/Transform/ValueObject/PropertyAssignToMethodCall.php b/rules/Transform/ValueObject/PropertyAssignToMethodCall.php index dafd2706a3a..057d7cd7576 100644 --- a/rules/Transform/ValueObject/PropertyAssignToMethodCall.php +++ b/rules/Transform/ValueObject/PropertyAssignToMethodCall.php @@ -1,46 +1,38 @@ class = $class; $this->oldPropertyName = $oldPropertyName; $this->newMethodName = $newMethodName; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getOldPropertyName(): string + public function getOldPropertyName() : string { return $this->oldPropertyName; } - - public function getNewMethodName(): string + public function getNewMethodName() : string { return $this->newMethodName; } diff --git a/rules/Transform/ValueObject/PropertyFetchToMethodCall.php b/rules/Transform/ValueObject/PropertyFetchToMethodCall.php index 3929ac135be..a2e793cded9 100644 --- a/rules/Transform/ValueObject/PropertyFetchToMethodCall.php +++ b/rules/Transform/ValueObject/PropertyFetchToMethodCall.php @@ -1,79 +1,62 @@ oldType = $oldType; $this->oldProperty = $oldProperty; $this->newGetMethod = $newGetMethod; $this->newSetMethod = $newSetMethod; $this->newGetArguments = $newGetArguments; } - - public function getOldObjectType(): ObjectType + public function getOldObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->oldType); + return new \PHPStan\Type\ObjectType($this->oldType); } - - public function getOldProperty(): string + public function getOldProperty() : string { return $this->oldProperty; } - - public function getNewGetMethod(): string + public function getNewGetMethod() : string { return $this->newGetMethod; } - - public function getNewSetMethod(): ?string + public function getNewSetMethod() : ?string { return $this->newSetMethod; } - /** * @return mixed[] */ - public function getNewGetArguments(): array + public function getNewGetArguments() : array { return $this->newGetArguments; } diff --git a/rules/Transform/ValueObject/ReplaceParentCallByPropertyCall.php b/rules/Transform/ValueObject/ReplaceParentCallByPropertyCall.php index 71796f88cf0..a1c3609f9e4 100644 --- a/rules/Transform/ValueObject/ReplaceParentCallByPropertyCall.php +++ b/rules/Transform/ValueObject/ReplaceParentCallByPropertyCall.php @@ -1,46 +1,38 @@ class = $class; $this->method = $method; $this->property = $property; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } - - public function getProperty(): string + public function getProperty() : string { return $this->property; } diff --git a/rules/Transform/ValueObject/ServiceGetterToConstructorInjection.php b/rules/Transform/ValueObject/ServiceGetterToConstructorInjection.php index bd43aad802b..2782d9aca7d 100644 --- a/rules/Transform/ValueObject/ServiceGetterToConstructorInjection.php +++ b/rules/Transform/ValueObject/ServiceGetterToConstructorInjection.php @@ -1,46 +1,38 @@ oldType = $oldType; $this->oldMethod = $oldMethod; $this->serviceType = $serviceType; } - - public function getOldObjectType(): ObjectType + public function getOldObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->oldType); + return new \PHPStan\Type\ObjectType($this->oldType); } - - public function getOldMethod(): string + public function getOldMethod() : string { return $this->oldMethod; } - - public function getServiceType(): string + public function getServiceType() : string { return $this->serviceType; } diff --git a/rules/Transform/ValueObject/SingleToManyMethod.php b/rules/Transform/ValueObject/SingleToManyMethod.php index 20f97d595c7..b31adb3c7b1 100644 --- a/rules/Transform/ValueObject/SingleToManyMethod.php +++ b/rules/Transform/ValueObject/SingleToManyMethod.php @@ -1,46 +1,38 @@ class = $class; $this->singleMethodName = $singleMethodName; $this->manyMethodName = $manyMethodName; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getSingleMethodName(): string + public function getSingleMethodName() : string { return $this->singleMethodName; } - - public function getManyMethodName(): string + public function getManyMethodName() : string { return $this->manyMethodName; } diff --git a/rules/Transform/ValueObject/StaticCallToFuncCall.php b/rules/Transform/ValueObject/StaticCallToFuncCall.php index 73006e0dbd0..0069931198e 100644 --- a/rules/Transform/ValueObject/StaticCallToFuncCall.php +++ b/rules/Transform/ValueObject/StaticCallToFuncCall.php @@ -1,46 +1,38 @@ class = $class; $this->method = $method; $this->function = $function; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } - - public function getFunction(): string + public function getFunction() : string { return $this->function; } diff --git a/rules/Transform/ValueObject/StaticCallToMethodCall.php b/rules/Transform/ValueObject/StaticCallToMethodCall.php index 95277f67e9f..c18ce726670 100644 --- a/rules/Transform/ValueObject/StaticCallToMethodCall.php +++ b/rules/Transform/ValueObject/StaticCallToMethodCall.php @@ -1,36 +1,30 @@ staticClass = $staticClass; @@ -38,42 +32,34 @@ final class StaticCallToMethodCall $this->classType = $classType; $this->methodName = $methodName; } - - public function getClassObjectType(): ObjectType + public function getClassObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->classType); + return new \PHPStan\Type\ObjectType($this->classType); } - - public function getClassType(): string + public function getClassType() : string { return $this->classType; } - - public function getMethodName(): string + public function getMethodName() : string { return $this->methodName; } - - public function isStaticCallMatch(StaticCall $staticCall): bool + public function isStaticCallMatch(\PhpParser\Node\Expr\StaticCall $staticCall) : bool { - if (! $staticCall->class instanceof Name) { - return false; + if (!$staticCall->class instanceof \PhpParser\Node\Name) { + return \false; } - $staticCallClassName = $staticCall->class->toString(); if ($staticCallClassName !== $this->staticClass) { - return false; + return \false; } - - if (! $staticCall->name instanceof Identifier) { - return false; + if (!$staticCall->name instanceof \PhpParser\Node\Identifier) { + return \false; } - // all methods if ($this->staticMethod === '*') { - return true; + return \true; } - $staticCallMethodName = $staticCall->name->toString(); return $staticCallMethodName === $this->staticMethod; } diff --git a/rules/Transform/ValueObject/StaticCallToNew.php b/rules/Transform/ValueObject/StaticCallToNew.php index 4ca5f6906dd..405814a5027 100644 --- a/rules/Transform/ValueObject/StaticCallToNew.php +++ b/rules/Transform/ValueObject/StaticCallToNew.php @@ -1,7 +1,6 @@ class = $class; $this->method = $method; } - - public function getClass(): string + public function getClass() : string { return $this->class; } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } diff --git a/rules/Transform/ValueObject/StringToClassConstant.php b/rules/Transform/ValueObject/StringToClassConstant.php index c89001affe2..219d5a235ad 100644 --- a/rules/Transform/ValueObject/StringToClassConstant.php +++ b/rules/Transform/ValueObject/StringToClassConstant.php @@ -1,7 +1,6 @@ string = $string; $this->class = $class; $this->constant = $constant; } - - public function getString(): string + public function getString() : string { return $this->string; } - - public function getClass(): string + public function getClass() : string { return $this->class; } - - public function getConstant(): string + public function getConstant() : string { return $this->constant; } diff --git a/rules/Transform/ValueObject/UnsetAndIssetToMethodCall.php b/rules/Transform/ValueObject/UnsetAndIssetToMethodCall.php index 078747e4079..ac86ddd95a9 100644 --- a/rules/Transform/ValueObject/UnsetAndIssetToMethodCall.php +++ b/rules/Transform/ValueObject/UnsetAndIssetToMethodCall.php @@ -1,46 +1,38 @@ type = $type; $this->issetMethodCall = $issetMethodCall; $this->unsedMethodCall = $unsedMethodCall; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->type); + return new \PHPStan\Type\ObjectType($this->type); } - - public function getIssetMethodCall(): string + public function getIssetMethodCall() : string { return $this->issetMethodCall; } - - public function getUnsedMethodCall(): string + public function getUnsedMethodCall() : string { return $this->unsedMethodCall; } diff --git a/rules/Transform/ValueObject/VariableMethodCallToServiceCall.php b/rules/Transform/ValueObject/VariableMethodCallToServiceCall.php index 5ec334fbbce..5bde7da4b61 100644 --- a/rules/Transform/ValueObject/VariableMethodCallToServiceCall.php +++ b/rules/Transform/ValueObject/VariableMethodCallToServiceCall.php @@ -1,65 +1,50 @@ variableType = $variableType; $this->methodName = $methodName; $this->argumentValue = $argumentValue; $this->serviceType = $serviceType; $this->serviceMethodName = $serviceMethodName; } - - public function getVariableObjectType(): ObjectType + public function getVariableObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->variableType); + return new \PHPStan\Type\ObjectType($this->variableType); } - - public function getMethodName(): string + public function getMethodName() : string { return $this->methodName; } - /** * @return mixed */ @@ -67,13 +52,11 @@ final class VariableMethodCallToServiceCall { return $this->argumentValue; } - - public function getServiceType(): string + public function getServiceType() : string { return $this->serviceType; } - - public function getServiceMethodName(): string + public function getServiceMethodName() : string { return $this->serviceMethodName; } diff --git a/rules/Transform/ValueObject/WrapReturn.php b/rules/Transform/ValueObject/WrapReturn.php index 67514412409..c3c92930469 100644 --- a/rules/Transform/ValueObject/WrapReturn.php +++ b/rules/Transform/ValueObject/WrapReturn.php @@ -1,46 +1,38 @@ type = $type; $this->method = $method; $this->isArrayWrap = $isArrayWrap; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->type); + return new \PHPStan\Type\ObjectType($this->type); } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } - - public function isArrayWrap(): bool + public function isArrayWrap() : bool { return $this->isArrayWrap; } diff --git a/rules/TypeDeclaration/AlreadyAssignDetector/ConstructorAssignDetector.php b/rules/TypeDeclaration/AlreadyAssignDetector/ConstructorAssignDetector.php index b2b4629f7ae..b3ca088d8e9 100644 --- a/rules/TypeDeclaration/AlreadyAssignDetector/ConstructorAssignDetector.php +++ b/rules/TypeDeclaration/AlreadyAssignDetector/ConstructorAssignDetector.php @@ -1,7 +1,6 @@ propertyAssignMatcher = $propertyAssignMatcher; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - - public function isPropertyAssigned(ClassLike $classLike, string $propertyName): bool + public function isPropertyAssigned(\PhpParser\Node\Stmt\ClassLike $classLike, string $propertyName) : bool { - $constructClassMethod = $classLike->getMethod(MethodName::CONSTRUCT); - if (! $constructClassMethod instanceof ClassMethod) { - return false; + $constructClassMethod = $classLike->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - - $isAssignedInConstructor = false; - + $isAssignedInConstructor = \false; foreach ((array) $constructClassMethod->stmts as $methodStmt) { - $methodStmt->setAttribute(self::IS_FIRST_LEVEL_STATEMENT, true); - if ($methodStmt instanceof Expression) { - $methodStmt->expr->setAttribute(self::IS_FIRST_LEVEL_STATEMENT, true); + $methodStmt->setAttribute(self::IS_FIRST_LEVEL_STATEMENT, \true); + if ($methodStmt instanceof \PhpParser\Node\Stmt\Expression) { + $methodStmt->expr->setAttribute(self::IS_FIRST_LEVEL_STATEMENT, \true); } } - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $constructClassMethod->stmts, function ( - Node $node - ) use ($propertyName, &$isAssignedInConstructor): ?int { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $constructClassMethod->stmts, function (\PhpParser\Node $node) use($propertyName, &$isAssignedInConstructor) : ?int { $expr = $this->matchAssignExprToPropertyName($node, $propertyName); - if (! $expr instanceof Expr) { + if (!$expr instanceof \PhpParser\Node\Expr) { return null; } - /** @var Assign $assign */ $assign = $node; $isFirstLevelStatement = $assign->getAttribute(self::IS_FIRST_LEVEL_STATEMENT); - // cannot be nested - if ($isFirstLevelStatement !== true) { + if ($isFirstLevelStatement !== \true) { return null; } - - $isAssignedInConstructor = true; - - return NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; + $isAssignedInConstructor = \true; + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; }); - return $isAssignedInConstructor; } - - private function matchAssignExprToPropertyName(Node $node, string $propertyName): ?Expr + private function matchAssignExprToPropertyName(\PhpParser\Node $node, string $propertyName) : ?\PhpParser\Node\Expr { - if (! $node instanceof Assign) { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - return $this->propertyAssignMatcher->matchPropertyAssignExpr($node, $propertyName); } } diff --git a/rules/TypeDeclaration/AlreadyAssignDetector/NullTypeAssignDetector.php b/rules/TypeDeclaration/AlreadyAssignDetector/NullTypeAssignDetector.php index ba2815d9346..de7a5e40a30 100644 --- a/rules/TypeDeclaration/AlreadyAssignDetector/NullTypeAssignDetector.php +++ b/rules/TypeDeclaration/AlreadyAssignDetector/NullTypeAssignDetector.php @@ -1,7 +1,6 @@ scopeNestingComparator = $scopeNestingComparator; $this->doctrineTypeAnalyzer = $doctrineTypeAnalyzer; $this->nodeTypeResolver = $nodeTypeResolver; $this->propertyAssignMatcher = $propertyAssignMatcher; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - - public function detect(ClassLike $classLike, string $propertyName): ?bool + public function detect(\PhpParser\Node\Stmt\ClassLike $classLike, string $propertyName) : ?bool { $needsNullType = null; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classLike->stmts, function (Node $node) use ( - $propertyName, - &$needsNullType - ): ?int { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classLike->stmts, function (\PhpParser\Node $node) use($propertyName, &$needsNullType) : ?int { $expr = $this->matchAssignExprToPropertyName($node, $propertyName); - if (! $expr instanceof Expr) { + if (!$expr instanceof \PhpParser\Node\Expr) { return null; } - if ($this->scopeNestingComparator->isNodeConditionallyScoped($expr)) { - $needsNullType = true; - return NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; + $needsNullType = \true; + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; } - // not in doctrine property $staticType = $this->nodeTypeResolver->getStaticType($expr); if ($this->doctrineTypeAnalyzer->isDoctrineCollectionWithIterableUnionType($staticType)) { - $needsNullType = false; - return NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; + $needsNullType = \false; + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN; } - return null; }); - return $needsNullType; } - - private function matchAssignExprToPropertyName(Node $node, string $propertyName): ?Expr + private function matchAssignExprToPropertyName(\PhpParser\Node $node, string $propertyName) : ?\PhpParser\Node\Expr { - if (! $node instanceof Assign) { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - return $this->propertyAssignMatcher->matchPropertyAssignExpr($node, $propertyName); } } diff --git a/rules/TypeDeclaration/AlreadyAssignDetector/PropertyDefaultAssignDetector.php b/rules/TypeDeclaration/AlreadyAssignDetector/PropertyDefaultAssignDetector.php index b6829d185bf..318e5df2c01 100644 --- a/rules/TypeDeclaration/AlreadyAssignDetector/PropertyDefaultAssignDetector.php +++ b/rules/TypeDeclaration/AlreadyAssignDetector/PropertyDefaultAssignDetector.php @@ -1,21 +1,18 @@ getProperty($propertyName); - if (! $property instanceof Property) { - return false; + if (!$property instanceof \PhpParser\Node\Stmt\Property) { + return \false; } - return $property->props[0]->default !== null; } } diff --git a/rules/TypeDeclaration/ChildPopulator/ChildParamPopulator.php b/rules/TypeDeclaration/ChildPopulator/ChildParamPopulator.php index 6f0fc67073c..f7cc6b7c77a 100644 --- a/rules/TypeDeclaration/ChildPopulator/ChildParamPopulator.php +++ b/rules/TypeDeclaration/ChildPopulator/ChildParamPopulator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->rectorChangeCollector = $rectorChangeCollector; $this->nodeRepository = $nodeRepository; $this->childTypeResolver = $childTypeResolver; } - /** * Add typehint to all children * @param ClassMethod|Function_ $functionLike */ - public function populateChildClassMethod(FunctionLike $functionLike, int $position, Type $paramType): void + public function populateChildClassMethod(\PhpParser\Node\FunctionLike $functionLike, int $position, \PHPStan\Type\Type $paramType) : void { - if (! $functionLike instanceof ClassMethod) { + if (!$functionLike instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - /** @var string|null $className */ - $className = $functionLike->getAttribute(AttributeKey::CLASS_NAME); + $className = $functionLike->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); // anonymous class if ($className === null) { return; } - $childrenClassLikes = $this->nodeRepository->findClassesAndInterfacesByType($className); - // update their methods as well foreach ($childrenClassLikes as $childClassLike) { - if ($childClassLike instanceof Class_) { + if ($childClassLike instanceof \PhpParser\Node\Stmt\Class_) { $usedTraits = $this->nodeRepository->findUsedTraitsInClass($childClassLike); - foreach ($usedTraits as $usedTrait) { $this->addParamTypeToMethod($usedTrait, $position, $functionLike, $paramType); } } - $this->addParamTypeToMethod($childClassLike, $position, $functionLike, $paramType); } } - - private function addParamTypeToMethod( - ClassLike $classLike, - int $position, - ClassMethod $classMethod, - Type $paramType - ): void { + private function addParamTypeToMethod(\PhpParser\Node\Stmt\ClassLike $classLike, int $position, \PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Type\Type $paramType) : void + { $methodName = $this->nodeNameResolver->getName($classMethod); - $currentClassMethod = $classLike->getMethod($methodName); - if (! $currentClassMethod instanceof ClassMethod) { + if (!$currentClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - - if (! isset($currentClassMethod->params[$position])) { + if (!isset($currentClassMethod->params[$position])) { return; } - $paramNode = $currentClassMethod->params[$position]; - // already has a type if ($paramNode->type !== null) { return; } - $resolvedChildType = $this->childTypeResolver->resolveChildTypeNode($paramType); if ($resolvedChildType === null) { return; } - // let the method know it was changed now $paramNode->type = $resolvedChildType; - $paramNode->type->setAttribute(NewType::HAS_NEW_INHERITED_TYPE, true); - + $paramNode->type->setAttribute(\Rector\TypeDeclaration\ValueObject\NewType::HAS_NEW_INHERITED_TYPE, \true); $this->rectorChangeCollector->notifyNodeFileInfo($paramNode); } } diff --git a/rules/TypeDeclaration/ChildPopulator/ChildReturnPopulator.php b/rules/TypeDeclaration/ChildPopulator/ChildReturnPopulator.php index 3897efb9ea0..ad6363a8cfe 100644 --- a/rules/TypeDeclaration/ChildPopulator/ChildReturnPopulator.php +++ b/rules/TypeDeclaration/ChildPopulator/ChildReturnPopulator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->nodeRepository = $nodeRepository; $this->childTypeResolver = $childTypeResolver; } - /** * Add typehint to all children class methods */ - public function populateChildren(ClassMethod $classMethod, Type $returnType): void + public function populateChildren(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Type\Type $returnType) : void { - $className = $classMethod->getAttribute(AttributeKey::CLASS_NAME); - if (! is_string($className)) { - throw new ShouldNotHappenException(); + $className = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + if (!\is_string($className)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $childrenClassLikes = $this->nodeRepository->findChildrenOfClass($className); if ($childrenClassLikes === []) { return; } - // update their methods as well foreach ($childrenClassLikes as $childClassLike) { $usedTraits = $this->nodeRepository->findUsedTraitsInClass($childClassLike); foreach ($usedTraits as $usedTrait) { $this->addReturnTypeToChildMethod($usedTrait, $classMethod, $returnType); } - $this->addReturnTypeToChildMethod($childClassLike, $classMethod, $returnType); } } - - private function addReturnTypeToChildMethod( - ClassLike $classLike, - ClassMethod $classMethod, - Type $returnType - ): void { + private function addReturnTypeToChildMethod(\PhpParser\Node\Stmt\ClassLike $classLike, \PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Type\Type $returnType) : void + { $methodName = $this->nodeNameResolver->getName($classMethod); - $currentClassMethod = $classLike->getMethod($methodName); - if (! $currentClassMethod instanceof ClassMethod) { + if (!$currentClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - $resolvedChildTypeNode = $this->childTypeResolver->resolveChildTypeNode($returnType); if ($resolvedChildTypeNode === null) { return; } - $currentClassMethod->returnType = $resolvedChildTypeNode; - // make sure the type is not overridden - $currentClassMethod->returnType->setAttribute(AttributeKey::DO_NOT_CHANGE, true); + $currentClassMethod->returnType->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::DO_NOT_CHANGE, \true); } } diff --git a/rules/TypeDeclaration/Contract/TypeInferer/ParamTypeInfererInterface.php b/rules/TypeDeclaration/Contract/TypeInferer/ParamTypeInfererInterface.php index de6f08c466d..a8b8f36318a 100644 --- a/rules/TypeDeclaration/Contract/TypeInferer/ParamTypeInfererInterface.php +++ b/rules/TypeDeclaration/Contract/TypeInferer/ParamTypeInfererInterface.php @@ -1,13 +1,11 @@ getPriority(), - PHP_EOL, - get_class($firstPriorityAwareTypeInferer), - PHP_EOL, - get_class($secondPriorityAwareTypeInferer), - PHP_EOL - ); - + public function __construct(\Rector\TypeDeclaration\Contract\TypeInferer\PriorityAwareTypeInfererInterface $firstPriorityAwareTypeInferer, \Rector\TypeDeclaration\Contract\TypeInferer\PriorityAwareTypeInfererInterface $secondPriorityAwareTypeInferer) + { + $message = \sprintf('There are 2 type inferers with %d priority:%s- %s%s- %s.%sChange value in "getPriority()" method in one of them to different value', $firstPriorityAwareTypeInferer->getPriority(), \PHP_EOL, \get_class($firstPriorityAwareTypeInferer), \PHP_EOL, \get_class($secondPriorityAwareTypeInferer), \PHP_EOL); parent::__construct($message); } } diff --git a/rules/TypeDeclaration/FunctionLikeReturnTypeResolver.php b/rules/TypeDeclaration/FunctionLikeReturnTypeResolver.php index caa01e0680d..c37230fb812 100644 --- a/rules/TypeDeclaration/FunctionLikeReturnTypeResolver.php +++ b/rules/TypeDeclaration/FunctionLikeReturnTypeResolver.php @@ -1,33 +1,28 @@ staticTypeMapper = $staticTypeMapper; } - - public function resolveFunctionLikeReturnTypeToPHPStanType(FunctionLike $functionLike): Type + public function resolveFunctionLikeReturnTypeToPHPStanType(\PhpParser\Node\FunctionLike $functionLike) : \PHPStan\Type\Type { $functionReturnType = $functionLike->getReturnType(); if ($functionReturnType === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - return $this->staticTypeMapper->mapPhpParserNodePHPStanType($functionReturnType); } } diff --git a/rules/TypeDeclaration/Matcher/PropertyAssignMatcher.php b/rules/TypeDeclaration/Matcher/PropertyAssignMatcher.php index b563e53a80a..ac3bd664b4c 100644 --- a/rules/TypeDeclaration/Matcher/PropertyAssignMatcher.php +++ b/rules/TypeDeclaration/Matcher/PropertyAssignMatcher.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; } - /** * Covers: * - $this->propertyName = $expr; * - $this->propertyName[] = $expr; */ - public function matchPropertyAssignExpr(Assign $assign, string $propertyName): ?Expr + public function matchPropertyAssignExpr(\PhpParser\Node\Expr\Assign $assign, string $propertyName) : ?\PhpParser\Node\Expr { if ($this->isPropertyFetch($assign->var)) { - if (! $this->nodeNameResolver->isName($assign->var, $propertyName)) { + if (!$this->nodeNameResolver->isName($assign->var, $propertyName)) { return null; } - return $assign->expr; } - - if ($assign->var instanceof ArrayDimFetch && $this->isPropertyFetch($assign->var->var)) { - if (! $this->nodeNameResolver->isName($assign->var->var, $propertyName)) { + if ($assign->var instanceof \PhpParser\Node\Expr\ArrayDimFetch && $this->isPropertyFetch($assign->var->var)) { + if (!$this->nodeNameResolver->isName($assign->var->var, $propertyName)) { return null; } - return $assign->expr; } - return null; } - - private function isPropertyFetch(Node $node): bool + private function isPropertyFetch(\PhpParser\Node $node) : bool { - if ($node instanceof PropertyFetch) { - return true; + if ($node instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \true; } - - return $node instanceof StaticPropertyFetch; + return $node instanceof \PhpParser\Node\Expr\StaticPropertyFetch; } } diff --git a/rules/TypeDeclaration/NodeAnalyzer/CallTypesResolver.php b/rules/TypeDeclaration/NodeAnalyzer/CallTypesResolver.php index 22e18841803..ab5aad2b62a 100644 --- a/rules/TypeDeclaration/NodeAnalyzer/CallTypesResolver.php +++ b/rules/TypeDeclaration/NodeAnalyzer/CallTypesResolver.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->typeFactory = $typeFactory; } - /** * @param MethodCall[]|StaticCall[]|ArrayCallable[] $calls * @return Type[] */ - public function resolveStrictTypesFromCalls(array $calls): array + public function resolveStrictTypesFromCalls(array $calls) : array { - return $this->resolveTypesFromCalls($calls, TypeStrictness::STRICTNESS_TYPE_DECLARATION); + return $this->resolveTypesFromCalls($calls, \Rector\TypeDeclaration\ValueObject\TypeStrictness::STRICTNESS_TYPE_DECLARATION); } - /** * @param MethodCall[]|StaticCall[]|ArrayCallable[] $calls * @return Type[] */ - public function resolveWeakTypesFromCalls(array $calls): array + public function resolveWeakTypesFromCalls(array $calls) : array { - return $this->resolveTypesFromCalls($calls, TypeStrictness::STRICTNESS_DOCBLOCK); + return $this->resolveTypesFromCalls($calls, \Rector\TypeDeclaration\ValueObject\TypeStrictness::STRICTNESS_DOCBLOCK); } - /** * @param MethodCall[]|StaticCall[]|ArrayCallable[] $calls * @return Type[] */ - private function resolveTypesFromCalls(array $calls, string $strictnessLevel): array + private function resolveTypesFromCalls(array $calls, string $strictnessLevel) : array { $staticTypesByArgumentPosition = []; - foreach ($calls as $call) { - if (! $call instanceof StaticCall && ! $call instanceof MethodCall) { + if (!$call instanceof \PhpParser\Node\Expr\StaticCall && !$call instanceof \PhpParser\Node\Expr\MethodCall) { continue; } - foreach ($call->args as $position => $arg) { $argValueType = $this->resolveArgValueType($strictnessLevel, $arg); $staticTypesByArgumentPosition[$position][] = $argValueType; } } - // unite to single type return $this->unionToSingleType($staticTypesByArgumentPosition); } - - private function resolveArgValueType(string $strictnessLevel, Arg $arg): Type + private function resolveArgValueType(string $strictnessLevel, \PhpParser\Node\Arg $arg) : \PHPStan\Type\Type { - if ($strictnessLevel === TypeStrictness::STRICTNESS_TYPE_DECLARATION) { + if ($strictnessLevel === \Rector\TypeDeclaration\ValueObject\TypeStrictness::STRICTNESS_TYPE_DECLARATION) { $argValueType = $this->nodeTypeResolver->getNativeType($arg->value); } else { $argValueType = $this->nodeTypeResolver->resolve($arg->value); } - // "self" in another object is not correct, this make it independent return $this->correctSelfType($argValueType); } - - private function correctSelfType(Type $argValueType): Type + private function correctSelfType(\PHPStan\Type\Type $argValueType) : \PHPStan\Type\Type { - if ($argValueType instanceof ThisType) { - return new ObjectType($argValueType->getClassName()); + if ($argValueType instanceof \PHPStan\Type\ThisType) { + return new \PHPStan\Type\ObjectType($argValueType->getClassName()); } - return $argValueType; } - /** * @param array $staticTypesByArgumentPosition * @return array */ - private function unionToSingleType(array $staticTypesByArgumentPosition): array + private function unionToSingleType(array $staticTypesByArgumentPosition) : array { $staticTypeByArgumentPosition = []; foreach ($staticTypesByArgumentPosition as $position => $staticTypes) { $unionedType = $this->typeFactory->createMixedPassedOrUnionType($staticTypes); - // narrow parents to most child type $unionedType = $this->narrowParentObjectTreeToSingleObjectChildType($unionedType); $staticTypeByArgumentPosition[$position] = $unionedType; } - return $staticTypeByArgumentPosition; } - - private function narrowParentObjectTreeToSingleObjectChildType(Type $type): Type + private function narrowParentObjectTreeToSingleObjectChildType(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - if (! $type instanceof UnionType) { + if (!$type instanceof \PHPStan\Type\UnionType) { return $type; } - - if (! $this->isTypeWithClassNameOnly($type)) { + if (!$this->isTypeWithClassNameOnly($type)) { return $type; } - /** @var TypeWithClassName $firstUnionedType */ $firstUnionedType = $type->getTypes()[0]; - foreach ($type->getTypes() as $unionedType) { - if (! $unionedType instanceof TypeWithClassName) { + if (!$unionedType instanceof \PHPStan\Type\TypeWithClassName) { return $type; } - if ($unionedType->isSuperTypeOf($firstUnionedType)->yes()) { return $type; } } - return $firstUnionedType; } - - private function isTypeWithClassNameOnly(UnionType $unionType): bool + private function isTypeWithClassNameOnly(\PHPStan\Type\UnionType $unionType) : bool { foreach ($unionType->getTypes() as $unionedType) { - if (! $unionedType instanceof TypeWithClassName) { - return false; + if (!$unionedType instanceof \PHPStan\Type\TypeWithClassName) { + return \false; } } - - return true; + return \true; } } diff --git a/rules/TypeDeclaration/NodeAnalyzer/ClassMethodAndPropertyAnalyzer.php b/rules/TypeDeclaration/NodeAnalyzer/ClassMethodAndPropertyAnalyzer.php index ed1ea96141d..11b7da314d6 100644 --- a/rules/TypeDeclaration/NodeAnalyzer/ClassMethodAndPropertyAnalyzer.php +++ b/rules/TypeDeclaration/NodeAnalyzer/ClassMethodAndPropertyAnalyzer.php @@ -1,47 +1,37 @@ nodeNameResolver = $nodeNameResolver; } - - public function hasClassMethodOnlyStatementReturnOfPropertyFetch( - ClassMethod $classMethod, - string $propertyName - ): bool { + public function hasClassMethodOnlyStatementReturnOfPropertyFetch(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $propertyName) : bool + { $stmts = (array) $classMethod->stmts; - if (count($stmts) !== 1) { - return false; + if (\count($stmts) !== 1) { + return \false; } - $onlyClassMethodStmt = $stmts[0] ?? null; - if (! $onlyClassMethodStmt instanceof Return_) { - return false; + if (!$onlyClassMethodStmt instanceof \PhpParser\Node\Stmt\Return_) { + return \false; } - /** @var Return_ $return */ $return = $onlyClassMethodStmt; - - if (! $return->expr instanceof PropertyFetch) { - return false; + if (!$return->expr instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - return $this->nodeNameResolver->isName($return->expr, $propertyName); } } diff --git a/rules/TypeDeclaration/NodeAnalyzer/ClassMethodParamTypeCompleter.php b/rules/TypeDeclaration/NodeAnalyzer/ClassMethodParamTypeCompleter.php index 9527516e114..5532b439510 100644 --- a/rules/TypeDeclaration/NodeAnalyzer/ClassMethodParamTypeCompleter.php +++ b/rules/TypeDeclaration/NodeAnalyzer/ClassMethodParamTypeCompleter.php @@ -1,7 +1,6 @@ staticTypeMapper = $staticTypeMapper; $this->classMethodParamVendorLockResolver = $classMethodParamVendorLockResolver; } - /** * @param array $classParameterTypes */ - public function complete(ClassMethod $classMethod, array $classParameterTypes): ?ClassMethod + public function complete(\PhpParser\Node\Stmt\ClassMethod $classMethod, array $classParameterTypes) : ?\PhpParser\Node\Stmt\ClassMethod { - $hasChanged = false; - + $hasChanged = \false; foreach ($classParameterTypes as $position => $argumentStaticType) { if ($this->shouldSkipArgumentStaticType($classMethod, $argumentStaticType, $position)) { continue; } - $phpParserTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($argumentStaticType); - if (! $phpParserTypeNode instanceof Node) { + if (!$phpParserTypeNode instanceof \PhpParser\Node) { continue; } - // update parameter $classMethod->params[$position]->type = $phpParserTypeNode; - $hasChanged = true; + $hasChanged = \true; } - if ($hasChanged) { return $classMethod; } - return null; } - - private function shouldSkipArgumentStaticType( - ClassMethod $classMethod, - Type $argumentStaticType, - int $position - ): bool { - if ($argumentStaticType instanceof MixedType) { - return true; + private function shouldSkipArgumentStaticType(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Type\Type $argumentStaticType, int $position) : bool + { + if ($argumentStaticType instanceof \PHPStan\Type\MixedType) { + return \true; } - - if (! isset($classMethod->params[$position])) { - return true; + if (!isset($classMethod->params[$position])) { + return \true; } - if ($this->classMethodParamVendorLockResolver->isVendorLocked($classMethod)) { - return true; + return \true; } - $parameter = $classMethod->params[$position]; if ($parameter->type === null) { - return false; + return \false; } - $parameterStaticType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($parameter->type); - if ($this->isClosureAndCallableType($parameterStaticType, $argumentStaticType)) { - return true; + return \true; } - // already completed → skip return $parameterStaticType->equals($argumentStaticType); } - - private function isClosureAndCallableType(Type $parameterStaticType, Type $argumentStaticType): bool + private function isClosureAndCallableType(\PHPStan\Type\Type $parameterStaticType, \PHPStan\Type\Type $argumentStaticType) : bool { - if ($parameterStaticType instanceof CallableType && $this->isClosureObjectType($argumentStaticType)) { - return true; + if ($parameterStaticType instanceof \PHPStan\Type\CallableType && $this->isClosureObjectType($argumentStaticType)) { + return \true; } - - return $argumentStaticType instanceof CallableType && $this->isClosureObjectType($parameterStaticType); + return $argumentStaticType instanceof \PHPStan\Type\CallableType && $this->isClosureObjectType($parameterStaticType); } - - private function isClosureObjectType(Type $type): bool + private function isClosureObjectType(\PHPStan\Type\Type $type) : bool { - if (! $type instanceof ObjectType) { - return false; + if (!$type instanceof \PHPStan\Type\ObjectType) { + return \false; } - return $type->getClassName() === 'Closure'; } } diff --git a/rules/TypeDeclaration/NodeAnalyzer/TypeNodeUnwrapper.php b/rules/TypeDeclaration/NodeAnalyzer/TypeNodeUnwrapper.php index e4e47d4320e..96dbe94fdb4 100644 --- a/rules/TypeDeclaration/NodeAnalyzer/TypeNodeUnwrapper.php +++ b/rules/TypeDeclaration/NodeAnalyzer/TypeNodeUnwrapper.php @@ -1,7 +1,6 @@ nodeComparator = $nodeComparator; } - /** * @param array $typeNodes * @return array */ - public function unwrapNullableUnionTypes(array $typeNodes): array + public function unwrapNullableUnionTypes(array $typeNodes) : array { $unwrappedTypeNodes = []; - foreach ($typeNodes as $typeNode) { - if ($typeNode instanceof UnionType) { - $unwrappedTypeNodes = array_merge($unwrappedTypeNodes, $typeNode->types); - } elseif ($typeNode instanceof NullableType) { + if ($typeNode instanceof \PhpParser\Node\UnionType) { + $unwrappedTypeNodes = \array_merge($unwrappedTypeNodes, $typeNode->types); + } elseif ($typeNode instanceof \PhpParser\Node\NullableType) { $unwrappedTypeNodes[] = $typeNode->type; - $unwrappedTypeNodes[] = new Identifier('null'); + $unwrappedTypeNodes[] = new \PhpParser\Node\Identifier('null'); } else { $unwrappedTypeNodes[] = $typeNode; } } - return $this->uniquateNodes($unwrappedTypeNodes); } - /** * @param Node[] $nodes * @return Node[] */ - public function uniquateNodes(array $nodes): array + public function uniquateNodes(array $nodes) : array { $uniqueNodes = []; foreach ($nodes as $node) { $uniqueHash = $this->nodeComparator->printWithoutComments($node); $uniqueNodes[$uniqueHash] = $node; } - // reset keys from 0, for further compatibility - return array_values($uniqueNodes); + return \array_values($uniqueNodes); } } diff --git a/rules/TypeDeclaration/NodeTypeAnalyzer/CallTypeAnalyzer.php b/rules/TypeDeclaration/NodeTypeAnalyzer/CallTypeAnalyzer.php index bcaede0b645..1e0cc11a66f 100644 --- a/rules/TypeDeclaration/NodeTypeAnalyzer/CallTypeAnalyzer.php +++ b/rules/TypeDeclaration/NodeTypeAnalyzer/CallTypeAnalyzer.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; $this->nodeNameResolver = $nodeNameResolver; $this->nodeTypeResolver = $nodeTypeResolver; } - /** * @param MethodCall|StaticCall $node * @return Type[] */ - public function resolveMethodParameterTypes(Node $node): array + public function resolveMethodParameterTypes(\PhpParser\Node $node) : array { $callerType = $this->resolveCallerType($node); - if (! $callerType instanceof TypeWithClassName) { + if (!$callerType instanceof \PHPStan\Type\TypeWithClassName) { return []; } - $callerClassName = $callerType->getClassName(); - return $this->getMethodParameterTypes($callerClassName, $node); } - /** * @param StaticCall|MethodCall $node */ - private function resolveCallerType(Node $node): Type + private function resolveCallerType(\PhpParser\Node $node) : \PHPStan\Type\Type { - if ($node instanceof MethodCall) { + if ($node instanceof \PhpParser\Node\Expr\MethodCall) { return $this->nodeTypeResolver->getStaticType($node->var); } - return $this->nodeTypeResolver->resolve($node->class); } - /** * @param MethodCall|StaticCall $node * @return Type[] */ - private function getMethodParameterTypes(string $className, Node $node): array + private function getMethodParameterTypes(string $className, \PhpParser\Node $node) : array { $classReflection = $this->reflectionProvider->getClass($className); - $methodName = $this->nodeNameResolver->getName($node->name); - - if (! $methodName) { + if (!$methodName) { return []; } - - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return []; } - // method not found - if (! $classReflection->hasMethod($methodName)) { + if (!$classReflection->hasMethod($methodName)) { return []; } - $methodReflection = $classReflection->getMethod($methodName, $scope); - $parametersAcceptor = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants()); - + $parametersAcceptor = \PHPStan\Reflection\ParametersAcceptorSelector::selectSingle($methodReflection->getVariants()); $parameterTypes = []; - /** @var ParameterReflection $parameterReflection */ foreach ($parametersAcceptor->getParameters() as $parameterReflection) { $parameterTypes[] = $parameterReflection->getType(); } - return $parameterTypes; } } diff --git a/rules/TypeDeclaration/NodeTypeAnalyzer/ChildTypeResolver.php b/rules/TypeDeclaration/NodeTypeAnalyzer/ChildTypeResolver.php index 945edbfefbd..a1c49d076b4 100644 --- a/rules/TypeDeclaration/NodeTypeAnalyzer/ChildTypeResolver.php +++ b/rules/TypeDeclaration/NodeTypeAnalyzer/ChildTypeResolver.php @@ -1,7 +1,6 @@ staticTypeMapper = $staticTypeMapper; } - /** * @return Name|NullableType|UnionType|null */ - public function resolveChildTypeNode(Type $type): ?Node + public function resolveChildTypeNode(\PHPStan\Type\Type $type) : ?\PhpParser\Node { - if ($type instanceof MixedType) { + if ($type instanceof \PHPStan\Type\MixedType) { return null; } - - if ($type instanceof SelfObjectType || $type instanceof StaticType) { - $type = new ObjectType($type->getClassName()); + if ($type instanceof \Rector\StaticTypeMapper\ValueObject\Type\SelfObjectType || $type instanceof \PHPStan\Type\StaticType) { + $type = new \PHPStan\Type\ObjectType($type->getClassName()); } - return $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($type); } } diff --git a/rules/TypeDeclaration/NodeTypeAnalyzer/DetailedTypeAnalyzer.php b/rules/TypeDeclaration/NodeTypeAnalyzer/DetailedTypeAnalyzer.php index b20d90723e3..ed22375a548 100644 --- a/rules/TypeDeclaration/NodeTypeAnalyzer/DetailedTypeAnalyzer.php +++ b/rules/TypeDeclaration/NodeTypeAnalyzer/DetailedTypeAnalyzer.php @@ -1,44 +1,36 @@ getTypes()) > self::MAX_NUMBER_OF_TYPES; + if ($type instanceof \PHPStan\Type\UnionType) { + return \count($type->getTypes()) > self::MAX_NUMBER_OF_TYPES; } - - if ($type instanceof ConstantArrayType) { - return count($type->getValueTypes()) > self::MAX_NUMBER_OF_TYPES; + if ($type instanceof \PHPStan\Type\Constant\ConstantArrayType) { + return \count($type->getValueTypes()) > self::MAX_NUMBER_OF_TYPES; } - - if ($type instanceof GenericObjectType) { + if ($type instanceof \PHPStan\Type\Generic\GenericObjectType) { return $this->isTooDetailedGenericObjectType($type); } - - return false; + return \false; } - - private function isTooDetailedGenericObjectType(GenericObjectType $genericObjectType): bool + private function isTooDetailedGenericObjectType(\PHPStan\Type\Generic\GenericObjectType $genericObjectType) : bool { - if (count($genericObjectType->getTypes()) !== 1) { - return false; + if (\count($genericObjectType->getTypes()) !== 1) { + return \false; } - $genericType = $genericObjectType->getTypes()[0]; return $this->isTooDetailed($genericType); } diff --git a/rules/TypeDeclaration/NodeTypeAnalyzer/TraitTypeAnalyzer.php b/rules/TypeDeclaration/NodeTypeAnalyzer/TraitTypeAnalyzer.php index 37435778558..64184215984 100644 --- a/rules/TypeDeclaration/NodeTypeAnalyzer/TraitTypeAnalyzer.php +++ b/rules/TypeDeclaration/NodeTypeAnalyzer/TraitTypeAnalyzer.php @@ -1,40 +1,33 @@ nodeTypeResolver = $nodeTypeResolver; $this->reflectionProvider = $reflectionProvider; } - - public function isTraitType(Type $type): bool + public function isTraitType(\PHPStan\Type\Type $type) : bool { - if (! $type instanceof TypeWithClassName) { - return false; + if (!$type instanceof \PHPStan\Type\TypeWithClassName) { + return \false; } - $fullyQualifiedName = $this->nodeTypeResolver->getFullyQualifiedClassName($type); - $classReflection = $this->reflectionProvider->getClass($fullyQualifiedName); return $classReflection->isTrait(); } diff --git a/rules/TypeDeclaration/PHPStan/Type/ObjectTypeSpecifier.php b/rules/TypeDeclaration/PHPStan/Type/ObjectTypeSpecifier.php index 986cdeeef7e..24f28f92127 100644 --- a/rules/TypeDeclaration/PHPStan/Type/ObjectTypeSpecifier.php +++ b/rules/TypeDeclaration/PHPStan/Type/ObjectTypeSpecifier.php @@ -1,10 +1,9 @@ reflectionProvider = $reflectionProvider; } - /** * @return AliasedObjectType|FullyQualifiedObjectType|ObjectType|MixedType */ - public function narrowToFullyQualifiedOrAliasedObjectType(Node $node, ObjectType $objectType): SubtractableType + public function narrowToFullyQualifiedOrAliasedObjectType(\PhpParser\Node $node, \PHPStan\Type\ObjectType $objectType) : \PHPStan\Type\SubtractableType { /** @var Use_[]|null $uses */ - $uses = $node->getAttribute(AttributeKey::USE_NODES); + $uses = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::USE_NODES); if ($uses === null) { return $objectType; } - $aliasedObjectType = $this->matchAliasedObjectType($node, $objectType); if ($aliasedObjectType !== null) { return $aliasedObjectType; } - $shortenedObjectType = $this->matchShortenedObjectType($node, $objectType); if ($shortenedObjectType !== null) { return $shortenedObjectType; } - $sameNamespacedObjectType = $this->matchSameNamespacedObjectType($node, $objectType); if ($sameNamespacedObjectType !== null) { return $sameNamespacedObjectType; } - - $className = ltrim($objectType->getClassName(), '\\'); - + $className = \ltrim($objectType->getClassName(), '\\'); if ($this->reflectionProvider->hasClass($className)) { - return new FullyQualifiedObjectType($className); + return new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($className); } - // invalid type - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - private function matchAliasedObjectType(Node $node, ObjectType $objectType): ?AliasedObjectType + private function matchAliasedObjectType(\PhpParser\Node $node, \PHPStan\Type\ObjectType $objectType) : ?\Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType { /** @var Use_[]|null $uses */ - $uses = $node->getAttribute(AttributeKey::USE_NODES); + $uses = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::USE_NODES); if ($uses === null) { return null; } - $className = $objectType->getClassName(); - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); foreach ($uses as $use) { foreach ($use->uses as $useUse) { if ($useUse->alias === null) { continue; } - $useName = $useUse->name->toString(); $alias = $useUse->alias->toString(); $fullyQualifiedName = $useUse->name->toString(); - - $processAliasedObject = $this->processAliasedObject( - $alias, - $className, - $useName, - $parent, - $fullyQualifiedName - ); - if ($processAliasedObject instanceof AliasedObjectType) { + $processAliasedObject = $this->processAliasedObject($alias, $className, $useName, $parent, $fullyQualifiedName); + if ($processAliasedObject instanceof \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType) { return $processAliasedObject; } } } - return null; } - - private function processAliasedObject( - string $alias, - string $className, - string $useName, - ?Node $parentNode, - string $fullyQualifiedName - ): ?AliasedObjectType { + private function processAliasedObject(string $alias, string $className, string $useName, ?\PhpParser\Node $parentNode, string $fullyQualifiedName) : ?\Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType + { // A. is alias in use statement matching this class alias if ($alias === $className) { - return new AliasedObjectType($alias, $fullyQualifiedName); + return new \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType($alias, $fullyQualifiedName); } - // B. is aliased classes matching the class name and parent node is MethodCall/StaticCall - if ($useName === $className && ($parentNode instanceof MethodCall || $parentNode instanceof StaticCall)) { - return new AliasedObjectType($useName, $fullyQualifiedName); + if ($useName === $className && ($parentNode instanceof \PhpParser\Node\Expr\MethodCall || $parentNode instanceof \PhpParser\Node\Expr\StaticCall)) { + return new \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType($useName, $fullyQualifiedName); } - // C. is aliased classes matching the class name if ($useName === $className) { - return new AliasedObjectType($alias, $fullyQualifiedName); + return new \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType($alias, $fullyQualifiedName); } - return null; } - - private function matchShortenedObjectType(Node $node, ObjectType $objectType): ?ShortenedObjectType + private function matchShortenedObjectType(\PhpParser\Node $node, \PHPStan\Type\ObjectType $objectType) : ?\Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType { /** @var Use_[]|null $uses */ - $uses = $node->getAttribute(AttributeKey::USE_NODES); + $uses = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::USE_NODES); if ($uses === null) { return null; } - foreach ($uses as $use) { foreach ($use->uses as $useUse) { if ($useUse->alias !== null) { continue; } - $partialNamespaceObjectType = $this->matchPartialNamespaceObjectType($objectType, $useUse); if ($partialNamespaceObjectType !== null) { return $partialNamespaceObjectType; } - $partialNamespaceObjectType = $this->matchClassWithLastUseImportPart($objectType, $useUse); - if ($partialNamespaceObjectType instanceof FullyQualifiedObjectType) { + if ($partialNamespaceObjectType instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType) { return $partialNamespaceObjectType->getShortNameType(); } - - if ($partialNamespaceObjectType instanceof ShortenedObjectType) { + if ($partialNamespaceObjectType instanceof \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType) { return $partialNamespaceObjectType; } } } - return null; } - - private function matchSameNamespacedObjectType(Node $node, ObjectType $objectType): ?ObjectType + private function matchSameNamespacedObjectType(\PhpParser\Node $node, \PHPStan\Type\ObjectType $objectType) : ?\PHPStan\Type\ObjectType { - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $namespaceName = $scope->getNamespace(); if ($namespaceName === null) { return null; } - - $namespacedObject = $namespaceName . '\\' . ltrim($objectType->getClassName(), '\\'); - + $namespacedObject = $namespaceName . '\\' . \ltrim($objectType->getClassName(), '\\'); if ($this->reflectionProvider->hasClass($namespacedObject)) { - return new FullyQualifiedObjectType($namespacedObject); + return new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($namespacedObject); } - return null; } - - private function matchPartialNamespaceObjectType(ObjectType $objectType, UseUse $useUse): ?ShortenedObjectType + private function matchPartialNamespaceObjectType(\PHPStan\Type\ObjectType $objectType, \PhpParser\Node\Stmt\UseUse $useUse) : ?\Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType { // partial namespace - if (! Strings::startsWith($objectType->getClassName(), $useUse->name->getLast() . '\\')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::startsWith($objectType->getClassName(), $useUse->name->getLast() . '\\')) { return null; } - - $classNameWithoutLastUsePart = Strings::after($objectType->getClassName(), '\\', 1); - + $classNameWithoutLastUsePart = \RectorPrefix20210509\Nette\Utils\Strings::after($objectType->getClassName(), '\\', 1); $connectedClassName = $useUse->name->toString() . '\\' . $classNameWithoutLastUsePart; - if (! $this->reflectionProvider->hasClass($connectedClassName)) { + if (!$this->reflectionProvider->hasClass($connectedClassName)) { return null; } - if ($objectType->getClassName() === $connectedClassName) { return null; } - - return new ShortenedObjectType($objectType->getClassName(), $connectedClassName); + return new \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType($objectType->getClassName(), $connectedClassName); } - /** * @return FullyQualifiedObjectType|ShortenedObjectType|null */ - private function matchClassWithLastUseImportPart(ObjectType $objectType, UseUse $useUse): ?ObjectType + private function matchClassWithLastUseImportPart(\PHPStan\Type\ObjectType $objectType, \PhpParser\Node\Stmt\UseUse $useUse) : ?\PHPStan\Type\ObjectType { if ($useUse->name->getLast() !== $objectType->getClassName()) { return null; } - - if (! $this->reflectionProvider->hasClass($useUse->name->toString())) { + if (!$this->reflectionProvider->hasClass($useUse->name->toString())) { return null; } - if ($objectType->getClassName() === $useUse->name->toString()) { - return new FullyQualifiedObjectType($objectType->getClassName()); + return new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($objectType->getClassName()); } - - return new ShortenedObjectType($objectType->getClassName(), $useUse->name->toString()); + return new \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType($objectType->getClassName(), $useUse->name->toString()); } } diff --git a/rules/TypeDeclaration/PhpDoc/ShortClassExpander.php b/rules/TypeDeclaration/PhpDoc/ShortClassExpander.php index 140c26053a4..909aa7d99fb 100644 --- a/rules/TypeDeclaration/PhpDoc/ShortClassExpander.php +++ b/rules/TypeDeclaration/PhpDoc/ShortClassExpander.php @@ -1,10 +1,9 @@ reflectionProvider = $reflectionProvider; $this->objectTypeSpecifier = $objectTypeSpecifier; } - - public function resolveFqnTargetEntity(string $targetEntity, Node $node): string + public function resolveFqnTargetEntity(string $targetEntity, \PhpParser\Node $node) : string { $targetEntity = $this->getCleanedUpTargetEntity($targetEntity); if ($this->reflectionProvider->hasClass($targetEntity)) { return $targetEntity; } - - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return $targetEntity; } - $namespacedTargetEntity = $scope->getNamespace() . '\\' . $targetEntity; if ($this->reflectionProvider->hasClass($namespacedTargetEntity)) { return $namespacedTargetEntity; } - - $resolvedType = $this->objectTypeSpecifier->narrowToFullyQualifiedOrAliasedObjectType( - $node, - new ObjectType($targetEntity) - ); - if ($resolvedType instanceof ShortenedObjectType) { + $resolvedType = $this->objectTypeSpecifier->narrowToFullyQualifiedOrAliasedObjectType($node, new \PHPStan\Type\ObjectType($targetEntity)); + if ($resolvedType instanceof \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType) { return $resolvedType->getFullyQualifiedName(); } - // probably tested class return $targetEntity; } - - private function getCleanedUpTargetEntity(string $targetEntity): string + private function getCleanedUpTargetEntity(string $targetEntity) : string { - return Strings::replace($targetEntity, self::CLASS_CONST_REGEX, ''); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($targetEntity, self::CLASS_CONST_REGEX, ''); } } diff --git a/rules/TypeDeclaration/PhpDocParser/NonInformativeReturnTagRemover.php b/rules/TypeDeclaration/PhpDocParser/NonInformativeReturnTagRemover.php index 50d674057b9..6a1d622cd5d 100644 --- a/rules/TypeDeclaration/PhpDocParser/NonInformativeReturnTagRemover.php +++ b/rules/TypeDeclaration/PhpDocParser/NonInformativeReturnTagRemover.php @@ -1,10 +1,9 @@ , string[]> */ - private const USELESS_DOC_NAMES_BY_TYPE_CLASS = [ - IterableType::class => ['iterable'], - CallableType::class => ['callable'], - VoidType::class => ['void'], - ArrayType::class => ['array'], - SelfObjectType::class => ['self'], - ParentStaticType::class => ['parent'], - BooleanType::class => ['bool', 'boolean'], - ObjectWithoutClassType::class => ['object'], - ]; - + private const USELESS_DOC_NAMES_BY_TYPE_CLASS = [\PHPStan\Type\IterableType::class => ['iterable'], \PHPStan\Type\CallableType::class => ['callable'], \PHPStan\Type\VoidType::class => ['void'], \PHPStan\Type\ArrayType::class => ['array'], \Rector\StaticTypeMapper\ValueObject\Type\SelfObjectType::class => ['self'], \Rector\StaticTypeMapper\ValueObject\Type\ParentStaticType::class => ['parent'], \PHPStan\Type\BooleanType::class => ['bool', 'boolean'], \PHPStan\Type\ObjectWithoutClassType::class => ['object']]; /** * @var PhpDocInfoFactory */ private $phpDocInfoFactory; - /** * @var TypeChecker */ private $typeChecker; - - public function __construct(PhpDocInfoFactory $phpDocInfoFactory, TypeChecker $typeChecker) + public function __construct(\Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory $phpDocInfoFactory, \RectorPrefix20210509\Symplify\PackageBuilder\Php\TypeChecker $typeChecker) { $this->phpDocInfoFactory = $phpDocInfoFactory; $this->typeChecker = $typeChecker; } - /** * @param ClassMethod|Function_ $functionLike */ - public function removeReturnTagIfNotUseful(FunctionLike $functionLike): void + public function removeReturnTagIfNotUseful(\PhpParser\Node\FunctionLike $functionLike) : void { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($functionLike); - $returnTagValueNode = $phpDocInfo->getReturnTagValue(); - if (! $returnTagValueNode instanceof ReturnTagValueNode) { + if (!$returnTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode) { return; } - // useful if ($returnTagValueNode->description !== '') { return; } - $returnType = $phpDocInfo->getReturnType(); - // is bare type - if ($this->typeChecker->isInstanceOf($returnType, [FloatType::class, StringType::class, IntegerType::class])) { - $phpDocInfo->removeByType(ReturnTagValueNode::class); + if ($this->typeChecker->isInstanceOf($returnType, [\PHPStan\Type\FloatType::class, \PHPStan\Type\StringType::class, \PHPStan\Type\IntegerType::class])) { + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode::class); return; } - $this->removeNonUniqueUselessDocNames($returnType, $returnTagValueNode, $phpDocInfo); $this->removeShortObjectType($returnType, $returnTagValueNode, $phpDocInfo); $this->removeNullableType($returnType, $returnTagValueNode, $phpDocInfo); $this->removeFullyQualifiedObjectType($returnType, $returnTagValueNode, $phpDocInfo); } - - private function removeNonUniqueUselessDocNames( - Type $returnType, - ReturnTagValueNode $returnTagValueNode, - PhpDocInfo $phpDocInfo - ): void { + private function removeNonUniqueUselessDocNames(\PHPStan\Type\Type $returnType, \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode $returnTagValueNode, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void + { foreach (self::USELESS_DOC_NAMES_BY_TYPE_CLASS as $typeClass => $uselessDocNames) { - if (! is_a($returnType, $typeClass, true)) { + if (!\is_a($returnType, $typeClass, \true)) { continue; } - - if (! $this->isIdentifierWithValues($returnTagValueNode->type, $uselessDocNames)) { + if (!$this->isIdentifierWithValues($returnTagValueNode->type, $uselessDocNames)) { continue; } - - $phpDocInfo->removeByType(ReturnTagValueNode::class); + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode::class); return; } } - - private function removeShortObjectType( - Type $returnType, - ReturnTagValueNode $returnTagValueNode, - PhpDocInfo $phpDocInfo - ): void { - if (! $returnType instanceof ShortenedObjectType) { + private function removeShortObjectType(\PHPStan\Type\Type $returnType, \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode $returnTagValueNode, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void + { + if (!$returnType instanceof \Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType) { return; } - - if (! $this->isIdentifierWithValues($returnTagValueNode->type, [$returnType->getShortName()])) { + if (!$this->isIdentifierWithValues($returnTagValueNode->type, [$returnType->getShortName()])) { return; } - - $phpDocInfo->removeByType(ReturnTagValueNode::class); + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode::class); } - - private function removeNullableType( - Type $returnType, - ReturnTagValueNode $returnTagValueNode, - PhpDocInfo $phpDocInfo - ): void { + private function removeNullableType(\PHPStan\Type\Type $returnType, \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode $returnTagValueNode, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void + { $nullabledReturnType = $this->matchNullabledType($returnType); - if (! $nullabledReturnType instanceof Type) { + if (!$nullabledReturnType instanceof \PHPStan\Type\Type) { return; } - $nullabledReturnTagValueNode = $this->matchNullabledReturnTagValueNode($returnTagValueNode); - if (! $nullabledReturnTagValueNode instanceof TypeNode) { + if (!$nullabledReturnTagValueNode instanceof \PHPStan\PhpDocParser\Ast\Type\TypeNode) { return; } - - if (! $nullabledReturnType instanceof FullyQualifiedObjectType) { + if (!$nullabledReturnType instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType) { return; } - - if (! $nullabledReturnTagValueNode instanceof IdentifierTypeNode) { + if (!$nullabledReturnTagValueNode instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode) { return; } - - if (! Strings::endsWith($nullabledReturnType->getClassName(), $nullabledReturnTagValueNode->name)) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::endsWith($nullabledReturnType->getClassName(), $nullabledReturnTagValueNode->name)) { return; } - - $phpDocInfo->removeByType(ReturnTagValueNode::class); + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode::class); } - - private function removeFullyQualifiedObjectType( - Type $returnType, - ReturnTagValueNode $returnTagValueNode, - PhpDocInfo $phpDocInfo - ): void { - if (! $returnType instanceof FullyQualifiedObjectType) { + private function removeFullyQualifiedObjectType(\PHPStan\Type\Type $returnType, \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode $returnTagValueNode, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : void + { + if (!$returnType instanceof \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType) { return; } - - if (! $returnTagValueNode->type instanceof IdentifierTypeNode) { + if (!$returnTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode) { return; } - $className = $returnType->getClassName(); $returnTagValueNodeType = (string) $returnTagValueNode->type; - if ($this->isClassNameAndPartMatch($className, $returnTagValueNodeType)) { - $phpDocInfo->removeByType(ReturnTagValueNode::class); + $phpDocInfo->removeByType(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode::class); } } - /** * @param string[] $values */ - private function isIdentifierWithValues(TypeNode $typeNode, array $values): bool + private function isIdentifierWithValues(\PHPStan\PhpDocParser\Ast\Type\TypeNode $typeNode, array $values) : bool { - if (! $typeNode instanceof IdentifierTypeNode) { - return false; + if (!$typeNode instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode) { + return \false; } - - return in_array($typeNode->name, $values, true); + return \in_array($typeNode->name, $values, \true); } - - private function matchNullabledType(Type $returnType): ?Type + private function matchNullabledType(\PHPStan\Type\Type $returnType) : ?\PHPStan\Type\Type { - if (! $returnType instanceof UnionType) { + if (!$returnType instanceof \PHPStan\Type\UnionType) { return null; } - - if (! $returnType->isSuperTypeOf(new NullType())->yes()) { + if (!$returnType->isSuperTypeOf(new \PHPStan\Type\NullType())->yes()) { return null; } - - if (count($returnType->getTypes()) !== 2) { + if (\count($returnType->getTypes()) !== 2) { return null; } - foreach ($returnType->getTypes() as $unionedReturnType) { - if ($unionedReturnType instanceof NullType) { + if ($unionedReturnType instanceof \PHPStan\Type\NullType) { continue; } - return $unionedReturnType; } - return null; } - - private function matchNullabledReturnTagValueNode(ReturnTagValueNode $returnTagValueNode): ?TypeNode + private function matchNullabledReturnTagValueNode(\PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode $returnTagValueNode) : ?\PHPStan\PhpDocParser\Ast\Type\TypeNode { - if (! $returnTagValueNode->type instanceof UnionTypeNode) { + if (!$returnTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\UnionTypeNode) { return null; } - - if (count($returnTagValueNode->type->types) !== 2) { + if (\count($returnTagValueNode->type->types) !== 2) { return null; } - foreach ($returnTagValueNode->type->types as $unionedReturnTagValueNode) { if ($this->isIdentifierWithValues($unionedReturnTagValueNode, ['null'])) { continue; } - return $unionedReturnTagValueNode; } - return null; } - - private function isClassNameAndPartMatch(string $className, string $returnTagValueNodeType): bool + private function isClassNameAndPartMatch(string $className, string $returnTagValueNodeType) : bool { if ($className === $returnTagValueNodeType) { - return true; + return \true; } - if ('\\' . $className === $returnTagValueNodeType) { - return true; + return \true; } - - return Strings::endsWith($className, '\\' . $returnTagValueNodeType); + return \RectorPrefix20210509\Nette\Utils\Strings::endsWith($className, '\\' . $returnTagValueNodeType); } } diff --git a/rules/TypeDeclaration/PhpDocParser/ParamPhpDocNodeFactory.php b/rules/TypeDeclaration/PhpDocParser/ParamPhpDocNodeFactory.php index 4eb337dbc62..f036a39cadb 100644 --- a/rules/TypeDeclaration/PhpDocParser/ParamPhpDocNodeFactory.php +++ b/rules/TypeDeclaration/PhpDocParser/ParamPhpDocNodeFactory.php @@ -1,33 +1,24 @@ nodeNameResolver = $nodeNameResolver; } - - public function create(TypeNode $typeNode, Param $param): VariadicAwareParamTagValueNode + public function create(\PHPStan\PhpDocParser\Ast\Type\TypeNode $typeNode, \PhpParser\Node\Param $param) : \Rector\BetterPhpDocParser\ValueObject\PhpDoc\VariadicAwareParamTagValueNode { - return new VariadicAwareParamTagValueNode( - $typeNode, - $param->variadic, - '$' . $this->nodeNameResolver->getName($param), - '' - ); + return new \Rector\BetterPhpDocParser\ValueObject\PhpDoc\VariadicAwareParamTagValueNode($typeNode, $param->variadic, '$' . $this->nodeNameResolver->getName($param), ''); } } diff --git a/rules/TypeDeclaration/PhpParserTypeAnalyzer.php b/rules/TypeDeclaration/PhpParserTypeAnalyzer.php index 17a1e9de07d..09bf00b8d3e 100644 --- a/rules/TypeDeclaration/PhpParserTypeAnalyzer.php +++ b/rules/TypeDeclaration/PhpParserTypeAnalyzer.php @@ -1,7 +1,6 @@ staticTypeMapper = $staticTypeMapper; } - /** * @param Name|NullableType|UnionType|Identifier $possibleSubtype * @param Name|NullableType|UnionType|Identifier $possibleParentType */ - public function isCovariantSubtypeOf(Node $possibleSubtype, Node $possibleParentType): bool + public function isCovariantSubtypeOf(\PhpParser\Node $possibleSubtype, \PhpParser\Node $possibleParentType) : bool { // skip until PHP 8 is out if ($this->isUnionType($possibleSubtype, $possibleParentType)) { - return false; + return \false; } - // possible - https://3v4l.org/ZuJCh - if ($possibleSubtype instanceof NullableType && ! $possibleParentType instanceof NullableType) { + if ($possibleSubtype instanceof \PhpParser\Node\NullableType && !$possibleParentType instanceof \PhpParser\Node\NullableType) { return $this->isCovariantSubtypeOf($possibleSubtype->type, $possibleParentType); } - // not possible - https://3v4l.org/iNDTc - if (! $possibleSubtype instanceof NullableType && $possibleParentType instanceof NullableType) { - return false; + if (!$possibleSubtype instanceof \PhpParser\Node\NullableType && $possibleParentType instanceof \PhpParser\Node\NullableType) { + return \false; } - $subtypeType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($possibleParentType); $parentType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($possibleSubtype); - - return $parentType->isSuperTypeOf($subtypeType) - ->yes(); + return $parentType->isSuperTypeOf($subtypeType)->yes(); } - - private function isUnionType(Node $possibleSubtype, Node $possibleParentType): bool + private function isUnionType(\PhpParser\Node $possibleSubtype, \PhpParser\Node $possibleParentType) : bool { - if ($possibleSubtype instanceof UnionType) { - return true; + if ($possibleSubtype instanceof \PhpParser\Node\UnionType) { + return \true; } - - return $possibleParentType instanceof UnionType; + return $possibleParentType instanceof \PhpParser\Node\UnionType; } } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/AddArrayParamDocTypeRector.php b/rules/TypeDeclaration/Rector/ClassMethod/AddArrayParamDocTypeRector.php index d48d3abc8a7..74df7307737 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/AddArrayParamDocTypeRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/AddArrayParamDocTypeRector.php @@ -1,7 +1,6 @@ paramTypeInferer = $paramTypeInferer; $this->phpDocTypeChanger = $phpDocTypeChanger; $this->paramTagRemover = $paramTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Adds @param annotation to array parameters inferred from the rest of the code', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Adds @param annotation to array parameters inferred from the rest of the code', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -69,8 +56,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -87,90 +73,69 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->getParams() === []) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - foreach ($node->getParams() as $param) { if ($this->shouldSkipParam($param)) { continue; } - $paramType = $this->paramTypeInferer->inferParam($param); - if ($paramType instanceof MixedType) { + if ($paramType instanceof \PHPStan\Type\MixedType) { continue; } - $paramName = $this->getName($param); - $this->phpDocTypeChanger->changeParamType($phpDocInfo, $paramType, $param, $paramName); } - if ($phpDocInfo->hasChanged()) { - $node->setAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, true); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, \true); $this->paramTagRemover->removeParamTagsIfUseless($phpDocInfo, $node); return $node; } - return null; } - - private function shouldSkipParam(Param $param): bool + private function shouldSkipParam(\PhpParser\Node\Param $param) : bool { // type missing at all if ($param->type === null) { - return true; + return \true; } - // not an array type $paramType = $this->nodeTypeResolver->resolve($param->type); - // weird case for maybe interface - if ($paramType->isIterable()->maybe() && ($paramType instanceof ObjectType)) { - return true; + if ($paramType->isIterable()->maybe() && $paramType instanceof \PHPStan\Type\ObjectType) { + return \true; } - - $isArrayable = $paramType->isIterable() - ->yes() || $paramType->isArray() - ->yes() || ($paramType->isIterable()->maybe() || $paramType->isArray()->maybe()); - if (! $isArrayable) { - return true; + $isArrayable = $paramType->isIterable()->yes() || $paramType->isArray()->yes() || ($paramType->isIterable()->maybe() || $paramType->isArray()->maybe()); + if (!$isArrayable) { + return \true; } - return $this->isArrayExplicitMixed($paramType); } - - private function isArrayExplicitMixed(Type $type): bool + private function isArrayExplicitMixed(\PHPStan\Type\Type $type) : bool { - if (! $type instanceof ArrayType) { - return false; + if (!$type instanceof \PHPStan\Type\ArrayType) { + return \false; } - $iterableValueType = $type->getIterableValueType(); - if (! $iterableValueType instanceof MixedType) { - return false; + if (!$iterableValueType instanceof \PHPStan\Type\MixedType) { + return \false; } - return $iterableValueType->isExplicitMixed(); } } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/AddArrayReturnDocTypeRector.php b/rules/TypeDeclaration/Rector/ClassMethod/AddArrayReturnDocTypeRector.php index 7f802c33af5..f776aafa228 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/AddArrayReturnDocTypeRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/AddArrayReturnDocTypeRector.php @@ -1,7 +1,6 @@ returnTypeInferer = $returnTypeInferer; $this->classMethodReturnTypeOverrideGuard = $classMethodReturnTypeOverrideGuard; $this->advancedArrayAnalyzer = $advancedArrayAnalyzer; @@ -87,14 +71,9 @@ final class AddArrayReturnDocTypeRector extends AbstractRector $this->returnTagRemover = $returnTagRemover; $this->detailedTypeAnalyzer = $detailedTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Adds @return annotation to array parameters inferred from the rest of the code', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Adds @return annotation to array parameters inferred from the rest of the code', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -108,8 +87,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -126,185 +104,134 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); if ($this->shouldSkip($node, $phpDocInfo)) { return null; } - - $inferredReturnType = $this->returnTypeInferer->inferFunctionLikeWithExcludedInferers( - $node, - [ReturnTypeDeclarationReturnTypeInferer::class] - ); - - $inferredReturnType = $this->normalizeTypeToRespectArrayScalarType->normalizeToArray( - $inferredReturnType, - $node->returnType - ); - + $inferredReturnType = $this->returnTypeInferer->inferFunctionLikeWithExcludedInferers($node, [\Rector\TypeDeclaration\TypeInferer\ReturnTypeInferer\ReturnTypeDeclarationReturnTypeInferer::class]); + $inferredReturnType = $this->normalizeTypeToRespectArrayScalarType->normalizeToArray($inferredReturnType, $node->returnType); $currentReturnType = $phpDocInfo->getReturnType(); - - if ($this->classMethodReturnTypeOverrideGuard->shouldSkipClassMethodOldTypeWithNewType( - $currentReturnType, - $inferredReturnType - )) { + if ($this->classMethodReturnTypeOverrideGuard->shouldSkipClassMethodOldTypeWithNewType($currentReturnType, $inferredReturnType)) { return null; } - if ($this->shouldSkipType($inferredReturnType, $currentReturnType, $node, $phpDocInfo)) { return null; } - $this->phpDocTypeChanger->changeReturnType($phpDocInfo, $inferredReturnType); - if ($phpDocInfo->hasChanged()) { - $node->setAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, true); + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, \true); $this->returnTagRemover->removeReturnTagIfUseless($phpDocInfo, $node); return $node; } - return null; } - - private function shouldSkip(ClassMethod $classMethod, PhpDocInfo $phpDocInfo): bool + private function shouldSkip(\PhpParser\Node\Stmt\ClassMethod $classMethod, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : bool { if ($this->shouldSkipClassMethod($classMethod)) { - return true; + return \true; } - if ($this->hasArrayShapeNode($classMethod)) { - return true; + return \true; } - $currentPhpDocReturnType = $phpDocInfo->getReturnType(); - if ($currentPhpDocReturnType instanceof ArrayType && $currentPhpDocReturnType->getItemType() instanceof MixedType) { - return true; + if ($currentPhpDocReturnType instanceof \PHPStan\Type\ArrayType && $currentPhpDocReturnType->getItemType() instanceof \PHPStan\Type\MixedType) { + return \true; } - if ($this->hasInheritDoc($classMethod)) { - return true; + return \true; } - - return $currentPhpDocReturnType instanceof IterableType; + return $currentPhpDocReturnType instanceof \PHPStan\Type\IterableType; } - /** * @deprecated * @todo merge to * @see \Rector\TypeDeclaration\TypeAlreadyAddedChecker\ReturnTypeAlreadyAddedChecker */ - private function shouldSkipType( - Type $newType, - Type $currentType, - ClassMethod $classMethod, - PhpDocInfo $phpDocInfo - ): bool { - if ($newType instanceof ArrayType && $this->shouldSkipArrayType($newType, $classMethod, $phpDocInfo)) { - return true; + private function shouldSkipType(\PHPStan\Type\Type $newType, \PHPStan\Type\Type $currentType, \PhpParser\Node\Stmt\ClassMethod $classMethod, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : bool + { + if ($newType instanceof \PHPStan\Type\ArrayType && $this->shouldSkipArrayType($newType, $classMethod, $phpDocInfo)) { + return \true; } - if ($this->detailedTypeAnalyzer->isTooDetailed($newType)) { - return true; + return \true; } - // not an array type - if ($newType instanceof VoidType) { - return true; + if ($newType instanceof \PHPStan\Type\VoidType) { + return \true; } - if ($this->advancedArrayAnalyzer->isMoreSpecificArrayTypeOverride($newType, $classMethod, $phpDocInfo)) { - return true; + return \true; } - if ($this->isGenericTypeToMixedTypeOverride($newType, $currentType)) { - return true; + return \true; } - return $this->detailedTypeAnalyzer->isTooDetailed($newType); } - - private function shouldSkipClassMethod(ClassMethod $classMethod): bool + private function shouldSkipClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { if ($this->classMethodReturnTypeOverrideGuard->shouldSkipClassMethod($classMethod)) { - return true; + return \true; } - if ($classMethod->returnType === null) { - return false; + return \false; } - - return ! $this->isNames($classMethod->returnType, ['array', 'iterable', 'Iterator']); + return !$this->isNames($classMethod->returnType, ['array', 'iterable', 'Iterator']); } - - private function hasArrayShapeNode(ClassMethod $classMethod): bool + private function hasArrayShapeNode(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); - $returnTagValueNode = $phpDocInfo->getReturnTagValue(); - if (! $returnTagValueNode instanceof ReturnTagValueNode) { - return false; + if (!$returnTagValueNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode) { + return \false; } - - if ($returnTagValueNode->type instanceof GenericTypeNode) { - return true; + if ($returnTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\GenericTypeNode) { + return \true; } - - if ($returnTagValueNode->type instanceof ArrayShapeNode) { - return true; + if ($returnTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode) { + return \true; } - - if (! $returnTagValueNode->type instanceof ArrayTypeNode) { - return false; + if (!$returnTagValueNode->type instanceof \PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode) { + return \false; } - - return $returnTagValueNode->type->type instanceof ArrayShapeNode; + return $returnTagValueNode->type->type instanceof \PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; } - - private function hasInheritDoc(ClassMethod $classMethod): bool + private function hasInheritDoc(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); return $phpDocInfo->hasInheritDoc(); } - - private function shouldSkipArrayType(ArrayType $arrayType, ClassMethod $classMethod, PhpDocInfo $phpDocInfo): bool + private function shouldSkipArrayType(\PHPStan\Type\ArrayType $arrayType, \PhpParser\Node\Stmt\ClassMethod $classMethod, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : bool { if ($this->advancedArrayAnalyzer->isNewAndCurrentTypeBothCallable($arrayType, $phpDocInfo)) { - return true; + return \true; } - if ($this->advancedArrayAnalyzer->isClassStringArrayByStringArrayOverride($arrayType, $classMethod)) { - return true; + return \true; } - return $this->advancedArrayAnalyzer->isMixedOfSpecificOverride($arrayType, $phpDocInfo); } - - private function isGenericTypeToMixedTypeOverride(Type $newType, Type $currentType): bool + private function isGenericTypeToMixedTypeOverride(\PHPStan\Type\Type $newType, \PHPStan\Type\Type $currentType) : bool { - if ($newType instanceof GenericObjectType && $currentType instanceof MixedType) { + if ($newType instanceof \PHPStan\Type\Generic\GenericObjectType && $currentType instanceof \PHPStan\Type\MixedType) { $types = $newType->getTypes(); - if ($types[0] instanceof MixedType && $types[1] instanceof ArrayType) { - return true; + if ($types[0] instanceof \PHPStan\Type\MixedType && $types[1] instanceof \PHPStan\Type\ArrayType) { + return \true; } } - - return false; + return \false; } } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/AddMethodCallBasedStrictParamTypeRector.php b/rules/TypeDeclaration/Rector/ClassMethod/AddMethodCallBasedStrictParamTypeRector.php index ec5b82aeb62..c3910d80a5f 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/AddMethodCallBasedStrictParamTypeRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/AddMethodCallBasedStrictParamTypeRector.php @@ -1,7 +1,6 @@ callTypesResolver = $callTypesResolver; $this->classMethodParamTypeCompleter = $classMethodParamTypeCompleter; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Change param type to strict type of passed expression', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change param type to strict type of passed expression', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function getById($id) @@ -60,8 +51,7 @@ class CallerClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function getById(int $id) @@ -82,30 +72,25 @@ class CallerClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->params === []) { return null; } - $classMethodCalls = $this->nodeRepository->findCallsByClassMethod($node); $classMethodParameterTypes = $this->callTypesResolver->resolveStrictTypesFromCalls($classMethodCalls); - return $this->classMethodParamTypeCompleter->complete($node, $classMethodParameterTypes); } } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/AddParamTypeDeclarationRector.php b/rules/TypeDeclaration/Rector/ClassMethod/AddParamTypeDeclarationRector.php index 1d47d38296f..6f3c108776d 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/AddParamTypeDeclarationRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/AddParamTypeDeclarationRector.php @@ -1,7 +1,6 @@ typeComparator = $typeComparator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - $configuration = [ - self::PARAMETER_TYPEHINTS => [new AddParamTypeDeclaration('SomeClass', 'process', 0, new StringType())], - ]; - - return new RuleDefinition('Add param types where needed', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + $configuration = [self::PARAMETER_TYPEHINTS => [new \Rector\TypeDeclaration\ValueObject\AddParamTypeDeclaration('SomeClass', 'process', 0, new \PHPStan\Type\StringType())]]; + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add param types where needed', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function process($name) @@ -63,8 +52,7 @@ class SomeClass } } CODE_SAMPLE -, - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function process(string $name) @@ -72,105 +60,82 @@ class SomeClass } } CODE_SAMPLE - , - $configuration - ), - ]); +, $configuration)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->shouldSkip($node)) { return null; } - /** @var ClassLike $classLike */ - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); foreach ($this->parameterTypehints as $parameterTypehint) { - if (! $this->isObjectType($classLike, $parameterTypehint->getObjectType())) { + if (!$this->isObjectType($classLike, $parameterTypehint->getObjectType())) { continue; } - - if (! $this->isName($node, $parameterTypehint->getMethodName())) { + if (!$this->isName($node, $parameterTypehint->getMethodName())) { continue; } - $this->refactorClassMethodWithTypehintByParameterPosition($node, $parameterTypehint); } - return $node; } - /** * @param mixed[] $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $parameterTypehints = $configuration[self::PARAMETER_TYPEHINTS] ?? []; - Assert::allIsInstanceOf($parameterTypehints, AddParamTypeDeclaration::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($parameterTypehints, \Rector\TypeDeclaration\ValueObject\AddParamTypeDeclaration::class); $this->parameterTypehints = $parameterTypehints; } - - private function shouldSkip(ClassMethod $classMethod): bool + private function shouldSkip(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { // skip class methods without args if ($classMethod->params === []) { - return true; + return \true; } - - $classLike = $classMethod->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { - return true; + $classLike = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { + return \true; } - // skip traits - if ($classLike instanceof Trait_) { - return true; + if ($classLike instanceof \PhpParser\Node\Stmt\Trait_) { + return \true; } - // skip class without parents/interfaces - if ($classLike instanceof Class_) { + if ($classLike instanceof \PhpParser\Node\Stmt\Class_) { if ($classLike->implements !== []) { - return false; + return \false; } - if ($classLike->extends !== null) { - return false; + return \false; } - - return true; + return \true; } - // skip interface without parents /** @var Interface_ $classLike */ - return ! (bool) $classLike->extends; + return !(bool) $classLike->extends; } - - private function refactorClassMethodWithTypehintByParameterPosition( - ClassMethod $classMethod, - AddParamTypeDeclaration $addParamTypeDeclaration - ): void { + private function refactorClassMethodWithTypehintByParameterPosition(\PhpParser\Node\Stmt\ClassMethod $classMethod, \Rector\TypeDeclaration\ValueObject\AddParamTypeDeclaration $addParamTypeDeclaration) : void + { $parameter = $classMethod->params[$addParamTypeDeclaration->getPosition()] ?? null; - if (! $parameter instanceof Param) { + if (!$parameter instanceof \PhpParser\Node\Param) { return; } - $this->refactorParameter($parameter, $addParamTypeDeclaration); } - - private function refactorParameter(Param $param, AddParamTypeDeclaration $addParamTypeDeclaration): void + private function refactorParameter(\PhpParser\Node\Param $param, \Rector\TypeDeclaration\ValueObject\AddParamTypeDeclaration $addParamTypeDeclaration) : void { // already set → no change if ($param->type !== null) { @@ -179,17 +144,12 @@ CODE_SAMPLE return; } } - // remove it - if ($addParamTypeDeclaration->getParamType() instanceof MixedType) { + if ($addParamTypeDeclaration->getParamType() instanceof \PHPStan\Type\MixedType) { $param->type = null; return; } - - $returnTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode( - $addParamTypeDeclaration->getParamType() - ); - + $returnTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($addParamTypeDeclaration->getParamType()); $param->type = $returnTypeNode; } } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/AddParamTypeFromCallersRector.php b/rules/TypeDeclaration/Rector/ClassMethod/AddParamTypeFromCallersRector.php index 5fb8ab4a4f2..0cecb8b60e6 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/AddParamTypeFromCallersRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/AddParamTypeFromCallersRector.php @@ -1,7 +1,6 @@ callTypesResolver = $callTypesResolver; $this->classMethodParamTypeCompleter = $classMethodParamTypeCompleter; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add param type based on called types in that particular method', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add param type based on called types in that particular method', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run(Return_ $return) @@ -57,8 +48,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run(Return_ $return) @@ -71,32 +61,27 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->params === []) { return null; } - $calls = $this->nodeRepository->findCallsByClassMethod($node); if ($calls === []) { return null; } - $classMethodParameterTypes = $this->callTypesResolver->resolveWeakTypesFromCalls($calls); return $this->classMethodParamTypeCompleter->complete($node, $classMethodParameterTypes); } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/AddReturnTypeDeclarationRector.php b/rules/TypeDeclaration/Rector/ClassMethod/AddReturnTypeDeclarationRector.php index 60ff6346232..e6188b364c4 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/AddReturnTypeDeclarationRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/AddReturnTypeDeclarationRector.php @@ -1,7 +1,6 @@ typeComparator = $typeComparator; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - $arrayType = new ArrayType(new MixedType(), new MixedType()); - $configuration = [ - self::METHOD_RETURN_TYPES => [new AddReturnTypeDeclaration('SomeClass', 'getData', $arrayType)], - ]; - - return new RuleDefinition('Changes defined return typehint of method and class.', [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + $arrayType = new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); + $configuration = [self::METHOD_RETURN_TYPES => [new \Rector\TypeDeclaration\ValueObject\AddReturnTypeDeclaration('SomeClass', 'getData', $arrayType)]]; + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Changes defined return typehint of method and class.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public getData() @@ -59,8 +48,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public getData(): array @@ -68,61 +56,48 @@ class SomeClass } } CODE_SAMPLE - , - $configuration - ), - ]); +, $configuration)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->methodReturnTypes as $methodReturnType) { - if (! $this->isObjectType($node, $methodReturnType->getObjectType())) { + if (!$this->isObjectType($node, $methodReturnType->getObjectType())) { continue; } - - if (! $this->isName($node, $methodReturnType->getMethod())) { + if (!$this->isName($node, $methodReturnType->getMethod())) { continue; } - $this->processClassMethodNodeWithTypehints($node, $methodReturnType->getReturnType()); - return $node; } - return null; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $methodReturnTypes = $configuration[self::METHOD_RETURN_TYPES] ?? []; - Assert::allIsInstanceOf($methodReturnTypes, AddReturnTypeDeclaration::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($methodReturnTypes, \Rector\TypeDeclaration\ValueObject\AddReturnTypeDeclaration::class); $this->methodReturnTypes = $methodReturnTypes; } - - private function processClassMethodNodeWithTypehints(ClassMethod $classMethod, Type $newType): void + private function processClassMethodNodeWithTypehints(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PHPStan\Type\Type $newType) : void { // remove it - if ($newType instanceof MixedType) { + if ($newType instanceof \PHPStan\Type\MixedType) { $classMethod->returnType = null; return; } - // already set → no change if ($classMethod->returnType !== null) { $currentReturnType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($classMethod->returnType); @@ -130,7 +105,6 @@ CODE_SAMPLE return; } } - $returnTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($newType); $classMethod->returnType = $returnTypeNode; } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/AddVoidReturnTypeWhereNoReturnRector.php b/rules/TypeDeclaration/Rector/ClassMethod/AddVoidReturnTypeWhereNoReturnRector.php index 4aa1f11a3ec..40123275216 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/AddVoidReturnTypeWhereNoReturnRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/AddVoidReturnTypeWhereNoReturnRector.php @@ -1,7 +1,6 @@ silentVoidResolver = $silentVoidResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add return type void to function like without any return', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add return type void to function like without any return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function getValues() @@ -44,9 +38,7 @@ final class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function getValues(): void @@ -56,40 +48,33 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Function_::class, Closure::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Expr\Closure::class]; } - /** * @param ClassMethod|Function_|Closure $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::VOID_TYPE)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::VOID_TYPE)) { return null; } - if ($node->returnType !== null) { return null; } - - if ($node instanceof ClassMethod && ($node->isMagic() || $node->isAbstract())) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod && ($node->isMagic() || $node->isAbstract())) { return null; } - - if (! $this->silentVoidResolver->hasExlusiveVoid($node)) { + if (!$this->silentVoidResolver->hasExlusiveVoid($node)) { return null; } - - $node->returnType = new Identifier('void'); + $node->returnType = new \PhpParser\Node\Identifier('void'); return $node; } } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/ReturnNeverTypeRector.php b/rules/TypeDeclaration/Rector/ClassMethod/ReturnNeverTypeRector.php index a94d0b633fd..927393bf4d6 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/ReturnNeverTypeRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/ReturnNeverTypeRector.php @@ -1,7 +1,6 @@ parentClassMethodTypeOverrideGuard = $parentClassMethodTypeOverrideGuard; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add "never" type for methods that never return anything', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add "never" type for methods that never return anything', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -51,9 +45,7 @@ final class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run(): never @@ -62,76 +54,60 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Function_::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class]; } - /** * @param ClassMethod|Function_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::NEVER_TYPE)) { + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::NEVER_TYPE)) { return null; } - - $returns = $this->betterNodeFinder->findInstanceOf($node, Return_::class); + $returns = $this->betterNodeFinder->findInstanceOf($node, \PhpParser\Node\Stmt\Return_::class); if ($returns !== []) { return null; } - - $notNeverNodes = $this->betterNodeFinder->findInstancesOf($node, [Yield_::class]); + $notNeverNodes = $this->betterNodeFinder->findInstancesOf($node, [\PhpParser\Node\Expr\Yield_::class]); if ($notNeverNodes !== []) { return null; } - - $neverNodes = $this->betterNodeFinder->findInstancesOf($node, [Node\Expr\Throw_::class, Throw_::class]); + $neverNodes = $this->betterNodeFinder->findInstancesOf($node, [\PhpParser\Node\Expr\Throw_::class, \PhpParser\Node\Stmt\Throw_::class]); $hasNeverFuncCall = $this->resolveHasNeverFuncCall($node); - if ($neverNodes === [] && ! $hasNeverFuncCall) { + if ($neverNodes === [] && !$hasNeverFuncCall) { return null; } - - if ($node instanceof ClassMethod && ! $this->parentClassMethodTypeOverrideGuard->isReturnTypeChangeAllowed( - $node - )) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod && !$this->parentClassMethodTypeOverrideGuard->isReturnTypeChangeAllowed($node)) { return null; } - - $node->returnType = new Name('never'); - + $node->returnType = new \PhpParser\Node\Name('never'); return $node; } - /** * @param ClassMethod|Function_ $functionLike */ - private function resolveHasNeverFuncCall(FunctionLike $functionLike): bool + private function resolveHasNeverFuncCall(\PhpParser\Node\FunctionLike $functionLike) : bool { - $hasNeverType = false; - + $hasNeverType = \false; foreach ((array) $functionLike->stmts as $stmt) { - if ($stmt instanceof Expression) { + if ($stmt instanceof \PhpParser\Node\Stmt\Expression) { $stmt = $stmt->expr; } - - if ($stmt instanceof Stmt) { + if ($stmt instanceof \PhpParser\Node\Stmt) { continue; } - $stmtType = $this->getStaticType($stmt); - if ($stmtType instanceof NeverType) { - $hasNeverType = true; + if ($stmtType instanceof \PHPStan\Type\NeverType) { + $hasNeverType = \true; } } - return $hasNeverType; } } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromReturnNewRector.php b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromReturnNewRector.php index 188393a7e65..ca487172903 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromReturnNewRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromReturnNewRector.php @@ -1,7 +1,6 @@ typeFactory = $typeFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add return type void to function like without any return', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add return type void to function like without any return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function action() @@ -44,8 +38,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function action(): Respose @@ -54,56 +47,46 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::SCALAR_TYPES)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SCALAR_TYPES)) { return null; } - if ($node->returnType !== null) { return null; } - /** @var Return_[] $returns */ - $returns = $this->betterNodeFinder->findInstanceOf((array) $node->stmts, Return_::class); + $returns = $this->betterNodeFinder->findInstanceOf((array) $node->stmts, \PhpParser\Node\Stmt\Return_::class); if ($returns === []) { return null; } - $newTypes = []; foreach ($returns as $return) { - if (! $return->expr instanceof New_) { + if (!$return->expr instanceof \PhpParser\Node\Expr\New_) { return null; } - $new = $return->expr; - if (! $new->class instanceof Name) { + if (!$new->class instanceof \PhpParser\Node\Name) { return null; } - $className = $this->getName($new->class); - $newTypes[] = new ObjectType($className); + $newTypes[] = new \PHPStan\Type\ObjectType($className); } - $returnType = $this->typeFactory->createMixedPassedOrUnionType($newTypes); $returnTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($returnType); $node->returnType = $returnTypeNode; - return $node; } } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictTypedCallRector.php b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictTypedCallRector.php index 9251ac1c20d..65e9fbe8c85 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictTypedCallRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictTypedCallRector.php @@ -1,7 +1,6 @@ reflectionTypeResolver = $reflectionTypeResolver; $this->typeNodeUnwrapper = $typeNodeUnwrapper; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add return type from strict return type of call', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add return type from strict return type of call', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function getData() @@ -68,8 +61,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function getData(): int @@ -83,184 +75,143 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class, Function_::class, Closure::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Expr\Closure::class]; } - /** * @param ClassMethod|Function_|Closure $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($this->isSkipped($node)) { return null; } - /** @var Return_[] $returns */ - $returns = $this->betterNodeFinder->findInstanceOf((array) $node->stmts, Return_::class); - + $returns = $this->betterNodeFinder->findInstanceOf((array) $node->stmts, \PhpParser\Node\Stmt\Return_::class); $returnedStrictTypes = $this->collectStrictReturnTypes($returns); if ($returnedStrictTypes === []) { return null; } - - if (count($returnedStrictTypes) === 1) { + if (\count($returnedStrictTypes) === 1) { return $this->refactorSingleReturnType($returns[0], $returnedStrictTypes[0], $node); } - - if ($this->isAtLeastPhpVersion(PhpVersionFeature::UNION_TYPES)) { + if ($this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::UNION_TYPES)) { /** @var PhpParserUnionType[] $returnedStrictTypes */ $unwrappedTypes = $this->typeNodeUnwrapper->unwrapNullableUnionTypes($returnedStrictTypes); - $returnType = new PhpParserUnionType($unwrappedTypes); + $returnType = new \PhpParser\Node\UnionType($unwrappedTypes); $node->returnType = $returnType; return $node; } - return null; } - /** * @param ClassMethod|Function_|Closure $node */ - private function processSingleUnionType(Node $node, UnionType $unionType, NullableType $nullableType): FunctionLike + private function processSingleUnionType(\PhpParser\Node $node, \PHPStan\Type\UnionType $unionType, \PhpParser\Node\NullableType $nullableType) : \PhpParser\Node\FunctionLike { $types = $unionType->getTypes(); - $returnType = $types[0] instanceof ObjectType && $types[1] instanceof NullType - ? new NullableType(new FullyQualified($types[0]->getClassName())) - : $nullableType; - + $returnType = $types[0] instanceof \PHPStan\Type\ObjectType && $types[1] instanceof \PHPStan\Type\NullType ? new \PhpParser\Node\NullableType(new \PhpParser\Node\Name\FullyQualified($types[0]->getClassName())) : $nullableType; $node->returnType = $returnType; return $node; } - /** * @param ClassMethod|Function_|Closure $node */ - private function isSkipped(Node $node): bool + private function isSkipped(\PhpParser\Node $node) : bool { - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::SCALAR_TYPES)) { - return true; + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SCALAR_TYPES)) { + return \true; } - if ($node->returnType !== null) { - return true; + return \true; } - - return $node instanceof ClassMethod && $node->isMagic(); + return $node instanceof \PhpParser\Node\Stmt\ClassMethod && $node->isMagic(); } - /** * @param Return_[] $returns * @return array */ - private function collectStrictReturnTypes(array $returns): array + private function collectStrictReturnTypes(array $returns) : array { $returnedStrictTypeNodes = []; - foreach ($returns as $return) { if ($return->expr === null) { return []; } - $returnedExpr = $return->expr; - - if ($returnedExpr instanceof MethodCall) { + if ($returnedExpr instanceof \PhpParser\Node\Expr\MethodCall) { $returnNode = $this->resolveMethodCallReturnNode($returnedExpr); - } elseif ($returnedExpr instanceof StaticCall) { + } elseif ($returnedExpr instanceof \PhpParser\Node\Expr\StaticCall) { $returnNode = $this->resolveStaticCallReturnNode($returnedExpr); - } elseif ($returnedExpr instanceof FuncCall) { + } elseif ($returnedExpr instanceof \PhpParser\Node\Expr\FuncCall) { $returnNode = $this->resolveFuncCallReturnNode($returnedExpr); } else { return []; } - - if (! $returnNode instanceof Node) { + if (!$returnNode instanceof \PhpParser\Node) { return []; } - $returnedStrictTypeNodes[] = $returnNode; } - return $this->typeNodeUnwrapper->uniquateNodes($returnedStrictTypeNodes); } - - private function resolveMethodCallReturnNode(MethodCall $methodCall): ?Node + private function resolveMethodCallReturnNode(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node { $classMethod = $this->nodeRepository->findClassMethodByMethodCall($methodCall); - if ($classMethod instanceof ClassMethod) { + if ($classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return $classMethod->returnType; } - $returnType = $this->reflectionTypeResolver->resolveMethodCallReturnType($methodCall); - if (! $returnType instanceof Type) { + if (!$returnType instanceof \PHPStan\Type\Type) { return null; } - return $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($returnType); } - - private function resolveStaticCallReturnNode(StaticCall $staticCall): ?Node + private function resolveStaticCallReturnNode(\PhpParser\Node\Expr\StaticCall $staticCall) : ?\PhpParser\Node { $classMethod = $this->nodeRepository->findClassMethodByStaticCall($staticCall); - if ($classMethod instanceof ClassMethod) { + if ($classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return $classMethod->returnType; } - $returnType = $this->reflectionTypeResolver->resolveStaticCallReturnType($staticCall); - if (! $returnType instanceof Type) { + if (!$returnType instanceof \PHPStan\Type\Type) { return null; } - return $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($returnType); } - /** * @return Name|NullableType|PhpParserUnionType|null */ - private function resolveFuncCallReturnNode(FuncCall $funcCall): ?Node + private function resolveFuncCallReturnNode(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PhpParser\Node { $returnType = $this->reflectionTypeResolver->resolveFuncCallReturnType($funcCall); - if (! $returnType instanceof Type) { + if (!$returnType instanceof \PHPStan\Type\Type) { return null; } - return $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($returnType); } - /** * @param ClassMethod|Function_|Closure $functionLike * @param Name|NullableType|PhpParserUnionType $returnedStrictTypeNode */ - private function refactorSingleReturnType( - Return_ $return, - Node $returnedStrictTypeNode, - FunctionLike $functionLike - ): FunctionLike { + private function refactorSingleReturnType(\PhpParser\Node\Stmt\Return_ $return, \PhpParser\Node $returnedStrictTypeNode, \PhpParser\Node\FunctionLike $functionLike) : \PhpParser\Node\FunctionLike + { $resolvedType = $this->nodeTypeResolver->resolve($return); - - if ($resolvedType instanceof UnionType) { - if (! $returnedStrictTypeNode instanceof NullableType) { - throw new ShouldNotHappenException(); + if ($resolvedType instanceof \PHPStan\Type\UnionType) { + if (!$returnedStrictTypeNode instanceof \PhpParser\Node\NullableType) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - return $this->processSingleUnionType($functionLike, $resolvedType, $returnedStrictTypeNode); } - /** @var Name $returnType */ - $returnType = $resolvedType instanceof ObjectType - ? new FullyQualified($resolvedType->getClassName()) - : $returnedStrictTypeNode; - + $returnType = $resolvedType instanceof \PHPStan\Type\ObjectType ? new \PhpParser\Node\Name\FullyQualified($resolvedType->getClassName()) : $returnedStrictTypeNode; $functionLike->returnType = $returnType; - return $functionLike; } } diff --git a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictTypedPropertyRector.php b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictTypedPropertyRector.php index 09e767eb3a2..fc4569d1a63 100644 --- a/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictTypedPropertyRector.php +++ b/rules/TypeDeclaration/Rector/ClassMethod/ReturnTypeFromStrictTypedPropertyRector.php @@ -1,7 +1,6 @@ typeFactory = $typeFactory; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add return method return type based on strict typed property', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add return method return type based on strict typed property', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { private int $age = 100; @@ -50,9 +44,7 @@ final class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { private int $age = 100; @@ -63,87 +55,70 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::TYPED_PROPERTIES)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::TYPED_PROPERTIES)) { return null; } - if ($node->returnType !== null) { return null; } - $propertyTypeNodes = $this->resolveReturnPropertyTypeNodes($node); if ($propertyTypeNodes === []) { return null; } - $propertyTypes = []; foreach ($propertyTypeNodes as $propertyTypeNode) { $propertyTypes[] = $this->staticTypeMapper->mapPhpParserNodePHPStanType($propertyTypeNode); } - // add type to return type $propertyType = $this->typeFactory->createMixedPassedOrUnionType($propertyTypes); - if ($propertyType instanceof MixedType) { + if ($propertyType instanceof \PHPStan\Type\MixedType) { return null; } - $propertyTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($propertyType); - if (! $propertyTypeNode instanceof Node) { + if (!$propertyTypeNode instanceof \PhpParser\Node) { return null; } - $node->returnType = $propertyTypeNode; - return $node; } - /** * @return array */ - private function resolveReturnPropertyTypeNodes(ClassMethod $classMethod): array + private function resolveReturnPropertyTypeNodes(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { /** @var Return_[] $returns */ - $returns = $this->betterNodeFinder->findInstanceOf($classMethod, Return_::class); - + $returns = $this->betterNodeFinder->findInstanceOf($classMethod, \PhpParser\Node\Stmt\Return_::class); $propertyTypes = []; foreach ($returns as $return) { if ($return->expr === null) { return []; } - - if (! $return->expr instanceof PropertyFetch) { + if (!$return->expr instanceof \PhpParser\Node\Expr\PropertyFetch) { return []; } - $property = $this->nodeRepository->findPropertyByPropertyFetch($return->expr); - if (! $property instanceof Property) { + if (!$property instanceof \PhpParser\Node\Stmt\Property) { return []; } - if ($property->type === null) { return []; } - $propertyTypes[] = $property->type; } - return $propertyTypes; } } diff --git a/rules/TypeDeclaration/Rector/Closure/AddClosureReturnTypeRector.php b/rules/TypeDeclaration/Rector/Closure/AddClosureReturnTypeRector.php index 14ded7b7c8d..391c7575753 100644 --- a/rules/TypeDeclaration/Rector/Closure/AddClosureReturnTypeRector.php +++ b/rules/TypeDeclaration/Rector/Closure/AddClosureReturnTypeRector.php @@ -1,7 +1,6 @@ returnTypeInferer = $returnTypeInferer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add known return type to functions', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add known return type to functions', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run($meetups) @@ -44,8 +38,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function run($meetups) @@ -56,45 +49,36 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Closure::class]; + return [\PhpParser\Node\Expr\Closure::class]; } - /** * @param Closure $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::SCALAR_TYPES)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SCALAR_TYPES)) { return null; } - if ($node->returnType !== null) { return null; } - - $scope = $node->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $inferedReturnType = $this->returnTypeInferer->inferFunctionLike($node); - $returnTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($inferedReturnType); - if (! $returnTypeNode instanceof Node) { + if (!$returnTypeNode instanceof \PhpParser\Node) { return null; } - $node->returnType = $returnTypeNode; - return $node; } } diff --git a/rules/TypeDeclaration/Rector/FunctionLike/ParamTypeDeclarationRector.php b/rules/TypeDeclaration/Rector/FunctionLike/ParamTypeDeclarationRector.php index 807a606aa4a..26c6b72f029 100644 --- a/rules/TypeDeclaration/Rector/FunctionLike/ParamTypeDeclarationRector.php +++ b/rules/TypeDeclaration/Rector/FunctionLike/ParamTypeDeclarationRector.php @@ -1,7 +1,6 @@ paramTypeInferer = $paramTypeInferer; $this->childParamPopulator = $childParamPopulator; $this->traitTypeAnalyzer = $traitTypeAnalyzer; $this->paramTagRemover = $paramTagRemover; $this->vendorLockResolver = $vendorLockResolver; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, ClassMethod::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change @param types to type declarations if not a BC-break', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change @param types to type declarations if not a BC-break', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class ParentClass { /** @@ -115,8 +97,7 @@ final class ChildClass extends ParentClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class ParentClass { /** @@ -141,87 +122,65 @@ final class ChildClass extends ParentClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param ClassMethod|Function_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::SCALAR_TYPES)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SCALAR_TYPES)) { return null; } - if ($node->params === []) { return null; } - foreach ($node->params as $position => $param) { $this->refactorParam($param, $node, (int) $position); } - return null; } - /** * @param ClassMethod|Function_ $functionLike */ - private function refactorParam(Param $param, FunctionLike $functionLike, int $position): void + private function refactorParam(\PhpParser\Node\Param $param, \PhpParser\Node\FunctionLike $functionLike, int $position) : void { if ($this->shouldSkipParam($param, $functionLike)) { return; } - $inferedType = $this->paramTypeInferer->inferParam($param); - if ($inferedType instanceof MixedType) { + if ($inferedType instanceof \PHPStan\Type\MixedType) { return; } - if ($this->traitTypeAnalyzer->isTraitType($inferedType)) { return; } - - $paramTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode( - $inferedType, - TypeKind::KIND_PARAM - ); - - if (! $paramTypeNode instanceof Node) { + $paramTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($inferedType, \Rector\PHPStanStaticTypeMapper\ValueObject\TypeKind::KIND_PARAM); + if (!$paramTypeNode instanceof \PhpParser\Node) { return; } - - $parentNode = $functionLike->getAttribute(AttributeKey::PARENT_NODE); - if ($parentNode instanceof Interface_ && $parentNode->extends !== []) { + $parentNode = $functionLike->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Stmt\Interface_ && $parentNode->extends !== []) { return; } - $param->type = $paramTypeNode; - $functionLikePhpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($functionLike); $this->paramTagRemover->removeParamTagsIfUseless($functionLikePhpDocInfo, $functionLike); - $this->childParamPopulator->populateChildClassMethod($functionLike, $position, $inferedType); } - - private function shouldSkipParam(Param $param, FunctionLike $functionLike): bool + private function shouldSkipParam(\PhpParser\Node\Param $param, \PhpParser\Node\FunctionLike $functionLike) : bool { if ($param->variadic) { - return true; + return \true; } - if ($this->vendorLockResolver->isClassMethodParamLockedIn($functionLike)) { - return true; + return \true; } - // no type → check it if ($param->type === null) { - return false; + return \false; } - // already set → skip - return ! $param->type->getAttribute(NewType::HAS_NEW_INHERITED_TYPE, false); + return !$param->type->getAttribute(\Rector\TypeDeclaration\ValueObject\NewType::HAS_NEW_INHERITED_TYPE, \false); } } diff --git a/rules/TypeDeclaration/Rector/FunctionLike/ReturnTypeDeclarationRector.php b/rules/TypeDeclaration/Rector/FunctionLike/ReturnTypeDeclarationRector.php index 5961ad5d79e..010f04a2366 100644 --- a/rules/TypeDeclaration/Rector/FunctionLike/ReturnTypeDeclarationRector.php +++ b/rules/TypeDeclaration/Rector/FunctionLike/ReturnTypeDeclarationRector.php @@ -1,7 +1,6 @@ returnTypeInferer = $returnTypeInferer; $this->returnTypeAlreadyAddedChecker = $returnTypeAlreadyAddedChecker; $this->nonInformativeReturnTagRemover = $nonInformativeReturnTagRemover; @@ -97,22 +79,16 @@ final class ReturnTypeDeclarationRector extends AbstractRector $this->phpParserTypeAnalyzer = $phpParserTypeAnalyzer; $this->objectTypeComparator = $objectTypeComparator; } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Function_::class, ClassMethod::class]; + return [\PhpParser\Node\Stmt\Function_::class, \PhpParser\Node\Stmt\ClassMethod::class]; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change @return types and type from static analysis to type declarations if not a BC-break', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change @return types and type from static analysis to type declarations if not a BC-break', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { /** @@ -123,8 +99,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { public function getCount(): int @@ -132,169 +107,127 @@ class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @param ClassMethod|Function_ $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::SCALAR_TYPES)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::SCALAR_TYPES)) { return null; } - if ($this->shouldSkipClassLike($node)) { return null; } - - if ($node instanceof ClassMethod && $this->shouldSkipClassMethod($node)) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod && $this->shouldSkipClassMethod($node)) { return null; } - - $inferedReturnType = $this->returnTypeInferer->inferFunctionLikeWithExcludedInferers( - $node, - [ReturnTypeDeclarationReturnTypeInferer::class] - ); - - if ($inferedReturnType instanceof MixedType) { + $inferedReturnType = $this->returnTypeInferer->inferFunctionLikeWithExcludedInferers($node, [\Rector\TypeDeclaration\TypeInferer\ReturnTypeInferer\ReturnTypeDeclarationReturnTypeInferer::class]); + if ($inferedReturnType instanceof \PHPStan\Type\MixedType) { return null; } - if ($this->returnTypeAlreadyAddedChecker->isSameOrBetterReturnTypeAlreadyAdded($node, $inferedReturnType)) { return null; } - return $this->processType($node, $inferedReturnType); } - /** * @param ClassMethod|Function_ $node */ - private function processType(Node $node, Type $inferedType): ?Node + private function processType(\PhpParser\Node $node, \PHPStan\Type\Type $inferedType) : ?\PhpParser\Node { - $inferredReturnNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode( - $inferedType, - TypeKind::KIND_RETURN - ); - + $inferredReturnNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($inferedType, \Rector\PHPStanStaticTypeMapper\ValueObject\TypeKind::KIND_RETURN); // nothing to change in PHP code - if (! $inferredReturnNode instanceof Node) { + if (!$inferredReturnNode instanceof \PhpParser\Node) { return null; } - if ($this->shouldSkipInferredReturnNode($node)) { return null; } - // should be previous overridden? if ($node->returnType !== null && $this->shouldSkipExistingReturnType($node, $inferedType)) { return null; } - /** @var Name|NullableType|PhpParserUnionType $inferredReturnNode */ $this->addReturnType($node, $inferredReturnNode); - $this->nonInformativeReturnTagRemover->removeReturnTagIfNotUseful($node); - - if ($node instanceof ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { $this->childReturnPopulator->populateChildren($node, $inferedType); } - return $node; } - - private function shouldSkipClassMethod(ClassMethod $classMethod): bool + private function shouldSkipClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { if ($this->classMethodReturnTypeOverrideGuard->shouldSkipClassMethod($classMethod)) { - return true; + return \true; } - return $this->vendorLockResolver->isReturnChangeVendorLockedIn($classMethod); } - /** * @param ClassMethod|Function_ $functionLike */ - private function shouldSkipInferredReturnNode(FunctionLike $functionLike): bool + private function shouldSkipInferredReturnNode(\PhpParser\Node\FunctionLike $functionLike) : bool { // already overridden by previous populateChild() method run if ($functionLike->returnType === null) { - return false; + return \false; } - - return (bool) $functionLike->returnType->getAttribute(AttributeKey::DO_NOT_CHANGE); + return (bool) $functionLike->returnType->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::DO_NOT_CHANGE); } - /** * @param ClassMethod|Function_ $functionLike */ - private function shouldSkipExistingReturnType(FunctionLike $functionLike, Type $inferedType): bool + private function shouldSkipExistingReturnType(\PhpParser\Node\FunctionLike $functionLike, \PHPStan\Type\Type $inferedType) : bool { if ($functionLike->returnType === null) { - return false; + return \false; } - - if ($functionLike instanceof ClassMethod && $this->vendorLockResolver->isReturnChangeVendorLockedIn( - $functionLike - )) { - return true; + if ($functionLike instanceof \PhpParser\Node\Stmt\ClassMethod && $this->vendorLockResolver->isReturnChangeVendorLockedIn($functionLike)) { + return \true; } - $currentType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($functionLike->returnType); if ($this->objectTypeComparator->isCurrentObjectTypeSubType($currentType, $inferedType)) { - return true; + return \true; } - return $this->isNullableTypeSubType($currentType, $inferedType); } - /** * @param ClassMethod|Function_ $functionLike * @param Name|NullableType|PhpParserUnionType $inferredReturnNode */ - private function addReturnType(FunctionLike $functionLike, Node $inferredReturnNode): void + private function addReturnType(\PhpParser\Node\FunctionLike $functionLike, \PhpParser\Node $inferredReturnNode) : void { if ($functionLike->returnType === null) { $functionLike->returnType = $inferredReturnNode; return; } - $isSubtype = $this->phpParserTypeAnalyzer->isCovariantSubtypeOf($inferredReturnNode, $functionLike->returnType); - if ($this->isAtLeastPhpVersion(PhpVersionFeature::COVARIANT_RETURN) && $isSubtype) { + if ($this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::COVARIANT_RETURN) && $isSubtype) { $functionLike->returnType = $inferredReturnNode; return; } - - if (! $isSubtype) { + if (!$isSubtype) { // type override with correct one $functionLike->returnType = $inferredReturnNode; } } - - private function isNullableTypeSubType(Type $currentType, Type $inferedType): bool + private function isNullableTypeSubType(\PHPStan\Type\Type $currentType, \PHPStan\Type\Type $inferedType) : bool { - if (! $currentType instanceof UnionType) { - return false; + if (!$currentType instanceof \PHPStan\Type\UnionType) { + return \false; } - - if (! $inferedType instanceof UnionType) { - return false; + if (!$inferedType instanceof \PHPStan\Type\UnionType) { + return \false; } - - return $inferedType->isSubTypeOf($currentType) - ->yes(); + return $inferedType->isSubTypeOf($currentType)->yes(); } - - private function shouldSkipClassLike(FunctionLike $functionLike): bool + private function shouldSkipClassLike(\PhpParser\Node\FunctionLike $functionLike) : bool { - if (! $functionLike instanceof ClassMethod) { - return false; + if (!$functionLike instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - - $classLike = $functionLike->getAttribute(AttributeKey::CLASS_NODE); - return ! $classLike instanceof Class_; + $classLike = $functionLike->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + return !$classLike instanceof \PhpParser\Node\Stmt\Class_; } } diff --git a/rules/TypeDeclaration/Rector/MethodCall/FormerNullableArgumentToScalarTypedRector.php b/rules/TypeDeclaration/Rector/MethodCall/FormerNullableArgumentToScalarTypedRector.php index 13a033a04c4..1a869e1a64b 100644 --- a/rules/TypeDeclaration/Rector/MethodCall/FormerNullableArgumentToScalarTypedRector.php +++ b/rules/TypeDeclaration/Rector/MethodCall/FormerNullableArgumentToScalarTypedRector.php @@ -1,7 +1,6 @@ callTypeAnalyzer = $callTypeAnalyzer; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change null in argument, that is now not nullable anymore', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change null in argument, that is now not nullable anymore', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -55,8 +47,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { public function run() @@ -69,68 +60,55 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [MethodCall::class, StaticCall::class]; + return [\PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\StaticCall::class]; } - /** * @param MethodCall|StaticCall $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { if ($node->args === []) { return null; } - $methodParameterTypes = $this->callTypeAnalyzer->resolveMethodParameterTypes($node); if ($methodParameterTypes === []) { return null; } - foreach ($node->args as $key => $arg) { - if (! $this->valueResolver->isNull($arg->value)) { + if (!$this->valueResolver->isNull($arg->value)) { continue; } - /** @var int $key */ $this->refactorArg($arg, $methodParameterTypes, $key); } - return $node; } - /** * @param Type[] $methodParameterTypes */ - private function refactorArg(Arg $arg, array $methodParameterTypes, int $key): void + private function refactorArg(\PhpParser\Node\Arg $arg, array $methodParameterTypes, int $key) : void { - if (! isset($methodParameterTypes[$key])) { + if (!isset($methodParameterTypes[$key])) { return; } - $parameterType = $methodParameterTypes[$key]; - if ($parameterType instanceof StringType) { - $arg->value = new String_(''); + if ($parameterType instanceof \PHPStan\Type\StringType) { + $arg->value = new \PhpParser\Node\Scalar\String_(''); } - - if ($parameterType instanceof IntegerType) { - $arg->value = new LNumber(0); + if ($parameterType instanceof \PHPStan\Type\IntegerType) { + $arg->value = new \PhpParser\Node\Scalar\LNumber(0); } - - if ($parameterType instanceof FloatType) { - $arg->value = new DNumber(0); + if ($parameterType instanceof \PHPStan\Type\FloatType) { + $arg->value = new \PhpParser\Node\Scalar\DNumber(0); } - - if ($parameterType instanceof BooleanType) { + if ($parameterType instanceof \PHPStan\Type\BooleanType) { $arg->value = $this->nodeFactory->createFalse(); } } diff --git a/rules/TypeDeclaration/Rector/Param/ParamTypeFromStrictTypedPropertyRector.php b/rules/TypeDeclaration/Rector/Param/ParamTypeFromStrictTypedPropertyRector.php index cecb8600401..359739924fe 100644 --- a/rules/TypeDeclaration/Rector/Param/ParamTypeFromStrictTypedPropertyRector.php +++ b/rules/TypeDeclaration/Rector/Param/ParamTypeFromStrictTypedPropertyRector.php @@ -1,7 +1,6 @@ reflectionTypeResolver = $reflectionTypeResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add param type from $param set to typed property', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add param type from $param set to typed property', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { private int $age; @@ -52,9 +46,7 @@ final class SomeClass } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { private int $age; @@ -65,135 +57,108 @@ final class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Param::class]; + return [\PhpParser\Node\Param::class]; } - /** * @param Param $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::TYPED_PROPERTIES)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::TYPED_PROPERTIES)) { return null; } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof FunctionLike) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\FunctionLike) { return null; } - return $this->decorateParamWithType($parent, $node); } - - public function decorateParamWithType(FunctionLike $functionLike, Param $param): ?Param + public function decorateParamWithType(\PhpParser\Node\FunctionLike $functionLike, \PhpParser\Node\Param $param) : ?\PhpParser\Node\Param { if ($param->type !== null) { return null; } - $originalParamType = $this->resolveParamOriginalType($param); - $paramName = $this->getName($param); - /** @var Assign[] $assigns */ - $assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->getStmts(), Assign::class); + $assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->getStmts(), \PhpParser\Node\Expr\Assign::class); foreach ($assigns as $assign) { - if (! $this->nodeComparator->areNodesEqual($assign->expr, $param->var)) { + if (!$this->nodeComparator->areNodesEqual($assign->expr, $param->var)) { continue; } - - if (! $assign->var instanceof PropertyFetch) { + if (!$assign->var instanceof \PhpParser\Node\Expr\PropertyFetch) { continue; } - if ($this->hasTypeChangedBeforeAssign($assign, $paramName, $originalParamType)) { return null; } - $singlePropertyTypeNode = $this->matchPropertySingleTypeNode($assign->var); - if (! $singlePropertyTypeNode instanceof Node) { + if (!$singlePropertyTypeNode instanceof \PhpParser\Node) { return null; } - $param->type = $singlePropertyTypeNode; return $param; } - return null; } - /** * @return Node\Identifier|Node\Name|UnionType|NullableType|null */ - private function matchPropertySingleTypeNode(PropertyFetch $propertyFetch): ?Node + private function matchPropertySingleTypeNode(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : ?\PhpParser\Node { $property = $this->nodeRepository->findPropertyByPropertyFetch($propertyFetch); - if (! $property instanceof Property) { + if (!$property instanceof \PhpParser\Node\Stmt\Property) { // code from /vendor $propertyFetchType = $this->reflectionTypeResolver->resolvePropertyFetchType($propertyFetch); - if (! $propertyFetchType instanceof Type) { + if (!$propertyFetchType instanceof \PHPStan\Type\Type) { return null; } - return $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($propertyFetchType); } - if ($property->type === null) { return null; } - // move type to param if not union type - if ($property->type instanceof UnionType) { + if ($property->type instanceof \PhpParser\Node\UnionType) { return null; } - - if ($property->type instanceof NullableType) { + if ($property->type instanceof \PhpParser\Node\NullableType) { return null; } - // needed to avoid reprinting original tokens bug $typeNode = clone $property->type; - $typeNode->setAttribute(AttributeKey::ORIGINAL_NODE, null); - + $typeNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE, null); return $typeNode; } - - private function hasTypeChangedBeforeAssign(Assign $assign, string $paramName, Type $originalType): bool + private function hasTypeChangedBeforeAssign(\PhpParser\Node\Expr\Assign $assign, string $paramName, \PHPStan\Type\Type $originalType) : bool { - $scope = $assign->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - - if (! $scope->hasVariableType($paramName)->yes()) { - return false; + if (!$scope->hasVariableType($paramName)->yes()) { + return \false; } - $currentParamType = $scope->getVariableType($paramName); - return ! $currentParamType->equals($originalType); + return !$currentParamType->equals($originalType); } - - private function resolveParamOriginalType(Param $param): Type + private function resolveParamOriginalType(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { - $scope = $param->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return new MixedType(); + $scope = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return new \PHPStan\Type\MixedType(); } - $paramName = $this->getName($param); - if (! $scope->hasVariableType($paramName)->yes()) { - return new MixedType(); + if (!$scope->hasVariableType($paramName)->yes()) { + return new \PHPStan\Type\MixedType(); } - return $scope->getVariableType($paramName); } } diff --git a/rules/TypeDeclaration/Rector/Property/CompleteVarDocTypePropertyRector.php b/rules/TypeDeclaration/Rector/Property/CompleteVarDocTypePropertyRector.php index d1c6bae5105..172eec4b985 100644 --- a/rules/TypeDeclaration/Rector/Property/CompleteVarDocTypePropertyRector.php +++ b/rules/TypeDeclaration/Rector/Property/CompleteVarDocTypePropertyRector.php @@ -1,7 +1,6 @@ propertyTypeInferer = $propertyTypeInferer; $this->phpDocTypeChanger = $phpDocTypeChanger; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Complete property `@var` annotations or correct the old ones', - [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Complete property `@var` annotations or correct the old ones', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' final class SomeClass { private $eventDispatcher; @@ -52,8 +43,7 @@ final class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' final class SomeClass { /** @@ -67,36 +57,29 @@ final class SomeClass } } CODE_SAMPLE - ), - ] - ); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $propertyType = $this->propertyTypeInferer->inferProperty($node); - if ($propertyType instanceof MixedType) { + if ($propertyType instanceof \PHPStan\Type\MixedType) { return null; } - - if (! $node->isPrivate() && $propertyType instanceof NullType) { + if (!$node->isPrivate() && $propertyType instanceof \PHPStan\Type\NullType) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); $this->phpDocTypeChanger->changeVarType($phpDocInfo, $propertyType); - return $node; } } diff --git a/rules/TypeDeclaration/Rector/Property/PropertyTypeDeclarationRector.php b/rules/TypeDeclaration/Rector/Property/PropertyTypeDeclarationRector.php index 66c4326e139..24b57d7097d 100644 --- a/rules/TypeDeclaration/Rector/Property/PropertyTypeDeclarationRector.php +++ b/rules/TypeDeclaration/Rector/Property/PropertyTypeDeclarationRector.php @@ -1,7 +1,6 @@ propertyTypeInferer = $propertyTypeInferer; $this->phpDocTypeChanger = $phpDocTypeChanger; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add @var to properties that are missing it', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add @var to properties that are missing it', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { private $value; @@ -50,8 +43,7 @@ class SomeClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeClass { /** @@ -65,49 +57,39 @@ class SomeClass } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (count($node->props) !== 1) { + if (\count($node->props) !== 1) { return null; } - if ($node->type !== null) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - // is already set - if (! $phpDocInfo->getVarType() instanceof MixedType) { + if (!$phpDocInfo->getVarType() instanceof \PHPStan\Type\MixedType) { return null; } - $type = $this->propertyTypeInferer->inferProperty($node); - if ($type instanceof MixedType) { + if ($type instanceof \PHPStan\Type\MixedType) { return null; } - - if (! $node->isPrivate() && $type instanceof NullType) { + if (!$node->isPrivate() && $type instanceof \PHPStan\Type\NullType) { return null; } - $this->phpDocTypeChanger->changeVarType($phpDocInfo, $type); - return $node; } } diff --git a/rules/TypeDeclaration/Rector/Property/TypedPropertyFromStrictConstructorRector.php b/rules/TypeDeclaration/Rector/Property/TypedPropertyFromStrictConstructorRector.php index f263236112c..6205bab54e2 100644 --- a/rules/TypeDeclaration/Rector/Property/TypedPropertyFromStrictConstructorRector.php +++ b/rules/TypeDeclaration/Rector/Property/TypedPropertyFromStrictConstructorRector.php @@ -1,7 +1,6 @@ constructorPropertyTypeInferer = $constructorPropertyTypeInferer; $this->varTagRemover = $varTagRemover; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition('Add typed properties based only on strict constructor types', [ - new CodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Add typed properties based only on strict constructor types', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeObject { private $name; @@ -53,9 +44,7 @@ class SomeObject } } CODE_SAMPLE - - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class SomeObject { private string $name; @@ -66,50 +55,37 @@ class SomeObject } } CODE_SAMPLE - ), - ]); +)]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - if (! $this->isAtLeastPhpVersion(PhpVersionFeature::TYPED_PROPERTIES)) { + if (!$this->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::TYPED_PROPERTIES)) { return null; } - if ($node->type !== null) { return null; } - $varType = $this->constructorPropertyTypeInferer->inferProperty($node); - if ($varType instanceof MixedType) { + if ($varType instanceof \PHPStan\Type\MixedType) { return null; } - - $propertyTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode( - $varType, - TypeKind::KIND_PROPERTY - ); - - if (! $propertyTypeNode instanceof Node) { + $propertyTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($varType, \Rector\PHPStanStaticTypeMapper\ValueObject\TypeKind::KIND_PROPERTY); + if (!$propertyTypeNode instanceof \PhpParser\Node) { return null; } - $node->type = $propertyTypeNode; - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); $this->varTagRemover->removeVarTagIfUseless($phpDocInfo, $node); - return $node; } } diff --git a/rules/TypeDeclaration/Reflection/ReflectionTypeResolver.php b/rules/TypeDeclaration/Reflection/ReflectionTypeResolver.php index 601dcf126e0..b6130044170 100644 --- a/rules/TypeDeclaration/Reflection/ReflectionTypeResolver.php +++ b/rules/TypeDeclaration/Reflection/ReflectionTypeResolver.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->reflectionProvider = $reflectionProvider; $this->nodeNameResolver = $nodeNameResolver; $this->privatesCaller = $privatesCaller; } - - public function resolveMethodCallReturnType(MethodCall $methodCall): ?Type + public function resolveMethodCallReturnType(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PHPStan\Type\Type { $objectType = $this->nodeTypeResolver->resolve($methodCall->var); - if (! $objectType instanceof TypeWithClassName) { + if (!$objectType instanceof \PHPStan\Type\TypeWithClassName) { return null; } - $methodName = $this->nodeNameResolver->getName($methodCall->name); if ($methodName === null) { return null; } - return $this->resolveNativeReturnTypeFromClassAndMethod($objectType->getClassName(), $methodName, $methodCall); } - - public function resolveStaticCallReturnType(StaticCall $staticCall): ?Type + public function resolveStaticCallReturnType(\PhpParser\Node\Expr\StaticCall $staticCall) : ?\PHPStan\Type\Type { $className = $this->nodeNameResolver->getName($staticCall->class); if ($className === null) { return null; } - $methodName = $this->nodeNameResolver->getName($staticCall->name); if ($methodName === null) { return null; } - return $this->resolveNativeReturnTypeFromClassAndMethod($className, $methodName, $staticCall); } - - public function resolvePropertyFetchType(PropertyFetch $propertyFetch): ?Type + public function resolvePropertyFetchType(\PhpParser\Node\Expr\PropertyFetch $propertyFetch) : ?\PHPStan\Type\Type { $objectType = $this->nodeTypeResolver->resolve($propertyFetch->var); - if (! $objectType instanceof TypeWithClassName) { + if (!$objectType instanceof \PHPStan\Type\TypeWithClassName) { return null; } - $classReflection = $this->reflectionProvider->getClass($objectType->getClassName()); $propertyName = $this->nodeNameResolver->getName($propertyFetch); if ($propertyName === null) { return null; } - if ($classReflection->hasProperty($propertyName)) { - $propertyFetchScope = $propertyFetch->getAttribute(AttributeKey::SCOPE); + $propertyFetchScope = $propertyFetch->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); $propertyReflection = $classReflection->getProperty($propertyName, $propertyFetchScope); - - if ($propertyReflection instanceof PhpPropertyReflection) { + if ($propertyReflection instanceof \PHPStan\Reflection\Php\PhpPropertyReflection) { return $propertyReflection->getNativeType(); } } - return null; } - - public function resolveFuncCallReturnType(FuncCall $funcCall): ?Type + public function resolveFuncCallReturnType(\PhpParser\Node\Expr\FuncCall $funcCall) : ?\PHPStan\Type\Type { - $funcCallScope = $funcCall->getAttribute(AttributeKey::SCOPE); - + $funcCallScope = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); $funcCallName = $funcCall->name; - if ($funcCallName instanceof Expr) { + if ($funcCallName instanceof \PhpParser\Node\Expr) { return null; } - - if (! $this->reflectionProvider->hasFunction($funcCallName, $funcCallScope)) { + if (!$this->reflectionProvider->hasFunction($funcCallName, $funcCallScope)) { return null; } - $functionReflection = $this->reflectionProvider->getFunction($funcCallName, $funcCallScope); - if (! $functionReflection instanceof PhpFunctionReflection) { + if (!$functionReflection instanceof \PHPStan\Reflection\Php\PhpFunctionReflection) { return null; } - return $this->privatesCaller->callPrivateMethod($functionReflection, 'getNativeReturnType', []); } - - private function resolveNativeReturnTypeFromClassAndMethod(string $className, string $methodName, Expr $expr): ?Type + private function resolveNativeReturnTypeFromClassAndMethod(string $className, string $methodName, \PhpParser\Node\Expr $expr) : ?\PHPStan\Type\Type { - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return null; } - $classReflection = $this->reflectionProvider->getClass($className); - if (! $classReflection->hasMethod($methodName)) { + if (!$classReflection->hasMethod($methodName)) { return null; } - - $callerScope = $expr->getAttribute(AttributeKey::SCOPE); - + $callerScope = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); // probably trait - if (! $callerScope instanceof Scope) { + if (!$callerScope instanceof \PHPStan\Analyser\Scope) { return null; } - $methodReflection = $classReflection->getMethod($methodName, $callerScope); - if (! $methodReflection instanceof PhpMethodReflection) { + if (!$methodReflection instanceof \PHPStan\Reflection\Php\PhpMethodReflection) { return null; } - return $this->privatesCaller->callPrivateMethod($methodReflection, 'getNativeReturnType', []); } } diff --git a/rules/TypeDeclaration/Sorter/TypeInfererSorter.php b/rules/TypeDeclaration/Sorter/TypeInfererSorter.php index 23779b3a44d..c6b182c7e59 100644 --- a/rules/TypeDeclaration/Sorter/TypeInfererSorter.php +++ b/rules/TypeDeclaration/Sorter/TypeInfererSorter.php @@ -1,44 +1,35 @@ ensurePriorityIsUnique($sortedTypeInferers, $priorityAwareTypeInferer); $sortedTypeInferers[$priorityAwareTypeInferer->getPriority()] = $priorityAwareTypeInferer; } - - krsort($sortedTypeInferers); - + \krsort($sortedTypeInferers); return $sortedTypeInferers; } - /** * @param PriorityAwareTypeInfererInterface[] $sortedTypeInferers */ - private function ensurePriorityIsUnique( - array $sortedTypeInferers, - PriorityAwareTypeInfererInterface $priorityAwareTypeInferer - ): void { - if (! isset($sortedTypeInferers[$priorityAwareTypeInferer->getPriority()])) { + private function ensurePriorityIsUnique(array $sortedTypeInferers, \Rector\TypeDeclaration\Contract\TypeInferer\PriorityAwareTypeInfererInterface $priorityAwareTypeInferer) : void + { + if (!isset($sortedTypeInferers[$priorityAwareTypeInferer->getPriority()])) { return; } - $alreadySetPropertyTypeInferer = $sortedTypeInferers[$priorityAwareTypeInferer->getPriority()]; - throw new ConflictingPriorityException($priorityAwareTypeInferer, $alreadySetPropertyTypeInferer); + throw new \Rector\TypeDeclaration\Exception\ConflictingPriorityException($priorityAwareTypeInferer, $alreadySetPropertyTypeInferer); } } diff --git a/rules/TypeDeclaration/TypeAlreadyAddedChecker/ReturnTypeAlreadyAddedChecker.php b/rules/TypeDeclaration/TypeAlreadyAddedChecker/ReturnTypeAlreadyAddedChecker.php index 88e1e11d740..448ac6a59db 100644 --- a/rules/TypeDeclaration/TypeAlreadyAddedChecker/ReturnTypeAlreadyAddedChecker.php +++ b/rules/TypeDeclaration/TypeAlreadyAddedChecker/ReturnTypeAlreadyAddedChecker.php @@ -1,7 +1,6 @@ [] */ private const FOREACHABLE_TYPES = ['iterable', 'Iterator', 'Traversable', 'array']; - /** * @var StaticTypeMapper */ private $staticTypeMapper; - /** * @var NodeComparator */ private $nodeComparator; - /** * @var NodeNameResolver */ private $nodeNameResolver; - - public function __construct( - NodeNameResolver $nodeNameResolver, - StaticTypeMapper $staticTypeMapper, - NodeComparator $nodeComparator - ) { + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\StaticTypeMapper\StaticTypeMapper $staticTypeMapper, \Rector\Core\PhpParser\Comparing\NodeComparator $nodeComparator) + { $this->staticTypeMapper = $staticTypeMapper; $this->nodeNameResolver = $nodeNameResolver; $this->nodeComparator = $nodeComparator; } - /** * @param ClassMethod|Function_ $functionLike */ - public function isSameOrBetterReturnTypeAlreadyAdded(FunctionLike $functionLike, Type $returnType): bool + public function isSameOrBetterReturnTypeAlreadyAdded(\PhpParser\Node\FunctionLike $functionLike, \PHPStan\Type\Type $returnType) : bool { $nodeReturnType = $functionLike->returnType; - /** @param Identifier|Name|NullableType|PhpParserUnionType|null $returnTypeNode */ if ($nodeReturnType === null) { - return false; + return \false; } - $returnNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($returnType); if ($this->nodeComparator->areNodesEqual($nodeReturnType, $returnNode)) { - return true; + return \true; } - // is array <=> iterable <=> Iterator co-type? → skip if ($this->isArrayIterableIteratorCoType($nodeReturnType, $returnType)) { - return true; + return \true; } - if ($this->isUnionCoType($nodeReturnType, $returnType)) { - return true; + return \true; } - // is class-string type? → skip - if ($returnType instanceof GenericObjectType && $returnType->getClassName() === 'class-string') { - return true; + if ($returnType instanceof \PHPStan\Type\Generic\GenericObjectType && $returnType->getClassName() === 'class-string') { + return \true; } - // prevent overriding self with itself - if (! $functionLike->returnType instanceof Name) { - return false; + if (!$functionLike->returnType instanceof \PhpParser\Node\Name) { + return \false; } - if ($functionLike->returnType->toLowerString() !== 'self') { - return false; + return \false; } - - $className = $functionLike->getAttribute(AttributeKey::CLASS_NAME); - + $className = $functionLike->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); $nodeContent = $this->nodeComparator->printWithoutComments($returnNode); - $nodeContentWithoutPreslash = ltrim($nodeContent, '\\'); - + $nodeContentWithoutPreslash = \ltrim($nodeContent, '\\'); return $nodeContentWithoutPreslash === $className; } - /** * @param Identifier|Name|NullableType|PhpParserUnionType $returnTypeNode */ - private function isArrayIterableIteratorCoType(Node $returnTypeNode, Type $returnType): bool + private function isArrayIterableIteratorCoType(\PhpParser\Node $returnTypeNode, \PHPStan\Type\Type $returnType) : bool { - if (! $this->nodeNameResolver->isNames($returnTypeNode, self::FOREACHABLE_TYPES)) { - return false; + if (!$this->nodeNameResolver->isNames($returnTypeNode, self::FOREACHABLE_TYPES)) { + return \false; } - return $this->isStaticTypeIterable($returnType); } - /** * @param Identifier|Name|NullableType|PhpParserUnionType $returnTypeNode */ - private function isUnionCoType(Node $returnTypeNode, Type $type): bool + private function isUnionCoType(\PhpParser\Node $returnTypeNode, \PHPStan\Type\Type $type) : bool { - if (! $type instanceof UnionType) { - return false; + if (!$type instanceof \PHPStan\Type\UnionType) { + return \false; } - // skip nullable type - $nullType = new NullType(); + $nullType = new \PHPStan\Type\NullType(); if ($type->isSuperTypeOf($nullType)->yes()) { - return false; + return \false; } - $classMethodReturnType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($returnTypeNode); - return $type->isSuperTypeOf($classMethodReturnType) - ->yes(); + return $type->isSuperTypeOf($classMethodReturnType)->yes(); } - - private function isStaticTypeIterable(Type $type): bool + private function isStaticTypeIterable(\PHPStan\Type\Type $type) : bool { if ($this->isArrayIterableOrIteratorType($type)) { - return true; + return \true; } - - if ($type instanceof UnionType || $type instanceof IntersectionType) { + if ($type instanceof \PHPStan\Type\UnionType || $type instanceof \PHPStan\Type\IntersectionType) { foreach ($type->getTypes() as $joinedType) { - if (! $this->isStaticTypeIterable($joinedType)) { - return false; + if (!$this->isStaticTypeIterable($joinedType)) { + return \false; } } - - return true; + return \true; } - - return false; + return \false; } - - private function isArrayIterableOrIteratorType(Type $type): bool + private function isArrayIterableOrIteratorType(\PHPStan\Type\Type $type) : bool { - if ($type instanceof ArrayType) { - return true; + if ($type instanceof \PHPStan\Type\ArrayType) { + return \true; } - - if ($type instanceof IterableType) { - return true; + if ($type instanceof \PHPStan\Type\IterableType) { + return \true; } - if (! $type instanceof ObjectType) { - return false; + if (!$type instanceof \PHPStan\Type\ObjectType) { + return \false; } - return $type->getClassName() === Iterator::class; + return $type->getClassName() === \Iterator::class; } } diff --git a/rules/TypeDeclaration/TypeAnalyzer/AdvancedArrayAnalyzer.php b/rules/TypeDeclaration/TypeAnalyzer/AdvancedArrayAnalyzer.php index 33e7a098b0a..8383e72d0b6 100644 --- a/rules/TypeDeclaration/TypeAnalyzer/AdvancedArrayAnalyzer.php +++ b/rules/TypeDeclaration/TypeAnalyzer/AdvancedArrayAnalyzer.php @@ -1,7 +1,6 @@ typeNormalizer = $typeNormalizer; $this->phpDocInfoFactory = $phpDocInfoFactory; } - - public function isClassStringArrayByStringArrayOverride(ArrayType $arrayType, ClassMethod $classMethod): bool + public function isClassStringArrayByStringArrayOverride(\PHPStan\Type\ArrayType $arrayType, \PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - if (! $arrayType instanceof ConstantArrayType) { - return false; + if (!$arrayType instanceof \PHPStan\Type\Constant\ConstantArrayType) { + return \false; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); - $arrayType = $this->typeNormalizer->convertConstantArrayTypeToArrayType($arrayType); - if (! $arrayType instanceof ArrayType) { - return false; + if (!$arrayType instanceof \PHPStan\Type\ArrayType) { + return \false; } - $currentReturnType = $phpDocInfo->getReturnType(); - if (! $currentReturnType instanceof ArrayType) { - return false; + if (!$currentReturnType instanceof \PHPStan\Type\ArrayType) { + return \false; } - - if (! $currentReturnType->getItemType() instanceof ClassStringType) { - return false; + if (!$currentReturnType->getItemType() instanceof \PHPStan\Type\ClassStringType) { + return \false; } - - return $arrayType->getItemType() instanceof StringType; + return $arrayType->getItemType() instanceof \PHPStan\Type\StringType; } - - public function isMixedOfSpecificOverride(ArrayType $arrayType, PhpDocInfo $phpDocInfo): bool + public function isMixedOfSpecificOverride(\PHPStan\Type\ArrayType $arrayType, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : bool { - if (! $arrayType->getItemType() instanceof MixedType) { - return false; + if (!$arrayType->getItemType() instanceof \PHPStan\Type\MixedType) { + return \false; } - $currentReturnType = $phpDocInfo->getReturnType(); - return $currentReturnType instanceof ArrayType; + return $currentReturnType instanceof \PHPStan\Type\ArrayType; } - - public function isMoreSpecificArrayTypeOverride( - Type $newType, - ClassMethod $classMethod, - PhpDocInfo $phpDocInfo - ): bool { - if (! $newType instanceof ConstantArrayType) { - return false; + public function isMoreSpecificArrayTypeOverride(\PHPStan\Type\Type $newType, \PhpParser\Node\Stmt\ClassMethod $classMethod, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : bool + { + if (!$newType instanceof \PHPStan\Type\Constant\ConstantArrayType) { + return \false; } - - if (! $newType->getItemType() instanceof NeverType) { - return false; + if (!$newType->getItemType() instanceof \PHPStan\Type\NeverType) { + return \false; } - $phpDocReturnType = $phpDocInfo->getReturnType(); - if (! $phpDocReturnType instanceof ArrayType) { - return false; + if (!$phpDocReturnType instanceof \PHPStan\Type\ArrayType) { + return \false; } - - return ! $phpDocReturnType->getItemType() instanceof VoidType; + return !$phpDocReturnType->getItemType() instanceof \PHPStan\Type\VoidType; } - - public function isNewAndCurrentTypeBothCallable(ArrayType $newArrayType, PhpDocInfo $phpDocInfo): bool + public function isNewAndCurrentTypeBothCallable(\PHPStan\Type\ArrayType $newArrayType, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo $phpDocInfo) : bool { $currentReturnType = $phpDocInfo->getReturnType(); - if (! $currentReturnType instanceof ArrayType) { - return false; + if (!$currentReturnType instanceof \PHPStan\Type\ArrayType) { + return \false; } - - if (! $newArrayType->getItemType()->isCallable()->yes()) { - return false; + if (!$newArrayType->getItemType()->isCallable()->yes()) { + return \false; } - - return $currentReturnType->getItemType() - ->isCallable() - ->yes(); + return $currentReturnType->getItemType()->isCallable()->yes(); } } diff --git a/rules/TypeDeclaration/TypeAnalyzer/GenericClassStringTypeNormalizer.php b/rules/TypeDeclaration/TypeAnalyzer/GenericClassStringTypeNormalizer.php index ba63f908701..d85dc0aafb2 100644 --- a/rules/TypeDeclaration/TypeAnalyzer/GenericClassStringTypeNormalizer.php +++ b/rules/TypeDeclaration/TypeAnalyzer/GenericClassStringTypeNormalizer.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function normalize(Type $type): Type + public function normalize(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - return TypeTraverser::map($type, function (Type $type, $callback): Type { - if (! $type instanceof ConstantStringType) { + return \PHPStan\Type\TypeTraverser::map($type, function (\PHPStan\Type\Type $type, $callback) : Type { + if (!$type instanceof \PHPStan\Type\Constant\ConstantStringType) { return $callback($type); } - // skip string that look like classe if ($type->getValue() === 'error') { return $callback($type); } - - if (! $this->reflectionProvider->hasClass($type->getValue())) { + if (!$this->reflectionProvider->hasClass($type->getValue())) { return $callback($type); } - - return new GenericClassStringType(new ObjectType($type->getValue())); + return new \PHPStan\Type\Generic\GenericClassStringType(new \PHPStan\Type\ObjectType($type->getValue())); }); } } diff --git a/rules/TypeDeclaration/TypeAnalyzer/ObjectTypeComparator.php b/rules/TypeDeclaration/TypeAnalyzer/ObjectTypeComparator.php index 96f4b8842b3..735c5312fb4 100644 --- a/rules/TypeDeclaration/TypeAnalyzer/ObjectTypeComparator.php +++ b/rules/TypeDeclaration/TypeAnalyzer/ObjectTypeComparator.php @@ -1,54 +1,44 @@ isBothCallable($currentType, $newType)) { - return true; + return \true; } - - if (! $currentType instanceof ObjectType) { - return false; + if (!$currentType instanceof \PHPStan\Type\ObjectType) { + return \false; } - - if (! $newType instanceof ObjectType) { - return false; + if (!$newType instanceof \PHPStan\Type\ObjectType) { + return \false; } - - return $newType->isSuperTypeOf($currentType) - ->yes(); + return $newType->isSuperTypeOf($currentType)->yes(); } - - private function isBothCallable(Type $currentType, Type $newType): bool + private function isBothCallable(\PHPStan\Type\Type $currentType, \PHPStan\Type\Type $newType) : bool { - if ($currentType instanceof CallableType && $this->isClosure($newType)) { - return true; + if ($currentType instanceof \PHPStan\Type\CallableType && $this->isClosure($newType)) { + return \true; } - - return $newType instanceof CallableType && $this->isClosure($currentType); + return $newType instanceof \PHPStan\Type\CallableType && $this->isClosure($currentType); } - - private function isClosure(Type $type): bool + private function isClosure(\PHPStan\Type\Type $type) : bool { - $closureObjectType = new ObjectType('Closure'); + $closureObjectType = new \PHPStan\Type\ObjectType('Closure'); return $closureObjectType->equals($type); } } diff --git a/rules/TypeDeclaration/TypeInferer/AssignToPropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/AssignToPropertyTypeInferer.php index 42085616409..be04e15d915 100644 --- a/rules/TypeDeclaration/TypeInferer/AssignToPropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/AssignToPropertyTypeInferer.php @@ -1,7 +1,6 @@ constructorAssignDetector = $constructorAssignDetector; $this->propertyAssignMatcher = $propertyAssignMatcher; $this->propertyDefaultAssignDetector = $propertyDefaultAssignDetector; @@ -75,80 +59,63 @@ final class AssignToPropertyTypeInferer $this->typeFactory = $typeFactory; $this->nodeTypeResolver = $nodeTypeResolver; } - - public function inferPropertyInClassLike(string $propertyName, ClassLike $classLike): Type + public function inferPropertyInClassLike(string $propertyName, \PhpParser\Node\Stmt\ClassLike $classLike) : \PHPStan\Type\Type { $assignedExprTypes = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classLike->stmts, function (Node $node) use ( - $propertyName, - &$assignedExprTypes - ) { - if (! $node instanceof Assign) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classLike->stmts, function (\PhpParser\Node $node) use($propertyName, &$assignedExprTypes) { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - $expr = $this->propertyAssignMatcher->matchPropertyAssignExpr($node, $propertyName); - if (! $expr instanceof Expr) { + if (!$expr instanceof \PhpParser\Node\Expr) { return null; } - $exprStaticType = $this->resolveExprStaticTypeIncludingDimFetch($node); - if (! $exprStaticType instanceof Type) { + if (!$exprStaticType instanceof \PHPStan\Type\Type) { return null; } - $assignedExprTypes[] = $exprStaticType; - return null; }); - if ($this->shouldAddNullType($classLike, $propertyName, $assignedExprTypes)) { - $assignedExprTypes[] = new NullType(); + $assignedExprTypes[] = new \PHPStan\Type\NullType(); } - return $this->typeFactory->createMixedPassedOrUnionType($assignedExprTypes); } - - private function resolveExprStaticTypeIncludingDimFetch(Assign $assign): ?Type + private function resolveExprStaticTypeIncludingDimFetch(\PhpParser\Node\Expr\Assign $assign) : ?\PHPStan\Type\Type { $exprStaticType = $this->nodeTypeResolver->getStaticType($assign->expr); - if ($exprStaticType instanceof MixedType) { + if ($exprStaticType instanceof \PHPStan\Type\MixedType) { return null; } - - if ($assign->var instanceof ArrayDimFetch) { - return new ArrayType(new MixedType(), $exprStaticType); + if ($assign->var instanceof \PhpParser\Node\Expr\ArrayDimFetch) { + return new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), $exprStaticType); } - return $exprStaticType; } - /** * @param Type[] $assignedExprTypes */ - private function shouldAddNullType(ClassLike $classLike, string $propertyName, array $assignedExprTypes): bool + private function shouldAddNullType(\PhpParser\Node\Stmt\ClassLike $classLike, string $propertyName, array $assignedExprTypes) : bool { $hasPropertyDefaultValue = $this->propertyDefaultAssignDetector->detect($classLike, $propertyName); $isAssignedInConstructor = $this->constructorAssignDetector->isPropertyAssigned($classLike, $propertyName); $shouldAddNullType = $this->nullTypeAssignDetector->detect($classLike, $propertyName); - - if (($assignedExprTypes === []) && ($isAssignedInConstructor || $hasPropertyDefaultValue)) { - return false; + if ($assignedExprTypes === [] && ($isAssignedInConstructor || $hasPropertyDefaultValue)) { + return \false; } - - if ($shouldAddNullType === true) { + if ($shouldAddNullType === \true) { if ($isAssignedInConstructor) { - return false; + return \false; } - return ! $hasPropertyDefaultValue; + return !$hasPropertyDefaultValue; } if ($assignedExprTypes === []) { - return false; + return \false; } if ($isAssignedInConstructor) { - return false; + return \false; } - return ! $hasPropertyDefaultValue; + return !$hasPropertyDefaultValue; } } diff --git a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer.php index 3af907a43b8..81dee10a205 100644 --- a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer.php @@ -1,7 +1,6 @@ paramTypeInferers = $paramTypeInferers; $this->genericClassStringTypeNormalizer = $genericClassStringTypeNormalizer; } - - public function inferParam(Param $param): Type + public function inferParam(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { foreach ($this->paramTypeInferers as $paramTypeInferer) { $paramType = $paramTypeInferer->inferParam($param); - if ($paramType instanceof MixedType) { + if ($paramType instanceof \PHPStan\Type\MixedType) { continue; } - return $this->genericClassStringTypeNormalizer->normalize($paramType); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } } diff --git a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/FunctionLikeDocParamTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/FunctionLikeDocParamTypeInferer.php index 7ca3fd27ecb..0536a64f50f 100644 --- a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/FunctionLikeDocParamTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/FunctionLikeDocParamTypeInferer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->betterNodeFinder = $betterNodeFinder; } - - public function inferParam(Param $param): Type + public function inferParam(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { $functionLike = $this->resolveScopeNode($param); - if (! $functionLike instanceof FunctionLike) { - return new MixedType(); + if (!$functionLike instanceof \PhpParser\Node\FunctionLike) { + return new \PHPStan\Type\MixedType(); } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($functionLike); - $paramTypesByName = $phpDocInfo->getParamTypesByName(); if ($paramTypesByName === []) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - return $this->matchParamNodeFromDoc($paramTypesByName, $param); } - /** * @return ClassMethod|Function_|null */ - private function resolveScopeNode(Param $param): ?Node + private function resolveScopeNode(\PhpParser\Node\Param $param) : ?\PhpParser\Node { - return $this->betterNodeFinder->findParentTypes($param, [ClassMethod::class, Function_::class]); + return $this->betterNodeFinder->findParentTypes($param, [\PhpParser\Node\Stmt\ClassMethod::class, \PhpParser\Node\Stmt\Function_::class]); } - /** * @param Type[] $paramWithTypes */ - private function matchParamNodeFromDoc(array $paramWithTypes, Param $param): Type + private function matchParamNodeFromDoc(array $paramWithTypes, \PhpParser\Node\Param $param) : \PHPStan\Type\Type { $paramNodeName = '$' . $this->nodeNameResolver->getName($param->var); - return $paramWithTypes[$paramNodeName] ?? new MixedType(); + return $paramWithTypes[$paramNodeName] ?? new \PHPStan\Type\MixedType(); } } diff --git a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/GetterNodeParamTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/GetterNodeParamTypeInferer.php index 662c3bb8ac6..9132f146573 100644 --- a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/GetterNodeParamTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/GetterNodeParamTypeInferer.php @@ -1,7 +1,6 @@ propertyFetchAnalyzer = $propertyFetchAnalyzer; $this->propertyFetchAssignManipulator = $propertyFetchAssignManipulator; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - - public function inferParam(Param $param): Type + public function inferParam(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { - $classLike = $param->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return new MixedType(); + $classLike = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return new \PHPStan\Type\MixedType(); } - /** @var ClassMethod $classMethod */ - $classMethod = $param->getAttribute(AttributeKey::PARENT_NODE); - + $classMethod = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); /** @var string $paramName */ $paramName = $this->nodeNameResolver->getName($param); - - $propertyNames = $this->propertyFetchAssignManipulator->getPropertyNamesOfAssignOfVariable( - $classMethod, - $paramName - ); + $propertyNames = $this->propertyFetchAssignManipulator->getPropertyNamesOfAssignOfVariable($classMethod, $paramName); if ($propertyNames === []) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - $returnType = new MixedType(); - + $returnType = new \PHPStan\Type\MixedType(); // resolve property assigns - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classLike, function (Node $node) use ( - $propertyNames, - &$returnType - ): ?int { - if (! $node instanceof Return_) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classLike, function (\PhpParser\Node $node) use($propertyNames, &$returnType) : ?int { + if (!$node instanceof \PhpParser\Node\Stmt\Return_) { return null; } if ($node->expr === null) { return null; } $isMatch = $this->propertyFetchAnalyzer->isLocalPropertyOfNames($node->expr, $propertyNames); - if (! $isMatch) { + if (!$isMatch) { return null; } - // what is return type? - $classMethod = $node->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { + $classMethod = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return null; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classMethod); - $methodReturnType = $phpDocInfo->getReturnType(); - if ($methodReturnType instanceof MixedType) { + if ($methodReturnType instanceof \PHPStan\Type\MixedType) { return null; } - $returnType = $methodReturnType; - - return NodeTraverser::STOP_TRAVERSAL; + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; }); - return $returnType; } } diff --git a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/KnownArrayParamTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/KnownArrayParamTypeInferer.php index fe12780b249..cfc1ca4c861 100644 --- a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/KnownArrayParamTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/KnownArrayParamTypeInferer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; } - - public function inferParam(Param $param): Type + public function inferParam(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { - $classLike = $param->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return new MixedType(); + $classLike = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return new \PHPStan\Type\MixedType(); } - $className = $this->nodeNameResolver->getName($classLike); - if (! $className) { - return new MixedType(); + if (!$className) { + return new \PHPStan\Type\MixedType(); } - - if (! $this->reflectionProvider->hasClass($className)) { - return new MixedType(); + if (!$this->reflectionProvider->hasClass($className)) { + return new \PHPStan\Type\MixedType(); } - $classReflection = $this->reflectionProvider->getClass($className); $paramName = $this->nodeNameResolver->getName($param); - // @todo create map later - if ($paramName === 'configs' && $classReflection->isSubclassOf( - 'Symfony\Component\DependencyInjection\Extension\Extension' - )) { - return new ArrayType(new MixedType(), new StringType()); + if ($paramName === 'configs' && $classReflection->isSubclassOf('Symfony\\Component\\DependencyInjection\\Extension\\Extension')) { + return new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\StringType()); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } } diff --git a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/PHPUnitDataProviderParamTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/PHPUnitDataProviderParamTypeInferer.php index bd1f028211e..39646e79bbe 100644 --- a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/PHPUnitDataProviderParamTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/PHPUnitDataProviderParamTypeInferer.php @@ -1,10 +1,9 @@ \w+)(\(\))?#'; - + private const METHOD_NAME_REGEX = '#^(?\\w+)(\\(\\))?#'; /** * @var BetterNodeFinder */ private $betterNodeFinder; - /** * @var NodeTypeResolver */ private $nodeTypeResolver; - /** * @var TypeFactory */ private $typeFactory; - /** * @var PhpDocInfoFactory */ private $phpDocInfoFactory; - - public function __construct( - BetterNodeFinder $betterNodeFinder, - TypeFactory $typeFactory, - PhpDocInfoFactory $phpDocInfoFactory - ) { + public function __construct(\Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder, \Rector\NodeTypeResolver\PHPStan\Type\TypeFactory $typeFactory, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory $phpDocInfoFactory) + { $this->betterNodeFinder = $betterNodeFinder; $this->typeFactory = $typeFactory; $this->phpDocInfoFactory = $phpDocInfoFactory; } - /** * Prevents circular reference * @required */ - public function autowirePHPUnitDataProviderParamTypeInferer(NodeTypeResolver $nodeTypeResolver): void + public function autowirePHPUnitDataProviderParamTypeInferer(\Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver) : void { $this->nodeTypeResolver = $nodeTypeResolver; } - - public function inferParam(Param $param): Type + public function inferParam(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { $dataProviderClassMethod = $this->resolveDataProviderClassMethod($param); - if (! $dataProviderClassMethod instanceof ClassMethod) { - return new MixedType(); + if (!$dataProviderClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return new \PHPStan\Type\MixedType(); } - - $parameterPosition = $param->getAttribute(AttributeKey::PARAMETER_POSITION); + $parameterPosition = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARAMETER_POSITION); if ($parameterPosition === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - /** @var Return_[] $returns */ - $returns = $this->betterNodeFinder->findInstanceOf((array) $dataProviderClassMethod->stmts, Return_::class); + $returns = $this->betterNodeFinder->findInstanceOf((array) $dataProviderClassMethod->stmts, \PhpParser\Node\Stmt\Return_::class); if ($returns !== []) { return $this->resolveReturnStaticArrayTypeByParameterPosition($returns, $parameterPosition); } - /** @var Yield_[] $yields */ - $yields = $this->betterNodeFinder->findInstanceOf((array) $dataProviderClassMethod->stmts, Yield_::class); + $yields = $this->betterNodeFinder->findInstanceOf((array) $dataProviderClassMethod->stmts, \PhpParser\Node\Expr\Yield_::class); return $this->resolveYieldStaticArrayTypeByParameterPosition($yields, $parameterPosition); } - - private function resolveDataProviderClassMethod(Param $param): ?ClassMethod + private function resolveDataProviderClassMethod(\PhpParser\Node\Param $param) : ?\PhpParser\Node\Stmt\ClassMethod { $phpDocInfo = $this->getFunctionLikePhpDocInfo($param); - $phpDocTagNode = $phpDocInfo->getByName('@dataProvider'); - if (! $phpDocTagNode instanceof PhpDocTagNode) { + if (!$phpDocTagNode instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode) { return null; } - - $classLike = $param->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return null; } - - if (! $phpDocTagNode->value instanceof GenericTagValueNode) { + if (!$phpDocTagNode->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode) { return null; } - $content = $phpDocTagNode->value->value; - $match = Strings::match($content, self::METHOD_NAME_REGEX); + $match = \RectorPrefix20210509\Nette\Utils\Strings::match($content, self::METHOD_NAME_REGEX); if ($match === null) { return null; } - $methodName = $match['method_name']; return $classLike->getMethod($methodName); } - /** * @param Return_[] $returns */ - private function resolveReturnStaticArrayTypeByParameterPosition(array $returns, int $parameterPosition): Type + private function resolveReturnStaticArrayTypeByParameterPosition(array $returns, int $parameterPosition) : \PHPStan\Type\Type { $firstReturnedExpr = $returns[0]->expr; - - if (! $firstReturnedExpr instanceof Array_) { - throw new ShouldNotHappenException(); + if (!$firstReturnedExpr instanceof \PhpParser\Node\Expr\Array_) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $paramOnPositionTypes = $this->resolveParamOnPositionTypes($firstReturnedExpr, $parameterPosition); if ($paramOnPositionTypes === []) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - return $this->typeFactory->createMixedPassedOrUnionType($paramOnPositionTypes); } - /** * @param Yield_[] $yields */ - private function resolveYieldStaticArrayTypeByParameterPosition(array $yields, int $parameterPosition): Type + private function resolveYieldStaticArrayTypeByParameterPosition(array $yields, int $parameterPosition) : \PHPStan\Type\Type { $paramOnPositionTypes = []; - foreach ($yields as $yield) { - if (! $yield->value instanceof Array_) { + if (!$yield->value instanceof \PhpParser\Node\Expr\Array_) { continue; } - $type = $this->getTypeFromClassMethodYield($yield->value); - - if (! $type instanceof ConstantArrayType) { + if (!$type instanceof \PHPStan\Type\Constant\ConstantArrayType) { return $type; } - foreach ($type->getValueTypes() as $position => $valueType) { if ($position !== $parameterPosition) { continue; } - $paramOnPositionTypes[] = $valueType; } } - if ($paramOnPositionTypes === []) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - return $this->typeFactory->createMixedPassedOrUnionType($paramOnPositionTypes); } - - private function getTypeFromClassMethodYield(Array_ $classMethodYieldArrayNode): Type + private function getTypeFromClassMethodYield(\PhpParser\Node\Expr\Array_ $classMethodYieldArrayNode) : \PHPStan\Type\Type { $arrayTypes = $this->nodeTypeResolver->resolve($classMethodYieldArrayNode); - // impossible to resolve - if (! $arrayTypes instanceof ConstantArrayType) { - return new MixedType(); + if (!$arrayTypes instanceof \PHPStan\Type\Constant\ConstantArrayType) { + return new \PHPStan\Type\MixedType(); } - return $arrayTypes; } - - private function getFunctionLikePhpDocInfo(Param $param): PhpDocInfo + private function getFunctionLikePhpDocInfo(\PhpParser\Node\Param $param) : \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo { - $parent = $param->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof FunctionLike) { - throw new ShouldNotHappenException(); + $parent = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\FunctionLike) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - return $this->phpDocInfoFactory->createFromNodeOrEmpty($parent); } - /** * @return Type[] */ - private function resolveParamOnPositionTypes(Array_ $array, int $parameterPosition): array + private function resolveParamOnPositionTypes(\PhpParser\Node\Expr\Array_ $array, int $parameterPosition) : array { $paramOnPositionTypes = []; - foreach ($array->items as $singleDataProvidedSet) { - if (! $singleDataProvidedSet instanceof ArrayItem || ! $singleDataProvidedSet->value instanceof Array_) { - throw new ShouldNotHappenException(); + if (!$singleDataProvidedSet instanceof \PhpParser\Node\Expr\ArrayItem || !$singleDataProvidedSet->value instanceof \PhpParser\Node\Expr\Array_) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - foreach ($singleDataProvidedSet->value->items as $position => $singleDataProvidedSetItem) { if ($position !== $parameterPosition) { continue; } - if (! $singleDataProvidedSetItem instanceof ArrayItem) { + if (!$singleDataProvidedSetItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - $paramOnPositionTypes[] = $this->nodeTypeResolver->resolve($singleDataProvidedSetItem->value); } } - return $paramOnPositionTypes; } } diff --git a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/PropertyNodeParamTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/PropertyNodeParamTypeInferer.php index 0c7c5dd4da7..882fb58c63e 100644 --- a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/PropertyNodeParamTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/PropertyNodeParamTypeInferer.php @@ -1,7 +1,6 @@ propertyFetchAnalyzer = $propertyFetchAnalyzer; $this->nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeTypeResolver = $nodeTypeResolver; $this->typeFactory = $typeFactory; } - - public function inferParam(Param $param): Type + public function inferParam(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { - $classLike = $param->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return new MixedType(); + $classLike = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return new \PHPStan\Type\MixedType(); } - $paramName = $this->nodeNameResolver->getName($param); - /** @var ClassMethod $classMethod */ - $classMethod = $param->getAttribute(AttributeKey::PARENT_NODE); - + $classMethod = $param->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); $propertyStaticTypes = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classMethod, function (Node $node) use ( - $paramName, - &$propertyStaticTypes - ) { - if (! $node instanceof Assign) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classMethod, function (\PhpParser\Node $node) use($paramName, &$propertyStaticTypes) { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $this->propertyFetchAnalyzer->isVariableAssignToThisPropertyFetch($node, $paramName)) { + if (!$this->propertyFetchAnalyzer->isVariableAssignToThisPropertyFetch($node, $paramName)) { return null; } - $staticType = $this->nodeTypeResolver->getStaticType($node->var); - if ($staticType !== null) { $propertyStaticTypes[] = $staticType; } - return null; }); - return $this->typeFactory->createMixedPassedOrUnionType($propertyStaticTypes); } } diff --git a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/SplFixedArrayParamTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/SplFixedArrayParamTypeInferer.php index ab12ebb750d..cc624e89fec 100644 --- a/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/SplFixedArrayParamTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ParamTypeInferer/SplFixedArrayParamTypeInferer.php @@ -1,7 +1,6 @@ splArrayFixedTypeNarrower = $splArrayFixedTypeNarrower; $this->nodeTypeResolver = $nodeTypeResolver; } - - public function inferParam(Param $param): Type + public function inferParam(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { if ($param->type === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - $paramType = $this->nodeTypeResolver->resolve($param->type); return $this->splArrayFixedTypeNarrower->narrow($paramType); } diff --git a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer.php index a423b0ff8da..8f18bfefa87 100644 --- a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer.php @@ -1,7 +1,6 @@ propertyTypeInferers = $typeInfererSorter->sort($propertyTypeInferers); $this->defaultValuePropertyTypeInferer = $defaultValuePropertyTypeInferer; $this->typeFactory = $typeFactory; @@ -69,71 +54,56 @@ final class PropertyTypeInferer $this->varDocPropertyTypeInferer = $varDocPropertyTypeInferer; $this->genericClassStringTypeNormalizer = $genericClassStringTypeNormalizer; } - - public function inferProperty(Property $property): Type + public function inferProperty(\PhpParser\Node\Stmt\Property $property) : \PHPStan\Type\Type { $resolvedTypes = []; - foreach ($this->propertyTypeInferers as $propertyTypeInferer) { $type = $propertyTypeInferer->inferProperty($property); - if ($type instanceof VoidType) { + if ($type instanceof \PHPStan\Type\VoidType) { continue; } - - if ($type instanceof MixedType) { + if ($type instanceof \PHPStan\Type\MixedType) { continue; } - $resolvedTypes[] = $type; } - // if nothing is clear from variable use, we use @var doc as fallback if ($resolvedTypes !== []) { $resolvedType = $this->typeFactory->createMixedPassedOrUnionType($resolvedTypes); } else { $resolvedType = $this->varDocPropertyTypeInferer->inferProperty($property); } - // default value type must be added to each resolved type if set $propertyDefaultValue = $property->props[0]->default; - if ($propertyDefaultValue !== null) { $defaultValueType = $this->defaultValuePropertyTypeInferer->inferProperty($property); if ($this->shouldUnionWithDefaultValue($defaultValueType, $resolvedType)) { return $this->unionWithDefaultValueType($defaultValueType, $resolvedType); } } - return $this->genericClassStringTypeNormalizer->normalize($resolvedType); } - - private function shouldUnionWithDefaultValue(Type $defaultValueType, Type $type): bool + private function shouldUnionWithDefaultValue(\PHPStan\Type\Type $defaultValueType, \PHPStan\Type\Type $type) : bool { - if ($defaultValueType instanceof MixedType) { - return false; + if ($defaultValueType instanceof \PHPStan\Type\MixedType) { + return \false; } - // skip empty array type (mixed[]) - if ($defaultValueType instanceof ArrayType && $defaultValueType->getItemType() instanceof NeverType && ! $type instanceof MixedType) { - return false; + if ($defaultValueType instanceof \PHPStan\Type\ArrayType && $defaultValueType->getItemType() instanceof \PHPStan\Type\NeverType && !$type instanceof \PHPStan\Type\MixedType) { + return \false; } - - if ($type instanceof MixedType) { - return true; + if ($type instanceof \PHPStan\Type\MixedType) { + return \true; } - - return ! $this->doctrineTypeAnalyzer->isDoctrineCollectionWithIterableUnionType($type); + return !$this->doctrineTypeAnalyzer->isDoctrineCollectionWithIterableUnionType($type); } - - private function unionWithDefaultValueType(Type $defaultValueType, Type $resolvedType): Type + private function unionWithDefaultValueType(\PHPStan\Type\Type $defaultValueType, \PHPStan\Type\Type $resolvedType) : \PHPStan\Type\Type { $types = []; $types[] = $defaultValueType; - - if (! $resolvedType instanceof MixedType) { + if (!$resolvedType instanceof \PHPStan\Type\MixedType) { $types[] = $resolvedType; } - return $this->typeFactory->createMixedPassedOrUnionType($types); } } diff --git a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/AllAssignNodePropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/AllAssignNodePropertyTypeInferer.php index 1a21aed55da..5dd78c55a0d 100644 --- a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/AllAssignNodePropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/AllAssignNodePropertyTypeInferer.php @@ -1,7 +1,6 @@ assignToPropertyTypeInferer = $assignToPropertyTypeInferer; $this->nodeNameResolver = $nodeNameResolver; } - - public function inferProperty(Property $property): Type + public function inferProperty(\PhpParser\Node\Stmt\Property $property) : \PHPStan\Type\Type { - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { // anonymous class - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - $propertyName = $this->nodeNameResolver->getName($property); - return $this->assignToPropertyTypeInferer->inferPropertyInClassLike($propertyName, $classLike); } - - public function getPriority(): int + public function getPriority() : int { return 1500; } diff --git a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/ConstructorPropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/ConstructorPropertyTypeInferer.php index 6c426c992d4..873f5e74c66 100644 --- a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/ConstructorPropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/ConstructorPropertyTypeInferer.php @@ -1,10 +1,9 @@ classMethodPropertyFetchManipulator = $classMethodPropertyFetchManipulator; $this->reflectionProvider = $reflectionProvider; $this->nodeNameResolver = $nodeNameResolver; @@ -86,156 +70,120 @@ final class ConstructorPropertyTypeInferer implements PropertyTypeInfererInterfa $this->staticTypeMapper = $staticTypeMapper; $this->nodeTypeResolver = $nodeTypeResolver; } - - public function inferProperty(Property $property): Type + public function inferProperty(\PhpParser\Node\Stmt\Property $property) : \PHPStan\Type\Type { - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { // anonymous class - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - $classMethod = $classLike->getMethod(MethodName::CONSTRUCT); - if (! $classMethod instanceof ClassMethod) { - return new MixedType(); + $classMethod = $classLike->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return new \PHPStan\Type\MixedType(); } - $propertyName = $this->nodeNameResolver->getName($property); - $param = $this->classMethodPropertyFetchManipulator->resolveParamForPropertyFetch($classMethod, $propertyName); - if (! $param instanceof Param) { - return new MixedType(); + if (!$param instanceof \PhpParser\Node\Param) { + return new \PHPStan\Type\MixedType(); } - // A. infer from type declaration of parameter if ($param->type !== null) { return $this->resolveFromParamType($param, $classMethod, $propertyName); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - public function getPriority(): int + public function getPriority() : int { return 800; } - - private function resolveFromParamType(Param $param, ClassMethod $classMethod, string $propertyName): Type + private function resolveFromParamType(\PhpParser\Node\Param $param, \PhpParser\Node\Stmt\ClassMethod $classMethod, string $propertyName) : \PHPStan\Type\Type { $type = $this->resolveParamTypeToPHPStanType($param); - if ($type instanceof MixedType) { - return new MixedType(); + if ($type instanceof \PHPStan\Type\MixedType) { + return new \PHPStan\Type\MixedType(); } - $types = []; - // it's an array - annotation → make type more precise, if possible - if ($type instanceof ArrayType || $param->variadic) { + if ($type instanceof \PHPStan\Type\ArrayType || $param->variadic) { $types[] = $this->getResolveParamStaticTypeAsPHPStanType($classMethod, $propertyName); } else { $types[] = $type; } - if ($this->isParamNullable($param)) { - $types[] = new NullType(); + $types[] = new \PHPStan\Type\NullType(); } - return $this->typeFactory->createMixedPassedOrUnionType($types); } - - private function resolveParamTypeToPHPStanType(Param $param): Type + private function resolveParamTypeToPHPStanType(\PhpParser\Node\Param $param) : \PHPStan\Type\Type { if ($param->type === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - if ($param->type instanceof NullableType) { + if ($param->type instanceof \PhpParser\Node\NullableType) { $types = []; - $types[] = new NullType(); + $types[] = new \PHPStan\Type\NullType(); $types[] = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type->type); - return $this->typeFactory->createMixedPassedOrUnionType($types); } - // special case for alias - if ($param->type instanceof FullyQualified) { + if ($param->type instanceof \PhpParser\Node\Name\FullyQualified) { $type = $this->resolveFullyQualifiedOrAliasedObjectType($param); if ($type !== null) { return $type; } } - return $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type); } - - private function getResolveParamStaticTypeAsPHPStanType(ClassMethod $classMethod, string $propertyName): Type + private function getResolveParamStaticTypeAsPHPStanType(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $propertyName) : \PHPStan\Type\Type { - $paramStaticType = new ArrayType(new MixedType(), new MixedType()); - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $classMethod->stmts, - function (Node $node) use ($propertyName, &$paramStaticType): ?int { - if (! $node instanceof Variable) { - return null; - } - - if (! $this->nodeNameResolver->isName($node, $propertyName)) { - return null; - } - - $paramStaticType = $this->nodeTypeResolver->getStaticType($node); - - return NodeTraverser::STOP_TRAVERSAL; + $paramStaticType = new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \PHPStan\Type\MixedType()); + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->stmts, function (\PhpParser\Node $node) use($propertyName, &$paramStaticType) : ?int { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return null; } - ); - + if (!$this->nodeNameResolver->isName($node, $propertyName)) { + return null; + } + $paramStaticType = $this->nodeTypeResolver->getStaticType($node); + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; + }); return $paramStaticType; } - - private function isParamNullable(Param $param): bool + private function isParamNullable(\PhpParser\Node\Param $param) : bool { - if ($param->type instanceof NullableType) { - return true; + if ($param->type instanceof \PhpParser\Node\NullableType) { + return \true; } - if ($param->default !== null) { $defaultValueStaticType = $this->nodeTypeResolver->getStaticType($param->default); - if ($defaultValueStaticType instanceof NullType) { - return true; + if ($defaultValueStaticType instanceof \PHPStan\Type\NullType) { + return \true; } } - - return false; + return \false; } - - private function resolveFullyQualifiedOrAliasedObjectType(Param $param): ?Type + private function resolveFullyQualifiedOrAliasedObjectType(\PhpParser\Node\Param $param) : ?\PHPStan\Type\Type { if ($param->type === null) { return null; } - $fullyQualifiedName = $this->nodeNameResolver->getName($param->type); - if (! $fullyQualifiedName) { + if (!$fullyQualifiedName) { return null; } - - $originalName = $param->type->getAttribute(AttributeKey::ORIGINAL_NAME); - if (! $originalName instanceof Name) { + $originalName = $param->type->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NAME); + if (!$originalName instanceof \PhpParser\Node\Name) { return null; } - // if the FQN has different ending than the original, it was aliased and we need to return the alias - if (! Strings::endsWith($fullyQualifiedName, '\\' . $originalName->toString())) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::endsWith($fullyQualifiedName, '\\' . $originalName->toString())) { $className = $originalName->toString(); - if ($this->reflectionProvider->hasClass($className)) { - return new FullyQualifiedObjectType($className); + return new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($className); } - // @note: $fullyQualifiedName is a guess, needs real life test - return new AliasedObjectType($originalName->toString(), $fullyQualifiedName); + return new \Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType($originalName->toString(), $fullyQualifiedName); } - return null; } } diff --git a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DefaultValuePropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DefaultValuePropertyTypeInferer.php index e5b74e5b78d..fdcf546be22 100644 --- a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DefaultValuePropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DefaultValuePropertyTypeInferer.php @@ -1,14 +1,12 @@ nodeTypeResolver = $nodeTypeResolver; } - - public function inferProperty(Property $property): Type + public function inferProperty(\PhpParser\Node\Stmt\Property $property) : \PHPStan\Type\Type { $propertyProperty = $property->props[0]; if ($propertyProperty->default === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - return $this->nodeTypeResolver->getStaticType($propertyProperty->default); } - - public function getPriority(): int + public function getPriority() : int { return 100; } diff --git a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DoctrineColumnPropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DoctrineColumnPropertyTypeInferer.php index 503c152781c..a08a7c10822 100644 --- a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DoctrineColumnPropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DoctrineColumnPropertyTypeInferer.php @@ -1,7 +1,6 @@ typeFactory = $typeFactory; - $this->doctrineTypeToScalarType = [ - 'tinyint' => new BooleanType(), + 'tinyint' => new \PHPStan\Type\BooleanType(), // integers - 'smallint' => new IntegerType(), - 'mediumint' => new IntegerType(), - 'int' => new IntegerType(), - 'integer' => new IntegerType(), - 'bigint' => new IntegerType(), - 'numeric' => new IntegerType(), + 'smallint' => new \PHPStan\Type\IntegerType(), + 'mediumint' => new \PHPStan\Type\IntegerType(), + 'int' => new \PHPStan\Type\IntegerType(), + 'integer' => new \PHPStan\Type\IntegerType(), + 'bigint' => new \PHPStan\Type\IntegerType(), + 'numeric' => new \PHPStan\Type\IntegerType(), // floats - 'decimal' => new FloatType(), - 'float' => new FloatType(), - 'double' => new FloatType(), - 'real' => new FloatType(), + 'decimal' => new \PHPStan\Type\FloatType(), + 'float' => new \PHPStan\Type\FloatType(), + 'double' => new \PHPStan\Type\FloatType(), + 'real' => new \PHPStan\Type\FloatType(), // strings - 'tinytext' => new StringType(), - 'mediumtext' => new StringType(), - 'longtext' => new StringType(), - 'text' => new StringType(), - 'varchar' => new StringType(), - 'string' => new StringType(), - 'char' => new StringType(), - 'longblob' => new StringType(), - 'blob' => new StringType(), - 'mediumblob' => new StringType(), - 'tinyblob' => new StringType(), - 'binary' => new StringType(), - 'varbinary' => new StringType(), - 'set' => new StringType(), + 'tinytext' => new \PHPStan\Type\StringType(), + 'mediumtext' => new \PHPStan\Type\StringType(), + 'longtext' => new \PHPStan\Type\StringType(), + 'text' => new \PHPStan\Type\StringType(), + 'varchar' => new \PHPStan\Type\StringType(), + 'string' => new \PHPStan\Type\StringType(), + 'char' => new \PHPStan\Type\StringType(), + 'longblob' => new \PHPStan\Type\StringType(), + 'blob' => new \PHPStan\Type\StringType(), + 'mediumblob' => new \PHPStan\Type\StringType(), + 'tinyblob' => new \PHPStan\Type\StringType(), + 'binary' => new \PHPStan\Type\StringType(), + 'varbinary' => new \PHPStan\Type\StringType(), + 'set' => new \PHPStan\Type\StringType(), // date time objects - 'date' => new ObjectType(self::DATE_TIME_INTERFACE), - 'datetime' => new ObjectType(self::DATE_TIME_INTERFACE), - 'timestamp' => new ObjectType(self::DATE_TIME_INTERFACE), - 'time' => new ObjectType(self::DATE_TIME_INTERFACE), - 'year' => new ObjectType(self::DATE_TIME_INTERFACE), + 'date' => new \PHPStan\Type\ObjectType(self::DATE_TIME_INTERFACE), + 'datetime' => new \PHPStan\Type\ObjectType(self::DATE_TIME_INTERFACE), + 'timestamp' => new \PHPStan\Type\ObjectType(self::DATE_TIME_INTERFACE), + 'time' => new \PHPStan\Type\ObjectType(self::DATE_TIME_INTERFACE), + 'year' => new \PHPStan\Type\ObjectType(self::DATE_TIME_INTERFACE), ]; - $this->phpDocInfoFactory = $phpDocInfoFactory; } - - public function inferProperty(Property $property): Type + public function inferProperty(\PhpParser\Node\Stmt\Property $property) : \PHPStan\Type\Type { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); - - $doctrineAnnotationTagValueNode = $phpDocInfo->getByAnnotationClass('Doctrine\ORM\Mapping\Column'); - if (! $doctrineAnnotationTagValueNode instanceof DoctrineAnnotationTagValueNode) { - return new MixedType(); + $doctrineAnnotationTagValueNode = $phpDocInfo->getByAnnotationClass('Doctrine\\ORM\\Mapping\\Column'); + if (!$doctrineAnnotationTagValueNode instanceof \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode) { + return new \PHPStan\Type\MixedType(); } - $type = $doctrineAnnotationTagValueNode->getValueWithoutQuotes('type'); if ($type === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - $scalarType = $this->doctrineTypeToScalarType[$type] ?? null; - if (! $scalarType instanceof Type) { - return new MixedType(); + if (!$scalarType instanceof \PHPStan\Type\Type) { + return new \PHPStan\Type\MixedType(); } - $types = [$scalarType]; - $isNullable = $doctrineAnnotationTagValueNode->getValue('nullable'); - // is nullable? - if ($isNullable instanceof ConstExprTrueNode) { - $types[] = new NullType(); + if ($isNullable instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode) { + $types[] = new \PHPStan\Type\NullType(); } - return $this->typeFactory->createMixedPassedOrUnionType($types); } - - public function getPriority(): int + public function getPriority() : int { return 2000; } diff --git a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DoctrineRelationPropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DoctrineRelationPropertyTypeInferer.php index 3a6f248ce9b..fc2446d3e2f 100644 --- a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DoctrineRelationPropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/DoctrineRelationPropertyTypeInferer.php @@ -1,10 +1,9 @@ typeFactory = $typeFactory; $this->phpDocInfoFactory = $phpDocInfoFactory; $this->shortClassExpander = $shortClassExpander; $this->classAnnotationMatcher = $classAnnotationMatcher; } - - public function inferProperty(Property $property): Type + public function inferProperty(\PhpParser\Node\Stmt\Property $property) : \PHPStan\Type\Type { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); - - $toManyRelationTagValueNode = $phpDocInfo->getByAnnotationClasses([ - 'Doctrine\ORM\Mapping\OneToMany', - 'Doctrine\ORM\Mapping\ManyToMany', - ]); + $toManyRelationTagValueNode = $phpDocInfo->getByAnnotationClasses(['Doctrine\\ORM\\Mapping\\OneToMany', 'Doctrine\\ORM\\Mapping\\ManyToMany']); if ($toManyRelationTagValueNode !== null) { return $this->processToManyRelation($property, $toManyRelationTagValueNode); } - - $toOneRelationTagValueNode = $phpDocInfo->getByAnnotationClasses([ - 'Doctrine\ORM\Mapping\ManyToOne', - 'Doctrine\ORM\Mapping\OneToOne', - ]); - + $toOneRelationTagValueNode = $phpDocInfo->getByAnnotationClasses(['Doctrine\\ORM\\Mapping\\ManyToOne', 'Doctrine\\ORM\\Mapping\\OneToOne']); if ($toOneRelationTagValueNode !== null) { - $joinDoctrineAnnotationTagValueNode = $phpDocInfo->getByAnnotationClass('Doctrine\ORM\Mapping\JoinColumn'); - return $this->processToOneRelation( - $property, - $toOneRelationTagValueNode, - $joinDoctrineAnnotationTagValueNode - ); + $joinDoctrineAnnotationTagValueNode = $phpDocInfo->getByAnnotationClass('Doctrine\\ORM\\Mapping\\JoinColumn'); + return $this->processToOneRelation($property, $toOneRelationTagValueNode, $joinDoctrineAnnotationTagValueNode); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - public function getPriority(): int + public function getPriority() : int { return 2100; } - - private function processToManyRelation( - Property $property, - DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode - ): Type { + private function processToManyRelation(\PhpParser\Node\Stmt\Property $property, \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode) : \PHPStan\Type\Type + { $types = []; - $targetEntity = $doctrineAnnotationTagValueNode->getValueWithoutQuotes('targetEntity'); if ($targetEntity) { $entityFullyQualifiedClass = $this->shortClassExpander->resolveFqnTargetEntity($targetEntity, $property); - $types[] = new ArrayType(new MixedType(), new FullyQualifiedObjectType($entityFullyQualifiedClass)); + $types[] = new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($entityFullyQualifiedClass)); } - - $types[] = new FullyQualifiedObjectType(self::COLLECTION_TYPE); - + $types[] = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType(self::COLLECTION_TYPE); return $this->typeFactory->createMixedPassedOrUnionType($types); } - - private function processToOneRelation( - Property $property, - DoctrineAnnotationTagValueNode $toOneDoctrineAnnotationTagValueNode, - ?DoctrineAnnotationTagValueNode $joinDoctrineAnnotationTagValueNode - ): Type { + private function processToOneRelation(\PhpParser\Node\Stmt\Property $property, \Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode $toOneDoctrineAnnotationTagValueNode, ?\Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode $joinDoctrineAnnotationTagValueNode) : \PHPStan\Type\Type + { $targetEntity = $toOneDoctrineAnnotationTagValueNode->getValueWithoutQuotes('targetEntity'); if ($targetEntity === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - if (Strings::endsWith($targetEntity, '::class')) { - $targetEntity = Strings::before($targetEntity, '::class'); + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($targetEntity, '::class')) { + $targetEntity = \RectorPrefix20210509\Nette\Utils\Strings::before($targetEntity, '::class'); } - // resolve to FQN $tagFullyQualifiedName = $this->classAnnotationMatcher->resolveTagFullyQualifiedName($targetEntity, $property); - $types = []; - $types[] = new FullyQualifiedObjectType($tagFullyQualifiedName); - + $types[] = new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType($tagFullyQualifiedName); if ($this->shouldAddNullType($joinDoctrineAnnotationTagValueNode)) { - $types[] = new NullType(); + $types[] = new \PHPStan\Type\NullType(); } - return $this->typeFactory->createMixedPassedOrUnionType($types); } - - private function shouldAddNullType(?DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode): bool + private function shouldAddNullType(?\Rector\BetterPhpDocParser\PhpDoc\DoctrineAnnotationTagValueNode $doctrineAnnotationTagValueNode) : bool { if ($doctrineAnnotationTagValueNode === null) { - return true; + return \true; } - $isNullableValue = $doctrineAnnotationTagValueNode->getValue('nullable'); - return $isNullableValue instanceof ConstExprTrueNode; + return $isNullableValue instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode; } } diff --git a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/GetterPropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/GetterPropertyTypeInferer.php index 74ca579f0eb..8293976e9ea 100644 --- a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/GetterPropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/GetterPropertyTypeInferer.php @@ -1,7 +1,6 @@ returnedNodesReturnTypeInferer = $returnedNodesReturnTypeInferer; $this->returnTagReturnTypeInferer = $returnTagReturnTypeInferer; $this->functionLikeReturnTypeResolver = $functionLikeReturnTypeResolver; $this->classMethodAndPropertyAnalyzer = $classMethodAndPropertyAnalyzer; $this->nodeNameResolver = $nodeNameResolver; } - - public function inferProperty(Property $property): Type + public function inferProperty(\PhpParser\Node\Stmt\Property $property) : \PHPStan\Type\Type { - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { // anonymous class - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - /** @var string $propertyName */ $propertyName = $this->nodeNameResolver->getName($property); - foreach ($classLike->getMethods() as $classMethod) { - if (! $this->classMethodAndPropertyAnalyzer->hasClassMethodOnlyStatementReturnOfPropertyFetch( - $classMethod, - $propertyName - )) { + if (!$this->classMethodAndPropertyAnalyzer->hasClassMethodOnlyStatementReturnOfPropertyFetch($classMethod, $propertyName)) { continue; } - $returnType = $this->inferClassMethodReturnType($classMethod); - - if (! $returnType instanceof MixedType) { + if (!$returnType instanceof \PHPStan\Type\MixedType) { return $returnType; } } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - public function getPriority(): int + public function getPriority() : int { return 1700; } - - private function inferClassMethodReturnType(ClassMethod $classMethod): Type + private function inferClassMethodReturnType(\PhpParser\Node\Stmt\ClassMethod $classMethod) : \PHPStan\Type\Type { - $returnTypeDeclarationType = $this->functionLikeReturnTypeResolver->resolveFunctionLikeReturnTypeToPHPStanType( - $classMethod - ); - - if (! $returnTypeDeclarationType instanceof MixedType) { + $returnTypeDeclarationType = $this->functionLikeReturnTypeResolver->resolveFunctionLikeReturnTypeToPHPStanType($classMethod); + if (!$returnTypeDeclarationType instanceof \PHPStan\Type\MixedType) { return $returnTypeDeclarationType; } - $inferedType = $this->returnedNodesReturnTypeInferer->inferFunctionLike($classMethod); - if (! $inferedType instanceof MixedType) { + if (!$inferedType instanceof \PHPStan\Type\MixedType) { return $inferedType; } - return $this->returnTagReturnTypeInferer->inferFunctionLike($classMethod); } } diff --git a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/GetterTypeDeclarationPropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/GetterTypeDeclarationPropertyTypeInferer.php index b6179b9bb59..917c79c3b73 100644 --- a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/GetterTypeDeclarationPropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/GetterTypeDeclarationPropertyTypeInferer.php @@ -1,7 +1,6 @@ functionLikeReturnTypeResolver = $functionLikeReturnTypeResolver; $this->classMethodAndPropertyAnalyzer = $classMethodAndPropertyAnalyzer; $this->nodeNameResolver = $nodeNameResolver; } - - public function inferProperty(Property $property): Type + public function inferProperty(\PhpParser\Node\Stmt\Property $property) : \PHPStan\Type\Type { - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { // anonymous class - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - /** @var string $propertyName */ $propertyName = $this->nodeNameResolver->getName($property); - foreach ($classLike->getMethods() as $classMethod) { - if (! $this->classMethodAndPropertyAnalyzer->hasClassMethodOnlyStatementReturnOfPropertyFetch( - $classMethod, - $propertyName - )) { + if (!$this->classMethodAndPropertyAnalyzer->hasClassMethodOnlyStatementReturnOfPropertyFetch($classMethod, $propertyName)) { continue; } - - $returnType = $this->functionLikeReturnTypeResolver->resolveFunctionLikeReturnTypeToPHPStanType( - $classMethod - ); + $returnType = $this->functionLikeReturnTypeResolver->resolveFunctionLikeReturnTypeToPHPStanType($classMethod); // let PhpDoc solve that later for more precise type - if ($returnType instanceof ArrayType) { - return new MixedType(); + if ($returnType instanceof \PHPStan\Type\ArrayType) { + return new \PHPStan\Type\MixedType(); } - - if (! $returnType instanceof MixedType) { + if (!$returnType instanceof \PHPStan\Type\MixedType) { return $returnType; } } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - public function getPriority(): int + public function getPriority() : int { return 630; } diff --git a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/SingleMethodAssignedNodePropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/SingleMethodAssignedNodePropertyTypeInferer.php index 2262f5b0d1a..7cd9f077cf7 100644 --- a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/SingleMethodAssignedNodePropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/SingleMethodAssignedNodePropertyTypeInferer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->nodeTypeResolver = $nodeTypeResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - - public function inferProperty(Property $property): Type + public function inferProperty(\PhpParser\Node\Stmt\Property $property) : \PHPStan\Type\Type { - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { // anonymous class - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - $classMethod = $classLike->getMethod(MethodName::CONSTRUCT); - if (! $classMethod instanceof ClassMethod) { - return new MixedType(); + $classMethod = $classLike->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return new \PHPStan\Type\MixedType(); } - $propertyName = $this->nodeNameResolver->getName($property); - $assignedNode = $this->resolveAssignedNodeToProperty($classMethod, $propertyName); - if (! $assignedNode instanceof Expr) { - return new MixedType(); + if (!$assignedNode instanceof \PhpParser\Node\Expr) { + return new \PHPStan\Type\MixedType(); } - return $this->nodeTypeResolver->getStaticType($assignedNode); } - - public function getPriority(): int + public function getPriority() : int { return 750; } - - private function resolveAssignedNodeToProperty(ClassMethod $classMethod, string $propertyName): ?Expr + private function resolveAssignedNodeToProperty(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $propertyName) : ?\PhpParser\Node\Expr { $assignedNode = null; - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $classMethod->stmts, - function (Node $node) use ($propertyName, &$assignedNode): ?int { - if (! $node instanceof Assign) { - return null; - } - - if (! $this->nodeNameResolver->isName($node->var, $propertyName)) { - return null; - } - - $assignedNode = $node->expr; - - return NodeTraverser::STOP_TRAVERSAL; + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->stmts, function (\PhpParser\Node $node) use($propertyName, &$assignedNode) : ?int { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return null; } - ); - + if (!$this->nodeNameResolver->isName($node->var, $propertyName)) { + return null; + } + $assignedNode = $node->expr; + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; + }); return $assignedNode; } } diff --git a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/VarDocPropertyTypeInferer.php b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/VarDocPropertyTypeInferer.php index d636a769848..5b537b7f2bd 100644 --- a/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/VarDocPropertyTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/PropertyTypeInferer/VarDocPropertyTypeInferer.php @@ -1,26 +1,22 @@ phpDocInfoFactory = $phpDocInfoFactory; } - - public function inferProperty(Property $property): Type + public function inferProperty(\PhpParser\Node\Stmt\Property $property) : \PHPStan\Type\Type { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); return $phpDocInfo->getVarType(); diff --git a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer.php index 03cbfc29a78..2c57c962ba9 100644 --- a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer.php @@ -1,7 +1,6 @@ returnTypeInferers = $typeInfererSorter->sort($returnTypeInferers); $this->typeNormalizer = $typeNormalizer; $this->genericClassStringTypeNormalizer = $genericClassStringTypeNormalizer; } - - public function inferFunctionLike(FunctionLike $functionLike): Type + public function inferFunctionLike(\PhpParser\Node\FunctionLike $functionLike) : \PHPStan\Type\Type { return $this->inferFunctionLikeWithExcludedInferers($functionLike, []); } - /** * @param array> $excludedInferers */ - public function inferFunctionLikeWithExcludedInferers(FunctionLike $functionLike, array $excludedInferers): Type + public function inferFunctionLikeWithExcludedInferers(\PhpParser\Node\FunctionLike $functionLike, array $excludedInferers) : \PHPStan\Type\Type { foreach ($this->returnTypeInferers as $returnTypeInferer) { if ($this->shouldSkipExcludedTypeInferer($returnTypeInferer, $excludedInferers)) { continue; } - $originalType = $returnTypeInferer->inferFunctionLike($functionLike); - if ($originalType instanceof MixedType) { + if ($originalType instanceof \PHPStan\Type\MixedType) { continue; } - $type = $this->typeNormalizer->normalizeArrayTypeAndArrayNever($originalType); - // in case of void, check return type of children methods - if ($type instanceof MixedType) { + if ($type instanceof \PHPStan\Type\MixedType) { continue; } - // normalize ConstStringType to ClassStringType return $this->genericClassStringTypeNormalizer->normalize($type); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - /** * @param array> $excludedInferers */ - private function shouldSkipExcludedTypeInferer( - ReturnTypeInfererInterface $returnTypeInferer, - array $excludedInferers - ): bool { + private function shouldSkipExcludedTypeInferer(\Rector\TypeDeclaration\Contract\TypeInferer\ReturnTypeInfererInterface $returnTypeInferer, array $excludedInferers) : bool + { foreach ($excludedInferers as $excludedInferer) { - if (is_a($returnTypeInferer, $excludedInferer)) { - return true; + if (\is_a($returnTypeInferer, $excludedInferer)) { + return \true; } } - - return false; + return \false; } } diff --git a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnTagReturnTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnTagReturnTypeInferer.php index db64454bb80..4204cfcdc5c 100644 --- a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnTagReturnTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnTagReturnTypeInferer.php @@ -1,7 +1,6 @@ phpDocInfoFactory = $phpDocInfoFactory; } - /** * @param ClassMethod|Closure|Function_ $functionLike */ - public function inferFunctionLike(FunctionLike $functionLike): Type + public function inferFunctionLike(\PhpParser\Node\FunctionLike $functionLike) : \PHPStan\Type\Type { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($functionLike); return $phpDocInfo->getReturnType(); } - - public function getPriority(): int + public function getPriority() : int { return 400; } diff --git a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnTypeDeclarationReturnTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnTypeDeclarationReturnTypeInferer.php index cfcebb0f5ee..3468bfcc2ca 100644 --- a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnTypeDeclarationReturnTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnTypeDeclarationReturnTypeInferer.php @@ -1,7 +1,6 @@ functionLikeReturnTypeResolver = $functionLikeReturnTypeResolver; $this->nodeNameResolver = $nodeNameResolver; } - - public function inferFunctionLike(FunctionLike $functionLike): Type + public function inferFunctionLike(\PhpParser\Node\FunctionLike $functionLike) : \PHPStan\Type\Type { if ($functionLike->getReturnType() === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - // resolve later with more precise type, e.g. Type[] if ($this->nodeNameResolver->isNames($functionLike->getReturnType(), ['array', 'iterable'])) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - return $this->functionLikeReturnTypeResolver->resolveFunctionLikeReturnTypeToPHPStanType($functionLike); } - - public function getPriority(): int + public function getPriority() : int { return 2000; } diff --git a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnedNodesReturnTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnedNodesReturnTypeInferer.php index bc8260f2532..c718476dee7 100644 --- a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnedNodesReturnTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnedNodesReturnTypeInferer.php @@ -1,7 +1,6 @@ silentVoidResolver = $silentVoidResolver; $this->nodeTypeResolver = $nodeTypeResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; @@ -76,139 +62,109 @@ final class ReturnedNodesReturnTypeInferer implements ReturnTypeInfererInterface $this->splArrayFixedTypeNarrower = $splArrayFixedTypeNarrower; $this->nodeRepository = $nodeRepository; } - /** * @param ClassMethod|Closure|Function_ $functionLike */ - public function inferFunctionLike(FunctionLike $functionLike): Type + public function inferFunctionLike(\PhpParser\Node\FunctionLike $functionLike) : \PHPStan\Type\Type { /** @var Class_|Trait_|Interface_|null $classLike */ - $classLike = $functionLike->getAttribute(AttributeKey::CLASS_NODE); + $classLike = $functionLike->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); if ($classLike === null) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - if ($functionLike instanceof ClassMethod && $classLike instanceof Interface_) { - return new MixedType(); + if ($functionLike instanceof \PhpParser\Node\Stmt\ClassMethod && $classLike instanceof \PhpParser\Node\Stmt\Interface_) { + return new \PHPStan\Type\MixedType(); } - $types = []; - $localReturnNodes = $this->collectReturns($functionLike); if ($localReturnNodes === []) { return $this->resolveNoLocalReturnNodes($classLike, $functionLike); } - foreach ($localReturnNodes as $localReturnNode) { $returnedExprType = $this->nodeTypeResolver->getStaticType($localReturnNode); $returnedExprType = $this->correctWithNestedType($returnedExprType, $localReturnNode, $functionLike); - $types[] = $this->splArrayFixedTypeNarrower->narrow($returnedExprType); } - if ($this->silentVoidResolver->hasSilentVoid($functionLike)) { - $types[] = new VoidType(); + $types[] = new \PHPStan\Type\VoidType(); } - return $this->typeFactory->createMixedPassedOrUnionType($types); } - - public function getPriority(): int + public function getPriority() : int { return 1000; } - /** * @return Return_[] */ - private function collectReturns(FunctionLike $functionLike): array + private function collectReturns(\PhpParser\Node\FunctionLike $functionLike) : array { $returns = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $functionLike->getStmts(), function ( - Node $node - ) use (&$returns): ?int { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $functionLike->getStmts(), function (\PhpParser\Node $node) use(&$returns) : ?int { // skip Return_ nodes in nested functions or switch statements - if ($node instanceof FunctionLike) { - return NodeTraverser::DONT_TRAVERSE_CHILDREN; + if ($node instanceof \PhpParser\Node\FunctionLike) { + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CHILDREN; } - - if (! $node instanceof Return_) { + if (!$node instanceof \PhpParser\Node\Stmt\Return_) { return null; } - $returns[] = $node; - return null; }); - return $returns; } - - private function resolveNoLocalReturnNodes(ClassLike $classLike, FunctionLike $functionLike): Type + private function resolveNoLocalReturnNodes(\PhpParser\Node\Stmt\ClassLike $classLike, \PhpParser\Node\FunctionLike $functionLike) : \PHPStan\Type\Type { // void type - if (! $this->isAbstractMethod($classLike, $functionLike)) { - return new VoidType(); + if (!$this->isAbstractMethod($classLike, $functionLike)) { + return new \PHPStan\Type\VoidType(); } - - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - - private function isAbstractMethod(ClassLike $classLike, FunctionLike $functionLike): bool + private function isAbstractMethod(\PhpParser\Node\Stmt\ClassLike $classLike, \PhpParser\Node\FunctionLike $functionLike) : bool { - if ($functionLike instanceof ClassMethod && $functionLike->isAbstract()) { - return true; + if ($functionLike instanceof \PhpParser\Node\Stmt\ClassMethod && $functionLike->isAbstract()) { + return \true; } - - if (! $classLike instanceof Class_) { - return false; + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } return $classLike->isAbstract(); } - - private function inferFromReturnedMethodCall(Return_ $return, FunctionLike $originalFunctionLike): Type + private function inferFromReturnedMethodCall(\PhpParser\Node\Stmt\Return_ $return, \PhpParser\Node\FunctionLike $originalFunctionLike) : \PHPStan\Type\Type { - if (! $return->expr instanceof MethodCall) { - return new MixedType(); + if (!$return->expr instanceof \PhpParser\Node\Expr\MethodCall) { + return new \PHPStan\Type\MixedType(); } - $classMethod = $this->nodeRepository->findClassMethodByMethodCall($return->expr); - if (! $classMethod instanceof ClassMethod) { - return new MixedType(); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return new \PHPStan\Type\MixedType(); } - // avoid infinite looping over self call if ($classMethod === $originalFunctionLike) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - return $this->inferFunctionLike($classMethod); } - - private function isArrayTypeMixed(Type $type): bool + private function isArrayTypeMixed(\PHPStan\Type\Type $type) : bool { - if (! $type instanceof ArrayType) { - return false; + if (!$type instanceof \PHPStan\Type\ArrayType) { + return \false; } - - if (! $type->getItemType() instanceof MixedType) { - return false; + if (!$type->getItemType() instanceof \PHPStan\Type\MixedType) { + return \false; } - - return $type->getKeyType() instanceof MixedType; + return $type->getKeyType() instanceof \PHPStan\Type\MixedType; } - - private function correctWithNestedType(Type $resolvedType, Return_ $return, FunctionLike $functionLike): Type + private function correctWithNestedType(\PHPStan\Type\Type $resolvedType, \PhpParser\Node\Stmt\Return_ $return, \PhpParser\Node\FunctionLike $functionLike) : \PHPStan\Type\Type { - if ($resolvedType instanceof MixedType || $this->isArrayTypeMixed($resolvedType)) { + if ($resolvedType instanceof \PHPStan\Type\MixedType || $this->isArrayTypeMixed($resolvedType)) { $correctedType = $this->inferFromReturnedMethodCall($return, $functionLike); // override only if has some extra value - if (! $correctedType instanceof MixedType) { + if (!$correctedType instanceof \PHPStan\Type\MixedType) { return $correctedType; } } - return $resolvedType; } } diff --git a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/SetterNodeReturnTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/SetterNodeReturnTypeInferer.php index 83f972f20e5..e1f979a83ff 100644 --- a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/SetterNodeReturnTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/SetterNodeReturnTypeInferer.php @@ -1,7 +1,6 @@ functionLikeManipulator = $functionLikeManipulator; $this->assignToPropertyTypeInferer = $assignToPropertyTypeInferer; $this->typeFactory = $typeFactory; } - - public function inferFunctionLike(FunctionLike $functionLike): Type + public function inferFunctionLike(\PhpParser\Node\FunctionLike $functionLike) : \PHPStan\Type\Type { - $classLike = $functionLike->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { - return new MixedType(); + $classLike = $functionLike->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { + return new \PHPStan\Type\MixedType(); } - $returnedPropertyNames = $this->functionLikeManipulator->getReturnedLocalPropertyNames($functionLike); - $types = []; foreach ($returnedPropertyNames as $returnedPropertyName) { $types[] = $this->assignToPropertyTypeInferer->inferPropertyInClassLike($returnedPropertyName, $classLike); } - return $this->typeFactory->createMixedPassedOrUnionType($types); } - - public function getPriority(): int + public function getPriority() : int { return 600; } diff --git a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/YieldNodesReturnTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/YieldNodesReturnTypeInferer.php index 314c4a735d8..0cb5e128218 100644 --- a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/YieldNodesReturnTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/YieldNodesReturnTypeInferer.php @@ -1,7 +1,6 @@ nodeTypeResolver = $nodeTypeResolver; $this->typeFactory = $typeFactory; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - /** * @param ClassMethod|Function_|Closure $functionLike */ - public function inferFunctionLike(FunctionLike $functionLike): Type + public function inferFunctionLike(\PhpParser\Node\FunctionLike $functionLike) : \PHPStan\Type\Type { $yieldNodes = $this->findCurrentScopeYieldNodes($functionLike); - if ($yieldNodes === []) { - return new MixedType(); + return new \PHPStan\Type\MixedType(); } - $types = []; foreach ($yieldNodes as $yieldNode) { $value = $this->resolveYieldValue($yieldNode); - if (! $value instanceof Expr) { + if (!$value instanceof \PhpParser\Node\Expr) { continue; } - $resolvedType = $this->nodeTypeResolver->getStaticType($value); - if ($resolvedType instanceof MixedType) { + if ($resolvedType instanceof \PHPStan\Type\MixedType) { continue; } $types[] = $resolvedType; } - if ($types === []) { - return new FullyQualifiedObjectType('Iterator'); + return new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType('Iterator'); } - $types = $this->typeFactory->createMixedPassedOrUnionType($types); - return new FullyQualifiedGenericObjectType('Iterator', [$types]); + return new \Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedGenericObjectType('Iterator', [$types]); } - - public function getPriority(): int + public function getPriority() : int { return 1200; } - /** * @return Yield_[]|YieldFrom[] */ - private function findCurrentScopeYieldNodes(FunctionLike $functionLike): array + private function findCurrentScopeYieldNodes(\PhpParser\Node\FunctionLike $functionLike) : array { $yieldNodes = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $functionLike->getStmts(), function ( - Node $node - ) use (&$yieldNodes): ?int { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $functionLike->getStmts(), function (\PhpParser\Node $node) use(&$yieldNodes) : ?int { // skip nested scope - if ($node instanceof FunctionLike) { - return NodeTraverser::DONT_TRAVERSE_CHILDREN; + if ($node instanceof \PhpParser\Node\FunctionLike) { + return \PhpParser\NodeTraverser::DONT_TRAVERSE_CHILDREN; } - - if (! $node instanceof Yield_ && ! $node instanceof YieldFrom) { + if (!$node instanceof \PhpParser\Node\Expr\Yield_ && !$node instanceof \PhpParser\Node\Expr\YieldFrom) { return null; } - $yieldNodes[] = $node; return null; }); - return $yieldNodes; } - /** * @param Yield_|YieldFrom $yieldExpr */ - private function resolveYieldValue(Expr $yieldExpr): ?Expr + private function resolveYieldValue(\PhpParser\Node\Expr $yieldExpr) : ?\PhpParser\Node\Expr { - if ($yieldExpr instanceof Yield_) { + if ($yieldExpr instanceof \PhpParser\Node\Expr\Yield_) { return $yieldExpr->value; } - return $yieldExpr->expr; } } diff --git a/rules/TypeDeclaration/TypeInferer/SilentVoidResolver.php b/rules/TypeDeclaration/TypeInferer/SilentVoidResolver.php index 0680caf5d7b..a627127b26c 100644 --- a/rules/TypeDeclaration/TypeInferer/SilentVoidResolver.php +++ b/rules/TypeDeclaration/TypeInferer/SilentVoidResolver.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; } - /** * @param ClassMethod|Closure|Function_ $functionLike */ - public function hasExlusiveVoid(FunctionLike $functionLike): bool + public function hasExlusiveVoid(\PhpParser\Node\FunctionLike $functionLike) : bool { - $classLike = $functionLike->getAttribute(AttributeKey::CLASS_NODE); - if ($classLike instanceof Interface_) { - return false; + $classLike = $functionLike->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if ($classLike instanceof \PhpParser\Node\Stmt\Interface_) { + return \false; } - if ($this->hasNeverType($functionLike)) { - return false; + return \false; } - - if ($this->betterNodeFinder->hasInstancesOf((array) $functionLike->stmts, [Yield_::class])) { - return false; + if ($this->betterNodeFinder->hasInstancesOf((array) $functionLike->stmts, [\PhpParser\Node\Expr\Yield_::class])) { + return \false; } - /** @var Return_[] $returns */ - $returns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, Return_::class); + $returns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, \PhpParser\Node\Stmt\Return_::class); foreach ($returns as $return) { if ($return->expr !== null) { - return false; + return \false; } } - - return true; + return \true; } - /** * @param ClassMethod|Closure|Function_ $functionLike */ - public function hasSilentVoid(FunctionLike $functionLike): bool + public function hasSilentVoid(\PhpParser\Node\FunctionLike $functionLike) : bool { if ($this->hasStmtsAlwaysReturn((array) $functionLike->stmts)) { - return false; + return \false; } - foreach ((array) $functionLike->stmts as $stmt) { // has switch with always return - if ($stmt instanceof Switch_ && $this->isSwitchWithAlwaysReturn($stmt)) { - return false; + if ($stmt instanceof \PhpParser\Node\Stmt\Switch_ && $this->isSwitchWithAlwaysReturn($stmt)) { + return \false; } - // is part of try/catch - if ($stmt instanceof TryCatch && $this->isTryCatchAlwaysReturn($stmt)) { - return false; + if ($stmt instanceof \PhpParser\Node\Stmt\TryCatch && $this->isTryCatchAlwaysReturn($stmt)) { + return \false; } - - if ($stmt instanceof Throw_) { - return false; + if ($stmt instanceof \PhpParser\Node\Stmt\Throw_) { + return \false; } } - - return true; + return \true; } - /** * @param Stmt[]|Expression[] $stmts */ - private function hasStmtsAlwaysReturn(array $stmts): bool + private function hasStmtsAlwaysReturn(array $stmts) : bool { foreach ($stmts as $stmt) { - if ($stmt instanceof Expression) { + if ($stmt instanceof \PhpParser\Node\Stmt\Expression) { $stmt = $stmt->expr; } - // is 1st level return - if ($stmt instanceof Return_) { - return true; + if ($stmt instanceof \PhpParser\Node\Stmt\Return_) { + return \true; } } - - return false; + return \false; } - - private function isSwitchWithAlwaysReturn(Switch_ $switch): bool + private function isSwitchWithAlwaysReturn(\PhpParser\Node\Stmt\Switch_ $switch) : bool { - $hasDefault = false; - + $hasDefault = \false; foreach ($switch->cases as $case) { if ($case->cond === null) { - $hasDefault = true; + $hasDefault = \true; break; } } - - if (! $hasDefault) { - return false; + if (!$hasDefault) { + return \false; } - $casesWithReturnCount = $this->resolveReturnCount($switch); - // has same amount of returns as switches - return count($switch->cases) === $casesWithReturnCount; + return \count($switch->cases) === $casesWithReturnCount; } - - private function isTryCatchAlwaysReturn(TryCatch $tryCatch): bool + private function isTryCatchAlwaysReturn(\PhpParser\Node\Stmt\TryCatch $tryCatch) : bool { - if (! $this->hasStmtsAlwaysReturn($tryCatch->stmts)) { - return false; + if (!$this->hasStmtsAlwaysReturn($tryCatch->stmts)) { + return \false; } - foreach ($tryCatch->catches as $catch) { return $this->hasStmtsAlwaysReturn($catch->stmts); } - - return true; + return \true; } - /** * @see https://phpstan.org/writing-php-code/phpdoc-types#bottom-type * @param ClassMethod|Closure|Function_ $functionLike */ - private function hasNeverType(FunctionLike $functionLike): bool + private function hasNeverType(\PhpParser\Node\FunctionLike $functionLike) : bool { - return $this->betterNodeFinder->hasInstancesOf($functionLike, [Throw_::class]); + return $this->betterNodeFinder->hasInstancesOf($functionLike, [\PhpParser\Node\Stmt\Throw_::class]); } - - private function resolveReturnCount(Switch_ $switch): int + private function resolveReturnCount(\PhpParser\Node\Stmt\Switch_ $switch) : int { $casesWithReturnCount = 0; - foreach ($switch->cases as $case) { foreach ($case->stmts as $caseStmt) { - if (! $caseStmt instanceof Return_) { + if (!$caseStmt instanceof \PhpParser\Node\Stmt\Return_) { continue; } - ++$casesWithReturnCount; break; } } - return $casesWithReturnCount; } } diff --git a/rules/TypeDeclaration/TypeInferer/SplArrayFixedTypeNarrower.php b/rules/TypeDeclaration/TypeInferer/SplArrayFixedTypeNarrower.php index eb803c42641..b843f0b192b 100644 --- a/rules/TypeDeclaration/TypeInferer/SplArrayFixedTypeNarrower.php +++ b/rules/TypeDeclaration/TypeInferer/SplArrayFixedTypeNarrower.php @@ -1,44 +1,35 @@ isSuperTypeOf(new ObjectType('SplArrayFixed'))->no()) { + if ($paramType->isSuperTypeOf(new \PHPStan\Type\ObjectType('SplArrayFixed'))->no()) { return $paramType; } - - if (! $paramType instanceof TypeWithClassName) { + if (!$paramType instanceof \PHPStan\Type\TypeWithClassName) { return $paramType; } - - if ($paramType instanceof GenericObjectType) { + if ($paramType instanceof \PHPStan\Type\Generic\GenericObjectType) { return $paramType; } - $types = []; - - if ($paramType->getClassName() === 'PhpCsFixer\Tokenizer\Tokens') { - $types[] = new ObjectType('PhpCsFixer\Tokenizer\Token'); + if ($paramType->getClassName() === 'PhpCsFixer\\Tokenizer\\Tokens') { + $types[] = new \PHPStan\Type\ObjectType('PhpCsFixer\\Tokenizer\\Token'); } - - if ($paramType->getClassName() === 'PhpCsFixer\Doctrine\Annotation\Tokens') { - $types[] = new ObjectType('PhpCsFixer\Doctrine\Annotation\Token'); + if ($paramType->getClassName() === 'PhpCsFixer\\Doctrine\\Annotation\\Tokens') { + $types[] = new \PHPStan\Type\ObjectType('PhpCsFixer\\Doctrine\\Annotation\\Token'); } - if ($types === []) { return $paramType; } - - return new GenericObjectType($paramType->getClassName(), $types); + return new \PHPStan\Type\Generic\GenericObjectType($paramType->getClassName(), $types); } } diff --git a/rules/TypeDeclaration/TypeNormalizer.php b/rules/TypeDeclaration/TypeNormalizer.php index 066f0f4bed6..4d54dd3205b 100644 --- a/rules/TypeDeclaration/TypeNormalizer.php +++ b/rules/TypeDeclaration/TypeNormalizer.php @@ -1,7 +1,6 @@ typeFactory = $typeFactory; $this->unionTypeFactory = $unionTypeFactory; } - - public function convertConstantArrayTypeToArrayType(ConstantArrayType $constantArrayType): ?ArrayType + public function convertConstantArrayTypeToArrayType(\PHPStan\Type\Constant\ConstantArrayType $constantArrayType) : ?\PHPStan\Type\ArrayType { $nonConstantValueTypes = []; - - if ($constantArrayType->getItemType() instanceof UnionType) { + if ($constantArrayType->getItemType() instanceof \PHPStan\Type\UnionType) { /** @var UnionType $unionType */ $unionType = $constantArrayType->getItemType(); foreach ($unionType->getTypes() as $unionedType) { - if ($unionedType instanceof ConstantStringType) { - $stringType = new StringType(); - $nonConstantValueTypes[get_class($stringType)] = $stringType; - } elseif ($unionedType instanceof ObjectType) { + if ($unionedType instanceof \PHPStan\Type\Constant\ConstantStringType) { + $stringType = new \PHPStan\Type\StringType(); + $nonConstantValueTypes[\get_class($stringType)] = $stringType; + } elseif ($unionedType instanceof \PHPStan\Type\ObjectType) { $nonConstantValueTypes[] = $unionedType; } else { return null; @@ -63,115 +56,94 @@ final class TypeNormalizer } else { return null; } - return $this->createArrayTypeFromNonConstantValueTypes($nonConstantValueTypes); } - /** * Turn nested array union types to unique ones: * e.g. int[]|string[][]|bool[][]|string[][] * ↓ * int[]|string[][]|bool[][] */ - public function normalizeArrayOfUnionToUnionArray(Type $type, int $arrayNesting = 1): Type + public function normalizeArrayOfUnionToUnionArray(\PHPStan\Type\Type $type, int $arrayNesting = 1) : \PHPStan\Type\Type { - if (! $type instanceof ArrayType) { + if (!$type instanceof \PHPStan\Type\ArrayType) { return $type; } - // first collection of types if ($arrayNesting === 1) { $this->collectedNestedArrayTypes = []; } - - if ($type->getItemType() instanceof ArrayType) { + if ($type->getItemType() instanceof \PHPStan\Type\ArrayType) { ++$arrayNesting; $this->normalizeArrayOfUnionToUnionArray($type->getItemType(), $arrayNesting); - } elseif ($type->getItemType() instanceof UnionType) { + } elseif ($type->getItemType() instanceof \PHPStan\Type\UnionType) { $this->collectNestedArrayTypeFromUnionType($type->getItemType(), $arrayNesting); } else { - $this->collectedNestedArrayTypes[] = new NestedArrayType( - $type->getItemType(), - $arrayNesting, - $type->getKeyType() - ); + $this->collectedNestedArrayTypes[] = new \Rector\TypeDeclaration\ValueObject\NestedArrayType($type->getItemType(), $arrayNesting, $type->getKeyType()); } - return $this->createUnionedTypesFromArrayTypes($this->collectedNestedArrayTypes); } - /** * From "string[]|mixed[]" based on empty array to to "string[]" */ - public function normalizeArrayTypeAndArrayNever(Type $type): Type + public function normalizeArrayTypeAndArrayNever(\PHPStan\Type\Type $type) : \PHPStan\Type\Type { - if (! $type instanceof UnionType) { + if (!$type instanceof \PHPStan\Type\UnionType) { return $type; } - $nonNeverTypes = []; foreach ($type->getTypes() as $unionedType) { - if (! $unionedType instanceof ArrayType) { + if (!$unionedType instanceof \PHPStan\Type\ArrayType) { return $type; } - - if ($unionedType->getItemType() instanceof NeverType) { + if ($unionedType->getItemType() instanceof \PHPStan\Type\NeverType) { continue; } - $nonNeverTypes[] = $unionedType; } - return $this->typeFactory->createMixedPassedOrUnionType($nonNeverTypes); } - /** * @param array $nonConstantValueTypes */ - private function createArrayTypeFromNonConstantValueTypes(array $nonConstantValueTypes): ArrayType + private function createArrayTypeFromNonConstantValueTypes(array $nonConstantValueTypes) : \PHPStan\Type\ArrayType { - $nonConstantValueTypes = array_values($nonConstantValueTypes); - if (count($nonConstantValueTypes) > 1) { + $nonConstantValueTypes = \array_values($nonConstantValueTypes); + if (\count($nonConstantValueTypes) > 1) { $nonConstantValueType = $this->unionTypeFactory->createUnionObjectType($nonConstantValueTypes); } else { $nonConstantValueType = $nonConstantValueTypes[0]; } - - return new ArrayType(new MixedType(), $nonConstantValueType); + return new \PHPStan\Type\ArrayType(new \PHPStan\Type\MixedType(), $nonConstantValueType); } - - private function collectNestedArrayTypeFromUnionType(UnionType $unionType, int $arrayNesting): void + private function collectNestedArrayTypeFromUnionType(\PHPStan\Type\UnionType $unionType, int $arrayNesting) : void { foreach ($unionType->getTypes() as $unionedType) { - if ($unionedType instanceof ArrayType) { + if ($unionedType instanceof \PHPStan\Type\ArrayType) { ++$arrayNesting; $this->normalizeArrayOfUnionToUnionArray($unionedType, $arrayNesting); } else { - $this->collectedNestedArrayTypes[] = new NestedArrayType($unionedType, $arrayNesting); + $this->collectedNestedArrayTypes[] = new \Rector\TypeDeclaration\ValueObject\NestedArrayType($unionedType, $arrayNesting); } } } - /** * @param NestedArrayType[] $collectedNestedArrayTypes */ - private function createUnionedTypesFromArrayTypes(array $collectedNestedArrayTypes): Type + private function createUnionedTypesFromArrayTypes(array $collectedNestedArrayTypes) : \PHPStan\Type\Type { $unionedTypes = []; foreach ($collectedNestedArrayTypes as $collectedNestedArrayType) { $arrayType = $collectedNestedArrayType->getType(); for ($i = 0; $i < $collectedNestedArrayType->getArrayNestingLevel(); ++$i) { - $arrayType = new ArrayType($collectedNestedArrayType->getKeyType(), $arrayType); + $arrayType = new \PHPStan\Type\ArrayType($collectedNestedArrayType->getKeyType(), $arrayType); } - /** @var ArrayType $arrayType */ $unionedTypes[] = $arrayType; } - - if (count($unionedTypes) > 1) { + if (\count($unionedTypes) > 1) { return $this->unionTypeFactory->createUnionObjectType($unionedTypes); } - return $unionedTypes[0]; } } diff --git a/rules/TypeDeclaration/ValueObject/AddParamTypeDeclaration.php b/rules/TypeDeclaration/ValueObject/AddParamTypeDeclaration.php index 9686782c48b..b084eff7394 100644 --- a/rules/TypeDeclaration/ValueObject/AddParamTypeDeclaration.php +++ b/rules/TypeDeclaration/ValueObject/AddParamTypeDeclaration.php @@ -1,58 +1,48 @@ className = $className; $this->methodName = $methodName; $this->position = $position; $this->paramType = $paramType; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->className); + return new \PHPStan\Type\ObjectType($this->className); } - - public function getMethodName(): string + public function getMethodName() : string { return $this->methodName; } - - public function getPosition(): int + public function getPosition() : int { return $this->position; } - - public function getParamType(): Type + public function getParamType() : \PHPStan\Type\Type { return $this->paramType; } diff --git a/rules/TypeDeclaration/ValueObject/AddReturnTypeDeclaration.php b/rules/TypeDeclaration/ValueObject/AddReturnTypeDeclaration.php index 24ceb542f83..2d1cb796b53 100644 --- a/rules/TypeDeclaration/ValueObject/AddReturnTypeDeclaration.php +++ b/rules/TypeDeclaration/ValueObject/AddReturnTypeDeclaration.php @@ -1,53 +1,44 @@ class = $class; $this->method = $method; $this->returnType = $returnType; } - - public function getClass(): string + public function getClass() : string { return $this->class; } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } - - public function getReturnType(): Type + public function getReturnType() : \PHPStan\Type\Type { return $this->returnType; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } } diff --git a/rules/TypeDeclaration/ValueObject/NestedArrayType.php b/rules/TypeDeclaration/ValueObject/NestedArrayType.php index d97cb694175..5cf36d5d9e8 100644 --- a/rules/TypeDeclaration/ValueObject/NestedArrayType.php +++ b/rules/TypeDeclaration/ValueObject/NestedArrayType.php @@ -1,48 +1,40 @@ type = $valueType; $this->arrayNestingLevel = $arrayNestingLevel; $this->keyType = $keyType; } - - public function getType(): Type + public function getType() : \PHPStan\Type\Type { return $this->type; } - - public function getArrayNestingLevel(): int + public function getArrayNestingLevel() : int { return $this->arrayNestingLevel; } - - public function getKeyType(): Type + public function getKeyType() : \PHPStan\Type\Type { - return $this->keyType ?: new MixedType(); + return $this->keyType ?: new \PHPStan\Type\MixedType(); } } diff --git a/rules/TypeDeclaration/ValueObject/NewType.php b/rules/TypeDeclaration/ValueObject/NewType.php index f46b7ca34ed..c3635c0e23d 100644 --- a/rules/TypeDeclaration/ValueObject/NewType.php +++ b/rules/TypeDeclaration/ValueObject/NewType.php @@ -1,7 +1,6 @@ [ - new ChangeConstantVisibility('ParentObject', 'SOME_CONSTANT', Visibility::PROTECTED), - ], - ] - ), - ] - ); +, [self::CLASS_CONSTANT_VISIBILITY_CHANGES => [new \Rector\Visibility\ValueObject\ChangeConstantVisibility('ParentObject', 'SOME_CONSTANT', \Rector\Core\ValueObject\Visibility::PROTECTED)]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassConst::class]; + return [\PhpParser\Node\Stmt\ClassConst::class]; } - /** * @param ClassConst $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { foreach ($this->classConstantVisibilityChanges as $classConstantVisibilityChange) { - if (! $this->isObjectType($node, $classConstantVisibilityChange->getObjectType())) { + if (!$this->isObjectType($node, $classConstantVisibilityChange->getObjectType())) { continue; } - - if (! $this->isName($node, $classConstantVisibilityChange->getConstant())) { + if (!$this->isName($node, $classConstantVisibilityChange->getConstant())) { continue; } - $this->visibilityManipulator->changeNodeVisibility($node, $classConstantVisibilityChange->getVisibility()); - return $node; } - return null; } - - public function configure(array $configuration): void + public function configure(array $configuration) : void { $classConstantVisibilityChanges = $configuration[self::CLASS_CONSTANT_VISIBILITY_CHANGES] ?? []; - Assert::allIsInstanceOf($classConstantVisibilityChanges, ChangeConstantVisibility::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($classConstantVisibilityChanges, \Rector\Visibility\ValueObject\ChangeConstantVisibility::class); $this->classConstantVisibilityChanges = $classConstantVisibilityChanges; } } diff --git a/rules/Visibility/Rector/ClassMethod/ChangeMethodVisibilityRector.php b/rules/Visibility/Rector/ClassMethod/ChangeMethodVisibilityRector.php index a516d4eeeab..b631fc296fe 100644 --- a/rules/Visibility/Rector/ClassMethod/ChangeMethodVisibilityRector.php +++ b/rules/Visibility/Rector/ClassMethod/ChangeMethodVisibilityRector.php @@ -1,7 +1,6 @@ parentClassScopeResolver = $parentClassScopeResolver; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change visibility of method from parent class.', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change visibility of method from parent class.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class FrameworkClass { protected someMethod() @@ -61,8 +51,7 @@ class MyClass extends FrameworkClass } } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class FrameworkClass { protected someMethod() @@ -77,60 +66,43 @@ class MyClass extends FrameworkClass } } CODE_SAMPLE - , - [ - self::METHOD_VISIBILITIES => [ - new ChangeMethodVisibility('FrameworkClass', 'someMethod', Visibility::PROTECTED), - ], - ] - ), - ] - ); +, [self::METHOD_VISIBILITIES => [new \Rector\Visibility\ValueObject\ChangeMethodVisibility('FrameworkClass', 'someMethod', \Rector\Core\ValueObject\Visibility::PROTECTED)]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [ClassMethod::class]; + return [\PhpParser\Node\Stmt\ClassMethod::class]; } - /** * @param ClassMethod $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { $parentClassName = $this->parentClassScopeResolver->resolveParentClassName($node); if ($parentClassName === null) { return null; } - foreach ($this->methodVisibilities as $methodVisibility) { if ($methodVisibility->getClass() !== $parentClassName) { continue; } - - if (! $this->isName($node, $methodVisibility->getMethod())) { + if (!$this->isName($node, $methodVisibility->getMethod())) { continue; } - $this->visibilityManipulator->changeNodeVisibility($node, $methodVisibility->getVisibility()); - return $node; } - return $node; } - /** * @param array $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $methodVisibilities = $configuration[self::METHOD_VISIBILITIES] ?? []; - Assert::allIsInstanceOf($methodVisibilities, ChangeMethodVisibility::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsInstanceOf($methodVisibilities, \Rector\Visibility\ValueObject\ChangeMethodVisibility::class); $this->methodVisibilities = $methodVisibilities; } } diff --git a/rules/Visibility/Rector/Property/ChangePropertyVisibilityRector.php b/rules/Visibility/Rector/Property/ChangePropertyVisibilityRector.php index 57d60cff72c..549563f7f82 100644 --- a/rules/Visibility/Rector/Property/ChangePropertyVisibilityRector.php +++ b/rules/Visibility/Rector/Property/ChangePropertyVisibilityRector.php @@ -1,7 +1,6 @@ > */ private $propertyToVisibilityByClass = []; - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change visibility of property from parent class.', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change visibility of property from parent class.', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' class FrameworkClass { protected $someProperty; @@ -47,8 +39,7 @@ class MyClass extends FrameworkClass public $someProperty; } CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' class FrameworkClass { protected $someProperty; @@ -59,57 +50,39 @@ class MyClass extends FrameworkClass protected $someProperty; } CODE_SAMPLE - , - [ - self::PROPERTY_TO_VISIBILITY_BY_CLASS => [ - 'FrameworkClass' => [ - 'someProperty' => Visibility::PROTECTED, - ], - ], - ] - ), - ] - ); +, [self::PROPERTY_TO_VISIBILITY_BY_CLASS => ['FrameworkClass' => ['someProperty' => \Rector\Core\ValueObject\Visibility::PROTECTED]]])]); } - /** * @return array> */ - public function getNodeTypes(): array + public function getNodeTypes() : array { - return [Property::class]; + return [\PhpParser\Node\Stmt\Property::class]; } - /** * @param Property $node */ - public function refactor(Node $node): ?Node + public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node { - $classLike = $node->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof ClassLike) { + $classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\ClassLike) { return null; } - foreach ($this->propertyToVisibilityByClass as $type => $propertyToVisibility) { - if (! $this->isObjectType($classLike, new ObjectType($type))) { + if (!$this->isObjectType($classLike, new \PHPStan\Type\ObjectType($type))) { continue; } - foreach ($propertyToVisibility as $property => $visibility) { - if (! $this->isName($node, $property)) { + if (!$this->isName($node, $property)) { continue; } - $this->visibilityManipulator->changeNodeVisibility($node, $visibility); - return $node; } } - return null; } - - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->propertyToVisibilityByClass = $configuration[self::PROPERTY_TO_VISIBILITY_BY_CLASS] ?? []; } diff --git a/rules/Visibility/ValueObject/ChangeConstantVisibility.php b/rules/Visibility/ValueObject/ChangeConstantVisibility.php index ecc4cde28e9..f52d39bc3ec 100644 --- a/rules/Visibility/ValueObject/ChangeConstantVisibility.php +++ b/rules/Visibility/ValueObject/ChangeConstantVisibility.php @@ -1,46 +1,38 @@ class = $class; $this->constant = $constant; $this->visibility = $visibility; } - - public function getObjectType(): ObjectType + public function getObjectType() : \PHPStan\Type\ObjectType { - return new ObjectType($this->class); + return new \PHPStan\Type\ObjectType($this->class); } - - public function getConstant(): string + public function getConstant() : string { return $this->constant; } - - public function getVisibility(): int + public function getVisibility() : int { return $this->visibility; } diff --git a/rules/Visibility/ValueObject/ChangeMethodVisibility.php b/rules/Visibility/ValueObject/ChangeMethodVisibility.php index ef6a73f89aa..5c69c340eea 100644 --- a/rules/Visibility/ValueObject/ChangeMethodVisibility.php +++ b/rules/Visibility/ValueObject/ChangeMethodVisibility.php @@ -1,7 +1,6 @@ class = $class; $this->method = $method; $this->visibility = $visibility; } - - public function getClass(): string + public function getClass() : string { return $this->class; } - - public function getMethod(): string + public function getMethod() : string { return $this->method; } - - public function getVisibility(): int + public function getVisibility() : int { return $this->visibility; } diff --git a/src/Application/ApplicationFileProcessor.php b/src/Application/ApplicationFileProcessor.php index 3a22e53f7c9..ac9bd35fabd 100644 --- a/src/Application/ApplicationFileProcessor.php +++ b/src/Application/ApplicationFileProcessor.php @@ -1,7 +1,6 @@ fileProcessors = $fileProcessors; $this->smartFileSystem = $smartFileSystem; $this->configuration = $configuration; $this->fileDiffFileDecorator = $fileDiffFileDecorator; $this->fileFormatter = $fileFormatter; } - /** * @param File[] $files */ - public function run(array $files): void + public function run(array $files) : void { $this->processFiles($files); - $this->fileFormatter->format($files); - $this->fileDiffFileDecorator->decorate($files); - $this->printFiles($files); } - /** * @param File[] $files */ - private function processFiles(array $files): void + private function processFiles(array $files) : void { foreach ($this->fileProcessors as $fileProcessor) { - $supportedFiles = array_filter($files, function (File $file) use ($fileProcessor): bool { + $supportedFiles = \array_filter($files, function (\Rector\Core\ValueObject\Application\File $file) use($fileProcessor) : bool { return $fileProcessor->supports($file); }); - $fileProcessor->process($supportedFiles); } } - /** * @param File[] $files */ - private function printFiles(array $files): void + private function printFiles(array $files) : void { if ($this->configuration->isDryRun()) { return; } - foreach ($files as $file) { - if (! $file->hasChanged()) { + if (!$file->hasChanged()) { continue; } - $this->printFile($file); } } - - private function printFile(File $file): void + private function printFile(\Rector\Core\ValueObject\Application\File $file) : void { $smartFileInfo = $file->getSmartFileInfo(); - $this->smartFileSystem->dumpFile($smartFileInfo->getPathname(), $file->getFileContent()); $this->smartFileSystem->chmod($smartFileInfo->getRealPath(), $smartFileInfo->getPerms()); } diff --git a/src/Application/FileDecorator/FileDiffFileDecorator.php b/src/Application/FileDecorator/FileDiffFileDecorator.php index d8c212c3bf4..1ddcdd29058 100644 --- a/src/Application/FileDecorator/FileDiffFileDecorator.php +++ b/src/Application/FileDecorator/FileDiffFileDecorator.php @@ -1,41 +1,31 @@ fileDiffFactory = $fileDiffFactory; } - /** * @param File[] $files */ - public function decorate(array $files): void + public function decorate(array $files) : void { foreach ($files as $file) { - if (! $file->hasChanged()) { + if (!$file->hasChanged()) { continue; } - - $fileDiff = $this->fileDiffFactory->createFileDiff( - $file, - $file->getOriginalFileContent(), - $file->getFileContent() - ); - + $fileDiff = $this->fileDiffFactory->createFileDiff($file, $file->getOriginalFileContent(), $file->getFileContent()); $file->setFileDiff($fileDiff); } } diff --git a/src/Application/FileProcessor.php b/src/Application/FileProcessor.php index 184b3c605db..9697ce45494 100644 --- a/src/Application/FileProcessor.php +++ b/src/Application/FileProcessor.php @@ -1,7 +1,6 @@ parser = $parser; $this->lexer = $lexer; $this->rectorNodeTraverser = $rectorNodeTraverser; $this->nodeScopeAndMetadataDecorator = $nodeScopeAndMetadataDecorator; $this->affectedFilesCollector = $affectedFilesCollector; } - - public function parseFileInfoToLocalCache(File $file): void + public function parseFileInfoToLocalCache(\Rector\Core\ValueObject\Application\File $file) : void { // store tokens by absolute path, so we don't have to print them right now $smartFileInfo = $file->getSmartFileInfo(); $oldStmts = $this->parser->parseFileInfo($smartFileInfo); $oldTokens = $this->lexer->getTokens(); - $newStmts = $this->nodeScopeAndMetadataDecorator->decorateNodesFromFile($file, $oldStmts, $smartFileInfo); $file->hydrateStmtsAndTokens($newStmts, $oldStmts, $oldTokens); } - - public function refactor(File $file): void + public function refactor(\Rector\Core\ValueObject\Application\File $file) : void { $newStmts = $this->rectorNodeTraverser->traverse($file->getNewStmts()); $file->changeNewStmts($newStmts); - $this->affectedFilesCollector->removeFromList($file); while ($otherTouchedFile = $this->affectedFilesCollector->getNext()) { $this->refactor($otherTouchedFile); diff --git a/src/Application/FileProcessor/PhpFileProcessor.php b/src/Application/FileProcessor/PhpFileProcessor.php index 5500cb5b85a..14959231bfd 100644 --- a/src/Application/FileProcessor/PhpFileProcessor.php +++ b/src/Application/FileProcessor/PhpFileProcessor.php @@ -1,7 +1,6 @@ symfonyStyle = $symfonyStyle; $this->configuration = $configuration; $this->fileProcessor = $fileProcessor; @@ -124,177 +98,143 @@ final class PhpFileProcessor implements FileProcessorInterface $this->postFileProcessor = $postFileProcessor; $this->errorFactory = $errorFactory; } - /** * @param File[] $files */ - public function process(array $files): void + public function process(array $files) : void { - $fileCount = count($files); + $fileCount = \count($files); if ($fileCount === 0) { return; } - $this->prepareProgressBar($fileCount); - // 1. parse files to nodes foreach ($files as $file) { - $this->tryCatchWrapper($file, function (File $file): void { + $this->tryCatchWrapper($file, function (\Rector\Core\ValueObject\Application\File $file) : void { $this->fileProcessor->parseFileInfoToLocalCache($file); }, 'parsing'); } - // 2. change nodes with Rectors $this->refactorNodesWithRectors($files); - // 3. apply post rectors foreach ($files as $file) { - $this->tryCatchWrapper($file, function (File $file): void { + $this->tryCatchWrapper($file, function (\Rector\Core\ValueObject\Application\File $file) : void { $newStmts = $this->postFileProcessor->traverse($file->getNewStmts()); - // this is needed for new tokens added in "afterTraverse()" $file->changeNewStmts($newStmts); }, 'post rectors'); } - // 4. print to file or string foreach ($files as $file) { $this->currentFileProvider->setFile($file); - // cannot print file with errors, as print would break everything to original nodes if ($file->hasErrors()) { $this->advance($file, 'printing skipped due error'); continue; } - - $this->tryCatchWrapper($file, function (File $file): void { + $this->tryCatchWrapper($file, function (\Rector\Core\ValueObject\Application\File $file) : void { $this->printFile($file); }, 'printing'); } - if ($this->configuration->shouldShowProgressBar()) { $this->symfonyStyle->newLine(2); } - // 4. remove and add files $this->removedAndAddedFilesProcessor->run(); } - - public function supports(File $file): bool + public function supports(\Rector\Core\ValueObject\Application\File $file) : bool { $smartFileInfo = $file->getSmartFileInfo(); return $smartFileInfo->hasSuffixes($this->getSupportedFileExtensions()); } - /** * @return string[] */ - public function getSupportedFileExtensions(): array + public function getSupportedFileExtensions() : array { return $this->configuration->getFileExtensions(); } - - private function prepareProgressBar(int $fileCount): void + private function prepareProgressBar(int $fileCount) : void { if ($this->symfonyStyle->isVerbose()) { return; } - - if (! $this->configuration->shouldShowProgressBar()) { + if (!$this->configuration->shouldShowProgressBar()) { return; } - $this->configureStepCount($fileCount); } - /** * @param File[] $files */ - private function refactorNodesWithRectors(array $files): void + private function refactorNodesWithRectors(array $files) : void { foreach ($files as $file) { $this->currentFileProvider->setFile($file); - - $this->tryCatchWrapper($file, function (File $file): void { + $this->tryCatchWrapper($file, function (\Rector\Core\ValueObject\Application\File $file) : void { $this->fileProcessor->refactor($file); }, 'refactoring'); } } - - private function tryCatchWrapper(File $file, callable $callback, string $phase): void + private function tryCatchWrapper(\Rector\Core\ValueObject\Application\File $file, callable $callback, string $phase) : void { $this->currentFileProvider->setFile($file); - $this->advance($file, $phase); - try { - if (in_array($file, $this->notParsedFiles, true)) { + if (\in_array($file, $this->notParsedFiles, \true)) { // we cannot process this file return; } - $callback($file); - } catch (AnalysedCodeException $analysedCodeException) { + } catch (\PHPStan\AnalysedCodeException $analysedCodeException) { // inform about missing classes in tests - if (StaticPHPUnitEnvironment::isPHPUnitRun()) { + if (\Rector\Testing\PHPUnit\StaticPHPUnitEnvironment::isPHPUnitRun()) { throw $analysedCodeException; } - $this->notParsedFiles[] = $file; $error = $this->errorFactory->createAutoloadError($analysedCodeException); $file->addRectorError($error); - } catch (Throwable $throwable) { - if ($this->symfonyStyle->isVerbose() || StaticPHPUnitEnvironment::isPHPUnitRun()) { + } catch (\Throwable $throwable) { + if ($this->symfonyStyle->isVerbose() || \Rector\Testing\PHPUnit\StaticPHPUnitEnvironment::isPHPUnitRun()) { throw $throwable; } - - $rectorError = new RectorError($throwable->getMessage(), $throwable->getLine()); + $rectorError = new \Rector\Core\ValueObject\Application\RectorError($throwable->getMessage(), $throwable->getLine()); $file->addRectorError($rectorError); } } - - private function printFile(File $file): void + private function printFile(\Rector\Core\ValueObject\Application\File $file) : void { $smartFileInfo = $file->getSmartFileInfo(); if ($this->removedAndAddedFilesCollector->isFileRemoved($smartFileInfo)) { // skip, because this file exists no more return; } - - $newContent = $this->configuration->isDryRun() ? $this->formatPerservingPrinter->printParsedStmstAndTokensToString( - $file - ) : $this->formatPerservingPrinter->printParsedStmstAndTokens($file); - + $newContent = $this->configuration->isDryRun() ? $this->formatPerservingPrinter->printParsedStmstAndTokensToString($file) : $this->formatPerservingPrinter->printParsedStmstAndTokens($file); $file->changeFileContent($newContent); $this->fileDiffFileDecorator->decorate([$file]); } - /** * This prevent CI report flood with 1 file = 1 line in progress bar */ - private function configureStepCount(int $fileCount): void + private function configureStepCount(int $fileCount) : void { $this->symfonyStyle->progressStart($fileCount * self::PROGRESS_BAR_STEP_MULTIPLIER); - $progressBar = $this->privatesAccessor->getPrivateProperty($this->symfonyStyle, 'progressBar'); - if (! $progressBar instanceof ProgressBar) { - throw new ShouldNotHappenException(); + if (!$progressBar instanceof \RectorPrefix20210509\Symfony\Component\Console\Helper\ProgressBar) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - if ($progressBar->getMaxSteps() < 40) { return; } - $redrawFrequency = (int) ($progressBar->getMaxSteps() / 20); $progressBar->setRedrawFrequency($redrawFrequency); } - - private function advance(File $file, string $phase): void + private function advance(\Rector\Core\ValueObject\Application\File $file, string $phase) : void { if ($this->symfonyStyle->isVerbose()) { $smartFileInfo = $file->getSmartFileInfo(); - $relativeFilePath = $smartFileInfo->getRelativeFilePathFromDirectory(getcwd()); - $message = sprintf('[%s] %s', $phase, $relativeFilePath); + $relativeFilePath = $smartFileInfo->getRelativeFilePathFromDirectory(\getcwd()); + $message = \sprintf('[%s] %s', $phase, $relativeFilePath); $this->symfonyStyle->writeln($message); } elseif ($this->configuration->shouldShowProgressBar()) { $this->symfonyStyle->progressAdvance(); diff --git a/src/Application/FileSystem/RemovedAndAddedFilesCollector.php b/src/Application/FileSystem/RemovedAndAddedFilesCollector.php index ee89d980a6d..d346445c15e 100644 --- a/src/Application/FileSystem/RemovedAndAddedFilesCollector.php +++ b/src/Application/FileSystem/RemovedAndAddedFilesCollector.php @@ -1,96 +1,81 @@ removedFileInfos[] = $smartFileInfo; } - /** * @return SmartFileInfo[] */ - public function getRemovedFiles(): array + public function getRemovedFiles() : array { return $this->removedFileInfos; } - - public function isFileRemoved(SmartFileInfo $smartFileInfo): bool + public function isFileRemoved(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : bool { foreach ($this->removedFileInfos as $removedFileInfo) { if ($removedFileInfo->getPathname() !== $smartFileInfo->getPathname()) { continue; } - - return true; + return \true; } - - return false; + return \false; } - - public function addAddedFile(AddedFileInterface $addedFile): void + public function addAddedFile(\Rector\FileSystemRector\Contract\AddedFileInterface $addedFile) : void { $this->addedFiles[] = $addedFile; } - /** * @return AddedFileWithContent[] */ - public function getAddedFilesWithContent(): array + public function getAddedFilesWithContent() : array { - return array_filter($this->addedFiles, function (AddedFileInterface $addedFile): bool { - return $addedFile instanceof AddedFileWithContent; + return \array_filter($this->addedFiles, function (\Rector\FileSystemRector\Contract\AddedFileInterface $addedFile) : bool { + return $addedFile instanceof \Rector\FileSystemRector\ValueObject\AddedFileWithContent; }); } - /** * @return AddedFileWithNodes[] */ - public function getAddedFilesWithNodes(): array + public function getAddedFilesWithNodes() : array { - return array_filter($this->addedFiles, function (AddedFileInterface $addedFile): bool { - return $addedFile instanceof AddedFileWithNodes; + return \array_filter($this->addedFiles, function (\Rector\FileSystemRector\Contract\AddedFileInterface $addedFile) : bool { + return $addedFile instanceof \Rector\FileSystemRector\ValueObject\AddedFileWithNodes; }); } - - public function getAffectedFilesCount(): int + public function getAffectedFilesCount() : int { - return count($this->addedFiles) + count($this->removedFileInfos); + return \count($this->addedFiles) + \count($this->removedFileInfos); } - - public function getAddedFileCount(): int + public function getAddedFileCount() : int { - return count($this->addedFiles); + return \count($this->addedFiles); } - - public function getRemovedFilesCount(): int + public function getRemovedFilesCount() : int { - return count($this->removedFileInfos); + return \count($this->removedFileInfos); } - /** * For testing */ - public function reset(): void + public function reset() : void { $this->addedFiles = []; $this->removedFileInfos = []; diff --git a/src/Application/FileSystem/RemovedAndAddedFilesProcessor.php b/src/Application/FileSystem/RemovedAndAddedFilesProcessor.php index 6d81f25ca29..1a747f1b636 100644 --- a/src/Application/FileSystem/RemovedAndAddedFilesProcessor.php +++ b/src/Application/FileSystem/RemovedAndAddedFilesProcessor.php @@ -1,14 +1,12 @@ removedAndAddedFilesCollector = $removedAndAddedFilesCollector; $this->configuration = $configuration; $this->symfonyStyle = $symfonyStyle; $this->nodesWithFileDestinationPrinter = $nodesWithFileDestinationPrinter; $this->smartFileSystem = $smartFileSystem; } - - public function run(): void + public function run() : void { $this->processAddedFilesWithContent(); $this->processAddedFilesWithNodes(); - $this->processDeletedFiles(); } - - private function processDeletedFiles(): void + private function processDeletedFiles() : void { foreach ($this->removedAndAddedFilesCollector->getRemovedFiles() as $removedFile) { - $relativePath = $removedFile->getRelativeFilePathFromDirectory(getcwd()); - + $relativePath = $removedFile->getRelativeFilePathFromDirectory(\getcwd()); if ($this->configuration->isDryRun()) { - $message = sprintf('File "%s" will be removed', $relativePath); + $message = \sprintf('File "%s" will be removed', $relativePath); $this->symfonyStyle->warning($message); } else { - $message = sprintf('File "%s" was removed', $relativePath); + $message = \sprintf('File "%s" was removed', $relativePath); $this->symfonyStyle->warning($message); $this->smartFileSystem->remove($removedFile->getPathname()); } } } - - private function processAddedFilesWithContent(): void + private function processAddedFilesWithContent() : void { foreach ($this->removedAndAddedFilesCollector->getAddedFilesWithContent() as $addedFileWithContent) { if ($this->configuration->isDryRun()) { - $message = sprintf('File "%s" will be added', $addedFileWithContent->getFilePath()); + $message = \sprintf('File "%s" will be added', $addedFileWithContent->getFilePath()); $this->symfonyStyle->note($message); } else { - $this->smartFileSystem->dumpFile( - $addedFileWithContent->getFilePath(), - $addedFileWithContent->getFileContent() - ); - $message = sprintf('File "%s" was added', $addedFileWithContent->getFilePath()); + $this->smartFileSystem->dumpFile($addedFileWithContent->getFilePath(), $addedFileWithContent->getFileContent()); + $message = \sprintf('File "%s" was added', $addedFileWithContent->getFilePath()); $this->symfonyStyle->note($message); } } } - - private function processAddedFilesWithNodes(): void + private function processAddedFilesWithNodes() : void { foreach ($this->removedAndAddedFilesCollector->getAddedFilesWithNodes() as $addedFileWithNode) { - $fileContent = $this->nodesWithFileDestinationPrinter->printNodesWithFileDestination( - $addedFileWithNode - ); - + $fileContent = $this->nodesWithFileDestinationPrinter->printNodesWithFileDestination($addedFileWithNode); if ($this->configuration->isDryRun()) { - $message = sprintf('File "%s" will be added', $addedFileWithNode->getFilePath()); + $message = \sprintf('File "%s" will be added', $addedFileWithNode->getFilePath()); $this->symfonyStyle->note($message); } else { $this->smartFileSystem->dumpFile($addedFileWithNode->getFilePath(), $fileContent); - $message = sprintf('File "%s" was added', $addedFileWithNode->getFilePath()); + $message = \sprintf('File "%s" was added', $addedFileWithNode->getFilePath()); $this->symfonyStyle->note($message); } } diff --git a/src/Autoloading/AdditionalAutoloader.php b/src/Autoloading/AdditionalAutoloader.php index 21819b9d38b..64cb91bf2e4 100644 --- a/src/Autoloading/AdditionalAutoloader.php +++ b/src/Autoloading/AdditionalAutoloader.php @@ -1,15 +1,13 @@ fileSystemGuard = $fileSystemGuard; $this->parameterProvider = $parameterProvider; $this->dynamicSourceLocatorDecorator = $dynamicSourceLocatorDecorator; } - - public function autoloadInput(InputInterface $input): void + public function autoloadInput(\RectorPrefix20210509\Symfony\Component\Console\Input\InputInterface $input) : void { - if (! $input->hasOption(Option::OPTION_AUTOLOAD_FILE)) { + if (!$input->hasOption(\Rector\Core\Configuration\Option::OPTION_AUTOLOAD_FILE)) { return; } - /** @var string|null $autoloadFile */ - $autoloadFile = $input->getOption(Option::OPTION_AUTOLOAD_FILE); + $autoloadFile = $input->getOption(\Rector\Core\Configuration\Option::OPTION_AUTOLOAD_FILE); if ($autoloadFile === null) { return; } - $this->fileSystemGuard->ensureFileExists($autoloadFile, 'Extra autoload'); require_once $autoloadFile; } - - public function autoloadPaths(): void + public function autoloadPaths() : void { - $autoloadPaths = $this->parameterProvider->provideArrayParameter(Option::AUTOLOAD_PATHS); + $autoloadPaths = $this->parameterProvider->provideArrayParameter(\Rector\Core\Configuration\Option::AUTOLOAD_PATHS); if ($autoloadPaths === []) { return; } - $this->dynamicSourceLocatorDecorator->addPaths($autoloadPaths); } } diff --git a/src/Autoloading/BootstrapFilesIncluder.php b/src/Autoloading/BootstrapFilesIncluder.php index 2b6752bb660..11bcd31b093 100644 --- a/src/Autoloading/BootstrapFilesIncluder.php +++ b/src/Autoloading/BootstrapFilesIncluder.php @@ -1,52 +1,38 @@ parameterProvider = $parameterProvider; } - /** * Inspired by * @see https://github.com/phpstan/phpstan-src/commit/aad1bf888ab7b5808898ee5fe2228bb8bb4e4cf1 */ - public function includeBootstrapFiles(): void + public function includeBootstrapFiles() : void { - $bootstrapFiles = $this->parameterProvider->provideArrayParameter(Option::BOOTSTRAP_FILES); - + $bootstrapFiles = $this->parameterProvider->provideArrayParameter(\Rector\Core\Configuration\Option::BOOTSTRAP_FILES); foreach ($bootstrapFiles as $bootstrapFile) { - if (! is_file($bootstrapFile)) { - throw new ShouldNotHappenException('Bootstrap file %s does not exist.', $bootstrapFile); + if (!\is_file($bootstrapFile)) { + throw new \Rector\Core\Exception\ShouldNotHappenException('Bootstrap file %s does not exist.', $bootstrapFile); } - try { require_once $bootstrapFile; - } catch (Throwable $throwable) { - $errorMessage = sprintf( - '"%s" thrown in "%s" on line %d while loading bootstrap file %s: %s', - get_class($throwable), - $throwable->getFile(), - $throwable->getLine(), - $bootstrapFile, - $throwable->getMessage() - ); - - throw new ShouldNotHappenException($errorMessage, $throwable->getCode(), $throwable); + } catch (\Throwable $throwable) { + $errorMessage = \sprintf('"%s" thrown in "%s" on line %d while loading bootstrap file %s: %s', \get_class($throwable), $throwable->getFile(), $throwable->getLine(), $bootstrapFile, $throwable->getMessage()); + throw new \Rector\Core\Exception\ShouldNotHappenException($errorMessage, $throwable->getCode(), $throwable); } } } diff --git a/src/Bootstrap/ExtensionConfigResolver.php b/src/Bootstrap/ExtensionConfigResolver.php index 83f89135443..031de77285f 100644 --- a/src/Bootstrap/ExtensionConfigResolver.php +++ b/src/Bootstrap/ExtensionConfigResolver.php @@ -1,73 +1,51 @@ getFileName() === false) { + $generatedConfigReflectionClass = new \ReflectionClass('Rector\\RectorInstaller\\GeneratedConfig'); + if ($generatedConfigReflectionClass->getFileName() === \false) { return $configFileInfos; } - - $generatedConfigDirectory = dirname($generatedConfigReflectionClass->getFileName()); - foreach (GeneratedConfig::EXTENSIONS as $extensionConfig) { + $generatedConfigDirectory = \dirname($generatedConfigReflectionClass->getFileName()); + foreach (\Rector\RectorInstaller\GeneratedConfig::EXTENSIONS as $extensionConfig) { foreach ($extensionConfig['extra']['includes'] ?? [] as $includedFile) { - $includedFilePath = $this->resolveIncludeFilePath( - $extensionConfig, - $generatedConfigDirectory, - $includedFile - ); - + $includedFilePath = $this->resolveIncludeFilePath($extensionConfig, $generatedConfigDirectory, $includedFile); if ($includedFilePath === null) { - $includedFilePath = sprintf('%s/%s', $extensionConfig['install_path'], $includedFile); + $includedFilePath = \sprintf('%s/%s', $extensionConfig['install_path'], $includedFile); } - - $configFileInfos[] = new SmartFileInfo($includedFilePath); + $configFileInfos[] = new \Symplify\SmartFileSystem\SmartFileInfo($includedFilePath); } } - return $configFileInfos; } - /** * @param array $extensionConfig */ - private function resolveIncludeFilePath( - array $extensionConfig, - string $generatedConfigDirectory, - string $includedFile - ): ?string { - if (! isset($extensionConfig['relative_install_path'])) { + private function resolveIncludeFilePath(array $extensionConfig, string $generatedConfigDirectory, string $includedFile) : ?string + { + if (!isset($extensionConfig['relative_install_path'])) { return null; } - - $includedFilePath = sprintf( - '%s/%s/%s', - $generatedConfigDirectory, - $extensionConfig['relative_install_path'], - $includedFile - ); - if (! file_exists($includedFilePath)) { + $includedFilePath = \sprintf('%s/%s/%s', $generatedConfigDirectory, $extensionConfig['relative_install_path'], $includedFile); + if (!\file_exists($includedFilePath)) { return null; } - if (! is_readable($includedFilePath)) { + if (!\is_readable($includedFilePath)) { return null; } return $includedFilePath; diff --git a/src/Bootstrap/RectorConfigsResolver.php b/src/Bootstrap/RectorConfigsResolver.php index 18f10f45326..ef6d46a5ca6 100644 --- a/src/Bootstrap/RectorConfigsResolver.php +++ b/src/Bootstrap/RectorConfigsResolver.php @@ -1,89 +1,70 @@ */ private $resolvedConfigFileInfos = []; - /** * @var SetConfigResolver */ private $setConfigResolver; - public function __construct() { - $this->setConfigResolver = new SetConfigResolver(); - $this->configResolver = new ConfigResolver(); + $this->setConfigResolver = new \Rector\Core\Bootstrap\SetConfigResolver(); + $this->configResolver = new \RectorPrefix20210509\Symplify\SetConfigResolver\ConfigResolver(); } - /** * @return SmartFileInfo[] */ - public function resolveFromConfigFileInfo(SmartFileInfo $configFileInfo): array + public function resolveFromConfigFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $configFileInfo) : array { - $hash = sha1_file($configFileInfo->getRealPath()); - if ($hash === false) { + $hash = \sha1_file($configFileInfo->getRealPath()); + if ($hash === \false) { return []; } - if (isset($this->resolvedConfigFileInfos[$hash])) { return $this->resolvedConfigFileInfos[$hash]; } - $setFileInfos = $this->setConfigResolver->resolve($configFileInfo); - $configFileInfos = array_merge([$configFileInfo], $setFileInfos); - + $configFileInfos = \array_merge([$configFileInfo], $setFileInfos); $this->resolvedConfigFileInfos[$hash] = $configFileInfos; - return $configFileInfos; } - - public function provide(): BootstrapConfigs + public function provide() : \Rector\Core\ValueObject\Bootstrap\BootstrapConfigs { - $argvInput = new ArgvInput(); + $argvInput = new \RectorPrefix20210509\Symfony\Component\Console\Input\ArgvInput(); $mainConfigFileInfo = $this->configResolver->resolveFromInputWithFallback($argvInput, ['rector.php']); - - $configFileInfos = $mainConfigFileInfo instanceof SmartFileInfo ? $this->resolveFromConfigFileInfo( - $mainConfigFileInfo - ) : []; - + $configFileInfos = $mainConfigFileInfo instanceof \Symplify\SmartFileSystem\SmartFileInfo ? $this->resolveFromConfigFileInfo($mainConfigFileInfo) : []; $configFileInfos = $this->appendRectorRecipeConfig($argvInput, $configFileInfos); - - return new BootstrapConfigs($mainConfigFileInfo, $configFileInfos); + return new \Rector\Core\ValueObject\Bootstrap\BootstrapConfigs($mainConfigFileInfo, $configFileInfos); } - /** * @param SmartFileInfo[] $configFileInfos * @return SmartFileInfo[] */ - private function appendRectorRecipeConfig(ArgvInput $argvInput, array $configFileInfos): array + private function appendRectorRecipeConfig(\RectorPrefix20210509\Symfony\Component\Console\Input\ArgvInput $argvInput, array $configFileInfos) : array { if ($argvInput->getFirstArgument() !== 'generate') { return $configFileInfos; } - // autoload rector recipe file if present, just for \Rector\RectorGenerator\Command\GenerateCommand - $rectorRecipeFilePath = getcwd() . '/rector-recipe.php'; - if (file_exists($rectorRecipeFilePath)) { - $configFileInfos[] = new SmartFileInfo($rectorRecipeFilePath); + $rectorRecipeFilePath = \getcwd() . '/rector-recipe.php'; + if (\file_exists($rectorRecipeFilePath)) { + $configFileInfos[] = new \Symplify\SmartFileSystem\SmartFileInfo($rectorRecipeFilePath); } - return $configFileInfos; } } diff --git a/src/Bootstrap/SetConfigResolver.php b/src/Bootstrap/SetConfigResolver.php index e0792cfd906..0dfac439180 100644 --- a/src/Bootstrap/SetConfigResolver.php +++ b/src/Bootstrap/SetConfigResolver.php @@ -1,50 +1,42 @@ load($smartFileInfo->getRealPath()); - - if (! $containerBuilder->hasParameter(self::SETS)) { + if (!$containerBuilder->hasParameter(self::SETS)) { return []; } - $sets = (array) $containerBuilder->getParameter(self::SETS); return $this->wrapToFileInfos($sets); } - /** * @param string[] $sets * @return SmartFileInfo[] */ - private function wrapToFileInfos(array $sets): array + private function wrapToFileInfos(array $sets) : array { $setFileInfos = []; foreach ($sets as $set) { - $setFileInfos[] = new SmartFileInfo($set); + $setFileInfos[] = new \Symplify\SmartFileSystem\SmartFileInfo($set); } - return $setFileInfos; } } diff --git a/src/Configuration/Configuration.php b/src/Configuration/Configuration.php index e95a85161cf..fb43b720637 100644 --- a/src/Configuration/Configuration.php +++ b/src/Configuration/Configuration.php @@ -1,267 +1,214 @@ isCacheEnabled = (bool) $parameterProvider->provideParameter(Option::ENABLE_CACHE); - $this->fileExtensions = (array) $parameterProvider->provideParameter(Option::FILE_EXTENSIONS); - $this->paths = (array) $parameterProvider->provideParameter(Option::PATHS); + $this->isCacheEnabled = (bool) $parameterProvider->provideParameter(\Rector\Core\Configuration\Option::ENABLE_CACHE); + $this->fileExtensions = (array) $parameterProvider->provideParameter(\Rector\Core\Configuration\Option::FILE_EXTENSIONS); + $this->paths = (array) $parameterProvider->provideParameter(\Rector\Core\Configuration\Option::PATHS); $this->parameterProvider = $parameterProvider; } - /** * Needs to run in the start of the life cycle, since the rest of workflow uses it. */ - public function resolveFromInput(InputInterface $input): void + public function resolveFromInput(\RectorPrefix20210509\Symfony\Component\Console\Input\InputInterface $input) : void { - $this->isDryRun = (bool) $input->getOption(Option::OPTION_DRY_RUN); - $this->shouldClearCache = (bool) $input->getOption(Option::OPTION_CLEAR_CACHE); - + $this->isDryRun = (bool) $input->getOption(\Rector\Core\Configuration\Option::OPTION_DRY_RUN); + $this->shouldClearCache = (bool) $input->getOption(\Rector\Core\Configuration\Option::OPTION_CLEAR_CACHE); $this->showProgressBar = $this->canShowProgressBar($input); - $this->showDiffs = ! (bool) $input->getOption(Option::OPTION_NO_DIFFS); - $this->isCacheDebug = (bool) $input->getOption(Option::CACHE_DEBUG); - + $this->showDiffs = !(bool) $input->getOption(\Rector\Core\Configuration\Option::OPTION_NO_DIFFS); + $this->isCacheDebug = (bool) $input->getOption(\Rector\Core\Configuration\Option::CACHE_DEBUG); /** @var string|null $outputFileOption */ - $outputFileOption = $input->getOption(Option::OPTION_OUTPUT_FILE); + $outputFileOption = $input->getOption(\Rector\Core\Configuration\Option::OPTION_OUTPUT_FILE); $this->outputFile = $this->sanitizeOutputFileValue($outputFileOption); - - $this->outputFormat = (string) $input->getOption(Option::OPTION_OUTPUT_FORMAT); - - $commandLinePaths = (array) $input->getArgument(Option::SOURCE); - + $this->outputFormat = (string) $input->getOption(\Rector\Core\Configuration\Option::OPTION_OUTPUT_FORMAT); + $commandLinePaths = (array) $input->getArgument(\Rector\Core\Configuration\Option::SOURCE); // manual command line value has priority if ($commandLinePaths !== []) { $commandLinePaths = $this->correctBashSpacePaths($commandLinePaths); $this->paths = $commandLinePaths; } } - - public function getPrettyVersion(): string + public function getPrettyVersion() : string { - $version = PrettyVersions::getVersion('rector/rector'); + $version = \RectorPrefix20210509\Jean85\PrettyVersions::getVersion('rector/rector'); return $version->getPrettyVersion(); } - /** * @forTests */ - public function setIsDryRun(bool $isDryRun): void + public function setIsDryRun(bool $isDryRun) : void { $this->isDryRun = $isDryRun; } - - public function isDryRun(): bool + public function isDryRun() : bool { return $this->isDryRun; } - - public function shouldShowProgressBar(): bool + public function shouldShowProgressBar() : bool { if ($this->isCacheDebug) { - return false; + return \false; } - return $this->showProgressBar; } - - public function getOutputFile(): ?string + public function getOutputFile() : ?string { return $this->outputFile; } - - public function shouldClearCache(): bool + public function shouldClearCache() : bool { return $this->shouldClearCache; } - - public function isCacheDebug(): bool + public function isCacheDebug() : bool { return $this->isCacheDebug; } - - public function isCacheEnabled(): bool + public function isCacheEnabled() : bool { return $this->isCacheEnabled; } - /** * @return string[] */ - public function getFileExtensions(): array + public function getFileExtensions() : array { return $this->fileExtensions; } - /** * @return string[] */ - public function getPaths(): array + public function getPaths() : array { return $this->paths; } - - public function getOutputFormat(): string + public function getOutputFormat() : string { return $this->outputFormat; } - - public function validateConfigParameters(): void + public function validateConfigParameters() : void { - $symfonyContainerXmlPath = (string) $this->parameterProvider->provideParameter( - Option::SYMFONY_CONTAINER_XML_PATH_PARAMETER - ); + $symfonyContainerXmlPath = (string) $this->parameterProvider->provideParameter(\Rector\Core\Configuration\Option::SYMFONY_CONTAINER_XML_PATH_PARAMETER); if ($symfonyContainerXmlPath === '') { return; } - - if (file_exists($symfonyContainerXmlPath)) { + if (\file_exists($symfonyContainerXmlPath)) { return; } - - $message = sprintf( - 'Path "%s" for "$parameters->set(Option::%s, ...);" in your config was not found. Correct it', - $symfonyContainerXmlPath, - 'SYMFONY_CONTAINER_XML_PATH_PARAMETER' - ); - throw new InvalidConfigurationException($message); + $message = \sprintf('Path "%s" for "$parameters->set(Option::%s, ...);" in your config was not found. Correct it', $symfonyContainerXmlPath, 'SYMFONY_CONTAINER_XML_PATH_PARAMETER'); + throw new \Rector\Core\Exception\Configuration\InvalidConfigurationException($message); } - - public function shouldHideClutter(): bool + public function shouldHideClutter() : bool { - return $this->outputFormat !== ConsoleOutputFormatter::NAME; + return $this->outputFormat !== \Rector\ChangesReporting\Output\ConsoleOutputFormatter::NAME; } - - public function shouldShowDiffs(): bool + public function shouldShowDiffs() : bool { return $this->showDiffs; } - - public function setBootstrapConfigs(BootstrapConfigs $bootstrapConfigs): void + public function setBootstrapConfigs(\Rector\Core\ValueObject\Bootstrap\BootstrapConfigs $bootstrapConfigs) : void { $this->bootstrapConfigs = $bootstrapConfigs; } - - public function getMainConfigFilePath(): ?string + public function getMainConfigFilePath() : ?string { if ($this->bootstrapConfigs === null) { return null; } - $mainConfigFileInfo = $this->bootstrapConfigs->getMainConfigFileInfo(); - if (! $mainConfigFileInfo instanceof SmartFileInfo) { + if (!$mainConfigFileInfo instanceof \Symplify\SmartFileSystem\SmartFileInfo) { return null; } - return $mainConfigFileInfo->getRelativeFilePathFromCwd(); } - - private function canShowProgressBar(InputInterface $input): bool + private function canShowProgressBar(\RectorPrefix20210509\Symfony\Component\Console\Input\InputInterface $input) : bool { - $noProgressBar = (bool) $input->getOption(Option::OPTION_NO_PROGRESS_BAR); + $noProgressBar = (bool) $input->getOption(\Rector\Core\Configuration\Option::OPTION_NO_PROGRESS_BAR); if ($noProgressBar) { - return false; + return \false; } - - $optionOutputFormat = $input->getOption(Option::OPTION_OUTPUT_FORMAT); - return $optionOutputFormat === ConsoleOutputFormatter::NAME; + $optionOutputFormat = $input->getOption(\Rector\Core\Configuration\Option::OPTION_OUTPUT_FORMAT); + return $optionOutputFormat === \Rector\ChangesReporting\Output\ConsoleOutputFormatter::NAME; } - - private function sanitizeOutputFileValue(?string $outputFileOption): ?string + private function sanitizeOutputFileValue(?string $outputFileOption) : ?string { if ($outputFileOption === '') { return null; } - return $outputFileOption; } - /** * @param string[] $commandLinePaths * @return string[] */ - private function correctBashSpacePaths(array $commandLinePaths): array + private function correctBashSpacePaths(array $commandLinePaths) : array { // fixes bash edge-case that to merges string with space to one foreach ($commandLinePaths as $commandLinePath) { - if (Strings::contains($commandLinePath, ' ')) { - $commandLinePaths = explode(' ', $commandLinePath); + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($commandLinePath, ' ')) { + $commandLinePaths = \explode(' ', $commandLinePath); } } - return $commandLinePaths; } } diff --git a/src/Configuration/CurrentNodeProvider.php b/src/Configuration/CurrentNodeProvider.php index d61f54ed211..f8f1eb2a71e 100644 --- a/src/Configuration/CurrentNodeProvider.php +++ b/src/Configuration/CurrentNodeProvider.php @@ -1,24 +1,20 @@ node = $node; } - - public function getNode(): ?Node + public function getNode() : ?\PhpParser\Node { return $this->node; } diff --git a/src/Configuration/Option.php b/src/Configuration/Option.php index bb383675804..6c135be90e5 100644 --- a/src/Configuration/Option.php +++ b/src/Configuration/Option.php @@ -1,164 +1,132 @@ import() as it does the same job, just better and more explicit * @var string */ public const SETS = 'sets'; - /** * @var string */ - public const SKIP = SkipperOption::SKIP; - + public const SKIP = \RectorPrefix20210509\Symplify\Skipper\ValueObject\Option::SKIP; /** * @var string */ public const FILE_EXTENSIONS = 'file_extensions'; - /** * @var string */ public const NESTED_CHAIN_METHOD_CALL_LIMIT = 'nested_chain_method_call_limit'; - /** * @var string */ public const CACHE_DIR = 'cache_dir'; - /** * @var string */ public const OPTION_DEBUG = 'debug'; - /** * @var string */ public const XDEBUG = 'xdebug'; - /** * @var string */ public const OPTION_CONFIG = 'config'; - /** * @var string */ public const PHPSTAN_FOR_RECTOR_PATH = 'phpstan_for_rector_path'; - /** * @var string */ public const TYPES_TO_REMOVE_STATIC_FROM = 'types_to_remove_static_from'; - /** * @var string */ public const OPTION_NO_DIFFS = 'no-diffs'; - /** * @var string */ public const TEMPLATE_TYPE = 'template-type'; - /** * @var string */ diff --git a/src/Configuration/RenamedClassesDataCollector.php b/src/Configuration/RenamedClassesDataCollector.php index f6136cd7cff..ac1b8b17fcb 100644 --- a/src/Configuration/RenamedClassesDataCollector.php +++ b/src/Configuration/RenamedClassesDataCollector.php @@ -1,43 +1,36 @@ */ private $oldToNewClasses = []; - /** * @param array $oldToNewClasses */ - public function addOldToNewClasses(array $oldToNewClasses): void + public function addOldToNewClasses(array $oldToNewClasses) : void { - $this->oldToNewClasses = array_merge($this->oldToNewClasses, $oldToNewClasses); + $this->oldToNewClasses = \array_merge($this->oldToNewClasses, $oldToNewClasses); } - /** * @return array */ - public function getOldToNewClasses(): array + public function getOldToNewClasses() : array { return $this->oldToNewClasses; } - - public function matchClassName(ObjectType $objectType): ?ObjectType + public function matchClassName(\PHPStan\Type\ObjectType $objectType) : ?\PHPStan\Type\ObjectType { $className = $objectType->getClassName(); - $renamedClassName = $this->oldToNewClasses[$className] ?? null; if ($renamedClassName === null) { return null; } - - return new ObjectType($renamedClassName); + return new \PHPStan\Type\ObjectType($renamedClassName); } } diff --git a/src/Console/Command/InitCommand.php b/src/Console/Command/InitCommand.php index 50b9aa3bd8a..d268efff881 100644 --- a/src/Console/Command/InitCommand.php +++ b/src/Console/Command/InitCommand.php @@ -1,81 +1,59 @@ fileSystemGuard = $fileSystemGuard; $this->smartFileSystem = $smartFileSystem; $this->symfonyStyle = $symfonyStyle; $this->templateResolvers = $templateResolvers; parent::__construct(); } - - protected function configure(): void + protected function configure() : void { $this->setDescription('Generate rector.php configuration file'); - $this->addOption( - Option::TEMPLATE_TYPE, - null, - InputOption::VALUE_OPTIONAL, - 'A template type like default, nette, doctrine etc.', - 'default' - ); + $this->addOption(\Rector\Core\Configuration\Option::TEMPLATE_TYPE, null, \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_OPTIONAL, 'A template type like default, nette, doctrine etc.', 'default'); } - - protected function execute(InputInterface $input, OutputInterface $output): int + protected function execute(\RectorPrefix20210509\Symfony\Component\Console\Input\InputInterface $input, \RectorPrefix20210509\Symfony\Component\Console\Output\OutputInterface $output) : int { - $templateType = (string) $input->getOption(Option::TEMPLATE_TYPE); - + $templateType = (string) $input->getOption(\Rector\Core\Configuration\Option::TEMPLATE_TYPE); $rectorTemplateFilePath = $this->resolveTemplateFilePathByType($templateType); - $this->fileSystemGuard->ensureFileExists($rectorTemplateFilePath, __METHOD__); - - $rectorRootFilePath = getcwd() . '/rector.php'; - + $rectorRootFilePath = \getcwd() . '/rector.php'; $doesFileExist = $this->smartFileSystem->exists($rectorRootFilePath); if ($doesFileExist) { $this->symfonyStyle->warning('Config file "rector.php" already exists'); @@ -83,26 +61,21 @@ final class InitCommand extends Command $this->smartFileSystem->copy($rectorTemplateFilePath, $rectorRootFilePath); $this->symfonyStyle->success('"rector.php" config file was added'); } - - return ShellCode::SUCCESS; + return \RectorPrefix20210509\Symplify\PackageBuilder\Console\ShellCode::SUCCESS; } - - private function resolveTemplateFilePathByType(string $templateType): string + private function resolveTemplateFilePathByType(string $templateType) : string { $rectorTemplateFilePath = null; - foreach ($this->templateResolvers as $templateResolver) { if ($templateResolver->supports($templateType)) { $rectorTemplateFilePath = $templateResolver->provide(); break; } } - if ($rectorTemplateFilePath === null) { - $availableTemplateTypes = implode(', ', $this->templateResolvers); - throw TemplateTypeNotFound::typeNotFound($templateType, $availableTemplateTypes); + $availableTemplateTypes = \implode(', ', $this->templateResolvers); + throw \Rector\Core\Template\TemplateTypeNotFound::typeNotFound($templateType, $availableTemplateTypes); } - return $rectorTemplateFilePath; } } diff --git a/src/Console/Command/ProcessCommand.php b/src/Console/Command/ProcessCommand.php index 624a3a779fd..b69d65d992d 100644 --- a/src/Console/Command/ProcessCommand.php +++ b/src/Console/Command/ProcessCommand.php @@ -1,7 +1,6 @@ additionalAutoloader = $additionalAutoloader; $this->configuration = $configuration; $this->outputFormatterCollector = $outputFormatterCollector; $this->changedFilesDetector = $changedFilesDetector; $this->phpFilesFinder = $phpFilesFinder; $this->missingRectorRulesReporter = $missingRectorRulesReporter; - parent::__construct(); $this->applicationFileProcessor = $applicationFileProcessor; $this->fileFactory = $fileFactory; @@ -120,169 +93,100 @@ final class ProcessCommand extends Command $this->nodeScopeResolver = $nodeScopeResolver; $this->dynamicSourceLocatorDecorator = $dynamicSourceLocatorDecorator; } - - protected function configure(): void + protected function configure() : void { $this->setDescription('Upgrade or refactor source code with provided rectors'); - - $this->addArgument( - Option::SOURCE, - InputArgument::OPTIONAL | InputArgument::IS_ARRAY, - 'Files or directories to be upgraded.' - ); - - $this->addOption( - Option::OPTION_DRY_RUN, - 'n', - InputOption::VALUE_NONE, - 'See diff of changes, do not save them to files.' - ); - - $this->addOption( - Option::OPTION_AUTOLOAD_FILE, - 'a', - InputOption::VALUE_REQUIRED, - 'File with extra autoload' - ); - + $this->addArgument(\Rector\Core\Configuration\Option::SOURCE, \RectorPrefix20210509\Symfony\Component\Console\Input\InputArgument::OPTIONAL | \RectorPrefix20210509\Symfony\Component\Console\Input\InputArgument::IS_ARRAY, 'Files or directories to be upgraded.'); + $this->addOption(\Rector\Core\Configuration\Option::OPTION_DRY_RUN, 'n', \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_NONE, 'See diff of changes, do not save them to files.'); + $this->addOption(\Rector\Core\Configuration\Option::OPTION_AUTOLOAD_FILE, 'a', \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_REQUIRED, 'File with extra autoload'); $names = $this->outputFormatterCollector->getNames(); - - $description = sprintf('Select output format: "%s".', implode('", "', $names)); - $this->addOption( - Option::OPTION_OUTPUT_FORMAT, - 'o', - InputOption::VALUE_OPTIONAL, - $description, - ConsoleOutputFormatter::NAME - ); - - $this->addOption( - Option::OPTION_NO_PROGRESS_BAR, - null, - InputOption::VALUE_NONE, - 'Hide progress bar. Useful e.g. for nicer CI output.' - ); - - $this->addOption( - Option::OPTION_NO_DIFFS, - null, - InputOption::VALUE_NONE, - 'Hide diffs of changed files. Useful e.g. for nicer CI output.' - ); - - $this->addOption( - Option::OPTION_OUTPUT_FILE, - null, - InputOption::VALUE_REQUIRED, - 'Location for file to dump result in. Useful for Docker or automated processes' - ); - - $this->addOption(Option::CACHE_DEBUG, null, InputOption::VALUE_NONE, 'Debug changed file cache'); - $this->addOption(Option::OPTION_CLEAR_CACHE, null, InputOption::VALUE_NONE, 'Clear unchaged files cache'); + $description = \sprintf('Select output format: "%s".', \implode('", "', $names)); + $this->addOption(\Rector\Core\Configuration\Option::OPTION_OUTPUT_FORMAT, 'o', \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_OPTIONAL, $description, \Rector\ChangesReporting\Output\ConsoleOutputFormatter::NAME); + $this->addOption(\Rector\Core\Configuration\Option::OPTION_NO_PROGRESS_BAR, null, \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_NONE, 'Hide progress bar. Useful e.g. for nicer CI output.'); + $this->addOption(\Rector\Core\Configuration\Option::OPTION_NO_DIFFS, null, \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_NONE, 'Hide diffs of changed files. Useful e.g. for nicer CI output.'); + $this->addOption(\Rector\Core\Configuration\Option::OPTION_OUTPUT_FILE, null, \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_REQUIRED, 'Location for file to dump result in. Useful for Docker or automated processes'); + $this->addOption(\Rector\Core\Configuration\Option::CACHE_DEBUG, null, \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_NONE, 'Debug changed file cache'); + $this->addOption(\Rector\Core\Configuration\Option::OPTION_CLEAR_CACHE, null, \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_NONE, 'Clear unchaged files cache'); } - - protected function execute(InputInterface $input, OutputInterface $output): int + protected function execute(\RectorPrefix20210509\Symfony\Component\Console\Input\InputInterface $input, \RectorPrefix20210509\Symfony\Component\Console\Output\OutputInterface $output) : int { $exitCode = $this->missingRectorRulesReporter->reportIfMissing(); if ($exitCode !== null) { return $exitCode; } - $this->configuration->resolveFromInput($input); $this->configuration->validateConfigParameters(); - $paths = $this->configuration->getPaths(); $phpFileInfos = $this->phpFilesFinder->findInPaths($paths); - // register autoloaded and included files $this->bootstrapFilesIncluder->includeBootstrapFiles(); - $this->additionalAutoloader->autoloadInput($input); $this->additionalAutoloader->autoloadPaths(); - // PHPStan has to know about all files! $this->configurePHPStanNodeScopeResolver($phpFileInfos); - // 0. add files and directories to static locator $this->dynamicSourceLocatorDecorator->addPaths($paths); - $files = $this->fileFactory->createFromPaths($paths); $this->applicationFileProcessor->run($files); - // report diffs and errors - $outputFormat = (string) $input->getOption(Option::OPTION_OUTPUT_FORMAT); - + $outputFormat = (string) $input->getOption(\Rector\Core\Configuration\Option::OPTION_OUTPUT_FORMAT); $outputFormatter = $this->outputFormatterCollector->getByName($outputFormat); - // here should be value obect factory $processResult = $this->processResultFactory->create($files); $outputFormatter->report($processResult); - // invalidate affected files $this->invalidateCacheChangedFiles($processResult); - return $this->resolveReturnCode($processResult); } - - protected function initialize(InputInterface $input, OutputInterface $output): void + protected function initialize(\RectorPrefix20210509\Symfony\Component\Console\Input\InputInterface $input, \RectorPrefix20210509\Symfony\Component\Console\Output\OutputInterface $output) : void { $application = $this->getApplication(); - if (! $application instanceof Application) { - throw new ShouldNotHappenException(); + if (!$application instanceof \RectorPrefix20210509\Symfony\Component\Console\Application) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - $optionDebug = (bool) $input->getOption(Option::OPTION_DEBUG); + $optionDebug = (bool) $input->getOption(\Rector\Core\Configuration\Option::OPTION_DEBUG); if ($optionDebug) { - $application->setCatchExceptions(false); - + $application->setCatchExceptions(\false); // clear cache $this->changedFilesDetector->clear(); return; } - // clear cache - $optionClearCache = (bool) $input->getOption(Option::OPTION_CLEAR_CACHE); + $optionClearCache = (bool) $input->getOption(\Rector\Core\Configuration\Option::OPTION_CLEAR_CACHE); if ($optionClearCache) { $this->changedFilesDetector->clear(); } } - - private function invalidateCacheChangedFiles(ProcessResult $processResult): void + private function invalidateCacheChangedFiles(\Rector\Core\ValueObject\ProcessResult $processResult) : void { - if (! $this->configuration->isCacheEnabled()) { + if (!$this->configuration->isCacheEnabled()) { return; } - foreach ($processResult->getChangedFileInfos() as $changedFileInfo) { $this->changedFilesDetector->invalidateFile($changedFileInfo); } } - - private function resolveReturnCode(ProcessResult $processResult): int + private function resolveReturnCode(\Rector\Core\ValueObject\ProcessResult $processResult) : int { // some errors were found → fail if ($processResult->getErrors() !== []) { - return ShellCode::ERROR; + return \RectorPrefix20210509\Symplify\PackageBuilder\Console\ShellCode::ERROR; } - // inverse error code for CI dry-run - if (! $this->configuration->isDryRun()) { - return ShellCode::SUCCESS; + if (!$this->configuration->isDryRun()) { + return \RectorPrefix20210509\Symplify\PackageBuilder\Console\ShellCode::SUCCESS; } - - return $processResult->getFileDiffs() === [] ? ShellCode::SUCCESS : ShellCode::ERROR; + return $processResult->getFileDiffs() === [] ? \RectorPrefix20210509\Symplify\PackageBuilder\Console\ShellCode::SUCCESS : \RectorPrefix20210509\Symplify\PackageBuilder\Console\ShellCode::ERROR; } - /** * @param SmartFileInfo[] $fileInfos */ - private function configurePHPStanNodeScopeResolver(array $fileInfos): void + private function configurePHPStanNodeScopeResolver(array $fileInfos) : void { $filePaths = []; foreach ($fileInfos as $fileInfo) { $filePaths[] = $fileInfo->getPathname(); } - $this->nodeScopeResolver->setAnalysedFiles($filePaths); } } diff --git a/src/Console/Command/ShowCommand.php b/src/Console/Command/ShowCommand.php index 06815c3730b..b1773645d34 100644 --- a/src/Console/Command/ShowCommand.php +++ b/src/Console/Command/ShowCommand.php @@ -1,75 +1,58 @@ symfonyStyle = $symfonyStyle; $this->rectors = $rectors; - parent::__construct(); } - - protected function configure(): void + protected function configure() : void { $this->setDescription('Show loaded Rectors with their configuration'); } - - protected function execute(InputInterface $input, OutputInterface $output): int + protected function execute(\RectorPrefix20210509\Symfony\Component\Console\Input\InputInterface $input, \RectorPrefix20210509\Symfony\Component\Console\Output\OutputInterface $output) : int { $this->reportLoadedRectors(); - - return ShellCode::SUCCESS; + return \RectorPrefix20210509\Symplify\PackageBuilder\Console\ShellCode::SUCCESS; } - - private function reportLoadedRectors(): void + private function reportLoadedRectors() : void { - $rectors = array_filter($this->rectors, function (RectorInterface $rector) { - return ! $rector instanceof PostRectorInterface; + $rectors = \array_filter($this->rectors, function (\Rector\Core\Contract\Rector\RectorInterface $rector) { + return !$rector instanceof \Rector\PostRector\Contract\Rector\PostRectorInterface; }); - - $rectorCount = count($rectors); - + $rectorCount = \count($rectors); if ($rectorCount > 0) { $this->symfonyStyle->title('Loaded Rector rules'); - foreach ($rectors as $rector) { - $this->symfonyStyle->writeln(' * ' . get_class($rector)); + $this->symfonyStyle->writeln(' * ' . \get_class($rector)); } - - $message = sprintf('%d loaded Rectors', $rectorCount); + $message = \sprintf('%d loaded Rectors', $rectorCount); $this->symfonyStyle->success($message); } else { - $warningMessage = sprintf( - 'No Rectors were loaded.%sAre sure your "rector.php" config is in the root?%sTry "--config " option to include it.', - PHP_EOL . PHP_EOL, - PHP_EOL - ); + $warningMessage = \sprintf('No Rectors were loaded.%sAre sure your "rector.php" config is in the root?%sTry "--config " option to include it.', \PHP_EOL . \PHP_EOL, \PHP_EOL); $this->symfonyStyle->warning($warningMessage); } } diff --git a/src/Console/ConsoleApplication.php b/src/Console/ConsoleApplication.php index e55a347ea27..1929e9e42ec 100644 --- a/src/Console/ConsoleApplication.php +++ b/src/Console/ConsoleApplication.php @@ -1,177 +1,121 @@ getPrettyVersion(); - } catch (OutOfBoundsException $outOfBoundsException) { + } catch (\OutOfBoundsException $outOfBoundsException) { $version = 'Unknown'; } - parent::__construct(self::NAME, $version); - foreach ($commands as $command) { $commandName = $commandNaming->resolveFromCommand($command); $command->setName($commandName); } - $this->addCommands($commands); - $this->setDefaultCommand(CommandNaming::classToName(ProcessCommand::class)); + $this->setDefaultCommand(\RectorPrefix20210509\Symplify\PackageBuilder\Console\Command\CommandNaming::classToName(\Rector\Core\Console\Command\ProcessCommand::class)); } - - public function doRun(InputInterface $input, OutputInterface $output): int + public function doRun(\RectorPrefix20210509\Symfony\Component\Console\Input\InputInterface $input, \RectorPrefix20210509\Symfony\Component\Console\Output\OutputInterface $output) : int { // @fixes https://github.com/rectorphp/rector/issues/2205 $isXdebugAllowed = $input->hasParameterOption('--xdebug'); - if (! $isXdebugAllowed) { - $xdebugHandler = new XdebugHandler('rector'); + if (!$isXdebugAllowed) { + $xdebugHandler = new \RectorPrefix20210509\Composer\XdebugHandler\XdebugHandler('rector'); $xdebugHandler->check(); unset($xdebugHandler); } - - $shouldFollowByNewline = false; - + $shouldFollowByNewline = \false; // switch working dir $newWorkDir = $this->getNewWorkingDir($input); if ($newWorkDir !== '') { - $oldWorkingDir = getcwd(); - chdir($newWorkDir); - + $oldWorkingDir = \getcwd(); + \chdir($newWorkDir); if ($output->isDebug()) { - $message = sprintf('Changed working directory from "%s" to "%s"', $oldWorkingDir, getcwd()); + $message = \sprintf('Changed working directory from "%s" to "%s"', $oldWorkingDir, \getcwd()); $output->writeln($message); } } - // skip in this case, since generate content must be clear from meta-info if ($this->shouldPrintMetaInformation($input)) { $output->writeln($this->getLongVersion()); - $shouldFollowByNewline = true; + $shouldFollowByNewline = \true; } - if ($shouldFollowByNewline) { - $output->write(PHP_EOL); + $output->write(\PHP_EOL); } - return parent::doRun($input, $output); } - - protected function getDefaultInputDefinition(): InputDefinition + protected function getDefaultInputDefinition() : \RectorPrefix20210509\Symfony\Component\Console\Input\InputDefinition { $defaultInputDefinition = parent::getDefaultInputDefinition(); - $this->removeUnusedOptions($defaultInputDefinition); $this->addCustomOptions($defaultInputDefinition); - return $defaultInputDefinition; } - - private function getNewWorkingDir(InputInterface $input): string + private function getNewWorkingDir(\RectorPrefix20210509\Symfony\Component\Console\Input\InputInterface $input) : string { $workingDir = $input->getParameterOption('--working-dir'); - if ($workingDir !== false && ! is_dir($workingDir)) { - $errorMessage = sprintf('Invalid working directory specified, "%s" does not exist.', $workingDir); - throw new InvalidConfigurationException($errorMessage); + if ($workingDir !== \false && !\is_dir($workingDir)) { + $errorMessage = \sprintf('Invalid working directory specified, "%s" does not exist.', $workingDir); + throw new \Rector\Core\Exception\Configuration\InvalidConfigurationException($errorMessage); } - return (string) $workingDir; } - - private function shouldPrintMetaInformation(InputInterface $input): bool + private function shouldPrintMetaInformation(\RectorPrefix20210509\Symfony\Component\Console\Input\InputInterface $input) : bool { $hasNoArguments = $input->getFirstArgument() === null; if ($hasNoArguments) { - return false; + return \false; } - $hasVersionOption = $input->hasParameterOption('--version'); if ($hasVersionOption) { - return false; + return \false; } - $outputFormat = $input->getParameterOption(['-o', '--output-format']); - return $outputFormat === ConsoleOutputFormatter::NAME; + return $outputFormat === \Rector\ChangesReporting\Output\ConsoleOutputFormatter::NAME; } - - private function removeUnusedOptions(InputDefinition $inputDefinition): void + private function removeUnusedOptions(\RectorPrefix20210509\Symfony\Component\Console\Input\InputDefinition $inputDefinition) : void { $options = $inputDefinition->getOptions(); - unset($options['quiet'], $options['no-interaction']); - $inputDefinition->setOptions($options); } - - private function addCustomOptions(InputDefinition $inputDefinition): void + private function addCustomOptions(\RectorPrefix20210509\Symfony\Component\Console\Input\InputDefinition $inputDefinition) : void { - $inputDefinition->addOption(new InputOption( - Option::OPTION_CONFIG, - 'c', - InputOption::VALUE_REQUIRED, - 'Path to config file', - $this->getDefaultConfigPath() - )); - - $inputDefinition->addOption(new InputOption( - Option::OPTION_DEBUG, - null, - InputOption::VALUE_NONE, - 'Enable debug verbosity (-vvv)' - )); - - $inputDefinition->addOption(new InputOption( - Option::XDEBUG, - null, - InputOption::VALUE_NONE, - 'Allow running xdebug' - )); - - $inputDefinition->addOption(new InputOption( - Option::OPTION_CLEAR_CACHE, - null, - InputOption::VALUE_NONE, - 'Clear cache' - )); - - $inputDefinition->addOption(new InputOption( - 'working-dir', - null, - InputOption::VALUE_REQUIRED, - 'If specified, use the given directory as working directory.' - )); + $inputDefinition->addOption(new \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption(\Rector\Core\Configuration\Option::OPTION_CONFIG, 'c', \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_REQUIRED, 'Path to config file', $this->getDefaultConfigPath())); + $inputDefinition->addOption(new \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption(\Rector\Core\Configuration\Option::OPTION_DEBUG, null, \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_NONE, 'Enable debug verbosity (-vvv)')); + $inputDefinition->addOption(new \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption(\Rector\Core\Configuration\Option::XDEBUG, null, \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_NONE, 'Allow running xdebug')); + $inputDefinition->addOption(new \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption(\Rector\Core\Configuration\Option::OPTION_CLEAR_CACHE, null, \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_NONE, 'Clear cache')); + $inputDefinition->addOption(new \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption('working-dir', null, \RectorPrefix20210509\Symfony\Component\Console\Input\InputOption::VALUE_REQUIRED, 'If specified, use the given directory as working directory.')); } - - private function getDefaultConfigPath(): string + private function getDefaultConfigPath() : string { - return getcwd() . '/rector.php'; + return \getcwd() . '/rector.php'; } } diff --git a/src/Console/Output/OutputFormatterCollector.php b/src/Console/Output/OutputFormatterCollector.php index 30a2e3b9837..73bdb17d470 100644 --- a/src/Console/Output/OutputFormatterCollector.php +++ b/src/Console/Output/OutputFormatterCollector.php @@ -1,19 +1,16 @@ outputFormatters[$outputFormatter->getName()] = $outputFormatter; } } - - public function getByName(string $name): OutputFormatterInterface + public function getByName(string $name) : \Rector\ChangesReporting\Contract\Output\OutputFormatterInterface { $this->ensureOutputFormatExists($name); - return $this->outputFormatters[$name]; } - /** * @return int[]|string[] */ - public function getNames(): array + public function getNames() : array { - return array_keys($this->outputFormatters); + return \array_keys($this->outputFormatters); } - - private function ensureOutputFormatExists(string $name): void + private function ensureOutputFormatExists(string $name) : void { if (isset($this->outputFormatters[$name])) { return; } - - throw new InvalidConfigurationException(sprintf( - 'Output formatter "%s" was not found. Pick one of "%s".', - $name, - implode('", "', $this->getNames()) - )); + throw new \Rector\Core\Exception\Configuration\InvalidConfigurationException(\sprintf('Output formatter "%s" was not found. Pick one of "%s".', $name, \implode('", "', $this->getNames()))); } } diff --git a/src/Console/Output/RectorOutputStyle.php b/src/Console/Output/RectorOutputStyle.php index 22b888b7074..544fdb2e1af 100644 --- a/src/Console/Output/RectorOutputStyle.php +++ b/src/Console/Output/RectorOutputStyle.php @@ -1,67 +1,56 @@ symfonyStyle = $symfonyStyle; } - - public function error(string $message): void + public function error(string $message) : void { $this->symfonyStyle->error($message); } - - public function warning(string $message): void + public function warning(string $message) : void { $this->symfonyStyle->warning($message); } - - public function success(string $message): void + public function success(string $message) : void { $this->symfonyStyle->success($message); } - - public function note(string $message): void + public function note(string $message) : void { $this->symfonyStyle->note($message); } - - public function title(string $message): void + public function title(string $message) : void { $this->symfonyStyle->title($message); } - - public function writeln(string $message): void + public function writeln(string $message) : void { $this->symfonyStyle->writeln($message); } - - public function newline(int $count = 1): void + public function newline(int $count = 1) : void { $this->symfonyStyle->newLine($count); } - /** * @param string[] $elements */ - public function listing(array $elements): void + public function listing(array $elements) : void { $this->symfonyStyle->listing($elements); } diff --git a/src/Console/Style/SymfonyStyleFactory.php b/src/Console/Style/SymfonyStyleFactory.php index 6683c076f3f..47c96e59b98 100644 --- a/src/Console/Style/SymfonyStyleFactory.php +++ b/src/Console/Style/SymfonyStyleFactory.php @@ -1,42 +1,35 @@ privatesCaller = $privatesCaller; } - - public function create(): SymfonyStyle + public function create() : \RectorPrefix20210509\Symfony\Component\Console\Style\SymfonyStyle { - $argvInput = new ArgvInput(); - $consoleOutput = new ConsoleOutput(); - + $argvInput = new \RectorPrefix20210509\Symfony\Component\Console\Input\ArgvInput(); + $consoleOutput = new \RectorPrefix20210509\Symfony\Component\Console\Output\ConsoleOutput(); // to configure all -v, -vv, -vvv options without memory-lock to Application run() arguments - $this->privatesCaller->callPrivateMethod(new Application(), 'configureIO', [$argvInput, $consoleOutput]); + $this->privatesCaller->callPrivateMethod(new \RectorPrefix20210509\Symfony\Component\Console\Application(), 'configureIO', [$argvInput, $consoleOutput]); $debugArgvInputParameterOption = $argvInput->getParameterOption('--debug'); - // --debug is called if ($debugArgvInputParameterOption === null) { - $consoleOutput->setVerbosity(OutputInterface::VERBOSITY_DEBUG); + $consoleOutput->setVerbosity(\RectorPrefix20210509\Symfony\Component\Console\Output\OutputInterface::VERBOSITY_DEBUG); } - - return new SymfonyStyle($argvInput, $consoleOutput); + return new \RectorPrefix20210509\Symfony\Component\Console\Style\SymfonyStyle($argvInput, $consoleOutput); } } diff --git a/src/Contract/Application/FileDecoratorInterface.php b/src/Contract/Application/FileDecoratorInterface.php index 39059942a07..d5fd2931c9f 100644 --- a/src/Contract/Application/FileDecoratorInterface.php +++ b/src/Contract/Application/FileDecoratorInterface.php @@ -1,15 +1,13 @@ $configuration */ - public function configure(array $configuration): void; + public function configure(array $configuration) : void; } diff --git a/src/Contract/Rector/NonPhpRectorInterface.php b/src/Contract/Rector/NonPhpRectorInterface.php index 7b7e307df78..f84fda79853 100644 --- a/src/Contract/Rector/NonPhpRectorInterface.php +++ b/src/Contract/Rector/NonPhpRectorInterface.php @@ -1,10 +1,9 @@ > */ - public function getNodeTypes(): array; - + public function getNodeTypes() : array; /** * Process Node of matched type * @return Node|Node[]|null */ - public function refactor(Node $node); + public function refactor(\PhpParser\Node $node); } diff --git a/src/Contract/Rector/RectorInterface.php b/src/Contract/Rector/RectorInterface.php index d6a721d846c..832178afac4 100644 --- a/src/Contract/Rector/RectorInterface.php +++ b/src/Contract/Rector/RectorInterface.php @@ -1,11 +1,9 @@ parametersMerger = new ParametersMerger(); + $this->parametersMerger = new \RectorPrefix20210509\Symplify\PackageBuilder\Yaml\ParametersMerger(); } - /** * @return mixed[] */ - public function getConfigureCallValues(string $rectorClass): array + public function getConfigureCallValues(string $rectorClass) : array { return $this->configureCallValuesByRectorClass[$rectorClass] ?? []; } - - public function collectFromServiceAndClassName(string $className, Definition $definition): void + public function collectFromServiceAndClassName(string $className, \RectorPrefix20210509\Symfony\Component\DependencyInjection\Definition $definition) : void { foreach ($definition->getMethodCalls() as $methodCall) { if ($methodCall[0] !== 'configure') { continue; } - $this->addConfigureCallValues($className, $methodCall[1]); } } - /** * @param mixed[] $configureValues */ - private function addConfigureCallValues(string $rectorClass, array $configureValues): void + private function addConfigureCallValues(string $rectorClass, array $configureValues) : void { foreach ($configureValues as $configureValue) { - if (! isset($this->configureCallValuesByRectorClass[$rectorClass])) { + if (!isset($this->configureCallValuesByRectorClass[$rectorClass])) { $this->configureCallValuesByRectorClass[$rectorClass] = $configureValue; } else { - $mergedParameters = $this->parametersMerger->merge( - $this->configureCallValuesByRectorClass[$rectorClass], - $configureValue - ); - + $mergedParameters = $this->parametersMerger->merge($this->configureCallValuesByRectorClass[$rectorClass], $configureValue); $this->configureCallValuesByRectorClass[$rectorClass] = $mergedParameters; } } diff --git a/src/DependencyInjection/CompilerPass/DeprecationWarningCompilerPass.php b/src/DependencyInjection/CompilerPass/DeprecationWarningCompilerPass.php index 40b7546ddfa..0db8563312d 100644 --- a/src/DependencyInjection/CompilerPass/DeprecationWarningCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/DeprecationWarningCompilerPass.php @@ -1,40 +1,32 @@ */ - private const DEPRECATED_PARAMETERS = [ - Option::SETS => 'Use $containerConfigurator->import(); instead', - ]; - - public function process(ContainerBuilder $containerBuilder): void + private const DEPRECATED_PARAMETERS = [\Rector\Core\Configuration\Option::SETS => 'Use $containerConfigurator->import(); instead']; + public function process(\RectorPrefix20210509\Symfony\Component\DependencyInjection\ContainerBuilder $containerBuilder) : void { $parametersBag = $containerBuilder->getParameterBag(); - foreach (self::DEPRECATED_PARAMETERS as $parameter => $message) { - if (! $parametersBag->has($parameter)) { + if (!$parametersBag->has($parameter)) { continue; } - $setsParameters = $parametersBag->get($parameter); if ($setsParameters === []) { continue; } - - $message = sprintf('The "%s" parameter is deprecated. %s', $parameter, $message); - trigger_error($message); + $message = \sprintf('The "%s" parameter is deprecated. %s', $parameter, $message); + \trigger_error($message); // to make it noticable - sleep(2); + \sleep(2); } } } diff --git a/src/DependencyInjection/CompilerPass/MakeRectorsPublicCompilerPass.php b/src/DependencyInjection/CompilerPass/MakeRectorsPublicCompilerPass.php index 3950c1b23a7..14b3e951da1 100644 --- a/src/DependencyInjection/CompilerPass/MakeRectorsPublicCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/MakeRectorsPublicCompilerPass.php @@ -1,27 +1,23 @@ getDefinitions() as $definition) { if ($definition->getClass() === null) { continue; } - - if (! is_a($definition->getClass(), RectorInterface::class, true)) { + if (!\is_a($definition->getClass(), \Rector\Core\Contract\Rector\RectorInterface::class, \true)) { continue; } - - $definition->setPublic(true); + $definition->setPublic(\true); } } } diff --git a/src/DependencyInjection/CompilerPass/MergeImportedRectorConfigureCallValuesCompilerPass.php b/src/DependencyInjection/CompilerPass/MergeImportedRectorConfigureCallValuesCompilerPass.php index 76a7faa9c25..de7362e0292 100644 --- a/src/DependencyInjection/CompilerPass/MergeImportedRectorConfigureCallValuesCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/MergeImportedRectorConfigureCallValuesCompilerPass.php @@ -1,45 +1,38 @@ configureCallValuesCollector = $configureCallValuesCollector; } - - public function process(ContainerBuilder $containerBuilder): void + public function process(\RectorPrefix20210509\Symfony\Component\DependencyInjection\ContainerBuilder $containerBuilder) : void { foreach ($containerBuilder->getDefinitions() as $id => $definition) { $this->completeCollectedArguments($id, $definition); } } - - private function completeCollectedArguments(string $serviceClass, Definition $definition): void + private function completeCollectedArguments(string $serviceClass, \RectorPrefix20210509\Symfony\Component\DependencyInjection\Definition $definition) : void { $configureCallValues = $this->configureCallValuesCollector->getConfigureCallValues($serviceClass); if ($configureCallValues === []) { return; } - $definition->removeMethodCall(self::CONFIGURE_METHOD_NAME); $definition->addMethodCall(self::CONFIGURE_METHOD_NAME, [$configureCallValues]); } diff --git a/src/DependencyInjection/CompilerPass/RemoveSkippedRectorsCompilerPass.php b/src/DependencyInjection/CompilerPass/RemoveSkippedRectorsCompilerPass.php index 94f343000b0..41b5ffdc502 100644 --- a/src/DependencyInjection/CompilerPass/RemoveSkippedRectorsCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/RemoveSkippedRectorsCompilerPass.php @@ -1,58 +1,49 @@ resolveSkippedRectorClasses($containerBuilder); - foreach ($containerBuilder->getDefinitions() as $id => $definition) { if ($definition->getClass() === null) { continue; } - - if (! in_array($definition->getClass(), $skippedRectorClasses, true)) { + if (!\in_array($definition->getClass(), $skippedRectorClasses, \true)) { continue; } - $containerBuilder->removeDefinition($id); } } - /** * @return string[] */ - private function resolveSkippedRectorClasses(ContainerBuilder $containerBuilder): array + private function resolveSkippedRectorClasses(\RectorPrefix20210509\Symfony\Component\DependencyInjection\ContainerBuilder $containerBuilder) : array { - $skipParameters = (array) $containerBuilder->getParameter(Option::SKIP); - - return array_filter($skipParameters, function ($element): bool { + $skipParameters = (array) $containerBuilder->getParameter(\Rector\Core\Configuration\Option::SKIP); + return \array_filter($skipParameters, function ($element) : bool { return $this->isRectorClass($element); }); } - /** * @param mixed $element */ - private function isRectorClass($element): bool + private function isRectorClass($element) : bool { - if (! is_string($element)) { - return false; + if (!\is_string($element)) { + return \false; } - - return is_a($element, RectorInterface::class, true); + return \is_a($element, \Rector\Core\Contract\Rector\RectorInterface::class, \true); } } diff --git a/src/DependencyInjection/CompilerPass/VerifyRectorServiceExistsCompilerPass.php b/src/DependencyInjection/CompilerPass/VerifyRectorServiceExistsCompilerPass.php index 4d6bfe13693..239164cc43b 100644 --- a/src/DependencyInjection/CompilerPass/VerifyRectorServiceExistsCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/VerifyRectorServiceExistsCompilerPass.php @@ -1,33 +1,27 @@ getDefinitions() as $definition) { $class = $definition->getClass(); if ($class === null) { continue; } - - if (! Strings::endsWith($class, 'Rector')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::endsWith($class, 'Rector')) { continue; } - - if (! is_a($class, RectorInterface::class, true)) { - throw new ShouldNotHappenException( - sprintf('Rector rule "%s" not found, please verify that the rule exists', $class) - ); + if (!\is_a($class, \Rector\Core\Contract\Rector\RectorInterface::class, \true)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(\sprintf('Rector rule "%s" not found, please verify that the rule exists', $class)); } } } diff --git a/src/DependencyInjection/Loader/ConfigurableCallValuesCollectingPhpFileLoader.php b/src/DependencyInjection/Loader/ConfigurableCallValuesCollectingPhpFileLoader.php index fd87adfb4d0..5fa916ac5f9 100644 --- a/src/DependencyInjection/Loader/ConfigurableCallValuesCollectingPhpFileLoader.php +++ b/src/DependencyInjection/Loader/ConfigurableCallValuesCollectingPhpFileLoader.php @@ -1,69 +1,49 @@ configureCallValuesCollector = $configureCallValuesCollector; - parent::__construct($containerBuilder, $fileLocator); } - /** * @param mixed $resource * @param null|string $type */ - public function load($resource, $type = null): void + public function load($resource, $type = null) : void { // this call collects root values $this->collectConfigureCallsFromJustImportedConfigurableRectorDefinitions(); - parent::load($resource, $type); - $this->collectConfigureCallsFromJustImportedConfigurableRectorDefinitions(); } - - public function import( - $resource, - $type = null, - $ignoreErrors = false, - $sourceResource = null, - $exclude = null - ): void { + public function import($resource, $type = null, $ignoreErrors = \false, $sourceResource = null, $exclude = null) : void + { // this call collects root values $this->collectConfigureCallsFromJustImportedConfigurableRectorDefinitions(); - parent::import($resource, $type, $ignoreErrors, $sourceResource, $exclude); - $this->collectConfigureCallsFromJustImportedConfigurableRectorDefinitions(); } - - private function collectConfigureCallsFromJustImportedConfigurableRectorDefinitions(): void + private function collectConfigureCallsFromJustImportedConfigurableRectorDefinitions() : void { foreach ($this->container->getDefinitions() as $class => $definition) { /** @var string $class */ - if (! is_a($class, ConfigurableRectorInterface::class, true)) { + if (!\is_a($class, \Rector\Core\Contract\Rector\ConfigurableRectorInterface::class, \true)) { continue; } - $this->configureCallValuesCollector->collectFromServiceAndClassName($class, $definition); } } diff --git a/src/DependencyInjection/RectorContainerFactory.php b/src/DependencyInjection/RectorContainerFactory.php index 8f67d4470de..307b23c5a83 100644 --- a/src/DependencyInjection/RectorContainerFactory.php +++ b/src/DependencyInjection/RectorContainerFactory.php @@ -1,7 +1,6 @@ createEnvironment($configFileInfos); - // mt_rand is needed to invalidate container cache in case of class changes to be registered as services - $isPHPUnitRun = StaticPHPUnitEnvironment::isPHPUnitRun(); - if (! $isPHPUnitRun) { - $environment .= mt_rand(0, 10000); + $isPHPUnitRun = \Rector\Testing\PHPUnit\StaticPHPUnitEnvironment::isPHPUnitRun(); + if (!$isPHPUnitRun) { + $environment .= \mt_rand(0, 10000); } - - $phpStanStubLoader = new PHPStanStubLoader(); + $phpStanStubLoader = new \Rector\Core\Stubs\PHPStanStubLoader(); $phpStanStubLoader->loadStubs(); - - $rectorKernel = new RectorKernel($environment, $isDebug, $configFileInfos); + $rectorKernel = new \Rector\Core\HttpKernel\RectorKernel($environment, $isDebug, $configFileInfos); $rectorKernel->boot(); - return $rectorKernel->getContainer(); } - - public function createFromBootstrapConfigs(BootstrapConfigs $bootstrapConfigs): ContainerInterface + public function createFromBootstrapConfigs(\Rector\Core\ValueObject\Bootstrap\BootstrapConfigs $bootstrapConfigs) : \RectorPrefix20210509\Symfony\Component\DependencyInjection\ContainerInterface { $container = $this->createFromConfigs($bootstrapConfigs->getConfigFileInfos()); - $mainConfigFileInfo = $bootstrapConfigs->getMainConfigFileInfo(); if ($mainConfigFileInfo !== null) { /** @var ChangedFilesDetector $changedFilesDetector */ - $changedFilesDetector = $container->get(ChangedFilesDetector::class); + $changedFilesDetector = $container->get(\Rector\Caching\Detector\ChangedFilesDetector::class); $changedFilesDetector->setFirstResolvedConfigFileInfo($mainConfigFileInfo); } - /** @var Configuration $configuration */ - $configuration = $container->get(Configuration::class); + $configuration = $container->get(\Rector\Core\Configuration\Configuration::class); $configuration->setBootstrapConfigs($bootstrapConfigs); - return $container; } - /** * @see https://symfony.com/doc/current/components/dependency_injection/compilation.html#dumping-the-configuration-for-performance * @param SmartFileInfo[] $configFileInfos */ - private function createEnvironment(array $configFileInfos): string + private function createEnvironment(array $configFileInfos) : string { $configHashes = []; foreach ($configFileInfos as $configFileInfo) { - $configHashes[] = md5_file($configFileInfo->getRealPath()); + $configHashes[] = \md5_file($configFileInfo->getRealPath()); } - - $configHashString = implode('', $configHashes); - return sha1($configHashString); + $configHashString = \implode('', $configHashes); + return \sha1($configHashString); } } diff --git a/src/Differ/DefaultDiffer.php b/src/Differ/DefaultDiffer.php index a2ad4f5814a..f48d54ff8df 100644 --- a/src/Differ/DefaultDiffer.php +++ b/src/Differ/DefaultDiffer.php @@ -1,29 +1,22 @@ 'Original', - 'toFile' => 'New', - ]); - $this->differ = new Differ($strictUnifiedDiffOutputBuilder); + $strictUnifiedDiffOutputBuilder = new \RectorPrefix20210509\SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder(['fromFile' => 'Original', 'toFile' => 'New']); + $this->differ = new \RectorPrefix20210509\SebastianBergmann\Diff\Differ($strictUnifiedDiffOutputBuilder); } - - public function diff(string $old, string $new): string + public function diff(string $old, string $new) : string { if ($old === $new) { return ''; diff --git a/src/Error/ExceptionCorrector.php b/src/Error/ExceptionCorrector.php index 57ffe4bb1cf..706a1def3fc 100644 --- a/src/Error/ExceptionCorrector.php +++ b/src/Error/ExceptionCorrector.php @@ -1,40 +1,30 @@ getTrace()[0])) { + if (!isset($throwable->getTrace()[0])) { return null; } - - if (! isset($throwable->getTrace()[0]['class'])) { + if (!isset($throwable->getTrace()[0]['class'])) { return null; } - /** @var string $class */ $class = $throwable->getTrace()[0]['class']; - if (! is_a($class, RectorInterface::class, true)) { + if (!\is_a($class, \Rector\Core\Contract\Rector\RectorInterface::class, \true)) { return null; } - return $class; } - - public function getAutoloadExceptionMessageAndAddLocation(AnalysedCodeException $analysedCodeException): string + public function getAutoloadExceptionMessageAndAddLocation(\PHPStan\AnalysedCodeException $analysedCodeException) : string { - return sprintf( - 'Analyze error: "%s". Include your files in "$parameters->set(Option::AUTOLOAD_PATHS, [...]);" in "rector.php" config.%sSee https://github.com/rectorphp/rector#configuration', - $analysedCodeException->getMessage(), - PHP_EOL - ); + return \sprintf('Analyze error: "%s". Include your files in "$parameters->set(Option::AUTOLOAD_PATHS, [...]);" in "rector.php" config.%sSee https://github.com/rectorphp/rector#configuration', $analysedCodeException->getMessage(), \PHP_EOL); } } diff --git a/src/Exception/Application/FileProcessingException.php b/src/Exception/Application/FileProcessingException.php index a0edf8c50a0..349e7790a8d 100644 --- a/src/Exception/Application/FileProcessingException.php +++ b/src/Exception/Application/FileProcessingException.php @@ -1,24 +1,16 @@ getRealPath(), - PHP_EOL . PHP_EOL, - $throwable - ); - + $message = \sprintf('Processing file "%s" failed. %s%s', $smartFileInfo->getRealPath(), \PHP_EOL . \PHP_EOL, $throwable); parent::__construct($message); } } diff --git a/src/Exception/Configuration/InvalidConfigurationException.php b/src/Exception/Configuration/InvalidConfigurationException.php index 3d515beddeb..d029a1804b9 100644 --- a/src/Exception/Configuration/InvalidConfigurationException.php +++ b/src/Exception/Configuration/InvalidConfigurationException.php @@ -1,11 +1,9 @@ createDefaultMessageWithLocation(); } - parent::__construct($message, $code, $throwable); } - - private function createDefaultMessageWithLocation(): string + private function createDefaultMessageWithLocation() : string { - $debugBacktrace = debug_backtrace(); - + $debugBacktrace = \debug_backtrace(); $class = $debugBacktrace[2]['class'] ?? null; $function = $debugBacktrace[2]['function']; $line = $debugBacktrace[1]['line']; - - $method = $class ? ($class . '::' . $function) : $function; - - return sprintf('Look at "%s()" on line %d', $method, $line); + $method = $class ? $class . '::' . $function : $function; + return \sprintf('Look at "%s()" on line %d', $method, $line); } } diff --git a/src/Exception/Testing/SuperfluousAfterContentFixtureException.php b/src/Exception/Testing/SuperfluousAfterContentFixtureException.php index 1afef848155..1b994114a61 100644 --- a/src/Exception/Testing/SuperfluousAfterContentFixtureException.php +++ b/src/Exception/Testing/SuperfluousAfterContentFixtureException.php @@ -1,11 +1,9 @@ phpDocInfoFactory = $phpDocInfoFactory; } - - public function isNodeSkippedByRector(Node $node, PhpRectorInterface $phpRector): bool + public function isNodeSkippedByRector(\PhpParser\Node $node, \Rector\Core\Contract\Rector\PhpRectorInterface $phpRector) : bool { - if ($node instanceof PropertyProperty || $node instanceof Const_) { - $node = $node->getAttribute(AttributeKey::PARENT_NODE); + if ($node instanceof \PhpParser\Node\Stmt\PropertyProperty || $node instanceof \PhpParser\Node\Const_) { + $node = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); } - if ($this->hasNoRectorPhpDocTagMatch($node, $phpRector)) { - return true; + return \true; } - - if ($node instanceof Stmt) { - return false; + if ($node instanceof \PhpParser\Node\Stmt) { + return \false; } - // recurse up until a Stmt node is found since it might contain a noRector - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); if ($parentNode === null) { - return false; + return \false; } - return $this->isNodeSkippedByRector($parentNode, $phpRector); } - - private function hasNoRectorPhpDocTagMatch(Node $node, PhpRectorInterface $phpRector): bool + private function hasNoRectorPhpDocTagMatch(\PhpParser\Node $node, \Rector\Core\Contract\Rector\PhpRectorInterface $phpRector) : bool { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - /** @var PhpDocTagNode[] $noRectorTags */ - $noRectorTags = array_merge($phpDocInfo->getTagsByName('noRector'), $phpDocInfo->getTagsByName('norector')); - $rectorClass = get_class($phpRector); - + $noRectorTags = \array_merge($phpDocInfo->getTagsByName('noRector'), $phpDocInfo->getTagsByName('norector')); + $rectorClass = \get_class($phpRector); foreach ($noRectorTags as $noRectorTag) { - if (! $noRectorTag->value instanceof GenericTagValueNode) { - throw new ShouldNotHappenException(); + if (!$noRectorTag->value instanceof \PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - $description = $noRectorTag->value->value; if ($description === '') { - return true; + return \true; } - - $description = ltrim($description, '\\'); + $description = \ltrim($description, '\\'); if ($description === $rectorClass) { - return true; + return \true; } - - if (! is_a($description, RectorInterface::class, true)) { - return true; + if (!\is_a($description, \Rector\Core\Contract\Rector\RectorInterface::class, \true)) { + return \true; } } - - return false; + return \false; } } diff --git a/src/FileSystem/FilesFinder.php b/src/FileSystem/FilesFinder.php index c03c8d2cd12..a7b73884443 100644 --- a/src/FileSystem/FilesFinder.php +++ b/src/FileSystem/FilesFinder.php @@ -1,17 +1,15 @@ filesystemTweaker = $filesystemTweaker; $this->finderSanitizer = $finderSanitizer; $this->fileSystemFilter = $fileSystemFilter; $this->skippedPathsResolver = $skippedPathsResolver; } - /** * @param string[] $source * @param string[] $suffixes * @return SmartFileInfo[] */ - public function findInDirectoriesAndFiles(array $source, array $suffixes): array + public function findInDirectoriesAndFiles(array $source, array $suffixes) : array { - $cacheKey = md5(serialize($source) . serialize($suffixes)); - + $cacheKey = \md5(\serialize($source) . \serialize($suffixes)); if (isset($this->fileInfosBySourceAndSuffixes[$cacheKey])) { return $this->fileInfosBySourceAndSuffixes[$cacheKey]; } - $files = $this->fileSystemFilter->filterFiles($source); $directories = $this->fileSystemFilter->filterDirectories($source); - $smartFileInfos = []; foreach ($files as $file) { - $smartFileInfos[] = new SmartFileInfo($file); + $smartFileInfos[] = new \Symplify\SmartFileSystem\SmartFileInfo($file); } - - $smartFileInfos = array_merge($smartFileInfos, $this->findInDirectories($directories, $suffixes)); + $smartFileInfos = \array_merge($smartFileInfos, $this->findInDirectories($directories, $suffixes)); return $this->fileInfosBySourceAndSuffixes[$cacheKey] = $smartFileInfos; } - /** * @param string[] $directories * @param string[] $suffixes * @return SmartFileInfo[] */ - private function findInDirectories(array $directories, array $suffixes): array + private function findInDirectories(array $directories, array $suffixes) : array { if ($directories === []) { return []; } - $absoluteDirectories = $this->filesystemTweaker->resolveDirectoriesWithFnmatch($directories); if ($absoluteDirectories === []) { return []; } - $suffixesPattern = $this->normalizeSuffixesToPattern($suffixes); - - $finder = Finder::create() - ->followLinks() - ->files() - // skip empty files - ->size('> 0') - ->in($absoluteDirectories) - ->name($suffixesPattern) - ->sortByName(); - + $finder = \RectorPrefix20210509\Symfony\Component\Finder\Finder::create()->followLinks()->files()->size('> 0')->in($absoluteDirectories)->name($suffixesPattern)->sortByName(); $this->addFilterWithExcludedPaths($finder); - return $this->finderSanitizer->sanitize($finder); } - /** * @param string[] $suffixes */ - private function normalizeSuffixesToPattern(array $suffixes): string + private function normalizeSuffixesToPattern(array $suffixes) : string { - $suffixesPattern = implode('|', $suffixes); - return '#\.(' . $suffixesPattern . ')$#'; + $suffixesPattern = \implode('|', $suffixes); + return '#\\.(' . $suffixesPattern . ')$#'; } - - private function addFilterWithExcludedPaths(Finder $finder): void + private function addFilterWithExcludedPaths(\RectorPrefix20210509\Symfony\Component\Finder\Finder $finder) : void { $excludePaths = $this->skippedPathsResolver->resolve(); if ($excludePaths === []) { return; } - - $finder->filter(function (SplFileInfo $splFileInfo) use ($excludePaths): bool { + $finder->filter(function (\RectorPrefix20210509\Symfony\Component\Finder\SplFileInfo $splFileInfo) use($excludePaths) : bool { /** @var string|false $realPath */ $realPath = $splFileInfo->getRealPath(); - if (! $realPath) { + if (!$realPath) { //dead symlink - return false; + return \false; } - // make the path work accross different OSes - $realPath = str_replace('\\', '/', $realPath); - + $realPath = \str_replace('\\', '/', $realPath); // return false to remove file foreach ($excludePaths as $excludePath) { // make the path work accross different OSes - $excludePath = str_replace('\\', '/', $excludePath); - - if (Strings::match($realPath, '#' . preg_quote($excludePath, '#') . '#')) { - return false; + $excludePath = \str_replace('\\', '/', $excludePath); + if (\RectorPrefix20210509\Nette\Utils\Strings::match($realPath, '#' . \preg_quote($excludePath, '#') . '#')) { + return \false; } - $excludePath = $this->normalizeForFnmatch($excludePath); - if (fnmatch($excludePath, $realPath)) { - return false; + if (\fnmatch($excludePath, $realPath)) { + return \false; } } - - return true; + return \true; }); } - /** * "value*" → "*value*" * "*value" → "*value*" */ - private function normalizeForFnmatch(string $path): string + private function normalizeForFnmatch(string $path) : string { // ends with * - if (Strings::match($path, self::ENDS_WITH_ASTERISK_REGEX)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($path, self::ENDS_WITH_ASTERISK_REGEX)) { return '*' . $path; } - // starts with * - if (Strings::match($path, self::STARTS_WITH_ASTERISK_REGEX)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($path, self::STARTS_WITH_ASTERISK_REGEX)) { return $path . '*'; } - return $path; } } diff --git a/src/FileSystem/FilesystemTweaker.php b/src/FileSystem/FilesystemTweaker.php index a7645d78350..c432effa16b 100644 --- a/src/FileSystem/FilesystemTweaker.php +++ b/src/FileSystem/FilesystemTweaker.php @@ -1,63 +1,54 @@ fileSystemGuard = $fileSystemGuard; } - /** * This will turn paths like "src/Symfony/Component/*\/Tests" to existing directory paths * * @param string[] $directories * @return string[] */ - public function resolveDirectoriesWithFnmatch(array $directories): array + public function resolveDirectoriesWithFnmatch(array $directories) : array { $absoluteDirectories = []; foreach ($directories as $directory) { // is fnmatch for directories - if (Strings::contains($directory, '*')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($directory, '*')) { $foundDirectories = $this->foundDirectoriesInGlob($directory); - $absoluteDirectories = array_merge($absoluteDirectories, $foundDirectories); + $absoluteDirectories = \array_merge($absoluteDirectories, $foundDirectories); } else { // is classic directory $this->fileSystemGuard->ensureDirectoryExists($directory); $absoluteDirectories[] = $directory; } } - return $absoluteDirectories; } - /** * @return string[] */ - private function foundDirectoriesInGlob(string $directory): array + private function foundDirectoriesInGlob(string $directory) : array { $foundDirectories = []; - - foreach ((array) glob($directory, GLOB_ONLYDIR) as $foundDirectory) { - if (! is_string($foundDirectory)) { + foreach ((array) \glob($directory, \GLOB_ONLYDIR) as $foundDirectory) { + if (!\is_string($foundDirectory)) { continue; } - $foundDirectories[] = $foundDirectory; } - return $foundDirectories; } } diff --git a/src/FileSystem/PhpFilesFinder.php b/src/FileSystem/PhpFilesFinder.php index b381839eed9..a3024a03900 100644 --- a/src/FileSystem/PhpFilesFinder.php +++ b/src/FileSystem/PhpFilesFinder.php @@ -1,57 +1,43 @@ filesFinder = $filesFinder; $this->configuration = $configuration; $this->cachedFileInfoFilterAndReporter = $cachedFileInfoFilterAndReporter; } - /** * @param string[] $paths * @return SmartFileInfo[] */ - public function findInPaths(array $paths): array + public function findInPaths(array $paths) : array { - $phpFileInfos = $this->filesFinder->findInDirectoriesAndFiles( - $paths, - $this->configuration->getFileExtensions() - ); - + $phpFileInfos = $this->filesFinder->findInDirectoriesAndFiles($paths, $this->configuration->getFileExtensions()); // filter out non-PHP php files, e.g. blade templates in Laravel - $phpFileInfos = array_filter($phpFileInfos, function (SmartFileInfo $smartFileInfo): bool { - return ! Strings::endsWith($smartFileInfo->getPathname(), '.blade.php'); + $phpFileInfos = \array_filter($phpFileInfos, function (\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : bool { + return !\RectorPrefix20210509\Nette\Utils\Strings::endsWith($smartFileInfo->getPathname(), '.blade.php'); }); - return $this->cachedFileInfoFilterAndReporter->filterFileInfos($phpFileInfos); } } diff --git a/src/HttpKernel/RectorKernel.php b/src/HttpKernel/RectorKernel.php index 0f89a4d6854..d6a1bad7863 100644 --- a/src/HttpKernel/RectorKernel.php +++ b/src/HttpKernel/RectorKernel.php @@ -1,7 +1,6 @@ configureCallValuesCollector = new ConfigureCallValuesCollector(); + $this->configureCallValuesCollector = new \Rector\Core\DependencyInjection\Collector\ConfigureCallValuesCollector(); $this->configFileInfos = $configFileInfos; - parent::__construct($environment, $debug); } - - public function getCacheDir(): string + public function getCacheDir() : string { $cacheDirectory = $_ENV['KERNEL_CACHE_DIRECTORY'] ?? null; if ($cacheDirectory !== null) { return $cacheDirectory . '/' . $this->environment; } - // manually configured, so it can be replaced in phar - return sys_get_temp_dir() . '/rector/cache'; + return \sys_get_temp_dir() . '/rector/cache'; } - - public function getLogDir(): string + public function getLogDir() : string { // manually configured, so it can be replaced in phar - return sys_get_temp_dir() . '/rector/log'; + return \sys_get_temp_dir() . '/rector/log'; } - - public function registerContainerConfiguration(LoaderInterface $loader): void + public function registerContainerConfiguration(\RectorPrefix20210509\Symfony\Component\Config\Loader\LoaderInterface $loader) : void { $loader->load(__DIR__ . '/../../config/config.php'); - foreach ($this->configFileInfos as $configFileInfo) { $loader->load($configFileInfo->getRealPath()); } } - /** * @return iterable */ - public function registerBundles(): iterable + public function registerBundles() : iterable { - return [ - new ConsoleColorDiffBundle(), - new ComposerJsonManipulatorBundle(), - new SkipperBundle(), - new SimplePhpDocParserBundle(), - ]; + return [new \RectorPrefix20210509\Symplify\ConsoleColorDiff\Bundle\ConsoleColorDiffBundle(), new \RectorPrefix20210509\Symplify\ComposerJsonManipulator\Bundle\ComposerJsonManipulatorBundle(), new \RectorPrefix20210509\Symplify\Skipper\Bundle\SkipperBundle(), new \RectorPrefix20210509\Symplify\SimplePhpDocParser\Bundle\SimplePhpDocParserBundle()]; } - - protected function build(ContainerBuilder $containerBuilder): void + protected function build(\RectorPrefix20210509\Symfony\Component\DependencyInjection\ContainerBuilder $containerBuilder) : void { // @see https://symfony.com/blog/new-in-symfony-4-4-dependency-injection-improvements-part-1 - $containerBuilder->setParameter('container.dumper.inline_factories', true); + $containerBuilder->setParameter('container.dumper.inline_factories', \true); // to fix reincluding files again - $containerBuilder->setParameter('container.dumper.inline_class_loader', false); - + $containerBuilder->setParameter('container.dumper.inline_class_loader', \false); // must run before AutowireArrayParameterCompilerPass, as the autowired array cannot contain removed services - $containerBuilder->addCompilerPass(new RemoveSkippedRectorsCompilerPass()); - $containerBuilder->addCompilerPass(new AutowireArrayParameterCompilerPass()); - + $containerBuilder->addCompilerPass(new \Rector\Core\DependencyInjection\CompilerPass\RemoveSkippedRectorsCompilerPass()); + $containerBuilder->addCompilerPass(new \RectorPrefix20210509\Symplify\AutowireArrayParameter\DependencyInjection\CompilerPass\AutowireArrayParameterCompilerPass()); // autowire Rectors by default (mainly for tests) - $containerBuilder->addCompilerPass(new AutowireInterfacesCompilerPass([RectorInterface::class])); - $containerBuilder->addCompilerPass(new MakeRectorsPublicCompilerPass()); - - $containerBuilder->addCompilerPass(new DeprecationWarningCompilerPass()); - + $containerBuilder->addCompilerPass(new \RectorPrefix20210509\Symplify\PackageBuilder\DependencyInjection\CompilerPass\AutowireInterfacesCompilerPass([\Rector\Core\Contract\Rector\RectorInterface::class])); + $containerBuilder->addCompilerPass(new \Rector\Core\DependencyInjection\CompilerPass\MakeRectorsPublicCompilerPass()); + $containerBuilder->addCompilerPass(new \Rector\Core\DependencyInjection\CompilerPass\DeprecationWarningCompilerPass()); // add all merged arguments of Rector services - $containerBuilder->addCompilerPass( - new MergeImportedRectorConfigureCallValuesCompilerPass($this->configureCallValuesCollector) - ); - - $containerBuilder->addCompilerPass(new VerifyRectorServiceExistsCompilerPass()); + $containerBuilder->addCompilerPass(new \Rector\Core\DependencyInjection\CompilerPass\MergeImportedRectorConfigureCallValuesCompilerPass($this->configureCallValuesCollector)); + $containerBuilder->addCompilerPass(new \Rector\Core\DependencyInjection\CompilerPass\VerifyRectorServiceExistsCompilerPass()); } - /** * This allows to use "%vendor%" variables in imports * @param ContainerInterface|ContainerBuilder $container */ - protected function getContainerLoader(ContainerInterface $container): DelegatingLoader + protected function getContainerLoader(\RectorPrefix20210509\Symfony\Component\DependencyInjection\ContainerInterface $container) : \RectorPrefix20210509\Symfony\Component\Config\Loader\DelegatingLoader { - $fileLocator = new FileLocator($this); - - $loaderResolver = new LoaderResolver([ - new GlobFileLoader($fileLocator), - new ConfigurableCallValuesCollectingPhpFileLoader( - $container, - $fileLocator, - $this->configureCallValuesCollector - ), - ]); - - return new DelegatingLoader($loaderResolver); + $fileLocator = new \RectorPrefix20210509\Symfony\Component\HttpKernel\Config\FileLocator($this); + $loaderResolver = new \RectorPrefix20210509\Symfony\Component\Config\Loader\LoaderResolver([new \RectorPrefix20210509\Symfony\Component\Config\Loader\GlobFileLoader($fileLocator), new \Rector\Core\DependencyInjection\Loader\ConfigurableCallValuesCollectingPhpFileLoader($container, $fileLocator, $this->configureCallValuesCollector)]); + return new \RectorPrefix20210509\Symfony\Component\Config\Loader\DelegatingLoader($loaderResolver); } } diff --git a/src/Logging/CurrentRectorProvider.php b/src/Logging/CurrentRectorProvider.php index 0f9d4cc14e6..2e9f5e672b4 100644 --- a/src/Logging/CurrentRectorProvider.php +++ b/src/Logging/CurrentRectorProvider.php @@ -1,24 +1,20 @@ currentRector = $rector; } - - public function getCurrentRector(): ?RectorInterface + public function getCurrentRector() : ?\Rector\Core\Contract\Rector\RectorInterface { return $this->currentRector; } diff --git a/src/NodeAnalyzer/CallAnalyzer.php b/src/NodeAnalyzer/CallAnalyzer.php index b2e6ffe3025..241ad97f0b5 100644 --- a/src/NodeAnalyzer/CallAnalyzer.php +++ b/src/NodeAnalyzer/CallAnalyzer.php @@ -1,7 +1,6 @@ > */ - private const OBJECT_CALL_TYPES = [MethodCall::class, NullsafeMethodCall::class, StaticCall::class]; - - public function isObjectCall(Expr $expr): bool + private const OBJECT_CALL_TYPES = [\PhpParser\Node\Expr\MethodCall::class, \PhpParser\Node\Expr\NullsafeMethodCall::class, \PhpParser\Node\Expr\StaticCall::class]; + public function isObjectCall(\PhpParser\Node\Expr $expr) : bool { - if ($expr instanceof BooleanNot) { + if ($expr instanceof \PhpParser\Node\Expr\BooleanNot) { $expr = $expr->expr; } - - if ($expr instanceof BinaryOp) { + if ($expr instanceof \PhpParser\Node\Expr\BinaryOp) { $isObjectCallLeft = $this->isObjectCall($expr->left); $isObjectCallRight = $this->isObjectCall($expr->right); - return $isObjectCallLeft || $isObjectCallRight; } - foreach (self::OBJECT_CALL_TYPES as $objectCallType) { - if (is_a($expr, $objectCallType, true)) { - return true; + if (\is_a($expr, $objectCallType, \true)) { + return \true; } } - - return false; + return \false; } } diff --git a/src/NodeAnalyzer/ChangedNodeAnalyzer.php b/src/NodeAnalyzer/ChangedNodeAnalyzer.php index b3216c7a1b7..ac9c8d660d5 100644 --- a/src/NodeAnalyzer/ChangedNodeAnalyzer.php +++ b/src/NodeAnalyzer/ChangedNodeAnalyzer.php @@ -1,7 +1,6 @@ nodeComparator = $nodeComparator; } - - public function hasNodeChanged(Node $originalNode, Node $node): bool + public function hasNodeChanged(\PhpParser\Node $originalNode, \PhpParser\Node $node) : bool { if ($this->isNameIdentical($node, $originalNode)) { - return false; + return \false; } - // @see https://github.com/rectorphp/rector/issues/6169 - special check, as php-parser skips brackets - if ($node instanceof Encapsed) { + if ($node instanceof \PhpParser\Node\Scalar\Encapsed) { foreach ($node->parts as $encapsedPart) { - $originalEncapsedPart = $encapsedPart->getAttribute(AttributeKey::ORIGINAL_NODE); + $originalEncapsedPart = $encapsedPart->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE); if ($originalEncapsedPart === null) { - return true; + return \true; } } } - // php-parser has no idea about changed docblocks, so to report it correctly, we have to set up this attribute - if ($node->hasAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED)) { - $node->setAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, null); - return true; + if ($node->hasAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED)) { + $node->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, null); + return \true; } - - return ! $this->nodeComparator->areNodesEqual($originalNode, $node); + return !$this->nodeComparator->areNodesEqual($originalNode, $node); } - - private function isNameIdentical(Node $node, Node $originalNode): bool + private function isNameIdentical(\PhpParser\Node $node, \PhpParser\Node $originalNode) : bool { - if (! $originalNode instanceof Name) { - return false; + if (!$originalNode instanceof \PhpParser\Node\Name) { + return \false; } - // names are the same - $originalName = $originalNode->getAttribute(AttributeKey::ORIGINAL_NAME); + $originalName = $originalNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NAME); return $this->nodeComparator->areNodesEqual($originalName, $node); } } diff --git a/src/NodeAnalyzer/ClassAnalyzer.php b/src/NodeAnalyzer/ClassAnalyzer.php index 0d36b029b37..35e80fb57ee 100644 --- a/src/NodeAnalyzer/ClassAnalyzer.php +++ b/src/NodeAnalyzer/ClassAnalyzer.php @@ -1,55 +1,46 @@ nodeNameResolver = $nodeNameResolver; } - - public function isAnonymousClass(Node $node): bool + public function isAnonymousClass(\PhpParser\Node $node) : bool { - if (! $node instanceof Class_) { - return false; + if (!$node instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof New_) { - return false; + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node\Expr\New_) { + return \false; } - if ($node->isAnonymous()) { - return true; + return \true; } - $className = $this->nodeNameResolver->getName($node); if ($className === null) { - return true; + return \true; } - // match PHPStan pattern for anonymous classes - return (bool) Strings::match($className, self::ANONYMOUS_CLASS_REGEX); + return (bool) \RectorPrefix20210509\Nette\Utils\Strings::match($className, self::ANONYMOUS_CLASS_REGEX); } } diff --git a/src/NodeAnalyzer/CompactFuncCallAnalyzer.php b/src/NodeAnalyzer/CompactFuncCallAnalyzer.php index 9ebda807e9a..3d3bce11568 100644 --- a/src/NodeAnalyzer/CompactFuncCallAnalyzer.php +++ b/src/NodeAnalyzer/CompactFuncCallAnalyzer.php @@ -1,48 +1,40 @@ nodeNameResolver = $nodeNameResolver; } - - public function isInCompact(FuncCall $funcCall, Variable $variable): bool + public function isInCompact(\PhpParser\Node\Expr\FuncCall $funcCall, \PhpParser\Node\Expr\Variable $variable) : bool { - if (! $this->nodeNameResolver->isName($funcCall, 'compact')) { - return false; + if (!$this->nodeNameResolver->isName($funcCall, 'compact')) { + return \false; } - $variableName = $variable->name; - if (! is_string($variableName)) { - return false; + if (!\is_string($variableName)) { + return \false; } - $args = $funcCall->args; foreach ($args as $arg) { - if (! $arg->value instanceof String_) { + if (!$arg->value instanceof \PhpParser\Node\Scalar\String_) { continue; } - if ($arg->value->value === $variableName) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/src/NodeAnalyzer/ConstFetchAnalyzer.php b/src/NodeAnalyzer/ConstFetchAnalyzer.php index 60d12a4e470..8c87cde7038 100644 --- a/src/NodeAnalyzer/ConstFetchAnalyzer.php +++ b/src/NodeAnalyzer/ConstFetchAnalyzer.php @@ -1,47 +1,40 @@ isTrue($node)) { - return true; + return \true; } return $this->isFalse($node); } - - public function isFalse(Node $node): bool + public function isFalse(\PhpParser\Node $node) : bool { return $this->isConstantWithLowercasedName($node, 'false'); } - - public function isTrue(Node $node): bool + public function isTrue(\PhpParser\Node $node) : bool { return $this->isConstantWithLowercasedName($node, 'true'); } - - public function isNull(Node $node): bool + public function isNull(\PhpParser\Node $node) : bool { return $this->isConstantWithLowercasedName($node, 'null'); } - - private function isConstantWithLowercasedName(Node $node, string $name): bool + private function isConstantWithLowercasedName(\PhpParser\Node $node, string $name) : bool { - if (! $node instanceof ConstFetch) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\ConstFetch) { + return \false; } - return $node->name->toLowerString() === $name; } } diff --git a/src/NodeAnalyzer/ParamAnalyzer.php b/src/NodeAnalyzer/ParamAnalyzer.php index 1c94e369123..c1e24f42d65 100644 --- a/src/NodeAnalyzer/ParamAnalyzer.php +++ b/src/NodeAnalyzer/ParamAnalyzer.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeComparator = $nodeComparator; } - - public function isParamUsedInClassMethod(ClassMethod $classMethod, Param $param): bool + public function isParamUsedInClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Param $param) : bool { - return (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (Node $node) use ( - $param - ): bool { - if (! $node instanceof Variable) { - return false; + return (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (\PhpParser\Node $node) use($param) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeComparator->areNodesEqual($node, $param->var); }); } - /** * @param Param[] $params */ - public function hasPropertyPromotion(array $params): bool + public function hasPropertyPromotion(array $params) : bool { foreach ($params as $param) { if ($param->flags !== 0) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/src/NodeAnalyzer/PromotedPropertyParamCleaner.php b/src/NodeAnalyzer/PromotedPropertyParamCleaner.php index 044099edaf7..ba2936642f3 100644 --- a/src/NodeAnalyzer/PromotedPropertyParamCleaner.php +++ b/src/NodeAnalyzer/PromotedPropertyParamCleaner.php @@ -1,18 +1,16 @@ flags = 0; $cleanParams[] = $cleanParam; } - return $cleanParams; } } diff --git a/src/NodeAnalyzer/PropertyFetchAnalyzer.php b/src/NodeAnalyzer/PropertyFetchAnalyzer.php index f90b1155c56..a5490fad96e 100644 --- a/src/NodeAnalyzer/PropertyFetchAnalyzer.php +++ b/src/NodeAnalyzer/PropertyFetchAnalyzer.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; } - - public function isLocalPropertyFetch(Node $node): bool + public function isLocalPropertyFetch(\PhpParser\Node $node) : bool { - if ($node instanceof PropertyFetch) { - if ($node->var instanceof MethodCall) { - return false; + if ($node instanceof \PhpParser\Node\Expr\PropertyFetch) { + if ($node->var instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - return $this->nodeNameResolver->isName($node->var, 'this'); } - - if ($node instanceof StaticPropertyFetch) { + if ($node instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { return $this->nodeNameResolver->isName($node->class, 'self'); } - - return false; + return \false; } - - public function isLocalPropertyFetchName(Node $node, string $desiredPropertyName): bool + public function isLocalPropertyFetchName(\PhpParser\Node $node, string $desiredPropertyName) : bool { - if (! $this->isLocalPropertyFetch($node)) { - return false; + if (!$this->isLocalPropertyFetch($node)) { + return \false; } - /** @var PropertyFetch|StaticPropertyFetch $node */ return $this->nodeNameResolver->isName($node->name, $desiredPropertyName); } - - public function containsLocalPropertyFetchName(ClassMethod $classMethod, string $propertyName): bool + public function containsLocalPropertyFetchName(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $propertyName) : bool { - return (bool) $this->betterNodeFinder->findFirst($classMethod, function (Node $node) use ($propertyName): bool { - if (! $node instanceof PropertyFetch) { - return false; + return (bool) $this->betterNodeFinder->findFirst($classMethod, function (\PhpParser\Node $node) use($propertyName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - return $this->nodeNameResolver->isName($node->name, $propertyName); }); } - /** * @param PropertyFetch|StaticPropertyFetch $expr */ - public function isPropertyToSelf(Expr $expr): bool + public function isPropertyToSelf(\PhpParser\Node\Expr $expr) : bool { - if ($expr instanceof PropertyFetch && ! $this->nodeNameResolver->isName($expr->var, 'this')) { - return false; + if ($expr instanceof \PhpParser\Node\Expr\PropertyFetch && !$this->nodeNameResolver->isName($expr->var, 'this')) { + return \false; } - - if ($expr instanceof StaticPropertyFetch && ! $this->nodeNameResolver->isName($expr->class, 'self')) { - return false; + if ($expr instanceof \PhpParser\Node\Expr\StaticPropertyFetch && !$this->nodeNameResolver->isName($expr->class, 'self')) { + return \false; } - - $classLike = $expr->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return false; + $classLike = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } - foreach ($classLike->getProperties() as $property) { - if (! $this->nodeNameResolver->areNamesEqual($property->props[0], $expr)) { + if (!$this->nodeNameResolver->areNamesEqual($property->props[0], $expr)) { continue; } - - return true; + return \true; } - - return false; + return \false; } - /** * Matches: * "$this->someValue = $;" */ - public function isVariableAssignToThisPropertyFetch(Node $node, string $variableName): bool + public function isVariableAssignToThisPropertyFetch(\PhpParser\Node $node, string $variableName) : bool { - if (! $node instanceof Assign) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - if (! $node->expr instanceof Variable) { - return false; + if (!$node->expr instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - - if (! $this->nodeNameResolver->isName($node->expr, $variableName)) { - return false; + if (!$this->nodeNameResolver->isName($node->expr, $variableName)) { + return \false; } - return $this->isLocalPropertyFetch($node->var); } - /** * @param string[] $propertyNames */ - public function isLocalPropertyOfNames(Node $node, array $propertyNames): bool + public function isLocalPropertyOfNames(\PhpParser\Node $node, array $propertyNames) : bool { - if (! $this->isLocalPropertyFetch($node)) { - return false; + if (!$this->isLocalPropertyFetch($node)) { + return \false; } - /** @var PropertyFetch $node */ return $this->nodeNameResolver->isNames($node->name, $propertyNames); } diff --git a/src/NodeAnalyzer/PropertyPresenceChecker.php b/src/NodeAnalyzer/PropertyPresenceChecker.php index 4c63cd34b8d..c4f3f69f44e 100644 --- a/src/NodeAnalyzer/PropertyPresenceChecker.php +++ b/src/NodeAnalyzer/PropertyPresenceChecker.php @@ -1,7 +1,6 @@ promotedPropertyResolver = $promotedPropertyResolver; $this->nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; } - /** * Includes parent classes and traits */ - public function hasClassContextPropertyByName(Class_ $class, string $propertyName): bool + public function hasClassContextPropertyByName(\PhpParser\Node\Stmt\Class_ $class, string $propertyName) : bool { $className = $this->nodeNameResolver->getName($class); if ($className === null) { - return false; + return \false; } - - if (! $this->reflectionProvider->hasClass($className)) { - return false; + if (!$this->reflectionProvider->hasClass($className)) { + return \false; } - $property = $class->getProperty($propertyName); - if ($property instanceof Property) { - return true; + if ($property instanceof \PhpParser\Node\Stmt\Property) { + return \true; } - $availablePropertyReflections = $this->getParentClassPublicAndProtectedPropertyReflections($className); - foreach ($availablePropertyReflections as $availablePropertyReflection) { if ($availablePropertyReflection->getName() !== $propertyName) { continue; } - - return true; + return \true; } - $promotedPropertyParams = $this->promotedPropertyResolver->resolveFromClass($class); foreach ($promotedPropertyParams as $promotedPropertyParam) { if ($this->nodeNameResolver->isName($promotedPropertyParam, $propertyName)) { - return true; + return \true; } } - - return false; + return \false; } - /** * @return ReflectionProperty[] */ - private function getParentClassPublicAndProtectedPropertyReflections(string $className): array + private function getParentClassPublicAndProtectedPropertyReflections(string $className) : array { - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return []; } - $classReflection = $this->reflectionProvider->getClass($className); - $propertyReflections = []; foreach ($classReflection->getParents() as $parentClassReflection) { $nativeReflectionClass = $parentClassReflection->getNativeReflection(); - - $currentPropertyReflections = $nativeReflectionClass->getProperties( - ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED - ); - - $propertyReflections = array_merge($propertyReflections, $currentPropertyReflections); + $currentPropertyReflections = $nativeReflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED); + $propertyReflections = \array_merge($propertyReflections, $currentPropertyReflections); } - return $propertyReflections; } } diff --git a/src/NodeManipulator/ArrayManipulator.php b/src/NodeManipulator/ArrayManipulator.php index 6e865757d36..5ac6bbad490 100644 --- a/src/NodeManipulator/ArrayManipulator.php +++ b/src/NodeManipulator/ArrayManipulator.php @@ -1,7 +1,6 @@ rectorChangeCollector = $rectorChangeCollector; } - - public function isArrayOnlyScalarValues(Array_ $array): bool + public function isArrayOnlyScalarValues(\PhpParser\Node\Expr\Array_ $array) : bool { foreach ($array->items as $arrayItem) { - if (! $arrayItem instanceof ArrayItem) { + if (!$arrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - - if ($arrayItem->value instanceof Array_) { - if (! $this->isArrayOnlyScalarValues($arrayItem->value)) { - return false; + if ($arrayItem->value instanceof \PhpParser\Node\Expr\Array_) { + if (!$this->isArrayOnlyScalarValues($arrayItem->value)) { + return \false; } - continue; } - - if ($arrayItem->value instanceof Scalar) { + if ($arrayItem->value instanceof \PhpParser\Node\Scalar) { continue; } - - return false; + return \false; } - - return true; + return \true; } - - public function addItemToArrayUnderKey(Array_ $array, ArrayItem $newArrayItem, string $key): void + public function addItemToArrayUnderKey(\PhpParser\Node\Expr\Array_ $array, \PhpParser\Node\Expr\ArrayItem $newArrayItem, string $key) : void { foreach ($array->items as $item) { if ($item === null) { continue; } - if ($this->hasKeyName($item, $key)) { - if (! $item->value instanceof Array_) { + if (!$item->value instanceof \PhpParser\Node\Expr\Array_) { continue; } - $item->value->items[] = $newArrayItem; return; } } - - $array->items[] = new ArrayItem(new Array_([$newArrayItem]), new String_($key)); + $array->items[] = new \PhpParser\Node\Expr\ArrayItem(new \PhpParser\Node\Expr\Array_([$newArrayItem]), new \PhpParser\Node\Scalar\String_($key)); } - - public function findItemInInArrayByKeyAndUnset(Array_ $array, string $keyName): ?ArrayItem + public function findItemInInArrayByKeyAndUnset(\PhpParser\Node\Expr\Array_ $array, string $keyName) : ?\PhpParser\Node\Expr\ArrayItem { foreach ($array->items as $i => $item) { if ($item === null) { continue; } - - if (! $this->hasKeyName($item, $keyName)) { + if (!$this->hasKeyName($item, $keyName)) { continue; } - $removedArrayItem = $array->items[$i]; - if (! $removedArrayItem instanceof ArrayItem) { + if (!$removedArrayItem instanceof \PhpParser\Node\Expr\ArrayItem) { continue; } - // remove + recount for the printer unset($array->items[$i]); - $this->rectorChangeCollector->notifyNodeFileInfo($removedArrayItem); - return $item; } - return null; } - - public function hasKeyName(ArrayItem $arrayItem, string $name): bool + public function hasKeyName(\PhpParser\Node\Expr\ArrayItem $arrayItem, string $name) : bool { - if (! $arrayItem->key instanceof String_) { - return false; + if (!$arrayItem->key instanceof \PhpParser\Node\Scalar\String_) { + return \false; } return $arrayItem->key->value === $name; } diff --git a/src/NodeManipulator/AssignManipulator.php b/src/NodeManipulator/AssignManipulator.php index 44c83694784..51e8e573342 100644 --- a/src/NodeManipulator/AssignManipulator.php +++ b/src/NodeManipulator/AssignManipulator.php @@ -1,7 +1,6 @@ > */ - private const MODIFYING_NODE_TYPES = [ - AssignOp::class, - PreDec::class, - PostDec::class, - PreInc::class, - PostInc::class, - ]; - + private const MODIFYING_NODE_TYPES = [\PhpParser\Node\Expr\AssignOp::class, \PhpParser\Node\Expr\PreDec::class, \PhpParser\Node\Expr\PostDec::class, \PhpParser\Node\Expr\PreInc::class, \PhpParser\Node\Expr\PostInc::class]; /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var NodeComparator */ private $nodeComparator; - /** * @var BetterNodeFinder */ private $betterNodeFinder; - /** * @var PropertyFetchAnalyzer */ private $propertyFetchAnalyzer; - /** * @var TypeChecker */ private $typeChecker; - - public function __construct( - NodeNameResolver $nodeNameResolver, - NodeComparator $nodeComparator, - BetterNodeFinder $betterNodeFinder, - PropertyFetchAnalyzer $propertyFetchAnalyzer, - TypeChecker $typeChecker - ) { + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\Core\PhpParser\Comparing\NodeComparator $nodeComparator, \Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder, \Rector\Core\NodeAnalyzer\PropertyFetchAnalyzer $propertyFetchAnalyzer, \RectorPrefix20210509\Symplify\PackageBuilder\Php\TypeChecker $typeChecker) + { $this->nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; $this->propertyFetchAnalyzer = $propertyFetchAnalyzer; $this->typeChecker = $typeChecker; $this->nodeComparator = $nodeComparator; } - /** * Matches: * each() = [1, 2]; */ - public function isListToEachAssign(Assign $assign): bool + public function isListToEachAssign(\PhpParser\Node\Expr\Assign $assign) : bool { - if (! $assign->expr instanceof FuncCall) { - return false; + if (!$assign->expr instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - - if (! $assign->var instanceof List_) { - return false; + if (!$assign->var instanceof \PhpParser\Node\Expr\List_) { + return \false; } - return $this->nodeNameResolver->isName($assign->expr, 'each'); } - - public function isLeftPartOfAssign(Node $node): bool + public function isLeftPartOfAssign(\PhpParser\Node $node) : bool { - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Assign && $this->nodeComparator->areNodesEqual($parent->var, $node)) { - return true; + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Expr\Assign && $this->nodeComparator->areNodesEqual($parent->var, $node)) { + return \true; } - if ($parent !== null && $this->typeChecker->isInstanceOf($parent, self::MODIFYING_NODE_TYPES)) { - return true; + return \true; } - // traverse up to array dim fetches - if ($parent instanceof ArrayDimFetch) { + if ($parent instanceof \PhpParser\Node\Expr\ArrayDimFetch) { $previousParent = $parent; - while ($parent instanceof ArrayDimFetch) { + while ($parent instanceof \PhpParser\Node\Expr\ArrayDimFetch) { $previousParent = $parent; - $parent = $parent->getAttribute(AttributeKey::PARENT_NODE); + $parent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); } - - if ($parent instanceof Assign) { + if ($parent instanceof \PhpParser\Node\Expr\Assign) { return $parent->var === $previousParent; } } - - return false; + return \false; } - - public function isNodePartOfAssign(Node $node): bool + public function isNodePartOfAssign(\PhpParser\Node $node) : bool { $previousNode = $node; - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); - - while ($parentNode !== null && ! $parentNode instanceof Expression) { - if ($parentNode instanceof Assign && $this->nodeComparator->areNodesEqual( - $parentNode->var, - $previousNode - )) { - return true; + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + while ($parentNode !== null && !$parentNode instanceof \PhpParser\Node\Stmt\Expression) { + if ($parentNode instanceof \PhpParser\Node\Expr\Assign && $this->nodeComparator->areNodesEqual($parentNode->var, $previousNode)) { + return \true; } - $previousNode = $parentNode; - $parentNode = $parentNode->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); } - - return false; + return \false; } - /** * @return array */ - public function resolveAssignsToLocalPropertyFetches(FunctionLike $functionLike): array + public function resolveAssignsToLocalPropertyFetches(\PhpParser\Node\FunctionLike $functionLike) : array { - return $this->betterNodeFinder->find((array) $functionLike->getStmts(), function (Node $node): bool { - if (! $this->propertyFetchAnalyzer->isLocalPropertyFetch($node)) { - return false; + return $this->betterNodeFinder->find((array) $functionLike->getStmts(), function (\PhpParser\Node $node) : bool { + if (!$this->propertyFetchAnalyzer->isLocalPropertyFetch($node)) { + return \false; } - return $this->isLeftPartOfAssign($node); }); } diff --git a/src/NodeManipulator/BinaryOpManipulator.php b/src/NodeManipulator/BinaryOpManipulator.php index 49ab80aed96..55dec21a127 100644 --- a/src/NodeManipulator/BinaryOpManipulator.php +++ b/src/NodeManipulator/BinaryOpManipulator.php @@ -1,7 +1,6 @@ assignAndBinaryMap = $assignAndBinaryMap; } - /** * Tries to match left or right parts (xor), * returns null or match on first condition and then second condition. No matter what the origin order is. @@ -33,127 +29,102 @@ final class BinaryOpManipulator * @param callable|class-string $firstCondition * @param callable|class-string $secondCondition */ - public function matchFirstAndSecondConditionNode( - BinaryOp $binaryOp, - $firstCondition, - $secondCondition - ): ?TwoNodeMatch { + public function matchFirstAndSecondConditionNode(\PhpParser\Node\Expr\BinaryOp $binaryOp, $firstCondition, $secondCondition) : ?\Rector\Php71\ValueObject\TwoNodeMatch + { $this->validateCondition($firstCondition); $this->validateCondition($secondCondition); - $firstCondition = $this->normalizeCondition($firstCondition); $secondCondition = $this->normalizeCondition($secondCondition); - if ($firstCondition($binaryOp->left, $binaryOp->right) && $secondCondition($binaryOp->right, $binaryOp->left)) { - return new TwoNodeMatch($binaryOp->left, $binaryOp->right); + return new \Rector\Php71\ValueObject\TwoNodeMatch($binaryOp->left, $binaryOp->right); } - if (! $firstCondition($binaryOp->right, $binaryOp->left)) { + if (!$firstCondition($binaryOp->right, $binaryOp->left)) { return null; } - if (! $secondCondition($binaryOp->left, $binaryOp->right)) { + if (!$secondCondition($binaryOp->left, $binaryOp->right)) { return null; } - return new TwoNodeMatch($binaryOp->right, $binaryOp->left); + return new \Rector\Php71\ValueObject\TwoNodeMatch($binaryOp->right, $binaryOp->left); } - - public function inverseBinaryOp(BinaryOp $binaryOp): ?BinaryOp + public function inverseBinaryOp(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\PhpParser\Node\Expr\BinaryOp { // no nesting - if ($binaryOp->left instanceof BooleanOr) { + if ($binaryOp->left instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return null; } - - if ($binaryOp->right instanceof BooleanOr) { + if ($binaryOp->right instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return null; } - $inversedNodeClass = $this->resolveInversedNodeClass($binaryOp); if ($inversedNodeClass === null) { return null; } - $firstInversedNode = $this->inverseNode($binaryOp->left); $secondInversedNode = $this->inverseNode($binaryOp->right); - return new $inversedNodeClass($firstInversedNode, $secondInversedNode); } - - public function invertCondition(BinaryOp $binaryOp): ?BinaryOp + public function invertCondition(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?\PhpParser\Node\Expr\BinaryOp { // no nesting - if ($binaryOp->left instanceof BooleanOr) { + if ($binaryOp->left instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return null; } - - if ($binaryOp->right instanceof BooleanOr) { + if ($binaryOp->right instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { return null; } - $inversedNodeClass = $this->resolveInversedNodeClass($binaryOp); if ($inversedNodeClass === null) { return null; } - return new $inversedNodeClass($binaryOp->left, $binaryOp->right); } - - public function inverseNode(Expr $expr): Node + public function inverseNode(\PhpParser\Node\Expr $expr) : \PhpParser\Node { - if ($expr instanceof BinaryOp) { + if ($expr instanceof \PhpParser\Node\Expr\BinaryOp) { $inversedBinaryOp = $this->assignAndBinaryMap->getInversed($expr); if ($inversedBinaryOp) { return new $inversedBinaryOp($expr->left, $expr->right); } } - - if ($expr instanceof BooleanNot) { + if ($expr instanceof \PhpParser\Node\Expr\BooleanNot) { return $expr->expr; } - - return new BooleanNot($expr); + return new \PhpParser\Node\Expr\BooleanNot($expr); } - /** * @param callable|class-string $firstCondition */ - private function validateCondition($firstCondition): void + private function validateCondition($firstCondition) : void { - if (is_callable($firstCondition)) { + if (\is_callable($firstCondition)) { return; } - - if (is_a($firstCondition, Node::class, true)) { + if (\is_a($firstCondition, \PhpParser\Node::class, \true)) { return; } - - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - /** * @param callable|class-string $condition */ - private function normalizeCondition($condition): callable + private function normalizeCondition($condition) : callable { - if (is_callable($condition)) { + if (\is_callable($condition)) { return $condition; } - - return function (Node $node) use ($condition): bool { - return is_a($node, $condition, true); + return function (\PhpParser\Node $node) use($condition) : bool { + return \is_a($node, $condition, \true); }; } - - private function resolveInversedNodeClass(BinaryOp $binaryOp): ?string + private function resolveInversedNodeClass(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?string { $inversedNodeClass = $this->assignAndBinaryMap->getInversed($binaryOp); if ($inversedNodeClass !== null) { return $inversedNodeClass; } - - if ($binaryOp instanceof BooleanOr) { - return BooleanAnd::class; + if ($binaryOp instanceof \PhpParser\Node\Expr\BinaryOp\BooleanOr) { + return \PhpParser\Node\Expr\BinaryOp\BooleanAnd::class; } - return null; } } diff --git a/src/NodeManipulator/ChildAndParentClassManipulator.php b/src/NodeManipulator/ChildAndParentClassManipulator.php index f899dda00de..9c1b442f619 100644 --- a/src/NodeManipulator/ChildAndParentClassManipulator.php +++ b/src/NodeManipulator/ChildAndParentClassManipulator.php @@ -1,7 +1,6 @@ nodeFactory = $nodeFactory; $this->nodeNameResolver = $nodeNameResolver; $this->nodeRepository = $nodeRepository; @@ -62,106 +48,78 @@ final class ChildAndParentClassManipulator $this->reflectionProvider = $reflectionProvider; $this->parentClassScopeResolver = $parentClassScopeResolver; } - /** * Add "parent::__construct()" where needed */ - public function completeParentConstructor(Class_ $class, ClassMethod $classMethod): void + public function completeParentConstructor(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt\ClassMethod $classMethod) : void { $className = $this->nodeNameResolver->getName($class); if ($className === null) { return; } - - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return; } - $classReflection = $this->reflectionProvider->getClass($className); $parentClassReflection = $classReflection->getParentClass(); - if ($parentClassReflection === false) { + if ($parentClassReflection === \false) { return; } - // not in analyzed scope, nothing we can do $parentClassNode = $this->nodeRepository->findClass($parentClassReflection->getName()); - if ($parentClassNode instanceof Class_) { + if ($parentClassNode instanceof \PhpParser\Node\Stmt\Class_) { $this->completeParentConstructorBasedOnParentNode($parentClassNode, $classMethod); return; } - // complete parent call for __construct() - if ($parentClassReflection->hasMethod(MethodName::CONSTRUCT)) { + if ($parentClassReflection->hasMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT)) { $staticCall = $this->nodeFactory->createParentConstructWithParams([]); - $classMethod->stmts[] = new Expression($staticCall); + $classMethod->stmts[] = new \PhpParser\Node\Stmt\Expression($staticCall); } } - - public function completeChildConstructors(Class_ $class, ClassMethod $constructorClassMethod): void + public function completeChildConstructors(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt\ClassMethod $constructorClassMethod) : void { $className = $this->nodeNameResolver->getName($class); if ($className === null) { return; } - $childClasses = $this->nodeRepository->findChildrenOfClass($className); - foreach ($childClasses as $childClass) { - $childConstructorClassMethod = $childClass->getMethod(MethodName::CONSTRUCT); - if (! $childConstructorClassMethod instanceof ClassMethod) { + $childConstructorClassMethod = $childClass->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$childConstructorClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { continue; } - // replicate parent parameters - $childConstructorClassMethod->params = array_merge( - $constructorClassMethod->params, - $childConstructorClassMethod->params - ); - - $parentConstructCallNode = $this->nodeFactory->createParentConstructWithParams( - $constructorClassMethod->params - ); - - $childConstructorClassMethod->stmts = array_merge( - [new Expression($parentConstructCallNode)], - (array) $childConstructorClassMethod->stmts - ); + $childConstructorClassMethod->params = \array_merge($constructorClassMethod->params, $childConstructorClassMethod->params); + $parentConstructCallNode = $this->nodeFactory->createParentConstructWithParams($constructorClassMethod->params); + $childConstructorClassMethod->stmts = \array_merge([new \PhpParser\Node\Stmt\Expression($parentConstructCallNode)], (array) $childConstructorClassMethod->stmts); } } - - private function completeParentConstructorBasedOnParentNode(Class_ $parentClassNode, ClassMethod $classMethod): void + private function completeParentConstructorBasedOnParentNode(\PhpParser\Node\Stmt\Class_ $parentClassNode, \PhpParser\Node\Stmt\ClassMethod $classMethod) : void { $firstParentConstructMethodNode = $this->findFirstParentConstructor($parentClassNode); - if (! $firstParentConstructMethodNode instanceof ClassMethod) { + if (!$firstParentConstructMethodNode instanceof \PhpParser\Node\Stmt\ClassMethod) { return; } - $cleanParams = $this->promotedPropertyParamCleaner->cleanFromFlags($firstParentConstructMethodNode->params); - // replicate parent parameters - $classMethod->params = array_merge($cleanParams, $classMethod->params); - + $classMethod->params = \array_merge($cleanParams, $classMethod->params); $staticCall = $this->nodeFactory->createParentConstructWithParams($firstParentConstructMethodNode->params); - - $classMethod->stmts[] = new Expression($staticCall); + $classMethod->stmts[] = new \PhpParser\Node\Stmt\Expression($staticCall); } - - private function findFirstParentConstructor(Class_ $class): ?ClassMethod + private function findFirstParentConstructor(\PhpParser\Node\Stmt\Class_ $class) : ?\PhpParser\Node\Stmt\ClassMethod { while ($class !== null) { - $constructMethodNode = $class->getMethod(MethodName::CONSTRUCT); + $constructMethodNode = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); if ($constructMethodNode !== null) { return $constructMethodNode; } - $parentClassName = $this->parentClassScopeResolver->resolveParentClassName($class); if ($parentClassName === null) { return null; } - $class = $this->nodeRepository->findClass($parentClassName); } - return null; } } diff --git a/src/NodeManipulator/ClassConstManipulator.php b/src/NodeManipulator/ClassConstManipulator.php index 8afbc6d8e8c..7dcd3481d74 100644 --- a/src/NodeManipulator/ClassConstManipulator.php +++ b/src/NodeManipulator/ClassConstManipulator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; $this->classManipulator = $classManipulator; $this->nodeRepository = $nodeRepository; $this->nodeComparator = $nodeComparator; } - - public function hasClassConstFetch(ClassConst $classConst): bool + public function hasClassConstFetch(\PhpParser\Node\Stmt\ClassConst $classConst) : bool { - $classLike = $classConst->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return false; + $classLike = $classConst->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } - $searchInNodes = [$classLike]; - $usedTraitNames = $this->classManipulator->getUsedTraits($classLike); foreach ($usedTraitNames as $usedTraitName) { $usedTraitName = $this->nodeRepository->findTrait((string) $usedTraitName); - if (! $usedTraitName instanceof Trait_) { + if (!$usedTraitName instanceof \PhpParser\Node\Stmt\Trait_) { continue; } - $searchInNodes[] = $usedTraitName; } - - return (bool) $this->betterNodeFinder->find($searchInNodes, function (Node $node) use ($classConst): bool { + return (bool) $this->betterNodeFinder->find($searchInNodes, function (\PhpParser\Node $node) use($classConst) : bool { // itself if ($this->nodeComparator->areNodesEqual($node, $classConst)) { - return false; + return \false; } - // property + static fetch - if (! $node instanceof ClassConstFetch) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\ClassConstFetch) { + return \false; } - return $this->isNameMatch($node, $classConst); }); } - /** * @see https://github.com/myclabs/php-enum#declaration */ - public function isEnum(ClassConst $classConst): bool + public function isEnum(\PhpParser\Node\Stmt\ClassConst $classConst) : bool { - $classLike = $classConst->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return false; + $classLike = $classConst->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } - if ($classLike->extends === null) { - return false; + return \false; } - return $this->nodeNameResolver->isName($classLike->extends, '*Enum'); } - - private function isNameMatch(ClassConstFetch $classConstFetch, ClassConst $classConst): bool + private function isNameMatch(\PhpParser\Node\Expr\ClassConstFetch $classConstFetch, \PhpParser\Node\Stmt\ClassConst $classConst) : bool { $selfConstantName = 'self::' . $this->nodeNameResolver->getName($classConst); $staticConstantName = 'static::' . $this->nodeNameResolver->getName($classConst); - return $this->nodeNameResolver->isNames($classConstFetch, [$selfConstantName, $staticConstantName]); } } diff --git a/src/NodeManipulator/ClassDependencyManipulator.php b/src/NodeManipulator/ClassDependencyManipulator.php index 38e26f10108..a4193c1c5a2 100644 --- a/src/NodeManipulator/ClassDependencyManipulator.php +++ b/src/NodeManipulator/ClassDependencyManipulator.php @@ -1,7 +1,6 @@ classMethodAssignManipulator = $classMethodAssignManipulator; $this->nodeFactory = $nodeFactory; $this->childAndParentClassManipulator = $childAndParentClassManipulator; @@ -84,186 +66,132 @@ final class ClassDependencyManipulator $this->propertyPresenceChecker = $propertyPresenceChecker; $this->nodeNameResolver = $nodeNameResolver; } - - public function addConstructorDependency(Class_ $class, PropertyMetadata $propertyMetadata): void + public function addConstructorDependency(\PhpParser\Node\Stmt\Class_ $class, \Rector\PostRector\ValueObject\PropertyMetadata $propertyMetadata) : void { if ($this->hasClassPropertyAndDependency($class, $propertyMetadata)) { return; } - - if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::PROPERTY_PROMOTION)) { - $this->classInsertManipulator->addPropertyToClass( - $class, - $propertyMetadata->getName(), - $propertyMetadata->getType() - ); + if (!$this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::PROPERTY_PROMOTION)) { + $this->classInsertManipulator->addPropertyToClass($class, $propertyMetadata->getName(), $propertyMetadata->getType()); } - - if ($this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::PROPERTY_PROMOTION)) { + if ($this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::PROPERTY_PROMOTION)) { $this->addPromotedProperty($class, $propertyMetadata); } else { $assign = $this->nodeFactory->createPropertyAssignment($propertyMetadata->getName()); - - $this->addConstructorDependencyWithCustomAssign( - $class, - $propertyMetadata->getName(), - $propertyMetadata->getType(), - $assign - ); + $this->addConstructorDependencyWithCustomAssign($class, $propertyMetadata->getName(), $propertyMetadata->getType(), $assign); } } - - public function addConstructorDependencyWithCustomAssign( - Class_ $class, - string $name, - ?Type $type, - Assign $assign - ): void { + public function addConstructorDependencyWithCustomAssign(\PhpParser\Node\Stmt\Class_ $class, string $name, ?\PHPStan\Type\Type $type, \PhpParser\Node\Expr\Assign $assign) : void + { /** @var ClassMethod|null $constructorMethod */ - $constructorMethod = $class->getMethod(MethodName::CONSTRUCT); - + $constructorMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); if ($constructorMethod !== null) { - $this->classMethodAssignManipulator->addParameterAndAssignToMethod( - $constructorMethod, - $name, - $type, - $assign - ); + $this->classMethodAssignManipulator->addParameterAndAssignToMethod($constructorMethod, $name, $type, $assign); return; } - - $constructorMethod = $this->nodeFactory->createPublicMethod(MethodName::CONSTRUCT); - + $constructorMethod = $this->nodeFactory->createPublicMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); $this->classMethodAssignManipulator->addParameterAndAssignToMethod($constructorMethod, $name, $type, $assign); $this->classInsertManipulator->addAsFirstMethod($class, $constructorMethod); - $this->childAndParentClassManipulator->completeParentConstructor($class, $constructorMethod); $this->childAndParentClassManipulator->completeChildConstructors($class, $constructorMethod); } - /** * @param Stmt[] $stmts */ - public function addStmtsToConstructorIfNotThereYet(Class_ $class, array $stmts): void + public function addStmtsToConstructorIfNotThereYet(\PhpParser\Node\Stmt\Class_ $class, array $stmts) : void { - $classMethod = $class->getMethod(MethodName::CONSTRUCT); - - if (! $classMethod instanceof ClassMethod) { - $classMethod = $this->nodeFactory->createPublicMethod(MethodName::CONSTRUCT); - + $classMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + $classMethod = $this->nodeFactory->createPublicMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); // keep parent constructor call - if ($this->hasClassParentClassMethod($class, MethodName::CONSTRUCT)) { - $classMethod->stmts[] = $this->createParentClassMethodCall(MethodName::CONSTRUCT); + if ($this->hasClassParentClassMethod($class, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { + $classMethod->stmts[] = $this->createParentClassMethodCall(\Rector\Core\ValueObject\MethodName::CONSTRUCT); } - - $classMethod->stmts = array_merge((array) $classMethod->stmts, $stmts); - - $class->stmts = array_merge($class->stmts, [$classMethod]); + $classMethod->stmts = \array_merge((array) $classMethod->stmts, $stmts); + $class->stmts = \array_merge($class->stmts, [$classMethod]); return; } - $stmts = $this->stmtsManipulator->filterOutExistingStmts($classMethod, $stmts); - // all stmts are already there → skip if ($stmts === []) { return; } - - $classMethod->stmts = array_merge($stmts, (array) $classMethod->stmts); + $classMethod->stmts = \array_merge($stmts, (array) $classMethod->stmts); } - - public function addInjectProperty(Class_ $class, PropertyMetadata $propertyMetadata): void + public function addInjectProperty(\PhpParser\Node\Stmt\Class_ $class, \Rector\PostRector\ValueObject\PropertyMetadata $propertyMetadata) : void { if ($this->propertyPresenceChecker->hasClassContextPropertyByName($class, $propertyMetadata->getName())) { return; } - $this->classInsertManipulator->addInjectPropertyToClass($class, $propertyMetadata); } - - private function addPromotedProperty(Class_ $class, PropertyMetadata $propertyMetadata): void + private function addPromotedProperty(\PhpParser\Node\Stmt\Class_ $class, \Rector\PostRector\ValueObject\PropertyMetadata $propertyMetadata) : void { - $constructClassMethod = $class->getMethod(MethodName::CONSTRUCT); + $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); $param = $this->nodeFactory->createPromotedPropertyParam($propertyMetadata); - - if ($constructClassMethod instanceof ClassMethod) { + if ($constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { // parameter is already added if ($this->hasMethodParameter($constructClassMethod, $propertyMetadata->getName())) { return; } - $constructClassMethod->params[] = $param; } else { - $constructClassMethod = $this->nodeFactory->createPublicMethod(MethodName::CONSTRUCT); + $constructClassMethod = $this->nodeFactory->createPublicMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); $constructClassMethod->params[] = $param; $this->classInsertManipulator->addAsFirstMethod($class, $constructClassMethod); } - $this->childAndParentClassManipulator->completeParentConstructor($class, $constructClassMethod); $this->childAndParentClassManipulator->completeChildConstructors($class, $constructClassMethod); } - - private function hasClassParentClassMethod(Class_ $class, string $methodName): bool + private function hasClassParentClassMethod(\PhpParser\Node\Stmt\Class_ $class, string $methodName) : bool { - $scope = $class->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $class->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - foreach ($classReflection->getParents() as $parentClassReflection) { if ($parentClassReflection->hasMethod($methodName)) { - return true; + return \true; } } - - return false; + return \false; } - - private function createParentClassMethodCall(string $methodName): Expression + private function createParentClassMethodCall(string $methodName) : \PhpParser\Node\Stmt\Expression { - $staticCall = new StaticCall(new Name('parent'), $methodName); - - return new Expression($staticCall); + $staticCall = new \PhpParser\Node\Expr\StaticCall(new \PhpParser\Node\Name('parent'), $methodName); + return new \PhpParser\Node\Stmt\Expression($staticCall); } - - private function isParamInConstructor(Class_ $class, string $propertyName): bool + private function isParamInConstructor(\PhpParser\Node\Stmt\Class_ $class, string $propertyName) : bool { - $constructClassMethod = $class->getMethod(MethodName::CONSTRUCT); - if (! $constructClassMethod instanceof ClassMethod) { - return false; + $constructClassMethod = $class->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT); + if (!$constructClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - foreach ($constructClassMethod->params as $param) { if ($this->nodeNameResolver->isName($param, $propertyName)) { - return true; + return \true; } } - - return false; + return \false; } - - private function hasClassPropertyAndDependency(Class_ $class, PropertyMetadata $propertyMetadata): bool + private function hasClassPropertyAndDependency(\PhpParser\Node\Stmt\Class_ $class, \Rector\PostRector\ValueObject\PropertyMetadata $propertyMetadata) : bool { - if (! $this->propertyPresenceChecker->hasClassContextPropertyByName($class, $propertyMetadata->getName())) { - return false; + if (!$this->propertyPresenceChecker->hasClassContextPropertyByName($class, $propertyMetadata->getName())) { + return \false; } - return $this->isParamInConstructor($class, $propertyMetadata->getName()); } - - private function hasMethodParameter(ClassMethod $classMethod, string $name): bool + private function hasMethodParameter(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $name) : bool { foreach ($classMethod->params as $param) { if ($this->nodeNameResolver->isName($param->var, $name)) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/src/NodeManipulator/ClassInsertManipulator.php b/src/NodeManipulator/ClassInsertManipulator.php index 986fad0d2ce..a58ee9bd980 100644 --- a/src/NodeManipulator/ClassInsertManipulator.php +++ b/src/NodeManipulator/ClassInsertManipulator.php @@ -1,7 +1,6 @@ > */ - private const BEFORE_TRAIT_TYPES = [TraitUse::class, Property::class, ClassMethod::class]; - + private const BEFORE_TRAIT_TYPES = [\PhpParser\Node\Stmt\TraitUse::class, \PhpParser\Node\Stmt\Property::class, \PhpParser\Node\Stmt\ClassMethod::class]; /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var NodeFactory */ private $nodeFactory; - - public function __construct(NodeFactory $nodeFactory, NodeNameResolver $nodeNameResolver) + public function __construct(\Rector\Core\PhpParser\Node\NodeFactory $nodeFactory, \Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver) { $this->nodeNameResolver = $nodeNameResolver; $this->nodeFactory = $nodeFactory; } - /** * @param ClassMethod|Property|ClassConst|ClassMethod $stmt */ - public function addAsFirstMethod(Class_ $class, Stmt $stmt): void + public function addAsFirstMethod(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt $stmt) : void { if ($this->isSuccessToInsertBeforeFirstMethod($class, $stmt)) { return; @@ -50,130 +44,102 @@ final class ClassInsertManipulator if ($this->isSuccessToInsertAfterLastProperty($class, $stmt)) { return; } - $class->stmts[] = $stmt; } - - public function addConstantToClass(Class_ $class, string $constantName, ClassConst $classConst): void + public function addConstantToClass(\PhpParser\Node\Stmt\Class_ $class, string $constantName, \PhpParser\Node\Stmt\ClassConst $classConst) : void { if ($this->hasClassConstant($class, $constantName)) { return; } - $this->addAsFirstMethod($class, $classConst); } - /** * @param Property[] $properties */ - public function addPropertiesToClass(Class_ $class, array $properties): void + public function addPropertiesToClass(\PhpParser\Node\Stmt\Class_ $class, array $properties) : void { foreach ($properties as $property) { $this->addAsFirstMethod($class, $property); } } - /** * @internal Use PropertyAdder service instead */ - public function addPropertyToClass(Class_ $class, string $name, ?Type $type): void + public function addPropertyToClass(\PhpParser\Node\Stmt\Class_ $class, string $name, ?\PHPStan\Type\Type $type) : void { $existingProperty = $class->getProperty($name); - if ($existingProperty instanceof Property) { + if ($existingProperty instanceof \PhpParser\Node\Stmt\Property) { return; } - $property = $this->nodeFactory->createPrivatePropertyFromNameAndType($name, $type); $this->addAsFirstMethod($class, $property); } - - public function addInjectPropertyToClass(Class_ $class, PropertyMetadata $propertyMetadata): void + public function addInjectPropertyToClass(\PhpParser\Node\Stmt\Class_ $class, \Rector\PostRector\ValueObject\PropertyMetadata $propertyMetadata) : void { $existingProperty = $class->getProperty($propertyMetadata->getName()); - if ($existingProperty instanceof Property) { + if ($existingProperty instanceof \PhpParser\Node\Stmt\Property) { return; } - - $property = $this->nodeFactory->createPublicInjectPropertyFromNameAndType( - $propertyMetadata->getName(), - $propertyMetadata->getType() - ); + $property = $this->nodeFactory->createPublicInjectPropertyFromNameAndType($propertyMetadata->getName(), $propertyMetadata->getType()); $this->addAsFirstMethod($class, $property); } - - public function addAsFirstTrait(Class_ $class, string $traitName): void + public function addAsFirstTrait(\PhpParser\Node\Stmt\Class_ $class, string $traitName) : void { - $traitUse = new TraitUse([new FullyQualified($traitName)]); + $traitUse = new \PhpParser\Node\Stmt\TraitUse([new \PhpParser\Node\Name\FullyQualified($traitName)]); $this->addTraitUse($class, $traitUse); } - /** * @param Stmt[] $nodes * @return Stmt[] */ - public function insertBefore(array $nodes, Stmt $stmt, int $key): array + public function insertBefore(array $nodes, \PhpParser\Node\Stmt $stmt, int $key) : array { - array_splice($nodes, $key, 0, [$stmt]); - + \array_splice($nodes, $key, 0, [$stmt]); return $nodes; } - - private function isSuccessToInsertBeforeFirstMethod(Class_ $class, Stmt $stmt): bool + private function isSuccessToInsertBeforeFirstMethod(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt $stmt) : bool { foreach ($class->stmts as $key => $classStmt) { - if (! $classStmt instanceof ClassMethod) { + if (!$classStmt instanceof \PhpParser\Node\Stmt\ClassMethod) { continue; } - $class->stmts = $this->insertBefore($class->stmts, $stmt, $key); - - return true; + return \true; } - - return false; + return \false; } - - private function isSuccessToInsertAfterLastProperty(Class_ $class, Stmt $stmt): bool + private function isSuccessToInsertAfterLastProperty(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt $stmt) : bool { $previousElement = null; foreach ($class->stmts as $key => $classStmt) { - if ($previousElement instanceof Property && ! $classStmt instanceof Property) { + if ($previousElement instanceof \PhpParser\Node\Stmt\Property && !$classStmt instanceof \PhpParser\Node\Stmt\Property) { $class->stmts = $this->insertBefore($class->stmts, $stmt, $key); - - return true; + return \true; } - $previousElement = $classStmt; } - - return false; + return \false; } - - private function hasClassConstant(Class_ $class, string $constantName): bool + private function hasClassConstant(\PhpParser\Node\Stmt\Class_ $class, string $constantName) : bool { foreach ($class->getConstants() as $classConst) { if ($this->nodeNameResolver->isName($classConst, $constantName)) { - return true; + return \true; } } - - return false; + return \false; } - - private function addTraitUse(Class_ $class, TraitUse $traitUse): void + private function addTraitUse(\PhpParser\Node\Stmt\Class_ $class, \PhpParser\Node\Stmt\TraitUse $traitUse) : void { foreach (self::BEFORE_TRAIT_TYPES as $type) { foreach ($class->stmts as $key => $classStmt) { - if (! $classStmt instanceof $type) { + if (!$classStmt instanceof $type) { continue; } - $class->stmts = $this->insertBefore($class->stmts, $traitUse, $key); - return; } } - $class->stmts[] = $traitUse; } } diff --git a/src/NodeManipulator/ClassManipulator.php b/src/NodeManipulator/ClassManipulator.php index b9799cc440b..25e4de08c29 100644 --- a/src/NodeManipulator/ClassManipulator.php +++ b/src/NodeManipulator/ClassManipulator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->nodesToRemoveCollector = $nodesToRemoveCollector; $this->reflectionProvider = $reflectionProvider; } - /** * @deprecated * @param Class_|Trait_ $classLike * @return array */ - public function getUsedTraits(ClassLike $classLike): array + public function getUsedTraits(\PhpParser\Node\Stmt\ClassLike $classLike) : array { $usedTraits = []; foreach ($classLike->getTraitUses() as $traitUse) { @@ -58,102 +49,84 @@ final class ClassManipulator $usedTraits[$traitName] = $trait; } } - return $usedTraits; } - - public function hasParentMethodOrInterface(ObjectType $objectType, string $methodName): bool + public function hasParentMethodOrInterface(\PHPStan\Type\ObjectType $objectType, string $methodName) : bool { - if (! $this->reflectionProvider->hasClass($objectType->getClassName())) { - return false; + if (!$this->reflectionProvider->hasClass($objectType->getClassName())) { + return \false; } - $classReflection = $this->reflectionProvider->getClass($objectType->getClassName()); foreach ($classReflection->getAncestors() as $ancestorClassReflection) { if ($classReflection === $ancestorClassReflection) { continue; } - if ($ancestorClassReflection->hasMethod($methodName)) { - return true; + return \true; } } - - return false; + return \false; } - /** * @return string[] */ - public function getPrivatePropertyNames(Class_ $class): array + public function getPrivatePropertyNames(\PhpParser\Node\Stmt\Class_ $class) : array { - $privateProperties = array_filter($class->getProperties(), function (Property $property): bool { + $privateProperties = \array_filter($class->getProperties(), function (\PhpParser\Node\Stmt\Property $property) : bool { return $property->isPrivate(); }); - return $this->nodeNameResolver->getNames($privateProperties); } - /** * @return string[] */ - public function getImplementedInterfaceNames(Class_ $class): array + public function getImplementedInterfaceNames(\PhpParser\Node\Stmt\Class_ $class) : array { return $this->nodeNameResolver->getNames($class->implements); } - - public function hasInterface(Class_ $class, ObjectType $interfaceObjectType): bool + public function hasInterface(\PhpParser\Node\Stmt\Class_ $class, \PHPStan\Type\ObjectType $interfaceObjectType) : bool { return $this->nodeNameResolver->isName($class->implements, $interfaceObjectType->getClassName()); } - - public function hasTrait(Class_ $class, string $desiredTrait): bool + public function hasTrait(\PhpParser\Node\Stmt\Class_ $class, string $desiredTrait) : bool { foreach ($class->getTraitUses() as $traitUse) { - if (! $this->nodeNameResolver->isName($traitUse->traits, $desiredTrait)) { + if (!$this->nodeNameResolver->isName($traitUse->traits, $desiredTrait)) { continue; } - - return true; + return \true; } - - return false; + return \false; } - - public function replaceTrait(Class_ $class, string $oldTrait, string $newTrait): void + public function replaceTrait(\PhpParser\Node\Stmt\Class_ $class, string $oldTrait, string $newTrait) : void { foreach ($class->getTraitUses() as $traitUse) { foreach ($traitUse->traits as $key => $traitTrait) { - if (! $this->nodeNameResolver->isName($traitTrait, $oldTrait)) { + if (!$this->nodeNameResolver->isName($traitTrait, $oldTrait)) { continue; } - - $traitUse->traits[$key] = new FullyQualified($newTrait); + $traitUse->traits[$key] = new \PhpParser\Node\Name\FullyQualified($newTrait); break; } } } - /** * @param Class_|Interface_ $classLike * @return string[] */ - public function getClassLikeNodeParentInterfaceNames(ClassLike $classLike): array + public function getClassLikeNodeParentInterfaceNames(\PhpParser\Node\Stmt\ClassLike $classLike) : array { - if ($classLike instanceof Class_) { + if ($classLike instanceof \PhpParser\Node\Stmt\Class_) { return $this->nodeNameResolver->getNames($classLike->implements); } - return $this->nodeNameResolver->getNames($classLike->extends); } - - public function removeInterface(Class_ $class, string $desiredInterface): void + public function removeInterface(\PhpParser\Node\Stmt\Class_ $class, string $desiredInterface) : void { foreach ($class->implements as $implement) { - if (! $this->nodeNameResolver->isName($implement, $desiredInterface)) { + if (!$this->nodeNameResolver->isName($implement, $desiredInterface)) { continue; } - $this->nodesToRemoveCollector->addNodeToRemove($implement); } } diff --git a/src/NodeManipulator/ClassMethodAssignManipulator.php b/src/NodeManipulator/ClassMethodAssignManipulator.php index ce51746e3ac..c9417b753d4 100644 --- a/src/NodeManipulator/ClassMethodAssignManipulator.php +++ b/src/NodeManipulator/ClassMethodAssignManipulator.php @@ -1,7 +1,6 @@ */ private $alreadyAddedClassMethodNames = []; - - public function __construct( - BetterNodeFinder $betterNodeFinder, - SimpleCallableNodeTraverser $simpleCallableNodeTraverser, - NodeFactory $nodeFactory, - NodeNameResolver $nodeNameResolver, - VariableManipulator $variableManipulator, - CallReflectionResolver $callReflectionResolver, - NodeComparator $nodeComparator - ) { + public function __construct(\Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder, \RectorPrefix20210509\Symplify\Astral\NodeTraverser\SimpleCallableNodeTraverser $simpleCallableNodeTraverser, \Rector\Core\PhpParser\Node\NodeFactory $nodeFactory, \Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\Core\NodeManipulator\VariableManipulator $variableManipulator, \Rector\Core\PHPStan\Reflection\CallReflectionResolver $callReflectionResolver, \Rector\Core\PhpParser\Comparing\NodeComparator $nodeComparator) + { $this->variableManipulator = $variableManipulator; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeNameResolver = $nodeNameResolver; @@ -90,318 +73,246 @@ final class ClassMethodAssignManipulator $this->callReflectionResolver = $callReflectionResolver; $this->nodeComparator = $nodeComparator; } - /** * @return Assign[] */ - public function collectReadyOnlyAssignScalarVariables(ClassMethod $classMethod): array + public function collectReadyOnlyAssignScalarVariables(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { - $assignsOfScalarOrArrayToVariable = $this->variableManipulator->collectScalarOrArrayAssignsOfVariable( - $classMethod - ); - + $assignsOfScalarOrArrayToVariable = $this->variableManipulator->collectScalarOrArrayAssignsOfVariable($classMethod); // filter out [$value] = $array, array destructing - $readOnlyVariableAssigns = $this->filterOutArrayDestructedVariables( - $assignsOfScalarOrArrayToVariable, - $classMethod - ); - + $readOnlyVariableAssigns = $this->filterOutArrayDestructedVariables($assignsOfScalarOrArrayToVariable, $classMethod); $readOnlyVariableAssigns = $this->filterOutReferencedVariables($readOnlyVariableAssigns, $classMethod); $readOnlyVariableAssigns = $this->filterOutMultiAssigns($readOnlyVariableAssigns); $readOnlyVariableAssigns = $this->filterOutForeachVariables($readOnlyVariableAssigns); - return $this->variableManipulator->filterOutChangedVariables($readOnlyVariableAssigns, $classMethod); } - - public function addParameterAndAssignToMethod( - ClassMethod $classMethod, - string $name, - ?Type $type, - Assign $assign - ): void { + public function addParameterAndAssignToMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $name, ?\PHPStan\Type\Type $type, \PhpParser\Node\Expr\Assign $assign) : void + { if ($this->hasMethodParameter($classMethod, $name)) { return; } - $classMethod->params[] = $this->nodeFactory->createParamFromNameAndType($name, $type); - $classMethod->stmts[] = new Expression($assign); - - $classMethodHash = spl_object_hash($classMethod); + $classMethod->stmts[] = new \PhpParser\Node\Stmt\Expression($assign); + $classMethodHash = \spl_object_hash($classMethod); $this->alreadyAddedClassMethodNames[$classMethodHash][] = $name; } - /** * @param Assign[] $variableAssigns * @return Assign[] */ - private function filterOutArrayDestructedVariables(array $variableAssigns, ClassMethod $classMethod): array + private function filterOutArrayDestructedVariables(array $variableAssigns, \PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $arrayDestructionCreatedVariables = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classMethod, function (Node $node) use ( - &$arrayDestructionCreatedVariables - ) { - if (! $node instanceof Assign) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classMethod, function (\PhpParser\Node $node) use(&$arrayDestructionCreatedVariables) { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $node->var instanceof Array_ && ! $node->var instanceof List_) { + if (!$node->var instanceof \PhpParser\Node\Expr\Array_ && !$node->var instanceof \PhpParser\Node\Expr\List_) { return null; } - foreach ($node->var->items as $arrayItem) { // empty item if ($arrayItem === null) { continue; } - - if (! $arrayItem->value instanceof Variable) { + if (!$arrayItem->value instanceof \PhpParser\Node\Expr\Variable) { continue; } - /** @var string $variableName */ $variableName = $this->nodeNameResolver->getName($arrayItem->value); $arrayDestructionCreatedVariables[] = $variableName; } }); - - return array_filter($variableAssigns, function (Assign $assign) use ($arrayDestructionCreatedVariables): bool { - return ! $this->nodeNameResolver->isNames($assign->var, $arrayDestructionCreatedVariables); + return \array_filter($variableAssigns, function (\PhpParser\Node\Expr\Assign $assign) use($arrayDestructionCreatedVariables) : bool { + return !$this->nodeNameResolver->isNames($assign->var, $arrayDestructionCreatedVariables); }); } - /** * @param Assign[] $variableAssigns * @return Assign[] */ - private function filterOutReferencedVariables(array $variableAssigns, ClassMethod $classMethod): array + private function filterOutReferencedVariables(array $variableAssigns, \PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $referencedVariables = $this->collectReferenceVariableNames($classMethod); - - return array_filter($variableAssigns, function (Assign $assign) use ($referencedVariables): bool { - return ! $this->nodeNameResolver->isNames($assign->var, $referencedVariables); + return \array_filter($variableAssigns, function (\PhpParser\Node\Expr\Assign $assign) use($referencedVariables) : bool { + return !$this->nodeNameResolver->isNames($assign->var, $referencedVariables); }); } - /** * E.g. $a = $b = $c = '...'; * * @param Assign[] $readOnlyVariableAssigns * @return Assign[] */ - private function filterOutMultiAssigns(array $readOnlyVariableAssigns): array + private function filterOutMultiAssigns(array $readOnlyVariableAssigns) : array { - return array_filter($readOnlyVariableAssigns, function (Assign $assign): bool { - $parent = $assign->getAttribute(AttributeKey::PARENT_NODE); - return ! $parent instanceof Assign; + return \array_filter($readOnlyVariableAssigns, function (\PhpParser\Node\Expr\Assign $assign) : bool { + $parent = $assign->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + return !$parent instanceof \PhpParser\Node\Expr\Assign; }); } - /** * @param Assign[] $variableAssigns * @return Assign[] */ - private function filterOutForeachVariables(array $variableAssigns): array + private function filterOutForeachVariables(array $variableAssigns) : array { foreach ($variableAssigns as $key => $variableAssign) { $foreach = $this->findParentForeach($variableAssign); - if (! $foreach instanceof Foreach_) { + if (!$foreach instanceof \PhpParser\Node\Stmt\Foreach_) { continue; } - if ($this->nodeComparator->areNodesEqual($foreach->valueVar, $variableAssign->var)) { unset($variableAssigns[$key]); continue; } - if ($this->nodeComparator->areNodesEqual($foreach->keyVar, $variableAssign->var)) { unset($variableAssigns[$key]); } } - return $variableAssigns; } - - private function hasMethodParameter(ClassMethod $classMethod, string $name): bool + private function hasMethodParameter(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $name) : bool { foreach ($classMethod->params as $param) { if ($this->nodeNameResolver->isName($param->var, $name)) { - return true; + return \true; } } - - $classMethodHash = spl_object_hash($classMethod); - if (! isset($this->alreadyAddedClassMethodNames[$classMethodHash])) { - return false; + $classMethodHash = \spl_object_hash($classMethod); + if (!isset($this->alreadyAddedClassMethodNames[$classMethodHash])) { + return \false; } - - return in_array($name, $this->alreadyAddedClassMethodNames[$classMethodHash], true); + return \in_array($name, $this->alreadyAddedClassMethodNames[$classMethodHash], \true); } - /** * @return string[] */ - private function collectReferenceVariableNames(ClassMethod $classMethod): array + private function collectReferenceVariableNames(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $referencedVariables = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classMethod, function (Node $node) use ( - &$referencedVariables - ) { - if (! $node instanceof Variable) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($classMethod, function (\PhpParser\Node $node) use(&$referencedVariables) { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { return null; } - if ($this->nodeNameResolver->isName($node, 'this')) { return null; } - - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); if ($parentNode !== null && $this->isExplicitlyReferenced($parentNode)) { /** @var string $variableName */ $variableName = $this->nodeNameResolver->getName($node); $referencedVariables[] = $variableName; return null; } - $argumentPosition = null; - if ($parentNode instanceof Arg) { - $argumentPosition = $parentNode->getAttribute(AttributeKey::ARGUMENT_POSITION); - $parentNode = $parentNode->getAttribute(AttributeKey::PARENT_NODE); + if ($parentNode instanceof \PhpParser\Node\Arg) { + $argumentPosition = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ARGUMENT_POSITION); + $parentNode = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); } - - if (! $parentNode instanceof Node) { + if (!$parentNode instanceof \PhpParser\Node) { return null; } - if ($argumentPosition === null) { return null; } - /** @var string $variableName */ $variableName = $this->nodeNameResolver->getName($node); - if ($this->isCallOrConstructorWithReference($parentNode, $node, $argumentPosition)) { $referencedVariables[] = $variableName; } }); - return $referencedVariables; } - - private function findParentForeach(Assign $assign): ?Foreach_ + private function findParentForeach(\PhpParser\Node\Expr\Assign $assign) : ?\PhpParser\Node\Stmt\Foreach_ { /** @var Foreach_|FunctionLike|null $foundNode */ - $foundNode = $this->betterNodeFinder->findFirstPreviousOfTypes($assign, [Foreach_::class, FunctionLike::class]); - if (! $foundNode instanceof Foreach_) { + $foundNode = $this->betterNodeFinder->findFirstPreviousOfTypes($assign, [\PhpParser\Node\Stmt\Foreach_::class, \PhpParser\Node\FunctionLike::class]); + if (!$foundNode instanceof \PhpParser\Node\Stmt\Foreach_) { return null; } - return $foundNode; } - - private function isExplicitlyReferenced(Node $node): bool + private function isExplicitlyReferenced(\PhpParser\Node $node) : bool { - if (! property_exists($node, 'byRef')) { - return false; + if (!\property_exists($node, 'byRef')) { + return \false; } - - if ($node instanceof Arg || $node instanceof ClosureUse || $node instanceof Param) { + if ($node instanceof \PhpParser\Node\Arg || $node instanceof \PhpParser\Node\Expr\ClosureUse || $node instanceof \PhpParser\Node\Param) { return $node->byRef; } - - return false; + return \false; } - - private function isCallOrConstructorWithReference(Node $node, Variable $variable, int $argumentPosition): bool + private function isCallOrConstructorWithReference(\PhpParser\Node $node, \PhpParser\Node\Expr\Variable $variable, int $argumentPosition) : bool { if ($this->isMethodCallWithReferencedArgument($node, $variable)) { - return true; + return \true; } - if ($this->isFuncCallWithReferencedArgument($node, $variable)) { - return true; + return \true; } return $this->isConstructorWithReference($node, $argumentPosition); } - - private function isMethodCallWithReferencedArgument(Node $node, Variable $variable): bool + private function isMethodCallWithReferencedArgument(\PhpParser\Node $node, \PhpParser\Node\Expr\Variable $variable) : bool { - if (! $node instanceof MethodCall) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - $methodReflection = $this->callReflectionResolver->resolveCall($node); - if (! $methodReflection instanceof MethodReflection) { - return false; + if (!$methodReflection instanceof \PHPStan\Reflection\MethodReflection) { + return \false; } - $variableName = $this->nodeNameResolver->getName($variable); $parametersAcceptor = $this->callReflectionResolver->resolveParametersAcceptor($methodReflection, $node); - if (! $parametersAcceptor instanceof ParametersAcceptor) { - return false; + if (!$parametersAcceptor instanceof \PHPStan\Reflection\ParametersAcceptor) { + return \false; } - /** @var ParameterReflection $parameterReflection */ foreach ($parametersAcceptor->getParameters() as $parameterReflection) { if ($parameterReflection->getName() !== $variableName) { continue; } - - return $parameterReflection->passedByReference() - ->yes(); + return $parameterReflection->passedByReference()->yes(); } - - return false; + return \false; } - /** * Matches e.g: * - array_shift($value) * - sort($values) */ - private function isFuncCallWithReferencedArgument(Node $node, Variable $variable): bool + private function isFuncCallWithReferencedArgument(\PhpParser\Node $node, \PhpParser\Node\Expr\Variable $variable) : bool { - if (! $node instanceof FuncCall) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - - if (! $this->nodeNameResolver->isNames($node, ['array_shift', '*sort'])) { - return false; + if (!$this->nodeNameResolver->isNames($node, ['array_shift', '*sort'])) { + return \false; } - // is 1t argument return $node->args[0]->value !== $variable; } - - private function isConstructorWithReference(Node $node, int $argumentPosition): bool + private function isConstructorWithReference(\PhpParser\Node $node, int $argumentPosition) : bool { - if (! $node instanceof New_) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\New_) { + return \false; } - return $this->isParameterReferencedInMethodReflection($node, $argumentPosition); } - - private function isParameterReferencedInMethodReflection(New_ $new, int $argumentPosition): bool + private function isParameterReferencedInMethodReflection(\PhpParser\Node\Expr\New_ $new, int $argumentPosition) : bool { $methodReflection = $this->callReflectionResolver->resolveConstructor($new); $parametersAcceptor = $this->callReflectionResolver->resolveParametersAcceptor($methodReflection, $new); - - if (! $parametersAcceptor instanceof ParametersAcceptor) { - return false; + if (!$parametersAcceptor instanceof \PHPStan\Reflection\ParametersAcceptor) { + return \false; } - /** @var ParameterReflection $parameterReflection */ foreach ($parametersAcceptor->getParameters() as $parameterPosition => $parameterReflection) { if ($parameterPosition !== $argumentPosition) { continue; } - - return $parameterReflection->passedByReference() - ->yes(); + return $parameterReflection->passedByReference()->yes(); } - - return false; + return \false; } } diff --git a/src/NodeManipulator/ClassMethodManipulator.php b/src/NodeManipulator/ClassMethodManipulator.php index 86cfac71399..64adcc2e51c 100644 --- a/src/NodeManipulator/ClassMethodManipulator.php +++ b/src/NodeManipulator/ClassMethodManipulator.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; $this->nodeComparator = $nodeComparator; $this->funcCallManipulator = $funcCallManipulator; } - - public function isParameterUsedInClassMethod(Param $param, ClassMethod $classMethod): bool + public function isParameterUsedInClassMethod(\PhpParser\Node\Param $param, \PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - $isUsedDirectly = (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (Node $node) use ( - $param - ): bool { + $isUsedDirectly = (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (\PhpParser\Node $node) use($param) : bool { return $this->nodeComparator->areNodesEqual($node, $param->var); }); - if ($isUsedDirectly) { - return true; + return \true; } - /** @var FuncCall[] $compactFuncCalls */ - $compactFuncCalls = $this->betterNodeFinder->find((array) $classMethod->stmts, function (Node $node): bool { - if (! $node instanceof FuncCall) { - return false; + $compactFuncCalls = $this->betterNodeFinder->find((array) $classMethod->stmts, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } - return $this->nodeNameResolver->isName($node, 'compact'); }); - $arguments = $this->funcCallManipulator->extractArgumentsFromCompactFuncCalls($compactFuncCalls); - return $this->nodeNameResolver->isNames($param, $arguments); } - - public function isNamedConstructor(ClassMethod $classMethod): bool + public function isNamedConstructor(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - if (! $this->nodeNameResolver->isName($classMethod, MethodName::CONSTRUCT)) { - return false; + if (!$this->nodeNameResolver->isName($classMethod, \Rector\Core\ValueObject\MethodName::CONSTRUCT)) { + return \false; } - - $classLike = $classMethod->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { - return false; + $classLike = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { + return \false; } if ($classMethod->isPrivate()) { - return true; + return \true; } if ($classLike->isFinal()) { - return false; + return \false; } return $classMethod->isProtected(); } - - public function hasParentMethodOrInterfaceMethod(ClassMethod $classMethod, ?string $methodName = null): bool + public function hasParentMethodOrInterfaceMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, ?string $methodName = null) : bool { $methodName = $methodName ?? $this->nodeNameResolver->getName($classMethod->name); if ($methodName === null) { - return false; + return \false; } - - $scope = $classMethod->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return false; + $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return \false; } - $classReflection = $scope->getClassReflection(); - if (! $classReflection instanceof ClassReflection) { - return false; + if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) { + return \false; } - foreach ($classReflection->getParents() as $parentClassReflection) { if ($parentClassReflection->hasMethod($methodName)) { - return true; + return \true; } } - foreach ($classReflection->getInterfaces() as $interfaceReflection) { if ($interfaceReflection->hasMethod($methodName)) { - return true; + return \true; } } - - return false; + return \false; } - /** * Is method actually static, or has some $this-> calls? */ - public function isStaticClassMethod(ClassMethod $classMethod): bool + public function isStaticClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { - return (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (Node $node): bool { - if (! $node instanceof Variable) { - return false; + return (bool) $this->betterNodeFinder->findFirst((array) $classMethod->stmts, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeNameResolver->isName($node, 'this'); }); } - /** * @param string[] $possibleNames */ - public function addMethodParameterIfMissing(Node $node, ObjectType $objectType, array $possibleNames): string + public function addMethodParameterIfMissing(\PhpParser\Node $node, \PHPStan\Type\ObjectType $objectType, array $possibleNames) : string { - $classMethodNode = $node->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethodNode instanceof ClassMethod) { + $classMethodNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethodNode instanceof \PhpParser\Node\Stmt\ClassMethod) { // or null? - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - foreach ($classMethodNode->params as $paramNode) { - if (! $this->nodeTypeResolver->isObjectType($paramNode, $objectType)) { + if (!$this->nodeTypeResolver->isObjectType($paramNode, $objectType)) { continue; } - $paramName = $this->nodeNameResolver->getName($paramNode); - if (! is_string($paramName)) { - throw new ShouldNotHappenException(); + if (!\is_string($paramName)) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - return $paramName; } - $paramName = $this->resolveName($classMethodNode, $possibleNames); - $classMethodNode->params[] = new Param(new Variable($paramName), null, new FullyQualified( - $objectType->getClassName() - )); - + $classMethodNode->params[] = new \PhpParser\Node\Param(new \PhpParser\Node\Expr\Variable($paramName), null, new \PhpParser\Node\Name\FullyQualified($objectType->getClassName())); return $paramName; } - - public function isPropertyPromotion(ClassMethod $classMethod): bool + public function isPropertyPromotion(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool { foreach ($classMethod->params as $param) { /** @var Param $param */ if ($param->flags !== 0) { - return true; + return \true; } } - - return false; + return \false; } - /** * @param string[] $possibleNames */ - private function resolveName(ClassMethod $classMethod, array $possibleNames): string + private function resolveName(\PhpParser\Node\Stmt\ClassMethod $classMethod, array $possibleNames) : string { foreach ($possibleNames as $possibleName) { foreach ($classMethod->params as $paramNode) { @@ -209,10 +168,8 @@ final class ClassMethodManipulator continue 2; } } - return $possibleName; } - - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } } diff --git a/src/NodeManipulator/ClassMethodPropertyFetchManipulator.php b/src/NodeManipulator/ClassMethodPropertyFetchManipulator.php index ec181d3b22b..f95bffcac62 100644 --- a/src/NodeManipulator/ClassMethodPropertyFetchManipulator.php +++ b/src/NodeManipulator/ClassMethodPropertyFetchManipulator.php @@ -1,7 +1,6 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeNameResolver = $nodeNameResolver; } - /** * In case the property name is different to param name: * @@ -43,45 +36,33 @@ final class ClassMethodPropertyFetchManipulator * ↓ * (SomeType $anotherValue) */ - public function resolveParamForPropertyFetch(ClassMethod $classMethod, string $propertyName): ?Param + public function resolveParamForPropertyFetch(\PhpParser\Node\Stmt\ClassMethod $classMethod, string $propertyName) : ?\PhpParser\Node\Param { $assignedParamName = null; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $classMethod->stmts, - function (Node $node) use ($propertyName, &$assignedParamName): ?int { - if (! $node instanceof Assign) { - return null; - } - - if (! $this->nodeNameResolver->isName($node->var, $propertyName)) { - return null; - } - - if ($node->expr instanceof MethodCall || $node->expr instanceof StaticCall) { - return null; - } - - $assignedParamName = $this->nodeNameResolver->getName($node->expr); - - return NodeTraverser::STOP_TRAVERSAL; + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->stmts, function (\PhpParser\Node $node) use($propertyName, &$assignedParamName) : ?int { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return null; } - ); - + if (!$this->nodeNameResolver->isName($node->var, $propertyName)) { + return null; + } + if ($node->expr instanceof \PhpParser\Node\Expr\MethodCall || $node->expr instanceof \PhpParser\Node\Expr\StaticCall) { + return null; + } + $assignedParamName = $this->nodeNameResolver->getName($node->expr); + return \PhpParser\NodeTraverser::STOP_TRAVERSAL; + }); /** @var string|null $assignedParamName */ if ($assignedParamName === null) { return null; } - /** @var Param $param */ foreach ($classMethod->params as $param) { - if (! $this->nodeNameResolver->isName($param, $assignedParamName)) { + if (!$this->nodeNameResolver->isName($param, $assignedParamName)) { continue; } - return $param; } - return null; } } diff --git a/src/NodeManipulator/ForeachManipulator.php b/src/NodeManipulator/ForeachManipulator.php index e09b766782d..3805656b87f 100644 --- a/src/NodeManipulator/ForeachManipulator.php +++ b/src/NodeManipulator/ForeachManipulator.php @@ -1,26 +1,21 @@ stmts; - - if (count($stmts) !== 1) { + if (\count($stmts) !== 1) { return null; } - $innerNode = $stmts[0]; - $innerNode = $innerNode instanceof Expression ? $innerNode->expr : $innerNode; - + $innerNode = $innerNode instanceof \PhpParser\Node\Stmt\Expression ? $innerNode->expr : $innerNode; return $callable($innerNode, $foreach); } } diff --git a/src/NodeManipulator/FuncCallManipulator.php b/src/NodeManipulator/FuncCallManipulator.php index 8733ea8927d..eb374d3744d 100644 --- a/src/NodeManipulator/FuncCallManipulator.php +++ b/src/NodeManipulator/FuncCallManipulator.php @@ -1,29 +1,25 @@ valueResolver = $valueResolver; } - /** * @param FuncCall[] $compactFuncCalls * @return string[] */ - public function extractArgumentsFromCompactFuncCalls(array $compactFuncCalls): array + public function extractArgumentsFromCompactFuncCalls(array $compactFuncCalls) : array { $arguments = []; foreach ($compactFuncCalls as $compactFuncCall) { @@ -32,11 +28,9 @@ final class FuncCallManipulator if ($value === null) { continue; } - $arguments[] = $value; } } - return $arguments; } } diff --git a/src/NodeManipulator/FunctionLikeManipulator.php b/src/NodeManipulator/FunctionLikeManipulator.php index ddd20192644..420746fc091 100644 --- a/src/NodeManipulator/FunctionLikeManipulator.php +++ b/src/NodeManipulator/FunctionLikeManipulator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->propertyFetchAnalyzer = $propertyFetchAnalyzer; } - /** * @return string[] */ - public function getReturnedLocalPropertyNames(FunctionLike $functionLike): array + public function getReturnedLocalPropertyNames(\PhpParser\Node\FunctionLike $functionLike) : array { // process only class methods - if ($functionLike instanceof Function_) { + if ($functionLike instanceof \PhpParser\Node\Stmt\Function_) { return []; } - $returnedLocalPropertyNames = []; - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($functionLike, function (Node $node) use ( - &$returnedLocalPropertyNames - ) { - if (! $node instanceof Return_) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($functionLike, function (\PhpParser\Node $node) use(&$returnedLocalPropertyNames) { + if (!$node instanceof \PhpParser\Node\Stmt\Return_) { return null; } if ($node->expr === null) { return null; } - if (! $this->propertyFetchAnalyzer->isLocalPropertyFetch($node->expr)) { + if (!$this->propertyFetchAnalyzer->isLocalPropertyFetch($node->expr)) { return null; } - $propertyName = $this->nodeNameResolver->getName($node->expr); if ($propertyName === null) { return null; } - $returnedLocalPropertyNames[] = $propertyName; }); - return $returnedLocalPropertyNames; } } diff --git a/src/NodeManipulator/IfManipulator.php b/src/NodeManipulator/IfManipulator.php index aa8093279df..22a062bec03 100644 --- a/src/NodeManipulator/IfManipulator.php +++ b/src/NodeManipulator/IfManipulator.php @@ -1,7 +1,6 @@ stmtsManipulator = $stmtsManipulator; $this->nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; @@ -72,7 +58,6 @@ final class IfManipulator $this->conditionInverter = $conditionInverter; $this->nodeComparator = $nodeComparator; } - /** * Matches: * @@ -80,25 +65,21 @@ final class IfManipulator * return $value; * } */ - public function matchIfNotNullReturnValue(If_ $if): ?Expr + public function matchIfNotNullReturnValue(\PhpParser\Node\Stmt\If_ $if) : ?\PhpParser\Node\Expr { $stmts = $if->stmts; - if (count($stmts) !== 1) { + if (\count($stmts) !== 1) { return null; } - $insideIfNode = $stmts[0]; - if (! $insideIfNode instanceof Return_) { + if (!$insideIfNode instanceof \PhpParser\Node\Stmt\Return_) { return null; } - - if (! $if->cond instanceof NotIdentical) { + if (!$if->cond instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical) { return null; } - return $this->matchComparedAndReturnedNode($if->cond, $insideIfNode); } - /** * Matches: * @@ -106,33 +87,27 @@ final class IfManipulator * $anotherValue = $value; * } */ - public function matchIfNotNullNextAssignment(If_ $if): ?Assign + public function matchIfNotNullNextAssignment(\PhpParser\Node\Stmt\If_ $if) : ?\PhpParser\Node\Expr\Assign { if ($if->stmts === []) { return null; } - - if (! $if->cond instanceof NotIdentical) { + if (!$if->cond instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical) { return null; } - - if (! $this->isNotIdenticalNullCompare($if->cond)) { + if (!$this->isNotIdenticalNullCompare($if->cond)) { return null; } - $insideIfNode = $if->stmts[0]; - if (! $insideIfNode instanceof Expression) { + if (!$insideIfNode instanceof \PhpParser\Node\Stmt\Expression) { return null; } - $assignedExpr = $insideIfNode->expr; - if (! $assignedExpr instanceof Assign) { + if (!$assignedExpr instanceof \PhpParser\Node\Expr\Assign) { return null; } - return $assignedExpr; } - /** * Matches: * @@ -144,289 +119,221 @@ final class IfManipulator * return 53; * } */ - public function matchIfValueReturnValue(If_ $if): ?Expr + public function matchIfValueReturnValue(\PhpParser\Node\Stmt\If_ $if) : ?\PhpParser\Node\Expr { $stmts = $if->stmts; - - if (count($stmts) !== 1) { + if (\count($stmts) !== 1) { return null; } - $insideIfNode = $stmts[0]; - if (! $insideIfNode instanceof Return_) { + if (!$insideIfNode instanceof \PhpParser\Node\Stmt\Return_) { return null; } - - if (! $if->cond instanceof Identical) { + if (!$if->cond instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { return null; } - if ($this->nodeComparator->areNodesEqual($if->cond->left, $insideIfNode->expr)) { return $if->cond->right; } - if ($this->nodeComparator->areNodesEqual($if->cond->right, $insideIfNode->expr)) { return $if->cond->left; } - return null; } - /** * @return mixed[] */ - public function collectNestedIfsWithOnlyReturn(If_ $if): array + public function collectNestedIfsWithOnlyReturn(\PhpParser\Node\Stmt\If_ $if) : array { $ifs = []; - $currentIf = $if; while ($this->isIfWithOnlyStmtIf($currentIf)) { $ifs[] = $currentIf; - $currentIf = $currentIf->stmts[0]; } - if ($ifs === []) { return []; } - - if (! $this->hasOnlyStmtOfType($currentIf, Return_::class)) { + if (!$this->hasOnlyStmtOfType($currentIf, \PhpParser\Node\Stmt\Return_::class)) { return []; } - // last node is with the return value $ifs[] = $currentIf; - return $ifs; } - - public function isIfAndElseWithSameVariableAssignAsLastStmts(If_ $if, Expr $desiredExpr): bool + public function isIfAndElseWithSameVariableAssignAsLastStmts(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node\Expr $desiredExpr) : bool { if ($if->else === null) { - return false; + return \false; } - if ((bool) $if->elseifs) { - return false; + return \false; } - $lastIfStmt = $this->stmtsManipulator->getUnwrappedLastStmt($if->stmts); - if (! $lastIfStmt instanceof Assign) { - return false; + if (!$lastIfStmt instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - $lastElseStmt = $this->stmtsManipulator->getUnwrappedLastStmt($if->else->stmts); - if (! $lastElseStmt instanceof Assign) { - return false; + if (!$lastElseStmt instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - if (! $lastIfStmt->var instanceof Variable) { - return false; + if (!$lastIfStmt->var instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - - if (! $this->nodeComparator->areNodesEqual($lastIfStmt->var, $lastElseStmt->var)) { - return false; + if (!$this->nodeComparator->areNodesEqual($lastIfStmt->var, $lastElseStmt->var)) { + return \false; } return $this->nodeComparator->areNodesEqual($desiredExpr, $lastElseStmt->var); } - /** * Matches: * if () { * } else { * } */ - public function isIfOrIfElseWithFunctionCondition(If_ $if, string $functionName): bool + public function isIfOrIfElseWithFunctionCondition(\PhpParser\Node\Stmt\If_ $if, string $functionName) : bool { if ((bool) $if->elseifs) { - return false; + return \false; } - - if (! $if->cond instanceof FuncCall) { - return false; + if (!$if->cond instanceof \PhpParser\Node\Expr\FuncCall) { + return \false; } return $this->nodeNameResolver->isName($if->cond, $functionName); } - /** * @return If_[] */ - public function collectNestedIfsWithNonBreaking(Foreach_ $foreach): array + public function collectNestedIfsWithNonBreaking(\PhpParser\Node\Stmt\Foreach_ $foreach) : array { - if (count($foreach->stmts) !== 1) { + if (\count($foreach->stmts) !== 1) { return []; } - $onlyForeachStmt = $foreach->stmts[0]; - if (! $onlyForeachStmt instanceof If_) { + if (!$onlyForeachStmt instanceof \PhpParser\Node\Stmt\If_) { return []; } - $ifs = []; - $currentIf = $onlyForeachStmt; while ($this->isIfWithOnlyStmtIf($currentIf)) { $ifs[] = $currentIf; - $currentIf = $currentIf->stmts[0]; } - // IfManipulator is not build to handle elseif and else - if (! $this->isIfWithoutElseAndElseIfs($currentIf)) { + if (!$this->isIfWithoutElseAndElseIfs($currentIf)) { return []; } - $betterNodeFinderFindInstanceOf = $this->betterNodeFinder->findInstanceOf($currentIf->stmts, Return_::class); - + $betterNodeFinderFindInstanceOf = $this->betterNodeFinder->findInstanceOf($currentIf->stmts, \PhpParser\Node\Stmt\Return_::class); if ($betterNodeFinderFindInstanceOf !== []) { return []; } - /** @var Exit_[] $exits */ - $exits = $this->betterNodeFinder->findInstanceOf($currentIf->stmts, Exit_::class); + $exits = $this->betterNodeFinder->findInstanceOf($currentIf->stmts, \PhpParser\Node\Expr\Exit_::class); if ($exits !== []) { return []; } - // last node is with the expression - $ifs[] = $currentIf; - return $ifs; } - /** * @param class-string $className */ - public function isIfWithOnly(Node $node, string $className): bool + public function isIfWithOnly(\PhpParser\Node $node, string $className) : bool { - if (! $node instanceof If_) { - return false; + if (!$node instanceof \PhpParser\Node\Stmt\If_) { + return \false; } - - if (! $this->isIfWithoutElseAndElseIfs($node)) { - return false; + if (!$this->isIfWithoutElseAndElseIfs($node)) { + return \false; } - return $this->hasOnlyStmtOfType($node, $className); } - - public function isIfWithOnlyOneStmt(If_ $if): bool + public function isIfWithOnlyOneStmt(\PhpParser\Node\Stmt\If_ $if) : bool { - return count($if->stmts) === 1; + return \count($if->stmts) === 1; } - - public function isIfCondUsingAssignIdenticalVariable(Node $if, Node $assign): bool + public function isIfCondUsingAssignIdenticalVariable(\PhpParser\Node $if, \PhpParser\Node $assign) : bool { - if (! ($if instanceof If_ && $assign instanceof Assign)) { - return false; + if (!($if instanceof \PhpParser\Node\Stmt\If_ && $assign instanceof \PhpParser\Node\Expr\Assign)) { + return \false; } - - if (! $if->cond instanceof Identical) { - return false; + if (!$if->cond instanceof \PhpParser\Node\Expr\BinaryOp\Identical) { + return \false; } - return $this->nodeComparator->areNodesEqual($this->getIfCondVar($if), $assign->var); } - - public function isIfCondUsingAssignNotIdenticalVariable(If_ $if, Node $node): bool + public function isIfCondUsingAssignNotIdenticalVariable(\PhpParser\Node\Stmt\If_ $if, \PhpParser\Node $node) : bool { - if (! $node instanceof MethodCall && ! $node instanceof PropertyFetch) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\MethodCall && !$node instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - if (! $if->cond instanceof NotIdentical) { - return false; + if (!$if->cond instanceof \PhpParser\Node\Expr\BinaryOp\NotIdentical) { + return \false; } - return ! $this->nodeComparator->areNodesEqual($this->getIfCondVar($if), $node->var); + return !$this->nodeComparator->areNodesEqual($this->getIfCondVar($if), $node->var); } - - public function isIfWithoutElseAndElseIfs(If_ $if): bool + public function isIfWithoutElseAndElseIfs(\PhpParser\Node\Stmt\If_ $if) : bool { if ($if->else !== null) { - return false; + return \false; } - - return ! (bool) $if->elseifs; + return !(bool) $if->elseifs; } - - public function createIfNegation(Expr $expr, Stmt $stmt): If_ + public function createIfNegation(\PhpParser\Node\Expr $expr, \PhpParser\Node\Stmt $stmt) : \PhpParser\Node\Stmt\If_ { $expr = $this->conditionInverter->createInvertedCondition($expr); - - return new If_( - $expr, - [ - 'stmts' => [$stmt], - ] - ); + return new \PhpParser\Node\Stmt\If_($expr, ['stmts' => [$stmt]]); } - - public function createIfExpr(Expr $expr, Stmt $stmt): If_ + public function createIfExpr(\PhpParser\Node\Expr $expr, \PhpParser\Node\Stmt $stmt) : \PhpParser\Node\Stmt\If_ { - return new If_( - $expr, - [ - 'stmts' => [$stmt], - ] - ); + return new \PhpParser\Node\Stmt\If_($expr, ['stmts' => [$stmt]]); } - - private function matchComparedAndReturnedNode(NotIdentical $notIdentical, Return_ $return): ?Expr + private function matchComparedAndReturnedNode(\PhpParser\Node\Expr\BinaryOp\NotIdentical $notIdentical, \PhpParser\Node\Stmt\Return_ $return) : ?\PhpParser\Node\Expr { - if ($this->nodeComparator->areNodesEqual( - $notIdentical->left, - $return->expr - ) && $this->valueResolver->isNull($notIdentical->right)) { + if ($this->nodeComparator->areNodesEqual($notIdentical->left, $return->expr) && $this->valueResolver->isNull($notIdentical->right)) { return $notIdentical->left; } - - if (! $this->nodeComparator->areNodesEqual($notIdentical->right, $return->expr)) { + if (!$this->nodeComparator->areNodesEqual($notIdentical->right, $return->expr)) { return null; } if ($this->valueResolver->isNull($notIdentical->left)) { return $notIdentical->right; } - return null; } - - private function isNotIdenticalNullCompare(NotIdentical $notIdentical): bool + private function isNotIdenticalNullCompare(\PhpParser\Node\Expr\BinaryOp\NotIdentical $notIdentical) : bool { if ($this->nodeComparator->areNodesEqual($notIdentical->left, $notIdentical->right)) { - return false; + return \false; } if ($this->valueResolver->isNull($notIdentical->right)) { - return true; + return \true; } return $this->valueResolver->isNull($notIdentical->left); } - - private function isIfWithOnlyStmtIf(If_ $if): bool + private function isIfWithOnlyStmtIf(\PhpParser\Node\Stmt\If_ $if) : bool { - if (! $this->isIfWithoutElseAndElseIfs($if)) { - return false; + if (!$this->isIfWithoutElseAndElseIfs($if)) { + return \false; } - - return $this->hasOnlyStmtOfType($if, If_::class); + return $this->hasOnlyStmtOfType($if, \PhpParser\Node\Stmt\If_::class); } - /** * @param class-string $desiredType */ - private function hasOnlyStmtOfType(If_ $if, string $desiredType): bool + private function hasOnlyStmtOfType(\PhpParser\Node\Stmt\If_ $if, string $desiredType) : bool { $stmts = $if->stmts; - if (count($stmts) !== 1) { - return false; + if (\count($stmts) !== 1) { + return \false; } - - return is_a($stmts[0], $desiredType); + return \is_a($stmts[0], $desiredType); } - - private function getIfCondVar(If_ $if): Expr + private function getIfCondVar(\PhpParser\Node\Stmt\If_ $if) : \PhpParser\Node\Expr { /** @var Identical|NotIdentical $ifCond */ $ifCond = $if->cond; - return $this->valueResolver->isNull($ifCond->left) ? $ifCond->right : $ifCond->left; } } diff --git a/src/NodeManipulator/MagicPropertyFetchAnalyzer.php b/src/NodeManipulator/MagicPropertyFetchAnalyzer.php index 48cd6a877e6..275ae9ec0ef 100644 --- a/src/NodeManipulator/MagicPropertyFetchAnalyzer.php +++ b/src/NodeManipulator/MagicPropertyFetchAnalyzer.php @@ -1,7 +1,6 @@ property" @@ -29,84 +27,66 @@ final class MagicPropertyFetchAnalyzer * @var NodeTypeResolver */ private $nodeTypeResolver; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var ReflectionProvider */ private $reflectionProvider; - - public function __construct( - NodeNameResolver $nodeNameResolver, - NodeTypeResolver $nodeTypeResolver, - ReflectionProvider $reflectionProvider - ) { + public function __construct(\Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver, \PHPStan\Reflection\ReflectionProvider $reflectionProvider) + { $this->nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; } - /** * @param PropertyFetch|Node\Expr\StaticPropertyFetch $expr */ - public function isMagicOnType(Expr $expr, Type $type): bool + public function isMagicOnType(\PhpParser\Node\Expr $expr, \PHPStan\Type\Type $type) : bool { $varNodeType = $this->nodeTypeResolver->resolve($expr); - - if ($varNodeType instanceof ErrorType) { - return true; + if ($varNodeType instanceof \PHPStan\Type\ErrorType) { + return \true; } - - if ($varNodeType instanceof MixedType) { - return false; + if ($varNodeType instanceof \PHPStan\Type\MixedType) { + return \false; } - if ($varNodeType->isSuperTypeOf($type)->yes()) { - return false; + return \false; } - $nodeName = $this->nodeNameResolver->getName($expr->name); if ($nodeName === null) { - return false; + return \false; } - - return ! $this->hasPublicProperty($expr, $nodeName); + return !$this->hasPublicProperty($expr, $nodeName); } - /** * @param PropertyFetch|StaticPropertyFetch $expr */ - private function hasPublicProperty(Expr $expr, string $propertyName): bool + private function hasPublicProperty(\PhpParser\Node\Expr $expr, string $propertyName) : bool { - $scope = $expr->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - throw new ShouldNotHappenException(); + $scope = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - - if ($expr instanceof PropertyFetch) { + if ($expr instanceof \PhpParser\Node\Expr\PropertyFetch) { $propertyFetchType = $scope->getType($expr->var); } else { $propertyFetchType = $this->nodeTypeResolver->resolve($expr->class); } - - if (! $propertyFetchType instanceof TypeWithClassName) { - return false; + if (!$propertyFetchType instanceof \PHPStan\Type\TypeWithClassName) { + return \false; } - $propertyFetchType = $propertyFetchType->getClassName(); - if (! $this->reflectionProvider->hasClass($propertyFetchType)) { - return false; + if (!$this->reflectionProvider->hasClass($propertyFetchType)) { + return \false; } - $classReflection = $this->reflectionProvider->getClass($propertyFetchType); - if (! $classReflection->hasProperty($propertyName)) { - return false; + if (!$classReflection->hasProperty($propertyName)) { + return \false; } - $propertyReflection = $classReflection->getProperty($propertyName, $scope); return $propertyReflection->isPublic(); } diff --git a/src/NodeManipulator/MethodCallManipulator.php b/src/NodeManipulator/MethodCallManipulator.php index 8543eccdfc6..053064c9912 100644 --- a/src/NodeManipulator/MethodCallManipulator.php +++ b/src/NodeManipulator/MethodCallManipulator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; $this->fluentChainMethodCallNodeAnalyzer = $fluentChainMethodCallNodeAnalyzer; } - /** * @return string[] */ - public function findMethodCallNamesOnVariable(Variable $variable): array + public function findMethodCallNamesOnVariable(\PhpParser\Node\Expr\Variable $variable) : array { $methodCallsOnVariable = $this->findMethodCallsOnVariable($variable); - $methodCallNamesOnVariable = []; foreach ($methodCallsOnVariable as $methodCallOnVariable) { $methodName = $this->nodeNameResolver->getName($methodCallOnVariable->name); if ($methodName === null) { continue; } - $methodCallNamesOnVariable[] = $methodName; } - - return array_unique($methodCallNamesOnVariable); + return \array_unique($methodCallNamesOnVariable); } - /** * @return MethodCall[] */ - public function findMethodCallsIncludingChain(MethodCall $methodCall): array + public function findMethodCallsIncludingChain(\PhpParser\Node\Expr\MethodCall $methodCall) : array { $chainMethodCalls = []; - // 1. collect method chain call $currentMethodCallee = $methodCall->var; - while ($currentMethodCallee instanceof MethodCall) { + while ($currentMethodCallee instanceof \PhpParser\Node\Expr\MethodCall) { $chainMethodCalls[] = $currentMethodCallee; $currentMethodCallee = $currentMethodCallee->var; } - // 2. collect on-same-variable calls $onVariableMethodCalls = []; - if ($currentMethodCallee instanceof Variable) { + if ($currentMethodCallee instanceof \PhpParser\Node\Expr\Variable) { $onVariableMethodCalls = $this->findMethodCallsOnVariable($currentMethodCallee); } - - $methodCalls = array_merge($chainMethodCalls, $onVariableMethodCalls); - + $methodCalls = \array_merge($chainMethodCalls, $onVariableMethodCalls); return $this->uniquateObjects($methodCalls); } - - public function findAssignToVariable(Variable $variable): ?Assign + public function findAssignToVariable(\PhpParser\Node\Expr\Variable $variable) : ?\PhpParser\Node\Expr\Assign { - $parentNode = $variable->getAttribute(AttributeKey::PARENT_NODE); - if (! $parentNode instanceof Node) { + $parentNode = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node) { return null; } - $variableName = $this->nodeNameResolver->getName($variable); if ($variableName === null) { return null; } - do { $assign = $this->findAssignToVariableName($parentNode, $variableName); - if ($assign instanceof Assign) { + if ($assign instanceof \PhpParser\Node\Expr\Assign) { return $assign; } - $parentNode = $this->resolvePreviousNodeInSameScope($parentNode); - } while ($parentNode instanceof Node && ! $parentNode instanceof FunctionLike); - + } while ($parentNode instanceof \PhpParser\Node && !$parentNode instanceof \PhpParser\Node\FunctionLike); return null; } - /** * @return MethodCall[] */ - public function findMethodCallsOnVariable(Variable $variable): array + public function findMethodCallsOnVariable(\PhpParser\Node\Expr\Variable $variable) : array { // get scope node, e.g. parent function call, method call or anonymous function - $classMethod = $variable->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { + $classMethod = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return []; } - $variableName = $this->nodeNameResolver->getName($variable); if ($variableName === null) { return []; } - - return $this->betterNodeFinder->find((array) $classMethod->stmts, function (Node $node) use ( - $variableName - ): bool { - if (! $node instanceof MethodCall) { - return false; + return $this->betterNodeFinder->find((array) $classMethod->stmts, function (\PhpParser\Node $node) use($variableName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\MethodCall) { + return \false; } - // cover fluent interfaces too $callerNode = $this->fluentChainMethodCallNodeAnalyzer->resolveRootExpr($node); - if (! $callerNode instanceof Variable) { - return false; + if (!$callerNode instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeNameResolver->isName($callerNode, $variableName); }); } - /** * @see https://stackoverflow.com/a/4507991/1348344 * @param object[] $objects @@ -154,49 +124,41 @@ final class MethodCallManipulator * @phpstan-param array|T[] $objects * @phpstan-return array|T[] */ - private function uniquateObjects(array $objects): array + private function uniquateObjects(array $objects) : array { $uniqueObjects = []; foreach ($objects as $object) { - if (in_array($object, $uniqueObjects, true)) { + if (\in_array($object, $uniqueObjects, \true)) { continue; } - $uniqueObjects[] = $object; } - // re-index - return array_values($uniqueObjects); + return \array_values($uniqueObjects); } - - private function findAssignToVariableName(Node $node, string $variableName): ?Node + private function findAssignToVariableName(\PhpParser\Node $node, string $variableName) : ?\PhpParser\Node { - return $this->betterNodeFinder->findFirst($node, function (Node $node) use ($variableName): bool { - if (! $node instanceof Assign) { - return false; + return $this->betterNodeFinder->findFirst($node, function (\PhpParser\Node $node) use($variableName) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - - if (! $node->var instanceof Variable) { - return false; + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - return $this->nodeNameResolver->isName($node->var, $variableName); }); } - - private function resolvePreviousNodeInSameScope(Node $parentNode): ?Node + private function resolvePreviousNodeInSameScope(\PhpParser\Node $parentNode) : ?\PhpParser\Node { $previousParentNode = $parentNode; - $parentNode = $parentNode->getAttribute(AttributeKey::PARENT_NODE); - - if (! $parentNode instanceof FunctionLike) { + $parentNode = $parentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parentNode instanceof \PhpParser\Node\FunctionLike) { // is about to leave → try previous expression - $previousStatement = $previousParentNode->getAttribute(AttributeKey::PREVIOUS_STATEMENT); - if ($previousStatement instanceof Expression) { + $previousStatement = $previousParentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT); + if ($previousStatement instanceof \PhpParser\Node\Stmt\Expression) { return $previousStatement->expr; } } - return $parentNode; } } diff --git a/src/NodeManipulator/NullsafeManipulator.php b/src/NodeManipulator/NullsafeManipulator.php index c195ab93667..60c964a9c07 100644 --- a/src/NodeManipulator/NullsafeManipulator.php +++ b/src/NodeManipulator/NullsafeManipulator.php @@ -1,7 +1,6 @@ var, $expr->name); + if ($expr instanceof \PhpParser\Node\Expr\MethodCall) { + return new \PhpParser\Node\Expr\NullsafeMethodCall($expr->var, $expr->name); } - - if ($expr instanceof PropertyFetch) { - return new NullsafePropertyFetch($expr->var, $expr->name); + if ($expr instanceof \PhpParser\Node\Expr\PropertyFetch) { + return new \PhpParser\Node\Expr\NullsafePropertyFetch($expr->var, $expr->name); } - return null; } - - public function processNullSafeExprResult(?Expr $expr, Identifier $nextExprIdentifier): ?Expr + public function processNullSafeExprResult(?\PhpParser\Node\Expr $expr, \PhpParser\Node\Identifier $nextExprIdentifier) : ?\PhpParser\Node\Expr { if ($expr === null) { return null; } - - $parentIdentifier = $nextExprIdentifier->getAttribute(AttributeKey::PARENT_NODE); - - if ($parentIdentifier instanceof MethodCall || $parentIdentifier instanceof NullsafeMethodCall) { - return new NullsafeMethodCall($expr, $nextExprIdentifier); + $parentIdentifier = $nextExprIdentifier->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parentIdentifier instanceof \PhpParser\Node\Expr\MethodCall || $parentIdentifier instanceof \PhpParser\Node\Expr\NullsafeMethodCall) { + return new \PhpParser\Node\Expr\NullsafeMethodCall($expr, $nextExprIdentifier); } - - return new NullsafePropertyFetch($expr, $nextExprIdentifier); + return new \PhpParser\Node\Expr\NullsafePropertyFetch($expr, $nextExprIdentifier); } } diff --git a/src/NodeManipulator/PropertyFetchAssignManipulator.php b/src/NodeManipulator/PropertyFetchAssignManipulator.php index d615d79192d..fdc7ede774f 100644 --- a/src/NodeManipulator/PropertyFetchAssignManipulator.php +++ b/src/NodeManipulator/PropertyFetchAssignManipulator.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser; } - /** * @return string[] */ - public function getPropertyNamesOfAssignOfVariable(Node $node, string $paramName): array + public function getPropertyNamesOfAssignOfVariable(\PhpParser\Node $node, string $paramName) : array { $propertyNames = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable($node, function (Node $node) use ( - $paramName, - &$propertyNames - ) { - if (! $node instanceof Assign) { + $this->simpleCallableNodeTraverser->traverseNodesWithCallable($node, function (\PhpParser\Node $node) use($paramName, &$propertyNames) { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $this->isVariableAssignToThisPropertyFetch($node, $paramName)) { + if (!$this->isVariableAssignToThisPropertyFetch($node, $paramName)) { return null; } - /** @var Assign $node */ $propertyName = $this->nodeNameResolver->getName($node->expr); if ($propertyName) { $propertyNames[] = $propertyName; } - return null; }); - return $propertyNames; } - /** * Matches: * "$this->someValue = $;" */ - private function isVariableAssignToThisPropertyFetch(Assign $assign, string $variableName): bool + private function isVariableAssignToThisPropertyFetch(\PhpParser\Node\Expr\Assign $assign, string $variableName) : bool { - if (! $assign->expr instanceof Variable) { - return false; + if (!$assign->expr instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - - if (! $this->nodeNameResolver->isName($assign->expr, $variableName)) { - return false; + if (!$this->nodeNameResolver->isName($assign->expr, $variableName)) { + return \false; } - - if (! $assign->var instanceof PropertyFetch) { - return false; + if (!$assign->var instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - $propertyFetch = $assign->var; - // must be local property return $this->nodeNameResolver->isName($propertyFetch->var, 'this'); } diff --git a/src/NodeManipulator/PropertyManipulator.php b/src/NodeManipulator/PropertyManipulator.php index 67d951f0be9..9e10acfc306 100644 --- a/src/NodeManipulator/PropertyManipulator.php +++ b/src/NodeManipulator/PropertyManipulator.php @@ -1,7 +1,6 @@ betterNodeFinder = $betterNodeFinder; $this->assignManipulator = $assignManipulator; $this->variableToConstantGuard = $variableToConstantGuard; @@ -99,108 +79,86 @@ final class PropertyManipulator $this->nodeRepository = $nodeRepository; $this->functionLikeReflectionParser = $functionLikeReflectionParser; } - - public function isPropertyUsedInReadContext(Property $property): bool + public function isPropertyUsedInReadContext(\PhpParser\Node\Stmt\Property $property) : bool { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); - if ($phpDocInfo->hasByAnnotationClasses(['Doctrine\ORM\*', 'JMS\Serializer\Annotation\Type'])) { - return true; + if ($phpDocInfo->hasByAnnotationClasses(['Doctrine\\ORM\\*', 'JMS\\Serializer\\Annotation\\Type'])) { + return \true; } - $privatePropertyFetches = $this->propertyFetchFinder->findPrivatePropertyFetches($property); foreach ($privatePropertyFetches as $privatePropertyFetch) { if ($this->readWritePropertyAnalyzer->isRead($privatePropertyFetch)) { - return true; + return \true; } } - // has classLike $this->$variable call? /** @var ClassLike $classLike */ - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - - return (bool) $this->betterNodeFinder->findFirst($classLike->stmts, function (Node $node): bool { - if (! $node instanceof PropertyFetch) { - return false; + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + return (bool) $this->betterNodeFinder->findFirst($classLike->stmts, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Expr\PropertyFetch) { + return \false; } - - if (! $this->readWritePropertyAnalyzer->isRead($node)) { - return false; + if (!$this->readWritePropertyAnalyzer->isRead($node)) { + return \false; } - - return $node->name instanceof Expr; + return $node->name instanceof \PhpParser\Node\Expr; }); } - - public function isPropertyChangeable(Property $property): bool + public function isPropertyChangeable(\PhpParser\Node\Stmt\Property $property) : bool { $propertyFetches = $this->propertyFetchFinder->findPrivatePropertyFetches($property); - foreach ($propertyFetches as $propertyFetch) { if ($this->isChangeableContext($propertyFetch)) { - return true; + return \true; } } - - return false; + return \false; } - /** * @param PropertyFetch|StaticPropertyFetch $expr */ - private function isChangeableContext(Expr $expr): bool + private function isChangeableContext(\PhpParser\Node\Expr $expr) : bool { - $parent = $expr->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Node) { - return false; + $parent = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node) { + return \false; } - - if ($this->typeChecker->isInstanceOf($parent, [PreInc::class, PreDec::class, PostInc::class, PostDec::class])) { - $parent = $parent->getAttribute(AttributeKey::PARENT_NODE); + if ($this->typeChecker->isInstanceOf($parent, [\PhpParser\Node\Expr\PreInc::class, \PhpParser\Node\Expr\PreDec::class, \PhpParser\Node\Expr\PostInc::class, \PhpParser\Node\Expr\PostDec::class])) { + $parent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); } - - if (! $parent instanceof Node) { - return false; + if (!$parent instanceof \PhpParser\Node) { + return \false; } - - if ($parent instanceof Arg) { + if ($parent instanceof \PhpParser\Node\Arg) { $readArg = $this->variableToConstantGuard->isReadArg($parent); - if (! $readArg) { - return true; + if (!$readArg) { + return \true; } - - $caller = $parent->getAttribute(AttributeKey::PARENT_NODE); - if ($caller instanceof MethodCall || $caller instanceof StaticCall) { + $caller = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($caller instanceof \PhpParser\Node\Expr\MethodCall || $caller instanceof \PhpParser\Node\Expr\StaticCall) { return $this->isFoundByRefParam($caller); } } - return $this->assignManipulator->isLeftPartOfAssign($expr); } - /** * @param MethodCall|StaticCall $node */ - private function isFoundByRefParam(Node $node): bool + private function isFoundByRefParam(\PhpParser\Node $node) : bool { - $classMethod = $node instanceof MethodCall - ? $this->nodeRepository->findClassMethodByMethodCall($node) - : $this->nodeRepository->findClassMethodByStaticCall($node); - - if (! $classMethod instanceof ClassMethod) { + $classMethod = $node instanceof \PhpParser\Node\Expr\MethodCall ? $this->nodeRepository->findClassMethodByMethodCall($node) : $this->nodeRepository->findClassMethodByStaticCall($node); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { $classMethod = $this->functionLikeReflectionParser->parseCaller($node); } - - if (! $classMethod instanceof ClassMethod) { - return false; + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - $params = $classMethod->getParams(); foreach ($params as $param) { if ($param->byRef) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/src/NodeManipulator/StmtsManipulator.php b/src/NodeManipulator/StmtsManipulator.php index d3469a038b1..8ecf4d24f6d 100644 --- a/src/NodeManipulator/StmtsManipulator.php +++ b/src/NodeManipulator/StmtsManipulator.php @@ -1,7 +1,6 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->nodeComparator = $nodeComparator; } - /** * @param Stmt[] $stmts */ - public function getUnwrappedLastStmt(array $stmts): ?Node + public function getUnwrappedLastStmt(array $stmts) : ?\PhpParser\Node { - $lastStmtKey = array_key_last($stmts); + \end($stmts); + $lastStmtKey = \key($stmts); $lastStmt = $stmts[$lastStmtKey]; - - if ($lastStmt instanceof Expression) { + if ($lastStmt instanceof \PhpParser\Node\Stmt\Expression) { return $lastStmt->expr; } - return $lastStmt; } - /** * @param Stmt[] $stmts * @return Stmt[] */ - public function filterOutExistingStmts(ClassMethod $classMethod, array $stmts): array + public function filterOutExistingStmts(\PhpParser\Node\Stmt\ClassMethod $classMethod, array $stmts) : array { - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $classMethod->stmts, - function (Node $node) use (&$stmts) { - foreach ($stmts as $key => $assign) { - if (! $this->nodeComparator->areNodesEqual($node, $assign)) { - continue; - } - - unset($stmts[$key]); + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->stmts, function (\PhpParser\Node $node) use(&$stmts) { + foreach ($stmts as $key => $assign) { + if (!$this->nodeComparator->areNodesEqual($node, $assign)) { + continue; } - - return null; + unset($stmts[$key]); } - ); - + return null; + }); return $stmts; } } diff --git a/src/NodeManipulator/VariableManipulator.php b/src/NodeManipulator/VariableManipulator.php index cc948a90370..7fa9e13dc96 100644 --- a/src/NodeManipulator/VariableManipulator.php +++ b/src/NodeManipulator/VariableManipulator.php @@ -1,10 +1,9 @@ simpleCallableNodeTraverser = $simpleCallableNodeTraverser; $this->assignManipulator = $assignManipulator; $this->betterNodeFinder = $betterNodeFinder; @@ -74,118 +58,91 @@ final class VariableManipulator $this->variableToConstantGuard = $variableToConstantGuard; $this->nodeComparator = $nodeComparator; } - /** * @return Assign[] */ - public function collectScalarOrArrayAssignsOfVariable(ClassMethod $classMethod): array + public function collectScalarOrArrayAssignsOfVariable(\PhpParser\Node\Stmt\ClassMethod $classMethod) : array { $assignsOfArrayToVariable = []; - - $this->simpleCallableNodeTraverser->traverseNodesWithCallable( - (array) $classMethod->getStmts(), - function (Node $node) use (&$assignsOfArrayToVariable) { - if (! $node instanceof Assign) { - return null; - } - - if (! $node->var instanceof Variable) { - return null; - } - - if (! $node->expr instanceof Array_ && ! $node->expr instanceof Scalar) { - return null; - } - - if ($node->expr instanceof Encapsed) { - return null; - } - - if ($node->expr instanceof Array_ && ! $this->arrayManipulator->isArrayOnlyScalarValues($node->expr)) { - return null; - } - - if ($this->isTestCaseExpectedVariable($node->var)) { - return null; - } - - $assignsOfArrayToVariable[] = $node; + $this->simpleCallableNodeTraverser->traverseNodesWithCallable((array) $classMethod->getStmts(), function (\PhpParser\Node $node) use(&$assignsOfArrayToVariable) { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return null; } - ); - + if (!$node->var instanceof \PhpParser\Node\Expr\Variable) { + return null; + } + if (!$node->expr instanceof \PhpParser\Node\Expr\Array_ && !$node->expr instanceof \PhpParser\Node\Scalar) { + return null; + } + if ($node->expr instanceof \PhpParser\Node\Scalar\Encapsed) { + return null; + } + if ($node->expr instanceof \PhpParser\Node\Expr\Array_ && !$this->arrayManipulator->isArrayOnlyScalarValues($node->expr)) { + return null; + } + if ($this->isTestCaseExpectedVariable($node->var)) { + return null; + } + $assignsOfArrayToVariable[] = $node; + }); return $assignsOfArrayToVariable; } - /** * @param Assign[] $assignsOfArrayToVariable * @return Assign[] */ - public function filterOutChangedVariables(array $assignsOfArrayToVariable, ClassMethod $classMethod): array + public function filterOutChangedVariables(array $assignsOfArrayToVariable, \PhpParser\Node\Stmt\ClassMethod $classMethod) : array { - return array_filter($assignsOfArrayToVariable, function (Assign $assign) use ($classMethod): bool { + return \array_filter($assignsOfArrayToVariable, function (\PhpParser\Node\Expr\Assign $assign) use($classMethod) : bool { return $this->isReadOnlyVariable($classMethod, $assign); }); } - - private function isTestCaseExpectedVariable(Variable $variable): bool + private function isTestCaseExpectedVariable(\PhpParser\Node\Expr\Variable $variable) : bool { /** @var string $className */ - $className = $variable->getAttribute(AttributeKey::CLASS_NAME); - if (! Strings::endsWith($className, 'Test')) { - return false; + $className = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + if (!\RectorPrefix20210509\Nette\Utils\Strings::endsWith($className, 'Test')) { + return \false; } - return $this->nodeNameResolver->isName($variable, 'expect*'); } - /** * Inspiration * @see \Rector\Core\NodeManipulator\PropertyManipulator::isReadOnlyProperty() */ - private function isReadOnlyVariable(ClassMethod $classMethod, Assign $assign): bool + private function isReadOnlyVariable(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Expr\Assign $assign) : bool { - if (! $assign->var instanceof Variable) { - return false; + if (!$assign->var instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - $variable = $assign->var; $variableUsages = $this->collectVariableUsages($classMethod, $variable, $assign); - foreach ($variableUsages as $variableUsage) { - $parent = $variableUsage->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Arg && ! $this->variableToConstantGuard->isReadArg($parent)) { - return false; + $parent = $variableUsage->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Arg && !$this->variableToConstantGuard->isReadArg($parent)) { + return \false; } - - if (! $this->assignManipulator->isLeftPartOfAssign($variableUsage)) { + if (!$this->assignManipulator->isLeftPartOfAssign($variableUsage)) { continue; } - - return false; + return \false; } - - return true; + return \true; } - /** * @return Variable[] */ - private function collectVariableUsages(ClassMethod $classMethod, Variable $variable, Assign $assign): array + private function collectVariableUsages(\PhpParser\Node\Stmt\ClassMethod $classMethod, \PhpParser\Node\Expr\Variable $variable, \PhpParser\Node\Expr\Assign $assign) : array { - return $this->betterNodeFinder->find((array) $classMethod->getStmts(), function (Node $node) use ( - $variable, - $assign - ): bool { - if (! $node instanceof Variable) { - return false; + return $this->betterNodeFinder->find((array) $classMethod->getStmts(), function (\PhpParser\Node $node) use($variable, $assign) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Variable) { + return \false; } - // skip initialization - $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); + $parentNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); if ($parentNode === $assign) { - return false; + return \false; } - return $this->nodeComparator->areNodesEqual($node, $variable); }); } diff --git a/src/NonPhpFile/NonPhpFileProcessor.php b/src/NonPhpFile/NonPhpFileProcessor.php index 9d7bfe92dff..c704db99e35 100644 --- a/src/NonPhpFile/NonPhpFileProcessor.php +++ b/src/NonPhpFile/NonPhpFileProcessor.php @@ -1,25 +1,22 @@ nonPhpRectors = $nonPhpRectors; } - /** * @param File[] $files */ - public function process(array $files): void + public function process(array $files) : void { foreach ($files as $file) { $this->processFile($file); } } - - public function supports(File $file): bool + public function supports(\Rector\Core\ValueObject\Application\File $file) : bool { $smartFileInfo = $file->getSmartFileInfo(); - // bug in path extension foreach ($this->getSupportedFileExtensions() as $supportedFileExtension) { - if (Strings::endsWith($smartFileInfo->getPathname(), '.' . $supportedFileExtension)) { - return true; + if (\RectorPrefix20210509\Nette\Utils\Strings::endsWith($smartFileInfo->getPathname(), '.' . $supportedFileExtension)) { + return \true; } } - - return false; + return \false; } - - public function getSupportedFileExtensions(): array + public function getSupportedFileExtensions() : array { - return StaticNonPhpFileSuffixes::SUFFIXES; + return \Rector\Core\ValueObject\StaticNonPhpFileSuffixes::SUFFIXES; } - - private function processFile(File $file): void + private function processFile(\Rector\Core\ValueObject\Application\File $file) : void { foreach ($this->nonPhpRectors as $nonPhpRector) { $newFileContent = $nonPhpRector->refactorFileContent($file->getFileContent()); diff --git a/src/NonPhpFile/Rector/RenameClassNonPhpRector.php b/src/NonPhpFile/Rector/RenameClassNonPhpRector.php index 4e4c7c74df4..fca49eb5809 100644 --- a/src/NonPhpFile/Rector/RenameClassNonPhpRector.php +++ b/src/NonPhpFile/Rector/RenameClassNonPhpRector.php @@ -1,10 +1,9 @@ |\.|\'))|(?\s+\\\\))'; - + private const STANDALONE_CLASS_PREFIX_REGEX = '#((?|\\.|\'))|(?\\s+\\\\))'; /** * @see https://regex101.com/r/HKUFJD/5 * @see https://stackoverflow.com/a/3926546/1348344 * @var string */ private const STANDALONE_CLASS_SUFFIX_REGEX = '(?=::)#'; - /** * @var RenamedClassesDataCollector */ private $renamedClassesDataCollector; - /** * @var RenamedClassesCollector */ private $renamedClassesCollector; - /** * @var array */ private $renameClasses = []; - - public function __construct( - RenamedClassesDataCollector $renamedClassesDataCollector, - RenamedClassesCollector $renamedClassesCollector - ) { + public function __construct(\Rector\Core\Configuration\RenamedClassesDataCollector $renamedClassesDataCollector, \Rector\PSR4\Collector\RenamedClassesCollector $renamedClassesCollector) + { $this->renamedClassesDataCollector = $renamedClassesDataCollector; $this->renamedClassesCollector = $renamedClassesCollector; } - - public function getRuleDefinition(): RuleDefinition + public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { - return new RuleDefinition( - 'Change class names and just renamed classes in non-PHP files, NEON, YAML, TWIG, LATTE, blade etc. mostly with regular expressions', - [ - new ConfiguredCodeSample( - <<<'CODE_SAMPLE' + return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change class names and just renamed classes in non-PHP files, NEON, YAML, TWIG, LATTE, blade etc. mostly with regular expressions', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE' services: - SomeOldClass CODE_SAMPLE - , - <<<'CODE_SAMPLE' +, <<<'CODE_SAMPLE' services: - SomeNewClass CODE_SAMPLE - , - [ - self::RENAME_CLASSES => [ - 'SomeOldClass' => 'SomeNewClass', - ], - ] - ), - ] - ); +, [self::RENAME_CLASSES => ['SomeOldClass' => 'SomeNewClass']])]); } - - public function refactorFileContent(string $fileContent): string + public function refactorFileContent(string $fileContent) : string { $classRenames = $this->getRenameClasses(); return $this->renameClasses($fileContent, $classRenames); } - /** * @param array> $configuration */ - public function configure(array $configuration): void + public function configure(array $configuration) : void { $this->renameClasses = $configuration[self::RENAME_CLASSES] ?? []; } - /** * @param array $classRenames */ - private function renameClasses(string $newContent, array $classRenames): string + private function renameClasses(string $newContent, array $classRenames) : string { $classRenames = $this->addDoubleSlahed($classRenames); - foreach ($classRenames as $oldClass => $newClass) { // the old class is without slashes, it can make mess as similar to a word in the text, so we have to be more strict about it $oldClassRegex = $this->createOldClassRegex($oldClass); - $newContent = Strings::replace($newContent, $oldClassRegex, function (array $match) use ( - $newClass - ): string { + $newContent = \RectorPrefix20210509\Nette\Utils\Strings::replace($newContent, $oldClassRegex, function (array $match) use($newClass) : string { return ($match['extra_space'] ?? '') . $newClass; }); } - return $newContent; } - /** * Process with double quotes too, e.g. in twig * * @param array $classRenames * @return array */ - private function addDoubleSlahed(array $classRenames): array + private function addDoubleSlahed(array $classRenames) : array { foreach ($classRenames as $oldClass => $newClass) { // to prevent no slash override - if (! Strings::contains($oldClass, '\\')) { + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($oldClass, '\\')) { continue; } - - $doubleSlashOldClass = str_replace('\\', '\\\\', $oldClass); - $doubleSlashNewClass = str_replace('\\', '\\\\', $newClass); - + $doubleSlashOldClass = \str_replace('\\', '\\\\', $oldClass); + $doubleSlashNewClass = \str_replace('\\', '\\\\', $newClass); $classRenames[$doubleSlashOldClass] = $doubleSlashNewClass; } - return $classRenames; } - /** * @return array */ - private function getRenameClasses(): array + private function getRenameClasses() : array { - return array_merge( - $this->renameClasses, - $this->renamedClassesDataCollector->getOldToNewClasses(), - $this->renamedClassesCollector->getOldToNewClasses() - ); + return \array_merge($this->renameClasses, $this->renamedClassesDataCollector->getOldToNewClasses(), $this->renamedClassesCollector->getOldToNewClasses()); } - - private function createOldClassRegex(string $oldClass): string + private function createOldClassRegex(string $oldClass) : string { - if (! Strings::contains($oldClass, '\\')) { - return self::STANDALONE_CLASS_PREFIX_REGEX - . preg_quote($oldClass, '#') - . self::STANDALONE_CLASS_SUFFIX_REGEX; + if (!\RectorPrefix20210509\Nette\Utils\Strings::contains($oldClass, '\\')) { + return self::STANDALONE_CLASS_PREFIX_REGEX . \preg_quote($oldClass, '#') . self::STANDALONE_CLASS_SUFFIX_REGEX; } - - return '#' . preg_quote($oldClass, '#') . '#'; + return '#' . \preg_quote($oldClass, '#') . '#'; } } diff --git a/src/PHPStan/Reflection/CallReflectionResolver.php b/src/PHPStan/Reflection/CallReflectionResolver.php index f9a58c88a3f..0a665d5959f 100644 --- a/src/PHPStan/Reflection/CallReflectionResolver.php +++ b/src/PHPStan/Reflection/CallReflectionResolver.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; $this->nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; $this->typeToCallReflectionResolverRegistry = $typeToCallReflectionResolverRegistry; } - - public function resolveConstructor(New_ $new): ?MethodReflection + public function resolveConstructor(\PhpParser\Node\Expr\New_ $new) : ?\PHPStan\Reflection\MethodReflection { - $scope = $new->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $new->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $classType = $this->nodeTypeResolver->resolve($new->class); - - if ($classType instanceof UnionType) { + if ($classType instanceof \PHPStan\Type\UnionType) { return $this->matchConstructorMethodInUnionType($classType, $scope); } - - if (! $classType->hasMethod(MethodName::CONSTRUCT)->yes()) { + if (!$classType->hasMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT)->yes()) { return null; } - - return $classType->getMethod(MethodName::CONSTRUCT, $scope); + return $classType->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT, $scope); } - /** * @param FuncCall|MethodCall|StaticCall $node * @return MethodReflection|FunctionReflection|null */ - public function resolveCall(Node $node) + public function resolveCall(\PhpParser\Node $node) { - if ($node instanceof FuncCall) { + if ($node instanceof \PhpParser\Node\Expr\FuncCall) { return $this->resolveFunctionCall($node); } - return $this->resolveMethodCall($node); } - /** * @param FunctionReflection|MethodReflection|null $reflection * @param FuncCall|MethodCall|StaticCall|New_ $node */ - public function resolveParametersAcceptor($reflection, Node $node): ?ParametersAcceptor + public function resolveParametersAcceptor($reflection, \PhpParser\Node $node) : ?\PHPStan\Reflection\ParametersAcceptor { if ($reflection === null) { return null; } - return $reflection->getVariants()[0]; } - - private function matchConstructorMethodInUnionType(UnionType $unionType, Scope $scope): ?MethodReflection + private function matchConstructorMethodInUnionType(\PHPStan\Type\UnionType $unionType, \PHPStan\Analyser\Scope $scope) : ?\PHPStan\Reflection\MethodReflection { foreach ($unionType->getTypes() as $unionedType) { - if (! $unionedType instanceof TypeWithClassName) { + if (!$unionedType instanceof \PHPStan\Type\TypeWithClassName) { continue; } - if (! $unionedType->hasMethod(MethodName::CONSTRUCT)->yes()) { + if (!$unionedType->hasMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT)->yes()) { continue; } - - return $unionedType->getMethod(MethodName::CONSTRUCT, $scope); + return $unionedType->getMethod(\Rector\Core\ValueObject\MethodName::CONSTRUCT, $scope); } - return null; } - /** * @return FunctionReflection|MethodReflection|null */ - private function resolveFunctionCall(FuncCall $funcCall) + private function resolveFunctionCall(\PhpParser\Node\Expr\FuncCall $funcCall) { /** @var Scope|null $scope */ - $scope = $funcCall->getAttribute(AttributeKey::SCOPE); - - if ($funcCall->name instanceof Name) { + $scope = $funcCall->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if ($funcCall->name instanceof \PhpParser\Node\Name) { if ($this->reflectionProvider->hasFunction($funcCall->name, $scope)) { return $this->reflectionProvider->getFunction($funcCall->name, $scope); } - return null; } - - if (! $scope instanceof Scope) { + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $funcCallNameType = $scope->getType($funcCall->name); return $this->typeToCallReflectionResolverRegistry->resolve($funcCallNameType, $scope); } - /** * @param MethodCall|StaticCall $expr */ - private function resolveMethodCall(Expr $expr): ?MethodReflection + private function resolveMethodCall(\PhpParser\Node\Expr $expr) : ?\PHPStan\Reflection\MethodReflection { - $scope = $expr->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { + $scope = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { return null; } - $methodName = $this->nodeNameResolver->getName($expr->name); if ($methodName === null) { return null; } - - $classType = $this->nodeTypeResolver->resolve($expr instanceof MethodCall ? $expr->var : $expr->class); - - if ($classType instanceof ThisType) { + $classType = $this->nodeTypeResolver->resolve($expr instanceof \PhpParser\Node\Expr\MethodCall ? $expr->var : $expr->class); + if ($classType instanceof \PHPStan\Type\ThisType) { $classType = $classType->getStaticObjectType(); } - - if ($classType instanceof ObjectType) { - if (! $this->reflectionProvider->hasClass($classType->getClassName())) { + if ($classType instanceof \PHPStan\Type\ObjectType) { + if (!$this->reflectionProvider->hasClass($classType->getClassName())) { return null; } - $classReflection = $this->reflectionProvider->getClass($classType->getClassName()); if ($classReflection->hasMethod($methodName)) { return $classReflection->getMethod($methodName, $scope); } } - return null; } } diff --git a/src/PHPStan/Reflection/TypeToCallReflectionResolver/ClosureTypeToCallReflectionResolver.php b/src/PHPStan/Reflection/TypeToCallReflectionResolver/ClosureTypeToCallReflectionResolver.php index 813c3238bc1..c00829a254a 100644 --- a/src/PHPStan/Reflection/TypeToCallReflectionResolver/ClosureTypeToCallReflectionResolver.php +++ b/src/PHPStan/Reflection/TypeToCallReflectionResolver/ClosureTypeToCallReflectionResolver.php @@ -1,7 +1,6 @@ getCallableParametersAcceptors($classMemberAccessAnswerer), - null, - TrinaryLogic::createMaybe() - ); + return new \PHPStan\Reflection\Native\NativeFunctionReflection('{closure}', $type->getCallableParametersAcceptors($classMemberAccessAnswerer), null, \PHPStan\TrinaryLogic::createMaybe()); } } diff --git a/src/PHPStan/Reflection/TypeToCallReflectionResolver/ConstantArrayTypeToCallReflectionResolver.php b/src/PHPStan/Reflection/TypeToCallReflectionResolver/ConstantArrayTypeToCallReflectionResolver.php index c6a9480b23d..1e4476a96e8 100644 --- a/src/PHPStan/Reflection/TypeToCallReflectionResolver/ConstantArrayTypeToCallReflectionResolver.php +++ b/src/PHPStan/Reflection/TypeToCallReflectionResolver/ConstantArrayTypeToCallReflectionResolver.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function supports(Type $type): bool + public function supports(\PHPStan\Type\Type $type) : bool { - return $type instanceof ConstantArrayType; + return $type instanceof \PHPStan\Type\Constant\ConstantArrayType; } - /** * @param ConstantArrayType $type */ - public function resolve(Type $type, ClassMemberAccessAnswerer $classMemberAccessAnswerer): ?MethodReflection + public function resolve(\PHPStan\Type\Type $type, \PHPStan\Reflection\ClassMemberAccessAnswerer $classMemberAccessAnswerer) : ?\PHPStan\Reflection\MethodReflection { $constantArrayTypeAndMethod = $this->findTypeAndMethodName($type); - if (! $constantArrayTypeAndMethod instanceof ConstantArrayTypeAndMethod) { + if (!$constantArrayTypeAndMethod instanceof \PHPStan\Type\Constant\ConstantArrayTypeAndMethod) { return null; } if ($constantArrayTypeAndMethod->isUnknown()) { return null; } - if (! $constantArrayTypeAndMethod->getCertainty()->yes()) { + if (!$constantArrayTypeAndMethod->getCertainty()->yes()) { return null; } - $constantArrayType = $constantArrayTypeAndMethod->getType(); - - $methodReflection = $constantArrayType->getMethod( - $constantArrayTypeAndMethod->getMethod(), - $classMemberAccessAnswerer - ); - if (! $classMemberAccessAnswerer->canCallMethod($methodReflection)) { + $methodReflection = $constantArrayType->getMethod($constantArrayTypeAndMethod->getMethod(), $classMemberAccessAnswerer); + if (!$classMemberAccessAnswerer->canCallMethod($methodReflection)) { return null; } - return $methodReflection; } - /** * @see https://github.com/phpstan/phpstan-src/blob/b1fd47bda2a7a7d25091197b125c0adf82af6757/src/Type/Constant/ConstantArrayType.php#L209 */ - private function findTypeAndMethodName(ConstantArrayType $constantArrayType): ?ConstantArrayTypeAndMethod + private function findTypeAndMethodName(\PHPStan\Type\Constant\ConstantArrayType $constantArrayType) : ?\PHPStan\Type\Constant\ConstantArrayTypeAndMethod { - if (! $this->areKeyTypesValid($constantArrayType)) { + if (!$this->areKeyTypesValid($constantArrayType)) { return null; } - - if (count($constantArrayType->getValueTypes()) !== 2) { + if (\count($constantArrayType->getValueTypes()) !== 2) { return null; } - $classOrObjectType = $constantArrayType->getValueTypes()[0]; $methodType = $constantArrayType->getValueTypes()[1]; - - if (! $methodType instanceof ConstantStringType) { - return ConstantArrayTypeAndMethod::createUnknown(); + if (!$methodType instanceof \PHPStan\Type\Constant\ConstantStringType) { + return \PHPStan\Type\Constant\ConstantArrayTypeAndMethod::createUnknown(); } - - $objectWithoutClassType = new ObjectWithoutClassType(); - - if ($classOrObjectType instanceof ConstantStringType) { + $objectWithoutClassType = new \PHPStan\Type\ObjectWithoutClassType(); + if ($classOrObjectType instanceof \PHPStan\Type\Constant\ConstantStringType) { $value = $classOrObjectType->getValue(); - if (! $this->reflectionProvider->hasClass($value)) { - return ConstantArrayTypeAndMethod::createUnknown(); + if (!$this->reflectionProvider->hasClass($value)) { + return \PHPStan\Type\Constant\ConstantArrayTypeAndMethod::createUnknown(); } - $classReflection = $this->reflectionProvider->getClass($value); - $type = new ObjectType($classReflection->getName()); + $type = new \PHPStan\Type\ObjectType($classReflection->getName()); } elseif ($objectWithoutClassType->isSuperTypeOf($classOrObjectType)->yes()) { $type = $classOrObjectType; } else { - return ConstantArrayTypeAndMethod::createUnknown(); + return \PHPStan\Type\Constant\ConstantArrayTypeAndMethod::createUnknown(); } - $trinaryLogic = $type->hasMethod($methodType->getValue()); - if (! $trinaryLogic->no()) { - return ConstantArrayTypeAndMethod::createConcrete($type, $methodType->getValue(), $trinaryLogic); + if (!$trinaryLogic->no()) { + return \PHPStan\Type\Constant\ConstantArrayTypeAndMethod::createConcrete($type, $methodType->getValue(), $trinaryLogic); } - return null; } - - private function areKeyTypesValid(ConstantArrayType $constantArrayType): bool + private function areKeyTypesValid(\PHPStan\Type\Constant\ConstantArrayType $constantArrayType) : bool { $keyTypes = $constantArrayType->getKeyTypes(); - - if (count($keyTypes) !== 2) { - return false; + if (\count($keyTypes) !== 2) { + return \false; } - - if ($keyTypes[0]->isSuperTypeOf(new ConstantIntegerType(0))->no()) { - return false; + if ($keyTypes[0]->isSuperTypeOf(new \PHPStan\Type\Constant\ConstantIntegerType(0))->no()) { + return \false; } - - return ! $keyTypes[1]->isSuperTypeOf(new ConstantIntegerType(1)) - ->no(); + return !$keyTypes[1]->isSuperTypeOf(new \PHPStan\Type\Constant\ConstantIntegerType(1))->no(); } } diff --git a/src/PHPStan/Reflection/TypeToCallReflectionResolver/ConstantStringTypeToCallReflectionResolver.php b/src/PHPStan/Reflection/TypeToCallReflectionResolver/ConstantStringTypeToCallReflectionResolver.php index 9304b367ec8..a2137369d1d 100644 --- a/src/PHPStan/Reflection/TypeToCallReflectionResolver/ConstantStringTypeToCallReflectionResolver.php +++ b/src/PHPStan/Reflection/TypeToCallReflectionResolver/ConstantStringTypeToCallReflectionResolver.php @@ -1,10 +1,9 @@ [a-zA-Z_\\x7f-\\xff\\\\][a-zA-Z0-9_\\x7f-\\xff\\\\]*)::(?[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)\\z#'; - /** * @var ReflectionProvider */ private $reflectionProvider; - - public function __construct(ReflectionProvider $reflectionProvider) + public function __construct(\PHPStan\Reflection\ReflectionProvider $reflectionProvider) { $this->reflectionProvider = $reflectionProvider; } - - public function supports(Type $type): bool + public function supports(\PHPStan\Type\Type $type) : bool { - return $type instanceof ConstantStringType; + return $type instanceof \PHPStan\Type\Constant\ConstantStringType; } - /** * @param ConstantStringType $type * @return FunctionReflection|MethodReflection|null */ - public function resolve(Type $type, ClassMemberAccessAnswerer $classMemberAccessAnswerer) + public function resolve(\PHPStan\Type\Type $type, \PHPStan\Reflection\ClassMemberAccessAnswerer $classMemberAccessAnswerer) { $value = $type->getValue(); - // 'my_function' - $name = new Name($value); + $name = new \PhpParser\Node\Name($value); if ($this->reflectionProvider->hasFunction($name, null)) { return $this->reflectionProvider->getFunction($name, null); } - // 'MyClass::myStaticFunction' - $matches = Strings::match($value, self::STATIC_METHOD_REGEX); + $matches = \RectorPrefix20210509\Nette\Utils\Strings::match($value, self::STATIC_METHOD_REGEX); if ($matches === null) { return null; } - - if (! $this->reflectionProvider->hasClass($matches['class'])) { + if (!$this->reflectionProvider->hasClass($matches['class'])) { return null; } - $classReflection = $this->reflectionProvider->getClass($matches['class']); - if (! $classReflection->hasMethod($matches['method'])) { + if (!$classReflection->hasMethod($matches['method'])) { return null; } - return $classReflection->getMethod($matches['method'], $classMemberAccessAnswerer); } } diff --git a/src/PHPStan/Reflection/TypeToCallReflectionResolver/ObjectTypeToCallReflectionResolver.php b/src/PHPStan/Reflection/TypeToCallReflectionResolver/ObjectTypeToCallReflectionResolver.php index 6ace991f2f2..ba55bfad299 100644 --- a/src/PHPStan/Reflection/TypeToCallReflectionResolver/ObjectTypeToCallReflectionResolver.php +++ b/src/PHPStan/Reflection/TypeToCallReflectionResolver/ObjectTypeToCallReflectionResolver.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function supports(Type $type): bool + public function supports(\PHPStan\Type\Type $type) : bool { - return $type instanceof ObjectType; + return $type instanceof \PHPStan\Type\ObjectType; } - /** * @param ObjectType $type */ - public function resolve(Type $type, ClassMemberAccessAnswerer $classMemberAccessAnswerer): ?MethodReflection + public function resolve(\PHPStan\Type\Type $type, \PHPStan\Reflection\ClassMemberAccessAnswerer $classMemberAccessAnswerer) : ?\PHPStan\Reflection\MethodReflection { $className = $type->getClassName(); - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return null; } - $classReflection = $this->reflectionProvider->getClass($className); - if (! $classReflection->hasNativeMethod('__invoke')) { + if (!$classReflection->hasNativeMethod('__invoke')) { return null; } - return $classReflection->getNativeMethod('__invoke'); } } diff --git a/src/PHPStan/Reflection/TypeToCallReflectionResolver/TypeToCallReflectionResolverRegistry.php b/src/PHPStan/Reflection/TypeToCallReflectionResolver/TypeToCallReflectionResolverRegistry.php index 6f345803824..36e30566ed3 100644 --- a/src/PHPStan/Reflection/TypeToCallReflectionResolver/TypeToCallReflectionResolverRegistry.php +++ b/src/PHPStan/Reflection/TypeToCallReflectionResolver/TypeToCallReflectionResolverRegistry.php @@ -1,7 +1,6 @@ resolvers = $resolvers; } - /** * @return FunctionReflection|MethodReflection|null */ - public function resolve(Type $type, Scope $scope) + public function resolve(\PHPStan\Type\Type $type, \PHPStan\Analyser\Scope $scope) { foreach ($this->resolvers as $resolver) { - if (! $resolver->supports($type)) { + if (!$resolver->supports($type)) { continue; } - return $resolver->resolve($type, $scope); } - return null; } } diff --git a/src/Php/PhpVersionProvider.php b/src/Php/PhpVersionProvider.php index 4433217484c..f9648c74b51 100644 --- a/src/Php/PhpVersionProvider.php +++ b/src/Php/PhpVersionProvider.php @@ -1,14 +1,12 @@ parameterProvider = $parameterProvider; $this->projectComposerJsonPhpVersionResolver = $projectComposerJsonPhpVersionResolver; } - - public function provide(): int + public function provide() : int { /** @var int|null $phpVersionFeatures */ - $phpVersionFeatures = $this->parameterProvider->provideParameter(Option::PHP_VERSION_FEATURES); + $phpVersionFeatures = $this->parameterProvider->provideParameter(\Rector\Core\Configuration\Option::PHP_VERSION_FEATURES); if ($phpVersionFeatures !== null) { return $phpVersionFeatures; } - // for tests - if (StaticPHPUnitEnvironment::isPHPUnitRun()) { + if (\Rector\Testing\PHPUnit\StaticPHPUnitEnvironment::isPHPUnitRun()) { // so we don't have to up return 100000; } - - $projectComposerJson = getcwd() . '/composer.json'; - if (file_exists($projectComposerJson)) { + $projectComposerJson = \getcwd() . '/composer.json'; + if (\file_exists($projectComposerJson)) { $phpVersion = $this->projectComposerJsonPhpVersionResolver->resolve($projectComposerJson); if ($phpVersion !== null) { return $phpVersion; } } - - return PHP_VERSION_ID; + return \PHP_VERSION_ID; } - - public function isAtLeastPhpVersion(int $phpVersion): bool + public function isAtLeastPhpVersion(int $phpVersion) : bool { return $phpVersion <= $this->provide(); } diff --git a/src/Php/PhpVersionResolver/ProjectComposerJsonPhpVersionResolver.php b/src/Php/PhpVersionResolver/ProjectComposerJsonPhpVersionResolver.php index 8fd722b81f0..34ee8b6540b 100644 --- a/src/Php/PhpVersionResolver/ProjectComposerJsonPhpVersionResolver.php +++ b/src/Php/PhpVersionResolver/ProjectComposerJsonPhpVersionResolver.php @@ -1,13 +1,11 @@ composerJsonFactory = $composerJsonFactory; $this->versionParser = $versionParser; $this->phpVersionFactory = $phpVersionFactory; } - - public function resolve(string $composerJson): ?int + public function resolve(string $composerJson) : ?int { $projectComposerJson = $this->composerJsonFactory->createFromFilePath($composerJson); - // see https://getcomposer.org/doc/06-config.md#platform $platformPhp = $projectComposerJson->getConfig()['platform']['php'] ?? null; if ($platformPhp !== null) { return $this->phpVersionFactory->createIntVersion($platformPhp); } - $requirePhpVersion = $projectComposerJson->getRequirePhpVersion(); if ($requirePhpVersion === null) { return null; } - return $this->createIntVersionFromComposerVersion($requirePhpVersion); } - - private function createIntVersionFromComposerVersion(string $projectPhpVersion): int + private function createIntVersionFromComposerVersion(string $projectPhpVersion) : int { $constraint = $this->versionParser->parseConstraints($projectPhpVersion); - $lowerBound = $constraint->getLowerBound(); $lowerBoundVersion = $lowerBound->getVersion(); - return $this->phpVersionFactory->createIntVersion($lowerBoundVersion); } } diff --git a/src/Php/Regex/RegexPatternArgumentManipulator.php b/src/Php/Regex/RegexPatternArgumentManipulator.php index c2a2a60ead6..d0cb6538914 100644 --- a/src/Php/Regex/RegexPatternArgumentManipulator.php +++ b/src/Php/Regex/RegexPatternArgumentManipulator.php @@ -1,10 +1,9 @@ */ - private const FUNCTIONS_WITH_PATTERNS_TO_ARGUMENT_POSITION = [ - 'preg_match' => 0, - 'preg_replace_callback_array' => 0, - 'preg_replace_callback' => 0, - 'preg_replace' => 0, - 'preg_match_all' => 0, - 'preg_split' => 0, - 'preg_grep' => 0, - ]; - + private const FUNCTIONS_WITH_PATTERNS_TO_ARGUMENT_POSITION = ['preg_match' => 0, 'preg_replace_callback_array' => 0, 'preg_replace_callback' => 0, 'preg_replace' => 0, 'preg_match_all' => 0, 'preg_split' => 0, 'preg_grep' => 0]; /** * @var array> */ - private const STATIC_METHODS_WITH_PATTERNS_TO_ARGUMENT_POSITION = [ - Strings::class => [ - 'match' => 1, - 'matchAll' => 1, - 'replace' => 1, - 'split' => 1, - ], - ]; - + private const STATIC_METHODS_WITH_PATTERNS_TO_ARGUMENT_POSITION = [\RectorPrefix20210509\Nette\Utils\Strings::class => ['match' => 1, 'matchAll' => 1, 'replace' => 1, 'split' => 1]]; /** * @var NodeTypeResolver */ private $nodeTypeResolver; - /** * @var NodeNameResolver */ private $nodeNameResolver; - /** * @var BetterNodeFinder */ private $betterNodeFinder; - /** * @var NodeRepository */ private $nodeRepository; - /** * @var NodeComparator */ private $nodeComparator; - - public function __construct( - BetterNodeFinder $betterNodeFinder, - NodeNameResolver $nodeNameResolver, - NodeTypeResolver $nodeTypeResolver, - NodeRepository $nodeRepository, - NodeComparator $nodeComparator - ) { + public function __construct(\Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder, \Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver, \Rector\NodeCollector\NodeCollector\NodeRepository $nodeRepository, \Rector\Core\PhpParser\Comparing\NodeComparator $nodeComparator) + { $this->nodeTypeResolver = $nodeTypeResolver; $this->nodeNameResolver = $nodeNameResolver; $this->betterNodeFinder = $betterNodeFinder; $this->nodeRepository = $nodeRepository; $this->nodeComparator = $nodeComparator; } - /** * @return String_[] */ - public function matchCallArgumentWithRegexPattern(Expr $expr): array + public function matchCallArgumentWithRegexPattern(\PhpParser\Node\Expr $expr) : array { - if ($expr instanceof FuncCall) { + if ($expr instanceof \PhpParser\Node\Expr\FuncCall) { return $this->processFuncCall($expr); } - - if ($expr instanceof StaticCall) { + if ($expr instanceof \PhpParser\Node\Expr\StaticCall) { return $this->processStaticCall($expr); } - return []; } - /** * @return String_[] */ - private function processFuncCall(FuncCall $funcCall): array + private function processFuncCall(\PhpParser\Node\Expr\FuncCall $funcCall) : array { foreach (self::FUNCTIONS_WITH_PATTERNS_TO_ARGUMENT_POSITION as $functionName => $argumentPosition) { - if (! $this->nodeNameResolver->isName($funcCall, $functionName)) { + if (!$this->nodeNameResolver->isName($funcCall, $functionName)) { continue; } - - if (! isset($funcCall->args[$argumentPosition])) { + if (!isset($funcCall->args[$argumentPosition])) { return []; } - return $this->resolveArgumentValues($funcCall->args[$argumentPosition]->value); } - return []; } - /** * @return String_[] */ - private function processStaticCall(StaticCall $staticCall): array + private function processStaticCall(\PhpParser\Node\Expr\StaticCall $staticCall) : array { foreach (self::STATIC_METHODS_WITH_PATTERNS_TO_ARGUMENT_POSITION as $type => $methodNamesToArgumentPosition) { - if (! $this->nodeTypeResolver->isObjectType($staticCall->class, new ObjectType($type))) { + if (!$this->nodeTypeResolver->isObjectType($staticCall->class, new \PHPStan\Type\ObjectType($type))) { continue; } - foreach ($methodNamesToArgumentPosition as $methodName => $argumentPosition) { - if (! $this->nodeNameResolver->isName($staticCall->name, $methodName)) { + if (!$this->nodeNameResolver->isName($staticCall->name, $methodName)) { continue; } - - if (! isset($staticCall->args[$argumentPosition])) { + if (!isset($staticCall->args[$argumentPosition])) { return []; } - return $this->resolveArgumentValues($staticCall->args[$argumentPosition]->value); } } - return []; } - /** * @return String_[] */ - private function resolveArgumentValues(Expr $expr): array + private function resolveArgumentValues(\PhpParser\Node\Expr $expr) : array { - if ($expr instanceof String_) { + if ($expr instanceof \PhpParser\Node\Scalar\String_) { return [$expr]; } - - if ($expr instanceof Variable) { + if ($expr instanceof \PhpParser\Node\Expr\Variable) { $strings = []; $assignNodes = $this->findAssignerForVariable($expr); foreach ($assignNodes as $assignNode) { - if ($assignNode->expr instanceof String_) { + if ($assignNode->expr instanceof \PhpParser\Node\Scalar\String_) { $strings[] = $assignNode->expr; } } - return $strings; } - - if ($expr instanceof ClassConstFetch) { + if ($expr instanceof \PhpParser\Node\Expr\ClassConstFetch) { return $this->resolveClassConstFetchValue($expr); } - return []; } - /** * @return Assign[] */ - private function findAssignerForVariable(Variable $variable): array + private function findAssignerForVariable(\PhpParser\Node\Expr\Variable $variable) : array { - $classMethod = $variable->getAttribute(AttributeKey::METHOD_NODE); - if (! $classMethod instanceof ClassMethod) { + $classMethod = $variable->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::METHOD_NODE); + if (!$classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return []; } - - return $this->betterNodeFinder->find([$classMethod], function (Node $node) use ($variable): ?Assign { - if (! $node instanceof Assign) { + return $this->betterNodeFinder->find([$classMethod], function (\PhpParser\Node $node) use($variable) : ?Assign { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { return null; } - - if (! $this->nodeComparator->areNodesEqual($node->var, $variable)) { + if (!$this->nodeComparator->areNodesEqual($node->var, $variable)) { return null; } - return $node; }); } - /** * @return String_[] */ - private function resolveClassConstFetchValue(ClassConstFetch $classConstFetch): array + private function resolveClassConstFetchValue(\PhpParser\Node\Expr\ClassConstFetch $classConstFetch) : array { $classConstNode = $this->nodeRepository->findClassConstByClassConstFetch($classConstFetch); - if (! $classConstNode instanceof ClassConst) { + if (!$classConstNode instanceof \PhpParser\Node\Stmt\ClassConst) { return []; } - - if ($classConstNode->consts[0]->value instanceof String_) { + if ($classConstNode->consts[0]->value instanceof \PhpParser\Node\Scalar\String_) { return [$classConstNode->consts[0]->value]; } - return []; } } diff --git a/src/Php/ReservedKeywordAnalyzer.php b/src/Php/ReservedKeywordAnalyzer.php index adc92a91c24..b4434732f8c 100644 --- a/src/Php/ReservedKeywordAnalyzer.php +++ b/src/Php/ReservedKeywordAnalyzer.php @@ -1,7 +1,6 @@ #'; - /** * @var string * @see https://regex101.com/r/57HGpC/1 */ - private const SQUARE_BRACKET_REGEX = '#(\[\])+$#'; - + private const SQUARE_BRACKET_REGEX = '#(\\[\\])+$#'; /** * @var string[] */ - private $phpSupportedTypes = [ - 'string', - 'bool', - 'int', - 'null', - 'array', - 'false', - 'true', - 'mixed', - 'iterable', - 'float', - 'self', - 'parent', - 'callable', - 'void', - ]; - - public function __construct(PhpVersionProvider $phpVersionProvider) + private $phpSupportedTypes = ['string', 'bool', 'int', 'null', 'array', 'false', 'true', 'mixed', 'iterable', 'float', 'self', 'parent', 'callable', 'void']; + public function __construct(\Rector\Core\Php\PhpVersionProvider $phpVersionProvider) { - if ($phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::OBJECT_TYPE)) { + if ($phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::OBJECT_TYPE)) { $this->phpSupportedTypes[] = 'object'; } } - - public function isPhpReservedType(string $type): bool + public function isPhpReservedType(string $type) : bool { - $types = explode('|', $type); - - $reservedTypes = array_merge($this->phpSupportedTypes, self::EXTRA_TYPES); - + $types = \explode('|', $type); + $reservedTypes = \array_merge($this->phpSupportedTypes, self::EXTRA_TYPES); foreach ($types as $type) { - $type = strtolower($type); - + $type = \strtolower($type); // remove [] from arrays - $type = Strings::replace($type, self::SQUARE_BRACKET_REGEX, ''); - - if (in_array($type, $reservedTypes, true)) { - return true; + $type = \RectorPrefix20210509\Nette\Utils\Strings::replace($type, self::SQUARE_BRACKET_REGEX, ''); + if (\in_array($type, $reservedTypes, \true)) { + return \true; } } - - return false; + return \false; } - - public function normalizeType(string $type): string + public function normalizeType(string $type) : string { - $loweredType = strtolower($type); + $loweredType = \strtolower($type); if ($loweredType === 'boolean') { return 'bool'; } - - if (in_array($loweredType, ['double', 'real'], true)) { + if (\in_array($loweredType, ['double', 'real'], \true)) { return 'float'; } - if ($loweredType === 'integer') { return 'int'; } - if ($loweredType === 'callback') { return 'callable'; } - - if (Strings::match($loweredType, self::ARRAY_TYPE_REGEX)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($loweredType, self::ARRAY_TYPE_REGEX)) { return 'array'; } - return $type; } } diff --git a/src/PhpParser/Comparing/ConditionSearcher.php b/src/PhpParser/Comparing/ConditionSearcher.php index c2f21f33a86..71273ba429b 100644 --- a/src/PhpParser/Comparing/ConditionSearcher.php +++ b/src/PhpParser/Comparing/ConditionSearcher.php @@ -1,7 +1,6 @@ var; - // search if for redeclaration of variable foreach ($if->stmts as $statementIf) { - if (! $statementIf instanceof Expression) { + if (!$statementIf instanceof \PhpParser\Node\Stmt\Expression) { continue; } - - if (! $statementIf->expr instanceof Assign) { + if (!$statementIf->expr instanceof \PhpParser\Node\Expr\Assign) { continue; } - $assignVar = $statementIf->expr->var; - if (! $assignVar instanceof Variable) { + if (!$assignVar instanceof \PhpParser\Node\Expr\Variable) { continue; } - if ($varNode->name !== $assignVar->name) { continue; } - $elseNode = $if->else; - if (! $elseNode instanceof Else_) { + if (!$elseNode instanceof \PhpParser\Node\Stmt\Else_) { continue; } - // search else for redeclaration of variable return $this->searchElseForVariableRedeclaration($assign, $elseNode); } - - return false; + return \false; } - - private function searchElseForVariableRedeclaration(Assign $assign, Else_ $else): bool + private function searchElseForVariableRedeclaration(\PhpParser\Node\Expr\Assign $assign, \PhpParser\Node\Stmt\Else_ $else) : bool { foreach ($else->stmts as $statementElse) { - if (! $statementElse instanceof Expression) { + if (!$statementElse instanceof \PhpParser\Node\Stmt\Expression) { continue; } - - if (! $statementElse->expr instanceof Assign) { + if (!$statementElse->expr instanceof \PhpParser\Node\Expr\Assign) { continue; } - /** @var Variable $varElse */ $varElse = $statementElse->expr->var; /** @var Variable $varNode */ @@ -66,10 +54,8 @@ final class ConditionSearcher if ($varNode->name !== $varElse->name) { continue; } - - return true; + return \true; } - - return false; + return \false; } } diff --git a/src/PhpParser/Comparing/NodeComparator.php b/src/PhpParser/Comparing/NodeComparator.php index dc6aaf1b73f..a41d0b30adb 100644 --- a/src/PhpParser/Comparing/NodeComparator.php +++ b/src/PhpParser/Comparing/NodeComparator.php @@ -1,95 +1,79 @@ commentRemover = $commentRemover; $this->betterStandardPrinter = $betterStandardPrinter; } - /** * Removes all comments from both nodes * @param Node|Node[]|null $node */ - public function printWithoutComments($node): string + public function printWithoutComments($node) : string { $node = $this->commentRemover->removeFromNode($node); $content = $this->betterStandardPrinter->print($node); - - return trim($content); + return \trim($content); } - /** * @param Node|Node[]|null $firstNode * @param Node|Node[]|null $secondNode */ - public function areNodesEqual($firstNode, $secondNode): bool + public function areNodesEqual($firstNode, $secondNode) : bool { return $this->printWithoutComments($firstNode) === $this->printWithoutComments($secondNode); } - /** * @param Node[] $availableNodes */ - public function isNodeEqual(Node $singleNode, array $availableNodes): bool + public function isNodeEqual(\PhpParser\Node $singleNode, array $availableNodes) : bool { // remove comments, only content is relevant $singleNode = clone $singleNode; - $singleNode->setAttribute(AttributeKey::COMMENTS, null); - + $singleNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, null); foreach ($availableNodes as $availableNode) { // remove comments, only content is relevant $availableNode = clone $availableNode; - $availableNode->setAttribute(AttributeKey::COMMENTS, null); - + $availableNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, null); if ($this->areNodesEqual($singleNode, $availableNode)) { - return true; + return \true; } } - - return false; + return \false; } - /** * Checks even clone nodes */ - public function areSameNode(Node $firstNode, Node $secondNode): bool + public function areSameNode(\PhpParser\Node $firstNode, \PhpParser\Node $secondNode) : bool { if ($firstNode === $secondNode) { - return true; + return \true; } - if ($firstNode->getStartTokenPos() !== $secondNode->getStartTokenPos()) { - return false; + return \false; } - if ($firstNode->getEndTokenPos() !== $secondNode->getEndTokenPos()) { - return false; + return \false; } - - $firstClass = get_class($firstNode); - $secondClass = get_class($secondNode); - + $firstClass = \get_class($firstNode); + $secondClass = \get_class($secondNode); return $firstClass === $secondClass; } } diff --git a/src/PhpParser/Node/AssignAndBinaryMap.php b/src/PhpParser/Node/AssignAndBinaryMap.php index c449816a090..df7fc423e50 100644 --- a/src/PhpParser/Node/AssignAndBinaryMap.php +++ b/src/PhpParser/Node/AssignAndBinaryMap.php @@ -1,7 +1,6 @@ , class-string> */ - private const BINARY_OP_TO_INVERSE_CLASSES = [ - Identical::class => NotIdentical::class, - NotIdentical::class => Identical::class, - Equal::class => NotEqual::class, - NotEqual::class => Equal::class, - Greater::class => SmallerOrEqual::class, - Smaller::class => GreaterOrEqual::class, - GreaterOrEqual::class => Smaller::class, - SmallerOrEqual::class => Greater::class, - ]; - + private const BINARY_OP_TO_INVERSE_CLASSES = [\PhpParser\Node\Expr\BinaryOp\Identical::class => \PhpParser\Node\Expr\BinaryOp\NotIdentical::class, \PhpParser\Node\Expr\BinaryOp\NotIdentical::class => \PhpParser\Node\Expr\BinaryOp\Identical::class, \PhpParser\Node\Expr\BinaryOp\Equal::class => \PhpParser\Node\Expr\BinaryOp\NotEqual::class, \PhpParser\Node\Expr\BinaryOp\NotEqual::class => \PhpParser\Node\Expr\BinaryOp\Equal::class, \PhpParser\Node\Expr\BinaryOp\Greater::class => \PhpParser\Node\Expr\BinaryOp\SmallerOrEqual::class, \PhpParser\Node\Expr\BinaryOp\Smaller::class => \PhpParser\Node\Expr\BinaryOp\GreaterOrEqual::class, \PhpParser\Node\Expr\BinaryOp\GreaterOrEqual::class => \PhpParser\Node\Expr\BinaryOp\Smaller::class, \PhpParser\Node\Expr\BinaryOp\SmallerOrEqual::class => \PhpParser\Node\Expr\BinaryOp\Greater::class]; /** * @var array, class-string> */ - private const ASSIGN_OP_TO_BINARY_OP_CLASSES = [ - AssignBitwiseOr::class => BitwiseOr::class, - AssignBitwiseAnd::class => BitwiseAnd::class, - AssignBitwiseXor::class => BitwiseXor::class, - AssignPlus::class => Plus::class, - AssignDiv::class => Div::class, - AssignMul::class => Mul::class, - AssignMinus::class => Minus::class, - AssignConcat::class => Concat::class, - AssignPow::class => Pow::class, - AssignMod::class => Mod::class, - AssignShiftLeft::class => ShiftLeft::class, - AssignShiftRight::class => ShiftRight::class, - ]; - + private const ASSIGN_OP_TO_BINARY_OP_CLASSES = [\PhpParser\Node\Expr\AssignOp\BitwiseOr::class => \PhpParser\Node\Expr\BinaryOp\BitwiseOr::class, \PhpParser\Node\Expr\AssignOp\BitwiseAnd::class => \PhpParser\Node\Expr\BinaryOp\BitwiseAnd::class, \PhpParser\Node\Expr\AssignOp\BitwiseXor::class => \PhpParser\Node\Expr\BinaryOp\BitwiseXor::class, \PhpParser\Node\Expr\AssignOp\Plus::class => \PhpParser\Node\Expr\BinaryOp\Plus::class, \PhpParser\Node\Expr\AssignOp\Div::class => \PhpParser\Node\Expr\BinaryOp\Div::class, \PhpParser\Node\Expr\AssignOp\Mul::class => \PhpParser\Node\Expr\BinaryOp\Mul::class, \PhpParser\Node\Expr\AssignOp\Minus::class => \PhpParser\Node\Expr\BinaryOp\Minus::class, \PhpParser\Node\Expr\AssignOp\Concat::class => \PhpParser\Node\Expr\BinaryOp\Concat::class, \PhpParser\Node\Expr\AssignOp\Pow::class => \PhpParser\Node\Expr\BinaryOp\Pow::class, \PhpParser\Node\Expr\AssignOp\Mod::class => \PhpParser\Node\Expr\BinaryOp\Mod::class, \PhpParser\Node\Expr\AssignOp\ShiftLeft::class => \PhpParser\Node\Expr\BinaryOp\ShiftLeft::class, \PhpParser\Node\Expr\AssignOp\ShiftRight::class => \PhpParser\Node\Expr\BinaryOp\ShiftRight::class]; /** * @var array, class-string> */ private $binaryOpToAssignClasses = []; - public function __construct() { - $this->binaryOpToAssignClasses = array_flip(self::ASSIGN_OP_TO_BINARY_OP_CLASSES); + $this->binaryOpToAssignClasses = \array_flip(self::ASSIGN_OP_TO_BINARY_OP_CLASSES); } - - public function getAlternative(Node $node): ?string + public function getAlternative(\PhpParser\Node $node) : ?string { - $nodeClass = get_class($node); - - if ($node instanceof AssignOp) { + $nodeClass = \get_class($node); + if ($node instanceof \PhpParser\Node\Expr\AssignOp) { return self::ASSIGN_OP_TO_BINARY_OP_CLASSES[$nodeClass] ?? null; } - - if ($node instanceof BinaryOp) { + if ($node instanceof \PhpParser\Node\Expr\BinaryOp) { return $this->binaryOpToAssignClasses[$nodeClass] ?? null; } - return null; } - - public function getInversed(BinaryOp $binaryOp): ?string + public function getInversed(\PhpParser\Node\Expr\BinaryOp $binaryOp) : ?string { - $nodeClass = get_class($binaryOp); + $nodeClass = \get_class($binaryOp); return self::BINARY_OP_TO_INVERSE_CLASSES[$nodeClass] ?? null; } - - public function getTruthyExpr(Expr $expr): Expr + public function getTruthyExpr(\PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr { - if ($expr instanceof Bool_) { + if ($expr instanceof \PhpParser\Node\Expr\Cast\Bool_) { return $expr; } - - if ($expr instanceof BooleanNot) { + if ($expr instanceof \PhpParser\Node\Expr\BooleanNot) { return $expr; } - - $scope = $expr->getAttribute(AttributeKey::SCOPE); - if (! $scope instanceof Scope) { - return new Bool_($expr); + $scope = $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE); + if (!$scope instanceof \PHPStan\Analyser\Scope) { + return new \PhpParser\Node\Expr\Cast\Bool_($expr); } - $type = $scope->getType($expr); - if ($type instanceof BooleanType) { + if ($type instanceof \PHPStan\Type\BooleanType) { return $expr; } - - return new Bool_($expr); + return new \PhpParser\Node\Expr\Cast\Bool_($expr); } } diff --git a/src/PhpParser/Node/BetterNodeFinder.php b/src/PhpParser/Node/BetterNodeFinder.php index cc1d131d9c3..3c6daff01a8 100644 --- a/src/PhpParser/Node/BetterNodeFinder.php +++ b/src/PhpParser/Node/BetterNodeFinder.php @@ -1,7 +1,6 @@ nodeFinder = $nodeFinder; $this->nodeNameResolver = $nodeNameResolver; $this->typeChecker = $typeChecker; $this->nodeComparator = $nodeComparator; $this->classAnalyzer = $classAnalyzer; } - /** * @template T of Node * @param class-string $type * @return T|null */ - public function findParentType(Node $node, string $type): ?Node + public function findParentType(\PhpParser\Node $node, string $type) : ?\PhpParser\Node { - Assert::isAOf($type, Node::class); - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Node) { + \RectorPrefix20210509\Webmozart\Assert\Assert::isAOf($type, \PhpParser\Node::class); + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node) { return null; } - do { - if (is_a($parent, $type, true)) { + if (\is_a($parent, $type, \true)) { return $parent; } - - if (! $parent instanceof Node) { + if (!$parent instanceof \PhpParser\Node) { return null; } - } while ($parent = $parent->getAttribute(AttributeKey::PARENT_NODE)); - + } while ($parent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE)); return null; } - /** * @template T of \PhpParser\Node * @param array> $types * @return T|null */ - public function findParentTypes(Node $node, array $types): ?Node + public function findParentTypes(\PhpParser\Node $node, array $types) : ?\PhpParser\Node { - Assert::allIsAOf($types, Node::class); - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if (! $parent instanceof Node) { + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsAOf($types, \PhpParser\Node::class); + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if (!$parent instanceof \PhpParser\Node) { return null; } - do { foreach ($types as $type) { - if (is_a($parent, $type, true)) { + if (\is_a($parent, $type, \true)) { return $parent; } } - if ($parent === null) { return null; } - } while ($parent = $parent->getAttribute(AttributeKey::PARENT_NODE)); - + } while ($parent = $parent->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE)); return null; } - /** * @template T of Node * @param array> $types * @param Node|Node[]|Stmt[] $nodes * @return T[] */ - public function findInstancesOf($nodes, array $types): array + public function findInstancesOf($nodes, array $types) : array { $foundInstances = []; foreach ($types as $type) { $currentFoundInstances = $this->findInstanceOf($nodes, $type); - $foundInstances = array_merge($foundInstances, $currentFoundInstances); + $foundInstances = \array_merge($foundInstances, $currentFoundInstances); } - return $foundInstances; } - /** * @template T of Node * @param class-string $type * @param Node|Node[]|Stmt[] $nodes * @return T[] */ - public function findInstanceOf($nodes, string $type): array + public function findInstanceOf($nodes, string $type) : array { - Assert::isAOf($type, Node::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::isAOf($type, \PhpParser\Node::class); return $this->nodeFinder->findInstanceOf($nodes, $type); } - /** * @template T of Node * @param class-string $type * @param Node|Node[] $nodes * @return T|null */ - public function findFirstInstanceOf($nodes, string $type): ?Node + public function findFirstInstanceOf($nodes, string $type) : ?\PhpParser\Node { - Assert::isAOf($type, Node::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::isAOf($type, \PhpParser\Node::class); return $this->nodeFinder->findFirstInstanceOf($nodes, $type); } - /** * @param class-string $type * @param Node|Node[] $nodes */ - public function hasInstanceOfName($nodes, string $type, string $name): bool + public function hasInstanceOfName($nodes, string $type, string $name) : bool { - Assert::isAOf($type, Node::class); + \RectorPrefix20210509\Webmozart\Assert\Assert::isAOf($type, \PhpParser\Node::class); return (bool) $this->findInstanceOfName($nodes, $type, $name); } - /** * @param Node|Node[] $nodes */ - public function hasVariableOfName($nodes, string $name): bool + public function hasVariableOfName($nodes, string $name) : bool { return (bool) $this->findVariableOfName($nodes, $name); } - /** * @param Node|Node[] $nodes * @return Variable|null */ - public function findVariableOfName($nodes, string $name): ?Node + public function findVariableOfName($nodes, string $name) : ?\PhpParser\Node { - return $this->findInstanceOfName($nodes, Variable::class, $name); + return $this->findInstanceOfName($nodes, \PhpParser\Node\Expr\Variable::class, $name); } - /** * @param Node|Node[] $nodes * @param array> $types */ - public function hasInstancesOf($nodes, array $types): bool + public function hasInstancesOf($nodes, array $types) : bool { - Assert::allIsAOf($types, Node::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::allIsAOf($types, \PhpParser\Node::class); foreach ($types as $type) { $foundNode = $this->nodeFinder->findFirstInstanceOf($nodes, $type); - if (! $foundNode instanceof Node) { + if (!$foundNode instanceof \PhpParser\Node) { continue; } - - return true; + return \true; } - - return false; + return \false; } - /** * @template T of Node * @param class-string $type * @param Node|Node[] $nodes * @return T|null */ - public function findLastInstanceOf($nodes, string $type): ?Node + public function findLastInstanceOf($nodes, string $type) : ?\PhpParser\Node { - Assert::isAOf($type, Node::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::isAOf($type, \PhpParser\Node::class); $foundInstances = $this->nodeFinder->findInstanceOf($nodes, $type); if ($foundInstances === []) { return null; } - - $lastItemKey = array_key_last($foundInstances); + \end($foundInstances); + $lastItemKey = \key($foundInstances); return $foundInstances[$lastItemKey]; } - /** * @param Node|Node[] $nodes * @return Node[] */ - public function find($nodes, callable $filter): array + public function find($nodes, callable $filter) : array { return $this->nodeFinder->find($nodes, $filter); } - /** * Excludes anonymous classes! * * @param Node[]|Node $nodes * @return ClassLike[] */ - public function findClassLikes($nodes): array + public function findClassLikes($nodes) : array { - return $this->find($nodes, function (Node $node): bool { - if (! $node instanceof ClassLike) { - return false; + return $this->find($nodes, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Stmt\ClassLike) { + return \false; } // skip anonymous classes - return ! ($node instanceof Class_ && $this->classAnalyzer->isAnonymousClass($node)); + return !($node instanceof \PhpParser\Node\Stmt\Class_ && $this->classAnalyzer->isAnonymousClass($node)); }); } - /** * @param Node[] $nodes * @return ClassLike|null */ - public function findFirstNonAnonymousClass(array $nodes): ?Node + public function findFirstNonAnonymousClass(array $nodes) : ?\PhpParser\Node { - return $this->findFirst($nodes, function (Node $node): bool { - if (! $node instanceof ClassLike) { - return false; + return $this->findFirst($nodes, function (\PhpParser\Node $node) : bool { + if (!$node instanceof \PhpParser\Node\Stmt\ClassLike) { + return \false; } - // skip anonymous classes - return ! ($node instanceof Class_ && $this->classAnalyzer->isAnonymousClass($node)); + return !($node instanceof \PhpParser\Node\Stmt\Class_ && $this->classAnalyzer->isAnonymousClass($node)); }); } - /** * @param Node|Node[] $nodes */ - public function findFirst($nodes, callable $filter): ?Node + public function findFirst($nodes, callable $filter) : ?\PhpParser\Node { return $this->nodeFinder->findFirst($nodes, $filter); } - /** * @return Assign|null */ - public function findPreviousAssignToExpr(Expr $expr): ?Node + public function findPreviousAssignToExpr(\PhpParser\Node\Expr $expr) : ?\PhpParser\Node { - return $this->findFirstPrevious($expr, function (Node $node) use ($expr): bool { - if (! $node instanceof Assign) { - return false; + return $this->findFirstPrevious($expr, function (\PhpParser\Node $node) use($expr) : bool { + if (!$node instanceof \PhpParser\Node\Expr\Assign) { + return \false; } - return $this->nodeComparator->areNodesEqual($node->var, $expr); }); } - - public function findFirstPreviousOfNode(Node $node, callable $filter): ?Node + public function findFirstPreviousOfNode(\PhpParser\Node $node, callable $filter) : ?\PhpParser\Node { // move to previous expression - $previousStatement = $node->getAttribute(AttributeKey::PREVIOUS_NODE); + $previousStatement = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_NODE); if ($previousStatement !== null) { $foundNode = $this->findFirst([$previousStatement], $filter); // we found what we need if ($foundNode !== null) { return $foundNode; } - return $this->findFirstPreviousOfNode($previousStatement, $filter); } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof FunctionLike) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\FunctionLike) { return null; } - - if ($parent instanceof Node) { + if ($parent instanceof \PhpParser\Node) { return $this->findFirstPreviousOfNode($parent, $filter); } - return null; } - - public function findFirstPrevious(Node $node, callable $filter): ?Node + public function findFirstPrevious(\PhpParser\Node $node, callable $filter) : ?\PhpParser\Node { - $node = $node instanceof Expression ? $node : $node->getAttribute(AttributeKey::CURRENT_STATEMENT); + $node = $node instanceof \PhpParser\Node\Stmt\Expression ? $node : $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CURRENT_STATEMENT); if ($node === null) { return null; } - $foundNode = $this->findFirst([$node], $filter); // we found what we need if ($foundNode !== null) { return $foundNode; } - // move to previous expression - $previousStatement = $node->getAttribute(AttributeKey::PREVIOUS_STATEMENT); + $previousStatement = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PREVIOUS_STATEMENT); if ($previousStatement !== null) { return $this->findFirstPrevious($previousStatement, $filter); } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); if ($parent === null) { return null; } - return $this->findFirstPrevious($parent, $filter); } - /** * @template T of Node * @param array> $types * @return T|null */ - public function findFirstPreviousOfTypes(Node $mainNode, array $types): ?Node + public function findFirstPreviousOfTypes(\PhpParser\Node $mainNode, array $types) : ?\PhpParser\Node { - return $this->findFirstPrevious($mainNode, function (Node $node) use ($types): bool { + return $this->findFirstPrevious($mainNode, function (\PhpParser\Node $node) use($types) : bool { return $this->typeChecker->isInstanceOf($node, $types); }); } - - public function findFirstNext(Node $node, callable $filter): ?Node + public function findFirstNext(\PhpParser\Node $node, callable $filter) : ?\PhpParser\Node { - $next = $node->getAttribute(AttributeKey::NEXT_NODE); - if ($next instanceof Node) { - if ($next instanceof Return_ && $next->expr === null) { + $next = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); + if ($next instanceof \PhpParser\Node) { + if ($next instanceof \PhpParser\Node\Stmt\Return_ && $next->expr === null) { return null; } - $found = $this->findFirst($next, $filter); - if ($found instanceof Node) { + if ($found instanceof \PhpParser\Node) { return $found; } - return $this->findFirstNext($next, $filter); } - - $parent = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($parent instanceof Return_ || $parent instanceof FunctionLike) { + $parent = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + if ($parent instanceof \PhpParser\Node\Stmt\Return_ || $parent instanceof \PhpParser\Node\FunctionLike) { return null; } - - if ($parent instanceof Node) { + if ($parent instanceof \PhpParser\Node) { return $this->findFirstNext($parent, $filter); } - return null; } - /** * @template T of Node * @param Node|Node[] $nodes * @param class-string $type * @return T|null */ - private function findInstanceOfName($nodes, string $type, string $name): ?Node + private function findInstanceOfName($nodes, string $type, string $name) : ?\PhpParser\Node { - Assert::isAOf($type, Node::class); - + \RectorPrefix20210509\Webmozart\Assert\Assert::isAOf($type, \PhpParser\Node::class); $foundInstances = $this->nodeFinder->findInstanceOf($nodes, $type); foreach ($foundInstances as $foundInstance) { - if (! $this->nodeNameResolver->isName($foundInstance, $name)) { + if (!$this->nodeNameResolver->isName($foundInstance, $name)) { continue; } - return $foundInstance; } - return null; } } diff --git a/src/PhpParser/Node/CustomNode/FileWithoutNamespace.php b/src/PhpParser/Node/CustomNode/FileWithoutNamespace.php index 673819ef8d6..67601dd0085 100644 --- a/src/PhpParser/Node/CustomNode/FileWithoutNamespace.php +++ b/src/PhpParser/Node/CustomNode/FileWithoutNamespace.php @@ -1,41 +1,35 @@ stmts = $stmts; - parent::__construct(); } - - public function getType(): string + public function getType() : string { return 'FileWithoutNamespace'; } - /** * @return string[] */ - public function getSubNodeNames(): array + public function getSubNodeNames() : array { return ['stmts']; } diff --git a/src/PhpParser/Node/NodeFactory.php b/src/PhpParser/Node/NodeFactory.php index cf89a5f14de..021aae264aa 100644 --- a/src/PhpParser/Node/NodeFactory.php +++ b/src/PhpParser/Node/NodeFactory.php @@ -1,7 +1,6 @@ builderFactory = $builderFactory; $this->staticTypeMapper = $staticTypeMapper; $this->phpDocInfoFactory = $phpDocInfoFactory; @@ -142,413 +121,324 @@ final class NodeFactory $this->phpDocTypeChanger = $phpDocTypeChanger; $this->currentNodeProvider = $currentNodeProvider; } - /** * Creates "SomeClass::CONSTANT" */ - public function createShortClassConstFetch(string $shortClassName, string $constantName): ClassConstFetch + public function createShortClassConstFetch(string $shortClassName, string $constantName) : \PhpParser\Node\Expr\ClassConstFetch { - $name = new Name($shortClassName); + $name = new \PhpParser\Node\Name($shortClassName); return $this->createClassConstFetchFromName($name, $constantName); } - /** * Creates "\SomeClass::CONSTANT" */ - public function createClassConstFetch(string $className, string $constantName): ClassConstFetch + public function createClassConstFetch(string $className, string $constantName) : \PhpParser\Node\Expr\ClassConstFetch { - $classNameNode = in_array($className, self::REFERENCES, true) ? new Name( - $className - ) : new FullyQualified($className); - + $classNameNode = \in_array($className, self::REFERENCES, \true) ? new \PhpParser\Node\Name($className) : new \PhpParser\Node\Name\FullyQualified($className); return $this->createClassConstFetchFromName($classNameNode, $constantName); } - /** * Creates "\SomeClass::class" */ - public function createClassConstReference(string $className): ClassConstFetch + public function createClassConstReference(string $className) : \PhpParser\Node\Expr\ClassConstFetch { return $this->createClassConstFetch($className, 'class'); } - /** * Creates "['item', $variable]" * * @param mixed[] $items */ - public function createArray(array $items): Array_ + public function createArray(array $items) : \PhpParser\Node\Expr\Array_ { $arrayItems = []; - $defaultKey = 0; foreach ($items as $key => $item) { $customKey = $key !== $defaultKey ? $key : null; $arrayItems[] = $this->createArrayItem($item, $customKey); - ++$defaultKey; } - - return new Array_($arrayItems); + return new \PhpParser\Node\Expr\Array_($arrayItems); } - /** * Creates "($args)" * * @param mixed[] $values * @return Arg[] */ - public function createArgs(array $values): array + public function createArgs(array $values) : array { $normalizedValues = []; foreach ($values as $key => $value) { $normalizedValues[$key] = $this->normalizeArgValue($value); } - return $this->builderFactory->args($normalizedValues); } - /** * Creates $this->property = $property; */ - public function createPropertyAssignment(string $propertyName): Assign + public function createPropertyAssignment(string $propertyName) : \PhpParser\Node\Expr\Assign { - $variable = new Variable($propertyName); + $variable = new \PhpParser\Node\Expr\Variable($propertyName); return $this->createPropertyAssignmentWithExpr($propertyName, $variable); } - - public function createPropertyAssignmentWithExpr(string $propertyName, Expr $expr): Assign + public function createPropertyAssignmentWithExpr(string $propertyName, \PhpParser\Node\Expr $expr) : \PhpParser\Node\Expr\Assign { $propertyFetch = $this->createPropertyFetch(self::THIS, $propertyName); - return new Assign($propertyFetch, $expr); + return new \PhpParser\Node\Expr\Assign($propertyFetch, $expr); } - /** * @param mixed $argument */ - public function createArg($argument): Arg + public function createArg($argument) : \PhpParser\Node\Arg { - return new Arg(BuilderHelpers::normalizeValue($argument)); + return new \PhpParser\Node\Arg(\PhpParser\BuilderHelpers::normalizeValue($argument)); } - - public function createPublicMethod(string $name): ClassMethod + public function createPublicMethod(string $name) : \PhpParser\Node\Stmt\ClassMethod { - $methodBuilder = new MethodBuilder($name); + $methodBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\MethodBuilder($name); $methodBuilder->makePublic(); - return $methodBuilder->getNode(); } - - public function createParamFromNameAndType(string $name, ?Type $type): Param + public function createParamFromNameAndType(string $name, ?\PHPStan\Type\Type $type) : \PhpParser\Node\Param { - $paramBuilder = new ParamBuilder($name); - + $paramBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\ParamBuilder($name); if ($type !== null) { $typeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($type); if ($typeNode !== null) { $paramBuilder->setType($typeNode); } } - return $paramBuilder->getNode(); } - - public function createPublicInjectPropertyFromNameAndType(string $name, ?Type $type): Property + public function createPublicInjectPropertyFromNameAndType(string $name, ?\PHPStan\Type\Type $type) : \PhpParser\Node\Stmt\Property { - $propertyBuilder = new PropertyBuilder($name); + $propertyBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\PropertyBuilder($name); $propertyBuilder->makePublic(); - $property = $propertyBuilder->getNode(); - $this->addPropertyType($property, $type); - // add @inject $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); - $phpDocInfo->addPhpDocTagNode(new PhpDocTagNode('@inject', new GenericTagValueNode(''))); - + $phpDocInfo->addPhpDocTagNode(new \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode('@inject', new \PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode(''))); return $property; } - - public function createPrivatePropertyFromNameAndType(string $name, ?Type $type): Property + public function createPrivatePropertyFromNameAndType(string $name, ?\PHPStan\Type\Type $type) : \PhpParser\Node\Stmt\Property { - $propertyBuilder = new PropertyBuilder($name); + $propertyBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\PropertyBuilder($name); $propertyBuilder->makePrivate(); - $property = $propertyBuilder->getNode(); $this->addPropertyType($property, $type); - return $property; } - /** * @param mixed[] $arguments */ - public function createLocalMethodCall(string $method, array $arguments = []): MethodCall + public function createLocalMethodCall(string $method, array $arguments = []) : \PhpParser\Node\Expr\MethodCall { - $variable = new Variable('this'); + $variable = new \PhpParser\Node\Expr\Variable('this'); return $this->createMethodCall($variable, $method, $arguments); } - /** * @param string|Expr $variable * @param mixed[] $arguments */ - public function createMethodCall($variable, string $method, array $arguments = []): MethodCall + public function createMethodCall($variable, string $method, array $arguments = []) : \PhpParser\Node\Expr\MethodCall { - if (is_string($variable)) { - $variable = new Variable($variable); + if (\is_string($variable)) { + $variable = new \PhpParser\Node\Expr\Variable($variable); } - - if ($variable instanceof PropertyFetch) { - $variable = new PropertyFetch($variable->var, $variable->name); + if ($variable instanceof \PhpParser\Node\Expr\PropertyFetch) { + $variable = new \PhpParser\Node\Expr\PropertyFetch($variable->var, $variable->name); } - - if ($variable instanceof StaticPropertyFetch) { - $variable = new StaticPropertyFetch($variable->class, $variable->name); + if ($variable instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { + $variable = new \PhpParser\Node\Expr\StaticPropertyFetch($variable->class, $variable->name); } - - if ($variable instanceof MethodCall) { - $variable = new MethodCall($variable->var, $variable->name, $variable->args); + if ($variable instanceof \PhpParser\Node\Expr\MethodCall) { + $variable = new \PhpParser\Node\Expr\MethodCall($variable->var, $variable->name, $variable->args); } - return $this->builderFactory->methodCall($variable, $method, $arguments); } - /** * @param string|Expr $variable */ - public function createPropertyFetch($variable, string $property): PropertyFetch + public function createPropertyFetch($variable, string $property) : \PhpParser\Node\Expr\PropertyFetch { - if (is_string($variable)) { - $variable = new Variable($variable); + if (\is_string($variable)) { + $variable = new \PhpParser\Node\Expr\Variable($variable); } - return $this->builderFactory->propertyFetch($variable, $property); } - /** * @param Param[] $params */ - public function createParentConstructWithParams(array $params): StaticCall + public function createParentConstructWithParams(array $params) : \PhpParser\Node\Expr\StaticCall { - return new StaticCall( - new Name(self::REFERENCE_PARENT), - new Identifier(MethodName::CONSTRUCT), - $this->createArgsFromParams($params) - ); + return new \PhpParser\Node\Expr\StaticCall(new \PhpParser\Node\Name(self::REFERENCE_PARENT), new \PhpParser\Node\Identifier(\Rector\Core\ValueObject\MethodName::CONSTRUCT), $this->createArgsFromParams($params)); } - - public function createStaticProtectedPropertyWithDefault(string $name, Node $node): Property + public function createStaticProtectedPropertyWithDefault(string $name, \PhpParser\Node $node) : \PhpParser\Node\Stmt\Property { - $propertyBuilder = new PropertyBuilder($name); + $propertyBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\PropertyBuilder($name); $propertyBuilder->makeProtected(); $propertyBuilder->makeStatic(); $propertyBuilder->setDefault($node); - return $propertyBuilder->getNode(); } - - public function createProperty(string $name): Property + public function createProperty(string $name) : \PhpParser\Node\Stmt\Property { - $propertyBuilder = new PropertyBuilder($name); - + $propertyBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\PropertyBuilder($name); $property = $propertyBuilder->getNode(); $this->phpDocInfoFactory->createFromNode($property); - return $property; } - - public function createPrivateProperty(string $name): Property + public function createPrivateProperty(string $name) : \PhpParser\Node\Stmt\Property { - $propertyBuilder = new PropertyBuilder($name); + $propertyBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\PropertyBuilder($name); $propertyBuilder->makePrivate(); - $property = $propertyBuilder->getNode(); - $this->phpDocInfoFactory->createFromNode($property); - return $property; } - - public function createPublicProperty(string $name): Property + public function createPublicProperty(string $name) : \PhpParser\Node\Stmt\Property { - $propertyBuilder = new PropertyBuilder($name); + $propertyBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\PropertyBuilder($name); $propertyBuilder->makePublic(); - $property = $propertyBuilder->getNode(); - $this->phpDocInfoFactory->createFromNode($property); - return $property; } - /** * @param mixed $value */ - public function createPrivateClassConst(string $name, $value): ClassConst + public function createPrivateClassConst(string $name, $value) : \PhpParser\Node\Stmt\ClassConst { - return $this->createClassConstant($name, $value, Class_::MODIFIER_PRIVATE); + return $this->createClassConstant($name, $value, \PhpParser\Node\Stmt\Class_::MODIFIER_PRIVATE); } - /** * @param mixed $value */ - public function createPublicClassConst(string $name, $value): ClassConst + public function createPublicClassConst(string $name, $value) : \PhpParser\Node\Stmt\ClassConst { - return $this->createClassConstant($name, $value, Class_::MODIFIER_PUBLIC); + return $this->createClassConstant($name, $value, \PhpParser\Node\Stmt\Class_::MODIFIER_PUBLIC); } - - public function createGetterClassMethod(string $propertyName, Type $type): ClassMethod + public function createGetterClassMethod(string $propertyName, \PHPStan\Type\Type $type) : \PhpParser\Node\Stmt\ClassMethod { - $methodBuilder = new MethodBuilder('get' . ucfirst($propertyName)); + $methodBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\MethodBuilder('get' . \ucfirst($propertyName)); $methodBuilder->makePublic(); - - $propertyFetch = new PropertyFetch(new Variable(self::THIS), $propertyName); - - $return = new Return_($propertyFetch); + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable(self::THIS), $propertyName); + $return = new \PhpParser\Node\Stmt\Return_($propertyFetch); $methodBuilder->addStmt($return); - $typeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($type); if ($typeNode !== null) { $methodBuilder->setReturnType($typeNode); } - return $methodBuilder->getNode(); } - - public function createSetterClassMethod(string $propertyName, Type $type): ClassMethod + public function createSetterClassMethod(string $propertyName, \PHPStan\Type\Type $type) : \PhpParser\Node\Stmt\ClassMethod { - $methodBuilder = new MethodBuilder('set' . ucfirst($propertyName)); + $methodBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\MethodBuilder('set' . \ucfirst($propertyName)); $methodBuilder->makePublic(); - - $variable = new Variable($propertyName); - + $variable = new \PhpParser\Node\Expr\Variable($propertyName); $param = $this->createParamWithType($variable, $type); $methodBuilder->addParam($param); - - $propertyFetch = new PropertyFetch(new Variable(self::THIS), $propertyName); - $assign = new Assign($propertyFetch, $variable); + $propertyFetch = new \PhpParser\Node\Expr\PropertyFetch(new \PhpParser\Node\Expr\Variable(self::THIS), $propertyName); + $assign = new \PhpParser\Node\Expr\Assign($propertyFetch, $variable); $methodBuilder->addStmt($assign); - - if ($this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::VOID_TYPE)) { - $methodBuilder->setReturnType(new Name('void')); + if ($this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::VOID_TYPE)) { + $methodBuilder->setReturnType(new \PhpParser\Node\Name('void')); } - return $methodBuilder->getNode(); } - /** * @todo decouple to StackNodeFactory * @param Expr[] $exprs */ - public function createConcat(array $exprs): ?Concat + public function createConcat(array $exprs) : ?\PhpParser\Node\Expr\BinaryOp\Concat { - if (count($exprs) < 2) { + if (\count($exprs) < 2) { return null; } - /** @var Expr $previousConcat */ - $previousConcat = array_shift($exprs); + $previousConcat = \array_shift($exprs); foreach ($exprs as $expr) { - $previousConcat = new Concat($previousConcat, $expr); + $previousConcat = new \PhpParser\Node\Expr\BinaryOp\Concat($previousConcat, $expr); } - /** @var Concat $previousConcat */ return $previousConcat; } - - public function createClosureFromClassMethod(ClassMethod $classMethod): Closure + public function createClosureFromClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : \PhpParser\Node\Expr\Closure { $classMethodName = $this->nodeNameResolver->getName($classMethod); $args = $this->createArgs($classMethod->params); - - $methodCall = new MethodCall(new Variable(self::THIS), $classMethodName, $args); - $return = new Return_($methodCall); - - return new Closure([ - 'params' => $classMethod->params, - 'stmts' => [$return], - 'returnType' => $classMethod->returnType, - ]); + $methodCall = new \PhpParser\Node\Expr\MethodCall(new \PhpParser\Node\Expr\Variable(self::THIS), $classMethodName, $args); + $return = new \PhpParser\Node\Stmt\Return_($methodCall); + return new \PhpParser\Node\Expr\Closure(['params' => $classMethod->params, 'stmts' => [$return], 'returnType' => $classMethod->returnType]); } - /** * @param string[] $names * @return Use_[] */ - public function createUsesFromNames(array $names): array + public function createUsesFromNames(array $names) : array { $uses = []; foreach ($names as $name) { - $useUse = new UseUse(new Name($name)); - $uses[] = new Use_([$useUse]); + $useUse = new \PhpParser\Node\Stmt\UseUse(new \PhpParser\Node\Name($name)); + $uses[] = new \PhpParser\Node\Stmt\Use_([$useUse]); } - return $uses; } - /** * @param Node[] $args */ - public function createStaticCall(string $class, string $method, array $args = []): StaticCall + public function createStaticCall(string $class, string $method, array $args = []) : \PhpParser\Node\Expr\StaticCall { -// -// $args = $this->wrapToArg($args); -// -// if (in_array($class, ['self', 'parent', 'static'], true)) { -// $class = new Name($class); -// } else { -// $class = new FullyQualified($class); -// } -// -// return new StaticCall($class, $method, $args); - - - + // + // $args = $this->wrapToArg($args); + // + // if (in_array($class, ['self', 'parent', 'static'], true)) { + // $class = new Name($class); + // } else { + // $class = new FullyQualified($class); + // } + // + // return new StaticCall($class, $method, $args); $class = $this->createClassPart($class); - $staticCall = new StaticCall($class, $method); + $staticCall = new \PhpParser\Node\Expr\StaticCall($class, $method); $staticCall->args = $this->createArgs($args); return $staticCall; } - /** * @param mixed[] $arguments */ - public function createFuncCall(string $name, array $arguments = []): FuncCall + public function createFuncCall(string $name, array $arguments = []) : \PhpParser\Node\Expr\FuncCall { $arguments = $this->createArgs($arguments); - return new FuncCall(new Name($name), $arguments); + return new \PhpParser\Node\Expr\FuncCall(new \PhpParser\Node\Name($name), $arguments); } - - public function createSelfFetchConstant(string $constantName, Node $node): ClassConstFetch + public function createSelfFetchConstant(string $constantName, \PhpParser\Node $node) : \PhpParser\Node\Expr\ClassConstFetch { - $name = new Name('self'); - $name->setAttribute(AttributeKey::CLASS_NAME, $node->getAttribute(AttributeKey::CLASS_NAME)); - return new ClassConstFetch($name, $constantName); + $name = new \PhpParser\Node\Name('self'); + $name->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME, $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME)); + return new \PhpParser\Node\Expr\ClassConstFetch($name, $constantName); } - /** * @param Param[] $params * @return Arg[] */ - public function createArgsFromParams(array $params): array + public function createArgsFromParams(array $params) : array { $args = []; foreach ($params as $param) { - $args[] = new Arg($param->var); + $args[] = new \PhpParser\Node\Arg($param->var); } - return $args; } - - public function createNull(): ConstFetch + public function createNull() : \PhpParser\Node\Expr\ConstFetch { - return new ConstFetch(new Name('null')); + return new \PhpParser\Node\Expr\ConstFetch(new \PhpParser\Node\Name('null')); } - - public function createPromotedPropertyParam(PropertyMetadata $propertyMetadata): Param + public function createPromotedPropertyParam(\Rector\PostRector\ValueObject\PropertyMetadata $propertyMetadata) : \PhpParser\Node\Param { - $paramBuilder = new ParamBuilder($propertyMetadata->getName()); + $paramBuilder = new \RectorPrefix20210509\Symplify\Astral\ValueObject\NodeBuilder\ParamBuilder($propertyMetadata->getName()); $propertyType = $propertyMetadata->getType(); if ($propertyType !== null) { $typeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($propertyType); @@ -556,206 +446,158 @@ final class NodeFactory $paramBuilder->setType($typeNode); } } - $param = $paramBuilder->getNode(); $propertyFlags = $propertyMetadata->getFlags(); - $param->flags = $propertyFlags !== 0 ? $propertyFlags : Class_::MODIFIER_PRIVATE; - + $param->flags = $propertyFlags !== 0 ? $propertyFlags : \PhpParser\Node\Stmt\Class_::MODIFIER_PRIVATE; return $param; } - - public function createFalse(): ConstFetch + public function createFalse() : \PhpParser\Node\Expr\ConstFetch { - return new ConstFetch(new Name('false')); + return new \PhpParser\Node\Expr\ConstFetch(new \PhpParser\Node\Name('false')); } - - public function createTrue(): ConstFetch + public function createTrue() : \PhpParser\Node\Expr\ConstFetch { - return new ConstFetch(new Name('true')); + return new \PhpParser\Node\Expr\ConstFetch(new \PhpParser\Node\Name('true')); } - - public function createClassConstFetchFromName(Name $className, string $constantName): ClassConstFetch + public function createClassConstFetchFromName(\PhpParser\Node\Name $className, string $constantName) : \PhpParser\Node\Expr\ClassConstFetch { $classConstFetch = $this->builderFactory->classConstFetch($className, $constantName); - $classNameString = $className->toString(); - if (in_array($classNameString, ['self', 'static'], true)) { + if (\in_array($classNameString, ['self', 'static'], \true)) { $currentNode = $this->currentNodeProvider->getNode(); if ($currentNode !== null) { - $className = $currentNode->getAttribute(AttributeKey::CLASS_NAME); - $classConstFetch->class->setAttribute(AttributeKey::RESOLVED_NAME, $className); - $classConstFetch->class->setAttribute(AttributeKey::CLASS_NAME, $className); + $className = $currentNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); + $classConstFetch->class->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::RESOLVED_NAME, $className); + $classConstFetch->class->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME, $className); } } else { - $classConstFetch->class->setAttribute(AttributeKey::RESOLVED_NAME, $classNameString); + $classConstFetch->class->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::RESOLVED_NAME, $classNameString); } - return $classConstFetch; } - /** * @param array $newNodes */ - public function createReturnBooleanAnd(array $newNodes): ?Expr + public function createReturnBooleanAnd(array $newNodes) : ?\PhpParser\Node\Expr { if ($newNodes === []) { return null; } - - if (count($newNodes) === 1) { + if (\count($newNodes) === 1) { return $newNodes[0]; } - return $this->createBooleanAndFromNodes($newNodes); } - /** * @param mixed $item * @param string|int|null $key */ - private function createArrayItem($item, $key = null): ArrayItem + private function createArrayItem($item, $key = null) : \PhpParser\Node\Expr\ArrayItem { $arrayItem = null; - - if ($item instanceof Variable - || $item instanceof MethodCall - || $item instanceof StaticCall - || $item instanceof FuncCall - || $item instanceof Concat - || $item instanceof Scalar - || $item instanceof Cast - ) { - $arrayItem = new ArrayItem($item); - } elseif ($item instanceof Identifier) { - $string = new String_($item->toString()); - $arrayItem = new ArrayItem($string); - } elseif (is_scalar($item) || $item instanceof Array_) { - $itemValue = BuilderHelpers::normalizeValue($item); - $arrayItem = new ArrayItem($itemValue); - } elseif (is_array($item)) { - $arrayItem = new ArrayItem($this->createArray($item)); + if ($item instanceof \PhpParser\Node\Expr\Variable || $item instanceof \PhpParser\Node\Expr\MethodCall || $item instanceof \PhpParser\Node\Expr\StaticCall || $item instanceof \PhpParser\Node\Expr\FuncCall || $item instanceof \PhpParser\Node\Expr\BinaryOp\Concat || $item instanceof \PhpParser\Node\Scalar || $item instanceof \PhpParser\Node\Expr\Cast) { + $arrayItem = new \PhpParser\Node\Expr\ArrayItem($item); + } elseif ($item instanceof \PhpParser\Node\Identifier) { + $string = new \PhpParser\Node\Scalar\String_($item->toString()); + $arrayItem = new \PhpParser\Node\Expr\ArrayItem($string); + } elseif (\is_scalar($item) || $item instanceof \PhpParser\Node\Expr\Array_) { + $itemValue = \PhpParser\BuilderHelpers::normalizeValue($item); + $arrayItem = new \PhpParser\Node\Expr\ArrayItem($itemValue); + } elseif (\is_array($item)) { + $arrayItem = new \PhpParser\Node\Expr\ArrayItem($this->createArray($item)); } - - if ($item instanceof ClassConstFetch) { - $itemValue = BuilderHelpers::normalizeValue($item); - $arrayItem = new ArrayItem($itemValue); + if ($item instanceof \PhpParser\Node\Expr\ClassConstFetch) { + $itemValue = \PhpParser\BuilderHelpers::normalizeValue($item); + $arrayItem = new \PhpParser\Node\Expr\ArrayItem($itemValue); } - - if ($item instanceof Arg) { - $arrayItem = new ArrayItem($item->value); + if ($item instanceof \PhpParser\Node\Arg) { + $arrayItem = new \PhpParser\Node\Expr\ArrayItem($item->value); } - if ($arrayItem !== null) { $this->decoreateArrayItemWithKey($key, $arrayItem); return $arrayItem; } - - $nodeClass = is_object($item) ? get_class($item) : $item; - throw new NotImplementedYetException(sprintf( - 'Not implemented yet. Go to "%s()" and add check for "%s" node.', - __METHOD__, - $nodeClass - )); + $nodeClass = \is_object($item) ? \get_class($item) : $item; + throw new \Rector\Core\Exception\NotImplementedYetException(\sprintf('Not implemented yet. Go to "%s()" and add check for "%s" node.', __METHOD__, $nodeClass)); } - /** * @param mixed $value * @return mixed|Error|Variable */ private function normalizeArgValue($value) { - if ($value instanceof Param) { + if ($value instanceof \PhpParser\Node\Param) { return $value->var; } - return $value; } - - private function addPropertyType(Property $property, ?Type $type): void + private function addPropertyType(\PhpParser\Node\Stmt\Property $property, ?\PHPStan\Type\Type $type) : void { if ($type === null) { return; } - $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property); - - if ($this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::TYPED_PROPERTIES)) { + if ($this->phpVersionProvider->isAtLeastPhpVersion(\Rector\Core\ValueObject\PhpVersionFeature::TYPED_PROPERTIES)) { $phpParserType = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($type); - if ($phpParserType !== null) { $property->type = $phpParserType; - - if ($type instanceof GenericObjectType) { + if ($type instanceof \PHPStan\Type\Generic\GenericObjectType) { $this->phpDocTypeChanger->changeVarType($phpDocInfo, $type); } - return; } } - $this->phpDocTypeChanger->changeVarType($phpDocInfo, $type); } - /** * @param mixed $value */ - private function createClassConstant(string $name, $value, int $modifier): ClassConst + private function createClassConstant(string $name, $value, int $modifier) : \PhpParser\Node\Stmt\ClassConst { - $value = BuilderHelpers::normalizeValue($value); - - $const = new Const_($name, $value); - $classConst = new ClassConst([$const]); + $value = \PhpParser\BuilderHelpers::normalizeValue($value); + $const = new \PhpParser\Node\Const_($name, $value); + $classConst = new \PhpParser\Node\Stmt\ClassConst([$const]); $classConst->flags |= $modifier; - // add @var type by default $staticType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($value); - - if (! $staticType instanceof MixedType) { + if (!$staticType instanceof \PHPStan\Type\MixedType) { $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classConst); $this->phpDocTypeChanger->changeVarType($phpDocInfo, $staticType); } - return $classConst; } - - private function createClassPart(string $class): Name + private function createClassPart(string $class) : \PhpParser\Node\Name { - if (in_array($class, self::REFERENCES, true)) { - return new Name($class); + if (\in_array($class, self::REFERENCES, \true)) { + return new \PhpParser\Node\Name($class); } - - return new FullyQualified($class); + return new \PhpParser\Node\Name\FullyQualified($class); } - /** * @param int|string|null $key */ - private function decoreateArrayItemWithKey($key, ArrayItem $arrayItem): void + private function decoreateArrayItemWithKey($key, \PhpParser\Node\Expr\ArrayItem $arrayItem) : void { if ($key !== null) { - $arrayItem->key = BuilderHelpers::normalizeValue($key); + $arrayItem->key = \PhpParser\BuilderHelpers::normalizeValue($key); } } - /** * @param NotIdentical[]|BooleanAnd[] $exprs */ - private function createBooleanAndFromNodes(array $exprs): BooleanAnd + private function createBooleanAndFromNodes(array $exprs) : \PhpParser\Node\Expr\BinaryOp\BooleanAnd { /** @var NotIdentical|BooleanAnd $booleanAnd */ - $booleanAnd = array_shift($exprs); + $booleanAnd = \array_shift($exprs); foreach ($exprs as $expr) { - $booleanAnd = new BooleanAnd($booleanAnd, $expr); + $booleanAnd = new \PhpParser\Node\Expr\BinaryOp\BooleanAnd($booleanAnd, $expr); } - /** @var BooleanAnd $booleanAnd */ return $booleanAnd; } - - private function createParamWithType(Variable $variable, Type $type): Param + private function createParamWithType(\PhpParser\Node\Expr\Variable $variable, \PHPStan\Type\Type $type) : \PhpParser\Node\Param { - $param = new Param($variable); - + $param = new \PhpParser\Node\Param($variable); $phpParserTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($type); $param->type = $phpParserTypeNode; return $param; diff --git a/src/PhpParser/Node/Value/ValueResolver.php b/src/PhpParser/Node/Value/ValueResolver.php index 8c816d239f6..d45f28bc19a 100644 --- a/src/PhpParser/Node/Value/ValueResolver.php +++ b/src/PhpParser/Node/Value/ValueResolver.php @@ -1,7 +1,6 @@ nodeNameResolver = $nodeNameResolver; $this->nodeTypeResolver = $nodeTypeResolver; $this->constFetchAnalyzer = $constFetchAnalyzer; $this->reflectionProvider = $reflectionProvider; $this->currentFileProvider = $currentFileProvider; } - /** * @param mixed $value */ - public function isValue(Expr $expr, $value): bool + public function isValue(\PhpParser\Node\Expr $expr, $value) : bool { return $this->getValue($expr) === $value; } - /** * @return mixed|null */ - public function getValue(Expr $expr, bool $resolvedClassReference = false) + public function getValue(\PhpParser\Node\Expr $expr, bool $resolvedClassReference = \false) { - if ($expr instanceof Concat) { + if ($expr instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { return $this->processConcat($expr, $resolvedClassReference); } - - if ($expr instanceof ClassConstFetch && $resolvedClassReference) { + if ($expr instanceof \PhpParser\Node\Expr\ClassConstFetch && $resolvedClassReference) { $class = $this->nodeNameResolver->getName($expr->class); - - if (in_array($class, ['self', 'static'], true)) { - return $expr->getAttribute(AttributeKey::CLASS_NAME); + if (\in_array($class, ['self', 'static'], \true)) { + return $expr->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); } - if ($this->nodeNameResolver->isName($expr->name, 'class')) { return $class; } } - try { $constExprEvaluator = $this->getConstExprEvaluator(); $value = $constExprEvaluator->evaluateDirectly($expr); - } catch (ConstExprEvaluationException $constExprEvaluationException) { + } catch (\PhpParser\ConstExprEvaluationException $constExprEvaluationException) { $value = null; } - if ($value !== null) { return $value; } - - if ($expr instanceof ConstFetch) { + if ($expr instanceof \PhpParser\Node\Expr\ConstFetch) { return $this->nodeNameResolver->getName($expr); } - $nodeStaticType = $this->nodeTypeResolver->getStaticType($expr); - - if ($nodeStaticType instanceof ConstantArrayType) { + if ($nodeStaticType instanceof \PHPStan\Type\Constant\ConstantArrayType) { return $this->extractConstantArrayTypeValue($nodeStaticType); } - - if ($nodeStaticType instanceof ConstantScalarType) { + if ($nodeStaticType instanceof \PHPStan\Type\ConstantScalarType) { return $nodeStaticType->getValue(); } - return null; } - /** * @param mixed[] $expectedValues */ - public function isValues(Expr $expr, array $expectedValues): bool + public function isValues(\PhpParser\Node\Expr $expr, array $expectedValues) : bool { foreach ($expectedValues as $expectedValue) { if ($this->isValue($expr, $expectedValue)) { - return true; + return \true; } } - - return false; + return \false; } - - public function isFalse(Node $node): bool + public function isFalse(\PhpParser\Node $node) : bool { return $this->constFetchAnalyzer->isFalse($node); } - - public function isTrueOrFalse(Node $node): bool + public function isTrueOrFalse(\PhpParser\Node $node) : bool { return $this->constFetchAnalyzer->isTrueOrFalse($node); } - - public function isTrue(Node $node): bool + public function isTrue(\PhpParser\Node $node) : bool { return $this->constFetchAnalyzer->isTrue($node); } - - public function isNull(Node $node): bool + public function isNull(\PhpParser\Node $node) : bool { return $this->constFetchAnalyzer->isNull($node); } - /** * @param Expr[]|null[] $nodes * @param mixed[] $expectedValues */ - public function areValues(array $nodes, array $expectedValues): bool + public function areValues(array $nodes, array $expectedValues) : bool { foreach ($nodes as $i => $node) { if ($node === null) { - return false; + return \false; } - - if (! $this->isValue($node, $expectedValues[$i])) { - return false; + if (!$this->isValue($node, $expectedValues[$i])) { + return \false; } } - - return true; + return \true; } - - private function processConcat(Concat $concat, bool $resolvedClassReference): string + private function processConcat(\PhpParser\Node\Expr\BinaryOp\Concat $concat, bool $resolvedClassReference) : string { - return $this->getValue($concat->left, $resolvedClassReference) . $this->getValue( - $concat->right, - $resolvedClassReference - ); + return $this->getValue($concat->left, $resolvedClassReference) . $this->getValue($concat->right, $resolvedClassReference); } - - private function getConstExprEvaluator(): ConstExprEvaluator + private function getConstExprEvaluator() : \PhpParser\ConstExprEvaluator { if ($this->constExprEvaluator !== null) { return $this->constExprEvaluator; } - - $this->constExprEvaluator = new ConstExprEvaluator(function (Expr $expr) { - if ($expr instanceof Dir) { + $this->constExprEvaluator = new \PhpParser\ConstExprEvaluator(function (\PhpParser\Node\Expr $expr) { + if ($expr instanceof \PhpParser\Node\Scalar\MagicConst\Dir) { // __DIR__ return $this->resolveDirConstant(); } - - if ($expr instanceof File) { + if ($expr instanceof \PhpParser\Node\Scalar\MagicConst\File) { // __FILE__ return $this->resolveFileConstant($expr); } - // resolve "SomeClass::SOME_CONST" - if ($expr instanceof ClassConstFetch) { + if ($expr instanceof \PhpParser\Node\Expr\ClassConstFetch) { return $this->resolveClassConstFetch($expr); } - - throw new ConstExprEvaluationException(sprintf( - 'Expression of type "%s" cannot be evaluated', - $expr->getType() - )); + throw new \PhpParser\ConstExprEvaluationException(\sprintf('Expression of type "%s" cannot be evaluated', $expr->getType())); }); - return $this->constExprEvaluator; } - /** * @return mixed[] */ - private function extractConstantArrayTypeValue(ConstantArrayType $constantArrayType): array + private function extractConstantArrayTypeValue(\PHPStan\Type\Constant\ConstantArrayType $constantArrayType) : array { $keys = []; foreach ($constantArrayType->getKeyTypes() as $i => $keyType) { /** @var ConstantScalarType $keyType */ $keys[$i] = $keyType->getValue(); } - $values = []; foreach ($constantArrayType->getValueTypes() as $i => $valueType) { - if ($valueType instanceof ConstantArrayType) { + if ($valueType instanceof \PHPStan\Type\Constant\ConstantArrayType) { $value = $this->extractConstantArrayTypeValue($valueType); - } elseif ($valueType instanceof ConstantScalarType) { + } elseif ($valueType instanceof \PHPStan\Type\ConstantScalarType) { $value = $valueType->getValue(); } else { // not sure about value continue; } - $values[$keys[$i]] = $value; } - return $values; } - - private function resolveDirConstant(): string + private function resolveDirConstant() : string { $file = $this->currentFileProvider->getFile(); $smartFileInfo = $file->getSmartFileInfo(); return $smartFileInfo->getPath(); } - - private function resolveFileConstant(File $file): string + private function resolveFileConstant(\PhpParser\Node\Scalar\MagicConst\File $file) : string { $file = $this->currentFileProvider->getFile(); - $smartFileInfo = $file->getSmartFileInfo(); return $smartFileInfo->getPathname(); } - /** * @return string|mixed */ - private function resolveClassConstFetch(ClassConstFetch $classConstFetch) + private function resolveClassConstFetch(\PhpParser\Node\Expr\ClassConstFetch $classConstFetch) { $class = $this->nodeNameResolver->getName($classConstFetch->class); $constant = $this->nodeNameResolver->getName($classConstFetch->name); - if ($class === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - if ($constant === null) { - throw new ShouldNotHappenException(); + throw new \Rector\Core\Exception\ShouldNotHappenException(); } - if ($class === 'self') { - $class = (string) $classConstFetch->class->getAttribute(AttributeKey::CLASS_NAME); + $class = (string) $classConstFetch->class->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NAME); } - if ($constant === 'class') { return $class; } - $classConstantReference = $class . '::' . $constant; - if (defined($classConstantReference)) { - return constant($classConstantReference); + if (\defined($classConstantReference)) { + return \constant($classConstantReference); } - if ($this->reflectionProvider->hasClass($class)) { $classReflection = $this->reflectionProvider->getClass($class); - if ($classReflection->hasConstant($constant)) { $constantReflection = $classReflection->getConstant($constant); return $constantReflection->getValue(); } } - // fallback to constant reference itself, to avoid fatal error return $classConstantReference; } diff --git a/src/PhpParser/NodeFinder/PropertyFetchFinder.php b/src/PhpParser/NodeFinder/PropertyFetchFinder.php index 3eff45af74f..cc6bf18d335 100644 --- a/src/PhpParser/NodeFinder/PropertyFetchFinder.php +++ b/src/PhpParser/NodeFinder/PropertyFetchFinder.php @@ -1,7 +1,6 @@ nodeRepository = $nodeRepository; $this->betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; } - /** * @return PropertyFetch[]|StaticPropertyFetch[] */ - public function findPrivatePropertyFetches(Property $property): array + public function findPrivatePropertyFetches(\PhpParser\Node\Stmt\Property $property) : array { - $classLike = $property->getAttribute(AttributeKey::CLASS_NODE); - if (! $classLike instanceof Class_) { + $classLike = $property->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) { return []; } - $classLikesToSearch = $this->nodeRepository->findUsedTraitsInClass($classLike); $classLikesToSearch[] = $classLike; - $singleProperty = $property->props[0]; - /** @var PropertyFetch[]|StaticPropertyFetch[] $propertyFetches */ - $propertyFetches = $this->betterNodeFinder->find($classLikesToSearch, function (Node $node) use ( - $singleProperty, - $classLikesToSearch - ): bool { + $propertyFetches = $this->betterNodeFinder->find($classLikesToSearch, function (\PhpParser\Node $node) use($singleProperty, $classLikesToSearch) : bool { // property + static fetch - if (! $node instanceof PropertyFetch && ! $node instanceof StaticPropertyFetch) { - return false; + if (!$node instanceof \PhpParser\Node\Expr\PropertyFetch && !$node instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { + return \false; } - // is it the name match? - if (! $this->nodeNameResolver->areNamesEqual($node, $singleProperty)) { - return false; + if (!$this->nodeNameResolver->areNamesEqual($node, $singleProperty)) { + return \false; } - - $currentClassLike = $node->getAttribute(AttributeKey::CLASS_NODE); - return in_array($currentClassLike, $classLikesToSearch, true); + $currentClassLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE); + return \in_array($currentClassLike, $classLikesToSearch, \true); }); - return $propertyFetches; } } diff --git a/src/PhpParser/NodeTransformer.php b/src/PhpParser/NodeTransformer.php index 466b91c9898..6a83e2c5ed0 100644 --- a/src/PhpParser/NodeTransformer.php +++ b/src/PhpParser/NodeTransformer.php @@ -1,10 +1,9 @@ splitMessageAndArgs($sprintfFuncCall); - if (! $sprintfStringAndArgs instanceof SprintfStringAndArgs) { + if (!$sprintfStringAndArgs instanceof \Rector\Core\ValueObject\SprintfStringAndArgs) { return null; } - $arrayItems = $sprintfStringAndArgs->getArrayItems(); $stringValue = $sprintfStringAndArgs->getStringValue(); - $messageParts = $this->splitBySpace($stringValue); - $arrayMessageParts = []; - foreach ($messageParts as $messagePart) { - if (Strings::match($messagePart, self::PERCENT_TEXT_REGEX)) { + if (\RectorPrefix20210509\Nette\Utils\Strings::match($messagePart, self::PERCENT_TEXT_REGEX)) { /** @var Expr $messagePartNode */ - $messagePartNode = array_shift($arrayItems); + $messagePartNode = \array_shift($arrayItems); } else { - $messagePartNode = new String_($messagePart); + $messagePartNode = new \PhpParser\Node\Scalar\String_($messagePart); } - - $arrayMessageParts[] = new ArrayItem($messagePartNode); + $arrayMessageParts[] = new \PhpParser\Node\Expr\ArrayItem($messagePartNode); } - - return new Array_($arrayMessageParts); + return new \PhpParser\Node\Expr\Array_($arrayMessageParts); } - /** * @param Yield_[]|Expression[] $yieldNodes */ - public function transformYieldsToArray(array $yieldNodes): Array_ + public function transformYieldsToArray(array $yieldNodes) : \PhpParser\Node\Expr\Array_ { $arrayItems = []; foreach ($yieldNodes as $yieldNode) { - if ($yieldNode instanceof Expression) { + if ($yieldNode instanceof \PhpParser\Node\Stmt\Expression) { $yieldNode = $yieldNode->expr; } - - if (! $yieldNode instanceof Yield_) { + if (!$yieldNode instanceof \PhpParser\Node\Expr\Yield_) { continue; } - if ($yieldNode->value === null) { continue; } - - $arrayItems[] = new ArrayItem($yieldNode->value, $yieldNode->key); + $arrayItems[] = new \PhpParser\Node\Expr\ArrayItem($yieldNode->value, $yieldNode->key); } - - return new Array_($arrayItems); + return new \PhpParser\Node\Expr\Array_($arrayItems); } - /** * @return Expression[] */ - public function transformArrayToYields(Array_ $array): array + public function transformArrayToYields(\PhpParser\Node\Expr\Array_ $array) : array { $yieldNodes = []; - foreach ($array->items as $arrayItem) { if ($arrayItem === null) { continue; } - - $expressionNode = new Expression(new Yield_($arrayItem->value, $arrayItem->key)); + $expressionNode = new \PhpParser\Node\Stmt\Expression(new \PhpParser\Node\Expr\Yield_($arrayItem->value, $arrayItem->key)); $arrayItemComments = $arrayItem->getComments(); if ($arrayItemComments !== []) { - $expressionNode->setAttribute(AttributeKey::COMMENTS, $arrayItemComments); + $expressionNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, $arrayItemComments); } - $yieldNodes[] = $expressionNode; } - return $yieldNodes; } - - public function transformConcatToStringArray(Concat $concat): Array_ + public function transformConcatToStringArray(\PhpParser\Node\Expr\BinaryOp\Concat $concat) : \PhpParser\Node\Expr\Array_ { $arrayItems = $this->transformConcatToItems($concat); - - return new Array_($arrayItems); + return new \PhpParser\Node\Expr\Array_($arrayItems); } - - private function splitMessageAndArgs(FuncCall $sprintfFuncCall): ?SprintfStringAndArgs + private function splitMessageAndArgs(\PhpParser\Node\Expr\FuncCall $sprintfFuncCall) : ?\Rector\Core\ValueObject\SprintfStringAndArgs { $stringArgument = null; $arrayItems = []; @@ -126,60 +104,48 @@ final class NodeTransformer $arrayItems[] = $arg->value; } } - - if (! $stringArgument instanceof String_) { + if (!$stringArgument instanceof \PhpParser\Node\Scalar\String_) { return null; } - if ($arrayItems === []) { return null; } - - return new SprintfStringAndArgs($stringArgument, $arrayItems); + return new \Rector\Core\ValueObject\SprintfStringAndArgs($stringArgument, $arrayItems); } - /** * @return string[] */ - private function splitBySpace(string $value): array + private function splitBySpace(string $value) : array { - $value = str_getcsv($value, ' '); - - return array_filter($value); + $value = \str_getcsv($value, ' '); + return \array_filter($value); } - /** * @return mixed[] */ - private function transformConcatToItems(Concat $concat): array + private function transformConcatToItems(\PhpParser\Node\Expr\BinaryOp\Concat $concat) : array { $arrayItems = $this->transformConcatItemToArrayItems($concat->left); - - return array_merge($arrayItems, $this->transformConcatItemToArrayItems($concat->right)); + return \array_merge($arrayItems, $this->transformConcatItemToArrayItems($concat->right)); } - /** * @return mixed[]|Expr[]|String_[] */ - private function transformConcatItemToArrayItems(Expr $expr): array + private function transformConcatItemToArrayItems(\PhpParser\Node\Expr $expr) : array { - if ($expr instanceof Concat) { + if ($expr instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { return $this->transformConcatToItems($expr); } - - if (! $expr instanceof String_) { + if (!$expr instanceof \PhpParser\Node\Scalar\String_) { return [$expr]; } - $arrayItems = []; - $parts = $this->splitBySpace($expr->value); foreach ($parts as $part) { - if (trim($part) !== '') { - $arrayItems[] = new String_($part); + if (\trim($part) !== '') { + $arrayItems[] = new \PhpParser\Node\Scalar\String_($part); } } - return $arrayItems; } } diff --git a/src/PhpParser/NodeTraverser/RectorNodeTraverser.php b/src/PhpParser/NodeTraverser/RectorNodeTraverser.php index c48a33225e4..61eaf166dc9 100644 --- a/src/PhpParser/NodeTraverser/RectorNodeTraverser.php +++ b/src/PhpParser/NodeTraverser/RectorNodeTraverser.php @@ -1,7 +1,6 @@ phpRectors = $phpRectors; $this->nodeFinder = $nodeFinder; } - /** * @param Stmt[] $nodes * @return Stmt[] */ - public function traverse(array $nodes): array + public function traverse(array $nodes) : array { $this->prepareNodeVisitors(); - - $hasNamespace = (bool) $this->nodeFinder->findFirstInstanceOf($nodes, Namespace_::class); - if (! $hasNamespace && $nodes !== []) { - $fileWithoutNamespace = new FileWithoutNamespace($nodes); + $hasNamespace = (bool) $this->nodeFinder->findFirstInstanceOf($nodes, \PhpParser\Node\Stmt\Namespace_::class); + if (!$hasNamespace && $nodes !== []) { + $fileWithoutNamespace = new \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace($nodes); return parent::traverse([$fileWithoutNamespace]); } - return parent::traverse($nodes); } - /** * This must happen after $this->configuration is set after ProcessCommand::execute() is run, * otherwise we get default false positives. * * This hack should be removed after https://github.com/rectorphp/rector/issues/5584 is resolved */ - private function prepareNodeVisitors(): void + private function prepareNodeVisitors() : void { if ($this->areNodeVisitorsPrepared) { return; } - foreach ($this->phpRectors as $phpRector) { $this->addVisitor($phpRector); } - - $this->areNodeVisitorsPrepared = true; + $this->areNodeVisitorsPrepared = \true; } } diff --git a/src/PhpParser/Parser/InlineCodeParser.php b/src/PhpParser/Parser/InlineCodeParser.php index fd05adcd544..d783d9164ed 100644 --- a/src/PhpParser/Parser/InlineCodeParser.php +++ b/src/PhpParser/Parser/InlineCodeParser.php @@ -1,10 +1,9 @@ parser = $parser; $this->betterStandardPrinter = $betterStandardPrinter; $this->nodeScopeAndMetadataDecorator = $nodeScopeAndMetadataDecorator; $this->smartFileSystem = $smartFileSystem; } - /** * @return Stmt[] */ - public function parse(string $content): array + public function parse(string $content) : array { // to cover files too - if (is_file($content)) { + if (\is_file($content)) { $content = $this->smartFileSystem->readFile($content); } - // wrap code so php-parser can interpret it - $content = Strings::match($content, self::OPEN_PHP_TAG_REGEX) ? $content : 'parser->parse($content); return $this->nodeScopeAndMetadataDecorator->decorateNodesFromString($nodes); } - - public function stringify(Expr $expr): string + public function stringify(\PhpParser\Node\Expr $expr) : string { - if ($expr instanceof String_) { + if ($expr instanceof \PhpParser\Node\Scalar\String_) { return $expr->value; } - - if ($expr instanceof Encapsed) { + if ($expr instanceof \PhpParser\Node\Scalar\Encapsed) { // remove " - $expr = trim($this->betterStandardPrinter->print($expr), '""'); + $expr = \trim($this->betterStandardPrinter->print($expr), '""'); // use \$ → $ - $expr = Strings::replace($expr, self::PRESLASHED_DOLLAR_REGEX, '$'); + $expr = \RectorPrefix20210509\Nette\Utils\Strings::replace($expr, self::PRESLASHED_DOLLAR_REGEX, '$'); // use \'{$...}\' → $... - return Strings::replace($expr, self::CURLY_BRACKET_WRAPPER_REGEX, '$1'); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($expr, self::CURLY_BRACKET_WRAPPER_REGEX, '$1'); } - - if ($expr instanceof Concat) { + if ($expr instanceof \PhpParser\Node\Expr\BinaryOp\Concat) { return $this->stringify($expr->left) . $this->stringify($expr->right); } - - if ($expr instanceof Variable || $expr instanceof PropertyFetch || $expr instanceof StaticPropertyFetch) { + if ($expr instanceof \PhpParser\Node\Expr\Variable || $expr instanceof \PhpParser\Node\Expr\PropertyFetch || $expr instanceof \PhpParser\Node\Expr\StaticPropertyFetch) { return $this->betterStandardPrinter->print($expr); } - - throw new ShouldNotHappenException(get_class($expr) . ' ' . __METHOD__); + throw new \Rector\Core\Exception\ShouldNotHappenException(\get_class($expr) . ' ' . __METHOD__); } } diff --git a/src/PhpParser/Parser/NikicPhpParserFactory.php b/src/PhpParser/Parser/NikicPhpParserFactory.php index 7fcbfcc2ae3..02a5116466e 100644 --- a/src/PhpParser/Parser/NikicPhpParserFactory.php +++ b/src/PhpParser/Parser/NikicPhpParserFactory.php @@ -1,38 +1,28 @@ lexer = $lexer; $this->parserFactory = $parserFactory; } - - public function create(): Parser + public function create() : \PhpParser\Parser { - return $this->parserFactory->create(ParserFactory::PREFER_PHP7, $this->lexer, [ - 'useIdentifierNodes' => true, - 'useConsistentVariableNodes' => true, - 'useExpressionStatements' => true, - 'useNopStatements' => false, - ]); + return $this->parserFactory->create(\PhpParser\ParserFactory::PREFER_PHP7, $this->lexer, ['useIdentifierNodes' => \true, 'useConsistentVariableNodes' => \true, 'useExpressionStatements' => \true, 'useNopStatements' => \false]); } } diff --git a/src/PhpParser/Parser/Parser.php b/src/PhpParser/Parser/Parser.php index e3ea008ad5e..098b2b04705 100644 --- a/src/PhpParser/Parser/Parser.php +++ b/src/PhpParser/Parser/Parser.php @@ -1,55 +1,45 @@ */ private $nodesByFile = []; - /** * @var NikicParser */ private $nikicParser; - /** * @var SmartFileSystem */ private $smartFileSystem; - - public function __construct(NikicParser $nikicParser, SmartFileSystem $smartFileSystem) + public function __construct(\PhpParser\Parser $nikicParser, \RectorPrefix20210509\Symplify\SmartFileSystem\SmartFileSystem $smartFileSystem) { $this->nikicParser = $nikicParser; $this->smartFileSystem = $smartFileSystem; } - /** * @return Stmt[] */ - public function parseFileInfo(SmartFileInfo $smartFileInfo): array + public function parseFileInfo(\Symplify\SmartFileSystem\SmartFileInfo $smartFileInfo) : array { $fileRealPath = $smartFileInfo->getRealPath(); - if (isset($this->nodesByFile[$fileRealPath])) { return $this->nodesByFile[$fileRealPath]; } - $fileContent = $this->smartFileSystem->readFile($fileRealPath); - $nodes = $this->nikicParser->parse($fileContent); if ($nodes === null) { $nodes = []; } - $this->nodesByFile[$fileRealPath] = $nodes; return $this->nodesByFile[$fileRealPath]; } diff --git a/src/PhpParser/Parser/PhpParserLexerFactory.php b/src/PhpParser/Parser/PhpParserLexerFactory.php index bc92c4610f7..c4998eb413b 100644 --- a/src/PhpParser/Parser/PhpParserLexerFactory.php +++ b/src/PhpParser/Parser/PhpParserLexerFactory.php @@ -1,22 +1,17 @@ ['comments', 'startLine', 'endLine', 'startTokenPos', 'endTokenPos'], - 'phpVersion' => PHP_VERSION, - ]); + return new \PhpParser\Lexer\Emulative(['usedAttributes' => ['comments', 'startLine', 'endLine', 'startTokenPos', 'endTokenPos'], 'phpVersion' => \PHP_VERSION]); } } diff --git a/src/PhpParser/Parser/SimplePhpParser.php b/src/PhpParser/Parser/SimplePhpParser.php index 3cabc8c3183..c9617e1c605 100644 --- a/src/PhpParser/Parser/SimplePhpParser.php +++ b/src/PhpParser/Parser/SimplePhpParser.php @@ -1,48 +1,40 @@ parser = $parser; $this->smartFileSystem = $smartFileSystem; } - /** * @return Node[] */ - public function parseFile(string $filePath): array + public function parseFile(string $filePath) : array { $fileContent = $this->smartFileSystem->readFile($filePath); $nodes = $this->parser->parse($fileContent); - if ($nodes === null) { return []; } - - $nodeTraverser = new NodeTraverser(); - $nodeTraverser->addVisitor(new NodeConnectingVisitor()); - + $nodeTraverser = new \PhpParser\NodeTraverser(); + $nodeTraverser->addVisitor(new \PhpParser\NodeVisitor\NodeConnectingVisitor()); return $nodeTraverser->traverse($nodes); } } diff --git a/src/PhpParser/Printer/BetterStandardPrinter.php b/src/PhpParser/Printer/BetterStandardPrinter.php index 4ca0a72838f..9d85155f6ae 100644 --- a/src/PhpParser/Printer/BetterStandardPrinter.php +++ b/src/PhpParser/Printer/BetterStandardPrinter.php @@ -1,10 +1,9 @@ initializeInsertionMap(); - $this->insertionMap['Stmt_ClassMethod->returnType'] = [')', false, ': ', null]; - $this->insertionMap['Stmt_Function->returnType'] = [')', false, ': ', null]; - $this->insertionMap['Expr_Closure->returnType'] = [')', false, ': ', null]; - + $this->insertionMap['Stmt_ClassMethod->returnType'] = [')', \false, ': ', null]; + $this->insertionMap['Stmt_Function->returnType'] = [')', \false, ': ', null]; + $this->insertionMap['Expr_Closure->returnType'] = [')', \false, ': ', null]; $this->indentCharacterDetector = $indentCharacterDetector; $this->docBlockUpdater = $docBlockUpdater; } - /** * @param Node[] $stmts * @param Node[] $origStmts * @param mixed[] $origTokens */ - public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens): string + public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens) : string { $newStmts = $this->resolveNewStmts($stmts); - // detect per print $this->tabOrSpaceIndentCharacter = $this->indentCharacterDetector->detect($origTokens); - $content = parent::printFormatPreserving($newStmts, $origStmts, $origTokens); - // add new line in case of added stmts - if (count($stmts) !== count($origStmts) && ! (bool) Strings::match($content, self::NEWLINE_END_REGEX)) { + if (\count($stmts) !== \count($origStmts) && !(bool) \RectorPrefix20210509\Nette\Utils\Strings::match($content, self::NEWLINE_END_REGEX)) { $content .= $this->nl; } - return $content; } - /** * @param Node|Node[]|null $node */ - public function print($node): string + public function print($node) : string { if ($node === null) { $node = []; } - - if (! is_array($node)) { + if (!\is_array($node)) { $node = [$node]; } - return $this->prettyPrint($node); } - /** * @param Node[] $stmts */ - public function prettyPrintFile(array $stmts): string + public function prettyPrintFile(array $stmts) : string { // to keep indexes from 0 - $stmts = array_values($stmts); - - return parent::prettyPrintFile($stmts) . PHP_EOL; + $stmts = \array_values($stmts); + return parent::prettyPrintFile($stmts) . \PHP_EOL; } - - public function pFileWithoutNamespace(FileWithoutNamespace $fileWithoutNamespace): string + public function pFileWithoutNamespace(\Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace $fileWithoutNamespace) : string { - $content = $this->pStmts($fileWithoutNamespace->stmts, false); - - return ltrim($content); + $content = $this->pStmts($fileWithoutNamespace->stmts, \false); + return \ltrim($content); } - /** * This allows to use both spaces and tabs vs. original space-only */ - protected function setIndentLevel(int $level): void + protected function setIndentLevel(int $level) : void { - $level = max($level, 0); + $level = \max($level, 0); $this->indentLevel = $level; - $this->nl = "\n" . str_repeat($this->tabOrSpaceIndentCharacter, $level); + $this->nl = "\n" . \str_repeat($this->tabOrSpaceIndentCharacter, $level); } - /** * This allows to use both spaces and tabs vs. original space-only */ - protected function indent(): void + protected function indent() : void { $multiplier = $this->tabOrSpaceIndentCharacter === ' ' ? 4 : 1; - $this->indentLevel += $multiplier; - $this->nl .= str_repeat($this->tabOrSpaceIndentCharacter, $multiplier); + $this->nl .= \str_repeat($this->tabOrSpaceIndentCharacter, $multiplier); } - /** * This allows to use both spaces and tabs vs. original space-only */ - protected function outdent(): void + protected function outdent() : void { if ($this->tabOrSpaceIndentCharacter === ' ') { // - 4 spaces - assert($this->indentLevel >= 4); + \assert($this->indentLevel >= 4); $this->indentLevel -= 4; } else { // - 1 tab - assert($this->indentLevel >= 1); + \assert($this->indentLevel >= 1); --$this->indentLevel; } - - $this->nl = "\n" . str_repeat($this->tabOrSpaceIndentCharacter, $this->indentLevel); + $this->nl = "\n" . \str_repeat($this->tabOrSpaceIndentCharacter, $this->indentLevel); } - /** * @param mixed[] $nodes * @param mixed[] $origNodes * @param int|null $fixup */ - protected function pArray( - array $nodes, - array $origNodes, - int &$pos, - int $indentAdjustment, - string $parentNodeType, - string $subNodeName, - $fixup - ): ?string { + protected function pArray(array $nodes, array $origNodes, int &$pos, int $indentAdjustment, string $parentNodeType, string $subNodeName, $fixup) : ?string + { // reindex positions for printer - $nodes = array_values($nodes); - + $nodes = \array_values($nodes); $this->moveCommentsFromAttributeObjectToCommentsAttribute($nodes); - $content = parent::pArray($nodes, $origNodes, $pos, $indentAdjustment, $parentNodeType, $subNodeName, $fixup); - if ($content === null) { return $content; } - - if (! $this->containsNop($nodes)) { + if (!$this->containsNop($nodes)) { return $content; } - - return Strings::replace($content, self::EXTRA_SPACE_BEFORE_NOP_REGEX, ''); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($content, self::EXTRA_SPACE_BEFORE_NOP_REGEX, ''); } - /** * Do not preslash all slashes (parent behavior), but only those: * @@ -235,233 +189,188 @@ final class BetterStandardPrinter extends Standard * * Prevents `Vendor\Class` => `Vendor\\Class`. */ - protected function pSingleQuotedString(string $string): string + protected function pSingleQuotedString(string $string) : string { - return "'" . Strings::replace($string, self::QUOTED_SLASH_REGEX, '\\\\$0') . "'"; + return "'" . \RectorPrefix20210509\Nette\Utils\Strings::replace($string, self::QUOTED_SLASH_REGEX, '\\\\$0') . "'"; } - /** * Emulates 1_000 in PHP 7.3- version */ - protected function pScalar_DNumber(DNumber $dNumber): string + protected function pScalar_DNumber(\PhpParser\Node\Scalar\DNumber $dNumber) : string { - if (is_string($dNumber->value)) { + if (\is_string($dNumber->value)) { return $dNumber->value; } - return parent::pScalar_DNumber($dNumber); } - /** * Add space: * "use(" * ↓ * "use (" */ - protected function pExpr_Closure(Closure $closure): string + protected function pExpr_Closure(\PhpParser\Node\Expr\Closure $closure) : string { $closureContent = parent::pExpr_Closure($closure); - - return Strings::replace($closureContent, self::USE_REGEX, '$1 ('); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($closureContent, self::USE_REGEX, '$1 ('); } - /** * Do not add "()" on Expressions * @see https://github.com/rectorphp/rector/pull/401#discussion_r181487199 */ - protected function pExpr_Yield(Yield_ $yield): string + protected function pExpr_Yield(\PhpParser\Node\Expr\Yield_ $yield) : string { if ($yield->value === null) { return 'yield'; } - - $parentNode = $yield->getAttribute(AttributeKey::PARENT_NODE); - $shouldAddBrackets = ! $parentNode instanceof Expression; - - return sprintf( - '%syield %s%s%s', - $shouldAddBrackets ? '(' : '', - $yield->key !== null ? $this->p($yield->key) . ' => ' : '', - $this->p($yield->value), - $shouldAddBrackets ? ')' : '' - ); + $parentNode = $yield->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE); + $shouldAddBrackets = !$parentNode instanceof \PhpParser\Node\Stmt\Expression; + return \sprintf('%syield %s%s%s', $shouldAddBrackets ? '(' : '', $yield->key !== null ? $this->p($yield->key) . ' => ' : '', $this->p($yield->value), $shouldAddBrackets ? ')' : ''); } - /** * Print arrays in short [] by default, * to prevent manual explicit array shortening. */ - protected function pExpr_Array(Array_ $array): string + protected function pExpr_Array(\PhpParser\Node\Expr\Array_ $array) : string { - if (! $array->hasAttribute(AttributeKey::KIND)) { - $array->setAttribute(AttributeKey::KIND, Array_::KIND_SHORT); + if (!$array->hasAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND)) { + $array->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND, \PhpParser\Node\Expr\Array_::KIND_SHORT); } - return parent::pExpr_Array($array); } - /** * Fixes escaping of regular patterns */ - protected function pScalar_String(String_ $string): string + protected function pScalar_String(\PhpParser\Node\Scalar\String_ $string) : string { - $isRegularPattern = $string->getAttribute(AttributeKey::IS_REGULAR_PATTERN); - if (! $isRegularPattern) { + $isRegularPattern = $string->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::IS_REGULAR_PATTERN); + if (!$isRegularPattern) { return parent::pScalar_String($string); } - - $kind = $string->getAttribute(AttributeKey::KIND, String_::KIND_SINGLE_QUOTED); - if ($kind === String_::KIND_DOUBLE_QUOTED) { + $kind = $string->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::KIND, \PhpParser\Node\Scalar\String_::KIND_SINGLE_QUOTED); + if ($kind === \PhpParser\Node\Scalar\String_::KIND_DOUBLE_QUOTED) { return $this->wrapValueWith($string, '"'); } - - if ($kind === String_::KIND_SINGLE_QUOTED) { + if ($kind === \PhpParser\Node\Scalar\String_::KIND_SINGLE_QUOTED) { return $this->wrapValueWith($string, "'"); } - return parent::pScalar_String($string); } - /** * @param Node[] $nodes */ - protected function pStmts(array $nodes, bool $indent = true): string + protected function pStmts(array $nodes, bool $indent = \true) : string { $this->moveCommentsFromAttributeObjectToCommentsAttribute($nodes); - return parent::pStmts($nodes, $indent); } - /** * "...$params) : ReturnType" * ↓ * "...$params): ReturnType" */ - protected function pStmt_ClassMethod(ClassMethod $classMethod): string + protected function pStmt_ClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod) : string { $content = parent::pStmt_ClassMethod($classMethod); - // this approach is chosen, to keep changes in parent pStmt_ClassMethod() updated - return Strings::replace($content, self::REPLACE_COLON_WITH_SPACE_REGEX, '$1: '); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($content, self::REPLACE_COLON_WITH_SPACE_REGEX, '$1: '); } - /** * Clean class and trait from empty "use x;" for traits causing invalid code */ - protected function pStmt_Class(Class_ $class): string + protected function pStmt_Class(\PhpParser\Node\Stmt\Class_ $class) : string { - $shouldReindex = false; - + $shouldReindex = \false; foreach ($class->stmts as $key => $stmt) { // remove empty ones - if ($stmt instanceof TraitUse && $stmt->traits === []) { + if ($stmt instanceof \PhpParser\Node\Stmt\TraitUse && $stmt->traits === []) { unset($class->stmts[$key]); - $shouldReindex = true; + $shouldReindex = \true; } } - if ($shouldReindex) { - $class->stmts = array_values($class->stmts); + $class->stmts = \array_values($class->stmts); } - return parent::pStmt_Class($class); } - /** * It remove all spaces extra to parent */ - protected function pStmt_Declare(Declare_ $declare): string + protected function pStmt_Declare(\PhpParser\Node\Stmt\Declare_ $declare) : string { $declareString = parent::pStmt_Declare($declare); - - return Strings::replace($declareString, '#\s+#', ''); + return \RectorPrefix20210509\Nette\Utils\Strings::replace($declareString, '#\\s+#', ''); } - /** * Remove extra \\ from FQN use imports, for easier use in the code */ - protected function pStmt_Use(Use_ $use): string + protected function pStmt_Use(\PhpParser\Node\Stmt\Use_ $use) : string { - if ($use->type !== Use_::TYPE_NORMAL) { + if ($use->type !== \PhpParser\Node\Stmt\Use_::TYPE_NORMAL) { return parent::pStmt_Use($use); } - foreach ($use->uses as $useUse) { - if (! $useUse->name instanceof FullyQualified) { + if (!$useUse->name instanceof \PhpParser\Node\Name\FullyQualified) { continue; } - - $useUse->name = new Name($useUse->name->toString()); + $useUse->name = new \PhpParser\Node\Name($useUse->name->toString()); } - return parent::pStmt_Use($use); } - - protected function pScalar_EncapsedStringPart(EncapsedStringPart $encapsedStringPart): string + protected function pScalar_EncapsedStringPart(\PhpParser\Node\Scalar\EncapsedStringPart $encapsedStringPart) : string { // parent throws exception, but we need to compare string return '`' . $encapsedStringPart->value . '`'; } - - protected function pCommaSeparated(array $nodes): string + protected function pCommaSeparated(array $nodes) : string { $result = parent::pCommaSeparated($nodes); - - $last = end($nodes); - - if ($last instanceof Node) { - $trailingComma = $last->getAttribute(AttributeKey::FUNC_ARGS_TRAILING_COMMA); - if ($trailingComma === false) { - $result = rtrim($result, ','); + $last = \end($nodes); + if ($last instanceof \PhpParser\Node) { + $trailingComma = $last->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::FUNC_ARGS_TRAILING_COMMA); + if ($trailingComma === \false) { + $result = \rtrim($result, ','); } } - return $result; } - /** * @param Node[] $stmts * @return Node[]|mixed[] */ - private function resolveNewStmts(array $stmts): array + private function resolveNewStmts(array $stmts) : array { - if (count($stmts) === 1 && $stmts[0] instanceof FileWithoutNamespace) { + if (\count($stmts) === 1 && $stmts[0] instanceof \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace) { return $stmts[0]->stmts; } - return $stmts; } - /** * @param array $nodes */ - private function moveCommentsFromAttributeObjectToCommentsAttribute(array $nodes): void + private function moveCommentsFromAttributeObjectToCommentsAttribute(array $nodes) : void { // move phpdoc from node to "comment" attribute foreach ($nodes as $node) { - if (! $node instanceof Node) { + if (!$node instanceof \PhpParser\Node) { continue; } - $this->docBlockUpdater->updateNodeWithPhpDocInfo($node); } } - /** * @param Node[] $nodes */ - private function containsNop(array $nodes): bool + private function containsNop(array $nodes) : bool { foreach ($nodes as $node) { - if ($node instanceof Nop) { - return true; + if ($node instanceof \PhpParser\Node\Stmt\Nop) { + return \true; } } - - return false; + return \false; } - - private function wrapValueWith(String_ $string, string $wrap): string + private function wrapValueWith(\PhpParser\Node\Scalar\String_ $string, string $wrap) : string { return $wrap . $string->value . $wrap; } diff --git a/src/PhpParser/Printer/FormatPerservingPrinter.php b/src/PhpParser/Printer/FormatPerservingPrinter.php index 0d2ddb7fbd8..973a952d6c8 100644 --- a/src/PhpParser/Printer/FormatPerservingPrinter.php +++ b/src/PhpParser/Printer/FormatPerservingPrinter.php @@ -1,7 +1,6 @@ betterStandardPrinter = $betterStandardPrinter; $this->smartFileSystem = $smartFileSystem; } - /** * @param Node[] $newStmts * @param Node[] $oldStmts * @param Node[] $oldTokens */ - public function printToFile(SmartFileInfo $fileInfo, array $newStmts, array $oldStmts, array $oldTokens): string + public function printToFile(\Symplify\SmartFileSystem\SmartFileInfo $fileInfo, array $newStmts, array $oldStmts, array $oldTokens) : string { $newContent = $this->betterStandardPrinter->printFormatPreserving($newStmts, $oldStmts, $oldTokens); - $this->smartFileSystem->dumpFile($fileInfo->getRealPath(), $newContent); $this->smartFileSystem->chmod($fileInfo->getRealPath(), $fileInfo->getPerms()); - return $newContent; } - - public function printParsedStmstAndTokensToString(File $file): string + public function printParsedStmstAndTokensToString(\Rector\Core\ValueObject\Application\File $file) : string { $newStmts = $this->resolveNewStmts($file); - - return $this->betterStandardPrinter->printFormatPreserving( - $newStmts, - $file->getOldStmts(), - $file->getOldTokens() - ); + return $this->betterStandardPrinter->printFormatPreserving($newStmts, $file->getOldStmts(), $file->getOldTokens()); } - - public function printParsedStmstAndTokens(File $file): string + public function printParsedStmstAndTokens(\Rector\Core\ValueObject\Application\File $file) : string { - return $this->printToFile( - $file->getSmartFileInfo(), - $file->getNewStmts(), - $file->getOldStmts(), - $file->getOldTokens() - ); + return $this->printToFile($file->getSmartFileInfo(), $file->getNewStmts(), $file->getOldStmts(), $file->getOldTokens()); } - /** * @return Stmt[]|mixed[] */ - private function resolveNewStmts(File $file): array + private function resolveNewStmts(\Rector\Core\ValueObject\Application\File $file) : array { - if (count($file->getNewStmts()) === 1) { + if (\count($file->getNewStmts()) === 1) { $onlyStmt = $file->getNewStmts()[0]; - if ($onlyStmt instanceof FileWithoutNamespace) { + if ($onlyStmt instanceof \Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace) { return $onlyStmt->stmts; } } - return $file->getNewStmts(); } } diff --git a/src/PhpParser/Printer/NodesWithFileDestinationPrinter.php b/src/PhpParser/Printer/NodesWithFileDestinationPrinter.php index 66537ad1a62..4b020f3194c 100644 --- a/src/PhpParser/Printer/NodesWithFileDestinationPrinter.php +++ b/src/PhpParser/Printer/NodesWithFileDestinationPrinter.php @@ -1,61 +1,48 @@ postFileProcessor = $postFileProcessor; $this->lexer = $lexer; $this->betterStandardPrinter = $betterStandardPrinter; } - - public function printNodesWithFileDestination(FileWithNodesInterface $fileWithNodes): string + public function printNodesWithFileDestination(\Rector\FileSystemRector\Contract\FileWithNodesInterface $fileWithNodes) : string { $nodes = $this->postFileProcessor->traverse($fileWithNodes->getNodes()); $prettyPrintContent = $this->betterStandardPrinter->prettyPrintFile($nodes); - return $this->resolveLastEmptyLine($prettyPrintContent); } - /** * Add empty line in the end, if it is in the original tokens */ - private function resolveLastEmptyLine(string $prettyPrintContent): string + private function resolveLastEmptyLine(string $prettyPrintContent) : string { $tokens = $this->lexer->getTokens(); - $lastToken = array_pop($tokens); - - if ($lastToken && isset($lastToken[1]) && Strings::contains($lastToken[1], "\n")) { - $prettyPrintContent = trim($prettyPrintContent) . PHP_EOL; + $lastToken = \array_pop($tokens); + if ($lastToken && isset($lastToken[1]) && \RectorPrefix20210509\Nette\Utils\Strings::contains($lastToken[1], "\n")) { + $prettyPrintContent = \trim($prettyPrintContent) . \PHP_EOL; } - return $prettyPrintContent; } } diff --git a/src/PhpParser/Printer/Whitespace/IndentCharacterDetector.php b/src/PhpParser/Printer/Whitespace/IndentCharacterDetector.php index 1f81c525948..28a2ff0432f 100644 --- a/src/PhpParser/Printer/Whitespace/IndentCharacterDetector.php +++ b/src/PhpParser/Printer/Whitespace/IndentCharacterDetector.php @@ -1,11 +1,9 @@ file = $file; } - - public function getFile(): ?File + public function getFile() : ?\Rector\Core\ValueObject\Application\File { return $this->file; } diff --git a/src/Rector/AbstractRector.php b/src/Rector/AbstractRector.php index b65b9fee7be..e9adb8477a8 100644 --- a/src/Rector/AbstractRector.php +++ b/src/Rector/AbstractRector.php @@ -1,7 +1,6 @@ */ private $nodesToReturn = []; - /** * @required */ - public function autowireAbstractRector( - NodesToRemoveCollector $nodesToRemoveCollector, - NodesToAddCollector $nodesToAddCollector, - RectorChangeCollector $rectorChangeCollector, - NodeRemover $nodeRemover, - PropertyAdder $propertyAdder, - RemovedAndAddedFilesCollector $removedAndAddedFilesCollector, - BetterStandardPrinter $betterStandardPrinter, - NodeNameResolver $nodeNameResolver, - NodeTypeResolver $nodeTypeResolver, - SimpleCallableNodeTraverser $simpleCallableNodeTraverser, - VisibilityManipulator $visibilityManipulator, - NodeFactory $nodeFactory, - PhpDocInfoFactory $phpDocInfoFactory, - SymfonyStyle $symfonyStyle, - PhpVersionProvider $phpVersionProvider, - ExclusionManager $exclusionManager, - StaticTypeMapper $staticTypeMapper, - ParameterProvider $parameterProvider, - CurrentRectorProvider $currentRectorProvider, - CurrentNodeProvider $currentNodeProvider, - Skipper $skipper, - ValueResolver $valueResolver, - NodeRepository $nodeRepository, - BetterNodeFinder $betterNodeFinder, - NodeComparator $nodeComparator, - CurrentFileProvider $currentFileProvider, - ChangedNodeAnalyzer $changedNodeAnalyzer - ): void { + public function autowireAbstractRector(\Rector\PostRector\Collector\NodesToRemoveCollector $nodesToRemoveCollector, \Rector\PostRector\Collector\NodesToAddCollector $nodesToAddCollector, \Rector\ChangesReporting\Collector\RectorChangeCollector $rectorChangeCollector, \Rector\NodeRemoval\NodeRemover $nodeRemover, \Rector\PostRector\DependencyInjection\PropertyAdder $propertyAdder, \Rector\Core\Application\FileSystem\RemovedAndAddedFilesCollector $removedAndAddedFilesCollector, \Rector\Core\PhpParser\Printer\BetterStandardPrinter $betterStandardPrinter, \Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver, \RectorPrefix20210509\Symplify\Astral\NodeTraverser\SimpleCallableNodeTraverser $simpleCallableNodeTraverser, \Rector\Privatization\NodeManipulator\VisibilityManipulator $visibilityManipulator, \Rector\Core\PhpParser\Node\NodeFactory $nodeFactory, \Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory $phpDocInfoFactory, \RectorPrefix20210509\Symfony\Component\Console\Style\SymfonyStyle $symfonyStyle, \Rector\Core\Php\PhpVersionProvider $phpVersionProvider, \Rector\Core\Exclusion\ExclusionManager $exclusionManager, \Rector\StaticTypeMapper\StaticTypeMapper $staticTypeMapper, \RectorPrefix20210509\Symplify\PackageBuilder\Parameter\ParameterProvider $parameterProvider, \Rector\Core\Logging\CurrentRectorProvider $currentRectorProvider, \Rector\Core\Configuration\CurrentNodeProvider $currentNodeProvider, \RectorPrefix20210509\Symplify\Skipper\Skipper\Skipper $skipper, \Rector\Core\PhpParser\Node\Value\ValueResolver $valueResolver, \Rector\NodeCollector\NodeCollector\NodeRepository $nodeRepository, \Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder, \Rector\Core\PhpParser\Comparing\NodeComparator $nodeComparator, \Rector\Core\Provider\CurrentFileProvider $currentFileProvider, \Rector\Core\NodeAnalyzer\ChangedNodeAnalyzer $changedNodeAnalyzer) : void + { $this->nodesToRemoveCollector = $nodesToRemoveCollector; $this->nodesToAddCollector = $nodesToAddCollector; $this->rectorChangeCollector = $rectorChangeCollector; @@ -283,343 +213,280 @@ abstract class AbstractRector extends NodeVisitorAbstract implements PhpRectorIn $this->currentFileProvider = $currentFileProvider; $this->changedNodeAnalyzer = $changedNodeAnalyzer; } - /** * @return Node[]|null */ - public function beforeTraverse(array $nodes): ?array + public function beforeTraverse(array $nodes) : ?array { $this->previousAppliedClass = null; - // workaround for file around refactor() $file = $this->currentFileProvider->getFile(); - if (! $file instanceof File) { - throw new ShouldNotHappenException('File is missing'); + if (!$file instanceof \Rector\Core\ValueObject\Application\File) { + throw new \Rector\Core\Exception\ShouldNotHappenException('File is missing'); } - $this->file = $file; - return parent::beforeTraverse($nodes); } - /** * @return Expression|Node|Node[]|null */ - final public function enterNode(Node $node) + public final function enterNode(\PhpParser\Node $node) { - $nodeClass = get_class($node); - if (! $this->isMatchingNodeType($nodeClass)) { + $nodeClass = \get_class($node); + if (!$this->isMatchingNodeType($nodeClass)) { return null; } - if ($this->shouldSkipCurrentNode($node)) { return null; } - $this->currentRectorProvider->changeCurrentRector($this); // for PHP doc info factory and change notifier $this->currentNodeProvider->setNode($node); - // show current Rector class on --debug $this->printDebugApplying(); - $originalAttributes = $node->getAttributes(); - $originalNode = $node->getAttribute(AttributeKey::ORIGINAL_NODE) ?? clone $node; - + $originalNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::ORIGINAL_NODE) ?? clone $node; $node = $this->refactor($node); - - if (is_array($node)) { - $originalNodeHash = spl_object_hash($originalNode); + if (\is_array($node)) { + $originalNodeHash = \spl_object_hash($originalNode); $this->nodesToReturn[$originalNodeHash] = $node; - if (($node !== []) > 0) { - $firstNodeKey = array_key_first($node); + \reset($node); + $firstNodeKey = \key($node); $this->mirrorComments($node[$firstNodeKey], $originalNode); } - // will be replaced in leaveNode() the original node must be passed return $originalNode; } - // nothing to change → continue - if (! $node instanceof Node) { + if (!$node instanceof \PhpParser\Node) { return null; } - // changed! if ($this->changedNodeAnalyzer->hasNodeChanged($originalNode, $node)) { - $rectorWithLineChange = new RectorWithLineChange($this, $originalNode->getLine()); + $rectorWithLineChange = new \Rector\ChangesReporting\ValueObject\RectorWithLineChange($this, $originalNode->getLine()); $this->file->addRectorClassWithLine($rectorWithLineChange); - // update parents relations $this->connectParentNodes($node); $this->mirrorAttributes($originalAttributes, $node); } - // if stmt ("$value;") was replaced by expr ("$value"), add the ending ";" (Expression) to prevent breaking the code - if ($originalNode instanceof Stmt && $node instanceof Expr) { - return new Expression($node); + if ($originalNode instanceof \PhpParser\Node\Stmt && $node instanceof \PhpParser\Node\Expr) { + return new \PhpParser\Node\Stmt\Expression($node); } - return $node; } - - public function leaveNode(Node $node) + public function leaveNode(\PhpParser\Node $node) { - $objectHash = spl_object_hash($node); - + $objectHash = \spl_object_hash($node); // update parents relations return $this->nodesToReturn[$objectHash] ?? null; } - - protected function isName(Node $node, string $name): bool + protected function isName(\PhpParser\Node $node, string $name) : bool { return $this->nodeNameResolver->isName($node, $name); } - /** * @param string[] $names */ - protected function isNames(Node $node, array $names): bool + protected function isNames(\PhpParser\Node $node, array $names) : bool { return $this->nodeNameResolver->isNames($node, $names); } - - protected function getName(Node $node): ?string + protected function getName(\PhpParser\Node $node) : ?string { return $this->nodeNameResolver->getName($node); } - - protected function isObjectType(Node $node, ObjectType $objectType): bool + protected function isObjectType(\PhpParser\Node $node, \PHPStan\Type\ObjectType $objectType) : bool { return $this->nodeTypeResolver->isObjectType($node, $objectType); } - - protected function getStaticType(Node $node): Type + protected function getStaticType(\PhpParser\Node $node) : \PHPStan\Type\Type { return $this->nodeTypeResolver->getStaticType($node); } - /** * @deprecated * Use getStaticType() instead, as single method to get types */ - protected function getObjectType(Node $node): Type + protected function getObjectType(\PhpParser\Node $node) : \PHPStan\Type\Type { return $this->nodeTypeResolver->resolve($node); } - /** * @param Node|Node[] $nodes */ - protected function traverseNodesWithCallable($nodes, callable $callable): void + protected function traverseNodesWithCallable($nodes, callable $callable) : void { $this->simpleCallableNodeTraverser->traverseNodesWithCallable($nodes, $callable); } - /** * @param Node|Node[]|null $node */ - protected function print($node): string + protected function print($node) : string { return $this->betterStandardPrinter->print($node); } - - protected function isAtLeastPhpVersion(int $version): bool + protected function isAtLeastPhpVersion(int $version) : bool { return $this->phpVersionProvider->isAtLeastPhpVersion($version); } - - protected function mirrorComments(Node $newNode, Node $oldNode): void + protected function mirrorComments(\PhpParser\Node $newNode, \PhpParser\Node $oldNode) : void { - $newNode->setAttribute(AttributeKey::PHP_DOC_INFO, $oldNode->getAttribute(AttributeKey::PHP_DOC_INFO)); - $newNode->setAttribute(AttributeKey::COMMENTS, $oldNode->getAttribute(AttributeKey::COMMENTS)); + $newNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, $oldNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO)); + $newNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, $oldNode->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS)); } - /** * @param Stmt[] $stmts */ - protected function unwrapStmts(array $stmts, Node $node): void + protected function unwrapStmts(array $stmts, \PhpParser\Node $node) : void { // move /* */ doc block from if to first element to keep it $currentPhpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); - foreach ($stmts as $key => $ifStmt) { if ($key === 0) { - $ifStmt->setAttribute(AttributeKey::PHP_DOC_INFO, $currentPhpDocInfo); - + $ifStmt->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PHP_DOC_INFO, $currentPhpDocInfo); // move // comments - $ifStmt->setAttribute(AttributeKey::COMMENTS, $node->getComments()); + $ifStmt->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::COMMENTS, $node->getComments()); } - $this->addNodeAfterNode($ifStmt, $node); } } - - protected function isOpenSourceProjectType(): bool + protected function isOpenSourceProjectType() : bool { - $projectType = $this->parameterProvider->provideStringParameter(Option::PROJECT_TYPE); - return $projectType === ProjectType::OPEN_SOURCE; + $projectType = $this->parameterProvider->provideStringParameter(\Rector\Core\Configuration\Option::PROJECT_TYPE); + return $projectType === \Rector\Core\ValueObject\ProjectType::OPEN_SOURCE; } - /** * @param Arg[] $currentArgs * @param Arg[] $appendingArgs * @return Arg[] */ - protected function appendArgs(array $currentArgs, array $appendingArgs): array + protected function appendArgs(array $currentArgs, array $appendingArgs) : array { foreach ($appendingArgs as $appendingArg) { - $currentArgs[] = new Arg($appendingArg->value); + $currentArgs[] = new \PhpParser\Node\Arg($appendingArg->value); } - return $currentArgs; } - - protected function unwrapExpression(Stmt $stmt): Node + protected function unwrapExpression(\PhpParser\Node\Stmt $stmt) : \PhpParser\Node { - if ($stmt instanceof Expression) { + if ($stmt instanceof \PhpParser\Node\Stmt\Expression) { return $stmt->expr; } - return $stmt; } - /** * @deprecated Use refactor() return of [] or directly $nodesToAddCollector * @param Node[] $newNodes */ - protected function addNodesAfterNode(array $newNodes, Node $positionNode): void + protected function addNodesAfterNode(array $newNodes, \PhpParser\Node $positionNode) : void { $this->nodesToAddCollector->addNodesAfterNode($newNodes, $positionNode); } - /** * @param Node[] $newNodes * @deprecated Use refactor() return of [] or directly $nodesToAddCollector */ - protected function addNodesBeforeNode(array $newNodes, Node $positionNode): void + protected function addNodesBeforeNode(array $newNodes, \PhpParser\Node $positionNode) : void { $this->nodesToAddCollector->addNodesBeforeNode($newNodes, $positionNode); } - /** * @deprecated Use refactor() return of [] or directly $nodesToAddCollector */ - protected function addNodeAfterNode(Node $newNode, Node $positionNode): void + protected function addNodeAfterNode(\PhpParser\Node $newNode, \PhpParser\Node $positionNode) : void { $this->nodesToAddCollector->addNodeAfterNode($newNode, $positionNode); } - /** * @deprecated Use refactor() return of [] or directly $nodesToAddCollector */ - protected function addNodeBeforeNode(Node $newNode, Node $positionNode): void + protected function addNodeBeforeNode(\PhpParser\Node $newNode, \PhpParser\Node $positionNode) : void { $this->nodesToAddCollector->addNodeBeforeNode($newNode, $positionNode); } - - protected function addConstructorDependencyToClass( - Class_ $class, - Type $propertyType, - string $propertyName, - int $propertyFlags = 0 - ): void { + protected function addConstructorDependencyToClass(\PhpParser\Node\Stmt\Class_ $class, \PHPStan\Type\Type $propertyType, string $propertyName, int $propertyFlags = 0) : void + { $this->propertyAdder->addConstructorDependencyToClass($class, $propertyType, $propertyName, $propertyFlags); } - - protected function removeNode(Node $node): void + protected function removeNode(\PhpParser\Node $node) : void { $this->nodeRemover->removeNode($node); } - /** * @param Class_|ClassMethod|Function_ $nodeWithStatements */ - protected function removeNodeFromStatements(Node $nodeWithStatements, Node $nodeToRemove): void + protected function removeNodeFromStatements(\PhpParser\Node $nodeWithStatements, \PhpParser\Node $nodeToRemove) : void { $this->nodeRemover->removeNodeFromStatements($nodeWithStatements, $nodeToRemove); } - /** * @param Node[] $nodes */ - protected function removeNodes(array $nodes): void + protected function removeNodes(array $nodes) : void { $this->nodeRemover->removeNodes($nodes); } - /** * @param class-string $nodeClass */ - private function isMatchingNodeType(string $nodeClass): bool + private function isMatchingNodeType(string $nodeClass) : bool { foreach ($this->getNodeTypes() as $nodeType) { - if (is_a($nodeClass, $nodeType, true)) { - return true; + if (\is_a($nodeClass, $nodeType, \true)) { + return \true; } } - - return false; + return \false; } - - private function shouldSkipCurrentNode(Node $node): bool + private function shouldSkipCurrentNode(\PhpParser\Node $node) : bool { if ($this->nodesToRemoveCollector->isNodeRemoved($node)) { - return true; + return \true; } - if ($this->exclusionManager->isNodeSkippedByRector($node, $this)) { - return true; + return \true; } - $smartFileInfo = $this->file->getSmartFileInfo(); return $this->skipper->shouldSkipElementAndFileInfo($this, $smartFileInfo); } - - private function printDebugApplying(): void + private function printDebugApplying() : void { - if (! $this->symfonyStyle->isDebug()) { + if (!$this->symfonyStyle->isDebug()) { return; } - if ($this->previousAppliedClass === static::class) { return; } - // prevent spamming with the same class over and over // indented on purpose to improve log nesting under [refactoring] $this->symfonyStyle->writeln(' [applying] ' . static::class); $this->previousAppliedClass = static::class; } - /** * @param array $originalAttributes */ - private function mirrorAttributes(array $originalAttributes, Node $newNode): void + private function mirrorAttributes(array $originalAttributes, \PhpParser\Node $newNode) : void { - if ($newNode instanceof Name) { - $newNode->setAttribute(AttributeKey::RESOLVED_NAME, $newNode->toString()); + if ($newNode instanceof \PhpParser\Node\Name) { + $newNode->setAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::RESOLVED_NAME, $newNode->toString()); } - foreach ($originalAttributes as $attributeName => $oldAttributeValue) { - if (! in_array($attributeName, self::ATTRIBUTES_TO_MIRROR, true)) { + if (!\in_array($attributeName, self::ATTRIBUTES_TO_MIRROR, \true)) { continue; } - $newNode->setAttribute($attributeName, $oldAttributeValue); } } - /** * @param Node|Node[] $node */ - private function connectParentNodes($node): void + private function connectParentNodes($node) : void { - $nodes = is_array($node) ? $node : [$node]; - - $nodeTraverser = new NodeTraverser(); - $nodeTraverser->addVisitor(new ParentConnectingVisitor()); + $nodes = \is_array($node) ? $node : [$node]; + $nodeTraverser = new \PhpParser\NodeTraverser(); + $nodeTraverser->addVisitor(new \PhpParser\NodeVisitor\ParentConnectingVisitor()); $nodeTraverser->traverse($nodes); } } diff --git a/src/Reflection/ClassMethodReflectionFactory.php b/src/Reflection/ClassMethodReflectionFactory.php index 4d0683c6cc9..e95e844a968 100644 --- a/src/Reflection/ClassMethodReflectionFactory.php +++ b/src/Reflection/ClassMethodReflectionFactory.php @@ -1,7 +1,6 @@ reflectionProvider = $reflectionProvider; } - - public function createFromPHPStanTypeAndMethodName(Type $type, string $methodName): ?ReflectionMethod + public function createFromPHPStanTypeAndMethodName(\PHPStan\Type\Type $type, string $methodName) : ?\ReflectionMethod { - if ($type instanceof ThisType) { + if ($type instanceof \PHPStan\Type\ThisType) { $type = $type->getStaticObjectType(); } - - if (! $type instanceof TypeWithClassName) { + if (!$type instanceof \PHPStan\Type\TypeWithClassName) { return null; } - return $this->createReflectionMethodIfExists($type, $methodName); } - - public function createReflectionMethodIfExists( - TypeWithClassName $typeWithClassName, - string $method - ): ?ReflectionMethod { - if (! $this->reflectionProvider->hasClass($typeWithClassName->getClassName())) { + public function createReflectionMethodIfExists(\PHPStan\Type\TypeWithClassName $typeWithClassName, string $method) : ?\ReflectionMethod + { + if (!$this->reflectionProvider->hasClass($typeWithClassName->getClassName())) { return null; } - $classReflection = $this->reflectionProvider->getClass($typeWithClassName->getClassName()); - $reflectionClass = $classReflection->getNativeReflection(); - if (! $reflectionClass->hasMethod($method)) { + if (!$reflectionClass->hasMethod($method)) { return null; } - return $reflectionClass->getMethod($method); } } diff --git a/src/Reflection/ClassReflectionToAstResolver.php b/src/Reflection/ClassReflectionToAstResolver.php index 663d2dfc614..e3ca8adaf00 100644 --- a/src/Reflection/ClassReflectionToAstResolver.php +++ b/src/Reflection/ClassReflectionToAstResolver.php @@ -1,7 +1,6 @@ parser = $parser; $this->smartFileSystem = $smartFileSystem; $this->betterNodeFinder = $betterNodeFinder; $this->reflectionProvider = $reflectionProvider; } - - public function getClassFromObjectType(ObjectType $objectType): ?Class_ + public function getClassFromObjectType(\PHPStan\Type\ObjectType $objectType) : ?\PhpParser\Node\Stmt\Class_ { - if (! $this->reflectionProvider->hasClass($objectType->getClassName())) { + if (!$this->reflectionProvider->hasClass($objectType->getClassName())) { return null; } - $classReflection = $this->reflectionProvider->getClass($objectType->getClassName()); return $this->getClass($classReflection, $objectType->getClassName()); } - - private function getClass(ClassReflection $classReflection, string $className): ?Class_ + private function getClass(\PHPStan\Reflection\ClassReflection $classReflection, string $className) : ?\PhpParser\Node\Stmt\Class_ { if ($classReflection->isBuiltin()) { return null; } - /** @var string $fileName */ $fileName = $classReflection->getFileName(); - /** @var Node[] $contentNodes */ $contentNodes = $this->parser->parse($this->smartFileSystem->readFile($fileName)); - /** @var Class_[] $classes */ - $classes = $this->betterNodeFinder->findInstanceOf($contentNodes, Class_::class); + $classes = $this->betterNodeFinder->findInstanceOf($contentNodes, \PhpParser\Node\Stmt\Class_::class); if ($classes === []) { return null; } - $reflectionClassName = $classReflection->getName(); foreach ($classes as $class) { if ($reflectionClassName === $className) { return $class; } } - return null; } } diff --git a/src/Reflection/FunctionLikeReflectionParser.php b/src/Reflection/FunctionLikeReflectionParser.php index 9cb1aa251a7..cdce69a48d8 100644 --- a/src/Reflection/FunctionLikeReflectionParser.php +++ b/src/Reflection/FunctionLikeReflectionParser.php @@ -1,7 +1,6 @@ parser = $parser; $this->smartFileSystem = $smartFileSystem; $this->nodeFinder = $nodeFinder; @@ -79,120 +63,91 @@ final class FunctionLikeReflectionParser $this->nodeNameResolver = $nodeNameResolver; $this->reflectionProvider = $reflectionProvider; } - - public function parseMethodReflection(MethodReflection $methodReflection): ?ClassMethod + public function parseMethodReflection(\PHPStan\Reflection\MethodReflection $methodReflection) : ?\PhpParser\Node\Stmt\ClassMethod { $classReflection = $methodReflection->getDeclaringClass(); - $fileName = $classReflection->getFileName(); - if ($fileName === false) { + if ($fileName === \false) { return null; } - $fileContent = $this->smartFileSystem->readFile($fileName); - if (! is_string($fileContent)) { + if (!\is_string($fileContent)) { return null; } - $nodes = (array) $this->parser->parse($fileContent); - - $smartFileInfo = new SmartFileInfo($fileName); - $file = new File($smartFileInfo, $smartFileInfo->getContents()); - + $smartFileInfo = new \Symplify\SmartFileSystem\SmartFileInfo($fileName); + $file = new \Rector\Core\ValueObject\Application\File($smartFileInfo, $smartFileInfo->getContents()); $nodes = $this->nodeScopeAndMetadataDecorator->decorateNodesFromFile($file, $nodes, $smartFileInfo); - - $class = $this->nodeFinder->findFirstInstanceOf($nodes, Class_::class); - if (! $class instanceof Class_) { + $class = $this->nodeFinder->findFirstInstanceOf($nodes, \PhpParser\Node\Stmt\Class_::class); + if (!$class instanceof \PhpParser\Node\Stmt\Class_) { return null; } - return $class->getMethod($methodReflection->getName()); } - /** * @param MethodCall|StaticCall|Node $node */ - public function parseCaller(Node $node): ?ClassMethod + public function parseCaller(\PhpParser\Node $node) : ?\PhpParser\Node\Stmt\ClassMethod { - if (! $node instanceof MethodCall && ! $node instanceof StaticCall) { + if (!$node instanceof \PhpParser\Node\Expr\MethodCall && !$node instanceof \PhpParser\Node\Expr\StaticCall) { return null; } - /** @var ObjectType|ThisType $objectType */ - $objectType = $node instanceof MethodCall - ? $this->nodeTypeResolver->resolve($node->var) - : $this->nodeTypeResolver->resolve($node->class); - - if ($objectType instanceof ThisType) { + $objectType = $node instanceof \PhpParser\Node\Expr\MethodCall ? $this->nodeTypeResolver->resolve($node->var) : $this->nodeTypeResolver->resolve($node->class); + if ($objectType instanceof \PHPStan\Type\ThisType) { $objectType = $objectType->getStaticObjectType(); } - $className = $objectType->getClassName(); - if (! $this->reflectionProvider->hasClass($className)) { + if (!$this->reflectionProvider->hasClass($className)) { return null; } - $classReflection = $this->reflectionProvider->getClass($className); $methodName = (string) $this->nodeNameResolver->getName($node->name); - if (! $classReflection->hasMethod($methodName)) { + if (!$classReflection->hasMethod($methodName)) { return null; } - if ($classReflection->isBuiltIn()) { return null; } - $fileName = $classReflection->getFileName(); - if (! $fileName) { + if (!$fileName) { return null; } - $fileContent = $this->smartFileSystem->readfile($fileName); $nodes = $this->parser->parse($fileContent); return $this->getClassMethodFromNodes((array) $nodes, $classReflection, $className, $methodName); } - /** * @param Stmt[] $nodes */ - private function getClassMethodFromNodes( - array $nodes, - ClassReflection $classReflection, - string $className, - string $methodName - ): ?ClassMethod { + private function getClassMethodFromNodes(array $nodes, \PHPStan\Reflection\ClassReflection $classReflection, string $className, string $methodName) : ?\PhpParser\Node\Stmt\ClassMethod + { $reflectionClass = $classReflection->getNativeReflection(); $shortName = $reflectionClass->getShortName(); - foreach ($nodes as $node) { - if ($node instanceof Namespace_) { + if ($node instanceof \PhpParser\Node\Stmt\Namespace_) { /** @var Stmt[] $nodeStmts */ $nodeStmts = $node->stmts; $classMethod = $this->getClassMethodFromNodes($nodeStmts, $classReflection, $className, $methodName); - - if ($classMethod instanceof ClassMethod) { + if ($classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return $classMethod; } } - $classMethod = $this->getClassMethod($node, $shortName, $methodName); - if ($classMethod instanceof ClassMethod) { + if ($classMethod instanceof \PhpParser\Node\Stmt\ClassMethod) { return $classMethod; } } - return null; } - - private function getClassMethod(Stmt $stmt, string $shortClassName, string $methodName): ?ClassMethod + private function getClassMethod(\PhpParser\Node\Stmt $stmt, string $shortClassName, string $methodName) : ?\PhpParser\Node\Stmt\ClassMethod { - if ($stmt instanceof Class_) { + if ($stmt instanceof \PhpParser\Node\Stmt\Class_) { $name = (string) $this->nodeNameResolver->getName($stmt); if ($name === $shortClassName) { return $stmt->getMethod($methodName); } } - return null; } } diff --git a/src/Reflection/MethodReflectionToAstResolver.php b/src/Reflection/MethodReflectionToAstResolver.php index 2a946eeaf8c..6c8f77435ca 100644 --- a/src/Reflection/MethodReflectionToAstResolver.php +++ b/src/Reflection/MethodReflectionToAstResolver.php @@ -1,10 +1,9 @@ > */ private $analyzedMethodsInFileName = []; - - public function __construct( - FileInfoParser $fileInfoParser, - BetterNodeFinder $betterNodeFinder, - NodeNameResolver $nodeNameResolver - ) { + public function __construct(\Rector\FileSystemRector\Parser\FileInfoParser $fileInfoParser, \Rector\Core\PhpParser\Node\BetterNodeFinder $betterNodeFinder, \Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver) + { $this->fileInfoParser = $fileInfoParser; $this->betterNodeFinder = $betterNodeFinder; $this->nodeNameResolver = $nodeNameResolver; } - - public function resolveProjectClassMethod(PhpMethodReflection $phpMethodReflection): ?ClassMethod + public function resolveProjectClassMethod(\PHPStan\Reflection\Php\PhpMethodReflection $phpMethodReflection) : ?\PhpParser\Node\Stmt\ClassMethod { $classReflection = $phpMethodReflection->getDeclaringClass(); - $fileName = $classReflection->getFileName(); - if ($fileName === false) { + if ($fileName === \false) { return null; } - // skip vendor - if (Strings::contains($fileName, '#\/vendor\/#')) { + if (\RectorPrefix20210509\Nette\Utils\Strings::contains($fileName, '#\\/vendor\\/#')) { return null; } - $methodName = $phpMethodReflection->getName(); - // skip already anayzed method to prevent cycling if (isset($this->analyzedMethodsInFileName[$fileName][$methodName])) { return $this->analyzedMethodsInFileName[$fileName][$methodName]; } - - $smartFileInfo = new SmartFileInfo($fileName); - + $smartFileInfo = new \Symplify\SmartFileSystem\SmartFileInfo($fileName); $nodes = $this->fileInfoParser->parseFileInfoToNodesAndDecorate($smartFileInfo); - /** @var ClassMethod|null $classMethod */ - $classMethod = $this->betterNodeFinder->findFirst( - $nodes, - function (Node $node) use ($methodName): bool { - if (! $node instanceof ClassMethod) { - return false; - } - - return $this->nodeNameResolver->isName($node, $methodName); + $classMethod = $this->betterNodeFinder->findFirst($nodes, function (\PhpParser\Node $node) use($methodName) : bool { + if (!$node instanceof \PhpParser\Node\Stmt\ClassMethod) { + return \false; } - ); - + return $this->nodeNameResolver->isName($node, $methodName); + }); $this->analyzedMethodsInFileName[$fileName][$methodName] = $classMethod; - return $classMethod; } } diff --git a/src/Reporting/MissingRectorRulesReporter.php b/src/Reporting/MissingRectorRulesReporter.php index 6ba1311fbe9..597119617b0 100644 --- a/src/Reporting/MissingRectorRulesReporter.php +++ b/src/Reporting/MissingRectorRulesReporter.php @@ -1,63 +1,51 @@ symfonyStyle = $symfonyStyle; $this->rectors = $rectors; } - - public function reportIfMissing(): ?int + public function reportIfMissing() : ?int { - $activeRectors = array_filter($this->rectors, function (RectorInterface $rector): bool { - return ! $rector instanceof PostRectorInterface; + $activeRectors = \array_filter($this->rectors, function (\Rector\Core\Contract\Rector\RectorInterface $rector) : bool { + return !$rector instanceof \Rector\PostRector\Contract\Rector\PostRectorInterface; }); - if ($activeRectors !== []) { return null; } - $this->report(); - - return ShellCode::ERROR; + return \RectorPrefix20210509\Symplify\PackageBuilder\Console\ShellCode::ERROR; } - - public function report(): void + public function report() : void { $this->symfonyStyle->warning('We could not find any Rector rules to run. You have 2 options to add them:'); - $this->symfonyStyle->title('1. Add single rule to "rector.php"'); $this->symfonyStyle->writeln(' $services = $containerConfigurator->services();'); $this->symfonyStyle->writeln(' $services->set(...);'); $this->symfonyStyle->newLine(1); - $this->symfonyStyle->title('2. Add set of rules to "rector.php"'); $this->symfonyStyle->writeln(' $containerConfigurator->import(SetList::...);'); $this->symfonyStyle->newLine(1); - $this->symfonyStyle->title('Missing "rector.php" in your project? Let Rector create it for you'); $this->symfonyStyle->writeln(' vendor/bin/rector init'); $this->symfonyStyle->newLine(); diff --git a/src/StaticReflection/DynamicSourceLocatorDecorator.php b/src/StaticReflection/DynamicSourceLocatorDecorator.php index 1464c8564c8..7649416eae2 100644 --- a/src/StaticReflection/DynamicSourceLocatorDecorator.php +++ b/src/StaticReflection/DynamicSourceLocatorDecorator.php @@ -1,13 +1,11 @@ fileSystemFilter = $fileSystemFilter; $this->dynamicSourceLocatorProvider = $dynamicSourceLocatorProvider; $this->phpFilesFinder = $phpFilesFinder; } - /** * @param string[] $paths */ - public function addPaths(array $paths): void + public function addPaths(array $paths) : void { $files = $this->fileSystemFilter->filterFiles($paths); $this->dynamicSourceLocatorProvider->addFiles($files); - $directories = $this->fileSystemFilter->filterDirectories($paths); foreach ($directories as $directory) { $filesInfosInDirectory = $this->phpFilesFinder->findInPaths([$directory]); - $filesInDirectory = []; foreach ($filesInfosInDirectory as $fileInfoInDirectory) { $filesInDirectory[] = $fileInfoInDirectory->getRealPath(); } - $this->dynamicSourceLocatorProvider->addFilesByDirectory($directory, $filesInDirectory); } } diff --git a/src/Stubs/PHPStanStubLoader.php b/src/Stubs/PHPStanStubLoader.php index bc0b0131095..748c66499e1 100644 --- a/src/Stubs/PHPStanStubLoader.php +++ b/src/Stubs/PHPStanStubLoader.php @@ -1,7 +1,6 @@ areStubsLoaded) { return; } - foreach (self::VENDOR_PATHS as $vendorPath) { - $vendorPath = realpath($vendorPath); - if (! $vendorPath) { + $vendorPath = \realpath($vendorPath); + if (!$vendorPath) { continue; } - foreach (self::STUBS as $stub) { - $path = sprintf('phar://%s/phpstan/phpstan/phpstan.phar/stubs/runtime/%s', $vendorPath, $stub); - $isExists = file_exists($path); - - if (! $isExists) { + $path = \sprintf('phar://%s/phpstan/phpstan/phpstan.phar/stubs/runtime/%s', $vendorPath, $stub); + $isExists = \file_exists($path); + if (!$isExists) { continue 2; } - require_once $path; } - - $this->areStubsLoaded = true; - + $this->areStubsLoaded = \true; // already loaded? stop loop break; } diff --git a/src/Template/DefaultResolver.php b/src/Template/DefaultResolver.php index 81e4b6ac80c..ad8403f2652 100644 --- a/src/Template/DefaultResolver.php +++ b/src/Template/DefaultResolver.php @@ -1,29 +1,24 @@ 1) { + $explodeDash = \explode('-', $version); + if (\count($explodeDash) > 1) { $version = $explodeDash[0]; } - - $explodeVersion = explode('.', $version); - $countExplodedVersion = count($explodeVersion); - + $explodeVersion = \explode('.', $version); + $countExplodedVersion = \count($explodeVersion); if ($countExplodedVersion === 2) { return (int) $explodeVersion[0] * 10000 + (int) $explodeVersion[1] * 100; } - if ($countExplodedVersion >= 3) { return (int) $explodeVersion[0] * 10000 + (int) $explodeVersion[1] * 100 + (int) $explodeVersion[2]; } - return (int) $version; } } diff --git a/src/Util/StaticRectorStrings.php b/src/Util/StaticRectorStrings.php index 8ca3a1d27c0..09ca17643dd 100644 --- a/src/Util/StaticRectorStrings.php +++ b/src/Util/StaticRectorStrings.php @@ -1,11 +1,9 @@ smartFileInfo = $smartFileInfo; $this->fileContent = $fileContent; $this->originalFileContent = $fileContent; } - - public function getSmartFileInfo(): SmartFileInfo + public function getSmartFileInfo() : \Symplify\SmartFileSystem\SmartFileInfo { return $this->smartFileInfo; } - - public function getFileContent(): string + public function getFileContent() : string { return $this->fileContent; } - - public function changeFileContent(string $newFileContent): void + public function changeFileContent(string $newFileContent) : void { if ($this->fileContent === $newFileContent) { return; } - $this->fileContent = $newFileContent; - $this->hasChanged = true; + $this->hasChanged = \true; } - - public function getOriginalFileContent(): string + public function getOriginalFileContent() : string { return $this->originalFileContent; } - - public function hasChanged(): bool + public function hasChanged() : bool { return $this->hasChanged; } - - public function setFileDiff(FileDiff $fileDiff): void + public function setFileDiff(\Rector\Core\ValueObject\Reporting\FileDiff $fileDiff) : void { $this->fileDiff = $fileDiff; } - - public function getFileDiff(): ?FileDiff + public function getFileDiff() : ?\Rector\Core\ValueObject\Reporting\FileDiff { return $this->fileDiff; } - /** * @param Stmt[] $newStmts * @param Stmt[] $oldStmts * @param mixed[] $oldTokens */ - public function hydrateStmtsAndTokens(array $newStmts, array $oldStmts, array $oldTokens): void + public function hydrateStmtsAndTokens(array $newStmts, array $oldStmts, array $oldTokens) : void { if ($this->oldStmts !== []) { - throw new ShouldNotHappenException('Double stmts override'); + throw new \Rector\Core\Exception\ShouldNotHappenException('Double stmts override'); } - $this->oldStmts = $oldStmts; $this->newStmts = $newStmts; $this->oldTokens = $oldTokens; } - /** * @return Stmt[] */ - public function getOldStmts(): array + public function getOldStmts() : array { return $this->oldStmts; } - /** * @return Stmt[] */ - public function getNewStmts(): array + public function getNewStmts() : array { return $this->newStmts; } - /** * @return mixed[] */ - public function getOldTokens(): array + public function getOldTokens() : array { return $this->oldTokens; } - /** * @param Stmt[] $newStmts */ - public function changeNewStmts(array $newStmts): void + public function changeNewStmts(array $newStmts) : void { $this->newStmts = $newStmts; } - - public function addRectorClassWithLine(RectorWithLineChange $rectorWithLineChange): void + public function addRectorClassWithLine(\Rector\ChangesReporting\ValueObject\RectorWithLineChange $rectorWithLineChange) : void { $this->rectorWithLineChanges[] = $rectorWithLineChange; } - /** * @return RectorWithLineChange[] */ - public function getRectorWithLineChanges(): array + public function getRectorWithLineChanges() : array { return $this->rectorWithLineChanges; } - - public function addRectorError(RectorError $rectorError): void + public function addRectorError(\Rector\Core\ValueObject\Application\RectorError $rectorError) : void { $this->rectorErrors[] = $rectorError; } - - public function hasErrors(): bool + public function hasErrors() : bool { return $this->rectorErrors !== []; } - /** * @return RectorError[] */ - public function getErrors(): array + public function getErrors() : array { return $this->rectorErrors; } diff --git a/src/ValueObject/Application/RectorError.php b/src/ValueObject/Application/RectorError.php index cee4e9c01a4..9becb40042a 100644 --- a/src/ValueObject/Application/RectorError.php +++ b/src/ValueObject/Application/RectorError.php @@ -1,61 +1,50 @@ message = $message; $this->line = $line; $this->rectorClass = $rectorClass; } - - public function getRelativeFilePath(): string + public function getRelativeFilePath() : string { return $this->fileInfo->getRelativeFilePathFromCwd(); } - - public function getFileInfo(): SmartFileInfo + public function getFileInfo() : \Symplify\SmartFileSystem\SmartFileInfo { return $this->fileInfo; } - - public function getMessage(): string + public function getMessage() : string { return $this->message; } - - public function getLine(): ?int + public function getLine() : ?int { return $this->line; } - - public function getRectorClass(): ?string + public function getRectorClass() : ?string { return $this->rectorClass; } diff --git a/src/ValueObject/Bootstrap/BootstrapConfigs.php b/src/ValueObject/Bootstrap/BootstrapConfigs.php index 36e9dfaa45f..67c07706b94 100644 --- a/src/ValueObject/Bootstrap/BootstrapConfigs.php +++ b/src/ValueObject/Bootstrap/BootstrapConfigs.php @@ -1,46 +1,40 @@ mainConfigFileInfo = $mainConfigFileInfo; $this->setConfigFileInfos = $setConfigFileInfos; } - - public function getMainConfigFileInfo(): ?SmartFileInfo + public function getMainConfigFileInfo() : ?\Symplify\SmartFileSystem\SmartFileInfo { return $this->mainConfigFileInfo; } - /** * @return SmartFileInfo[] */ - public function getConfigFileInfos(): array + public function getConfigFileInfos() : array { $configFileInfos = []; if ($this->mainConfigFileInfo !== null) { $configFileInfos[] = $this->mainConfigFileInfo; } - return array_merge($configFileInfos, $this->setConfigFileInfos); + return \array_merge($configFileInfos, $this->setConfigFileInfos); } } diff --git a/src/ValueObject/FrameworkName.php b/src/ValueObject/FrameworkName.php index ea77c49f198..683f8107a8d 100644 --- a/src/ValueObject/FrameworkName.php +++ b/src/ValueObject/FrameworkName.php @@ -1,7 +1,6 @@ fileDiffs = $fileDiffs; $this->errors = $errors; $this->addedFilesCount = $addedFilesCount; $this->removedFilesCount = $removedFilesCount; $this->removedNodeCount = $removedNodeCount; } - /** * @return FileDiff[] */ - public function getFileDiffs(): array + public function getFileDiffs() : array { return $this->fileDiffs; } - /** * @return RectorError[] */ - public function getErrors(): array + public function getErrors() : array { return $this->errors; } - - public function getAddedFilesCount(): int + public function getAddedFilesCount() : int { return $this->addedFilesCount; } - - public function getRemovedFilesCount(): int + public function getRemovedFilesCount() : int { return $this->removedFilesCount; } - - public function getRemovedAndAddedFilesCount(): int + public function getRemovedAndAddedFilesCount() : int { return $this->removedFilesCount + $this->addedFilesCount; } - - public function getRemovedNodeCount(): int + public function getRemovedNodeCount() : int { return $this->removedNodeCount; } - /** * @return SmartFileInfo[] */ - public function getChangedFileInfos(): array + public function getChangedFileInfos() : array { $fileInfos = []; foreach ($this->fileDiffs as $fileDiff) { $fileInfos[] = $fileDiff->getFileInfo(); } - - return array_unique($fileInfos); + return \array_unique($fileInfos); } } diff --git a/src/ValueObject/ProjectType.php b/src/ValueObject/ProjectType.php index 4aaf383680c..b41fe5ba63f 100644 --- a/src/ValueObject/ProjectType.php +++ b/src/ValueObject/ProjectType.php @@ -1,7 +1,6 @@ smartFileInfo = $smartFileInfo; $this->diff = $diff; $this->rectorWithLineChanges = $rectorWithLineChanges; $this->diffConsoleFormatted = $diffConsoleFormatted; } - - public function getDiff(): string + public function getDiff() : string { return $this->diff; } - - public function getDiffConsoleFormatted(): string + public function getDiffConsoleFormatted() : string { return $this->diffConsoleFormatted; } - - public function getRelativeFilePath(): string + public function getRelativeFilePath() : string { return $this->smartFileInfo->getRelativeFilePath(); } - - public function getFileInfo(): SmartFileInfo + public function getFileInfo() : \Symplify\SmartFileSystem\SmartFileInfo { return $this->smartFileInfo; } - /** * @return RectorWithLineChange[] */ - public function getRectorChanges(): array + public function getRectorChanges() : array { return $this->rectorWithLineChanges; } - /** * @return array> */ - public function getRectorClasses(): array + public function getRectorClasses() : array { $rectorClasses = []; foreach ($this->rectorWithLineChanges as $rectorWithLineChange) { $rectorClasses[] = $rectorWithLineChange->getRectorClass(); } - return $this->sortClasses($rectorClasses); } - /** * @template TType as object * @param array> $rectorClasses * @return array> */ - private function sortClasses(array $rectorClasses): array + private function sortClasses(array $rectorClasses) : array { - $rectorClasses = array_unique($rectorClasses); - sort($rectorClasses); - + $rectorClasses = \array_unique($rectorClasses); + \sort($rectorClasses); return $rectorClasses; } } diff --git a/src/ValueObject/SprintfStringAndArgs.php b/src/ValueObject/SprintfStringAndArgs.php index 1966a6ab3fc..dec3e7aad74 100644 --- a/src/ValueObject/SprintfStringAndArgs.php +++ b/src/ValueObject/SprintfStringAndArgs.php @@ -1,42 +1,36 @@ string = $string; $this->arrayItems = $arrayItems; } - /** * @return Expr[] */ - public function getArrayItems(): array + public function getArrayItems() : array { return $this->arrayItems; } - - public function getStringValue(): string + public function getStringValue() : string { return $this->string->value; } diff --git a/src/ValueObject/StaticNonPhpFileSuffixes.php b/src/ValueObject/StaticNonPhpFileSuffixes.php index 743fa5e2c0b..b8c2a75e5de 100644 --- a/src/ValueObject/StaticNonPhpFileSuffixes.php +++ b/src/ValueObject/StaticNonPhpFileSuffixes.php @@ -1,7 +1,6 @@ fileProcessors = $fileProcessors; $this->filesFinder = $filesFinder; } - /** * @param string[] $paths * @return File[] */ - public function createFromPaths(array $paths): array + public function createFromPaths(array $paths) : array { $supportedFileExtensions = $this->resolveSupportedFileExtensions(); $fileInfos = $this->filesFinder->findInDirectoriesAndFiles($paths, $supportedFileExtensions); - $files = []; foreach ($fileInfos as $fileInfo) { - $files[] = new File($fileInfo, $fileInfo->getContents()); + $files[] = new \Rector\Core\ValueObject\Application\File($fileInfo, $fileInfo->getContents()); } - return $files; } - /** * @return string[] */ - private function resolveSupportedFileExtensions(): array + private function resolveSupportedFileExtensions() : array { $supportedFileExtensions = []; - foreach ($this->fileProcessors as $fileProcessor) { - $supportedFileExtensions = array_merge( - $supportedFileExtensions, - $fileProcessor->getSupportedFileExtensions() - ); + $supportedFileExtensions = \array_merge($supportedFileExtensions, $fileProcessor->getSupportedFileExtensions()); } - - return array_unique($supportedFileExtensions); + return \array_unique($supportedFileExtensions); } } diff --git a/src/ValueObjectFactory/ProcessResultFactory.php b/src/ValueObjectFactory/ProcessResultFactory.php index 87432bdc47c..3702217c8f4 100644 --- a/src/ValueObjectFactory/ProcessResultFactory.php +++ b/src/ValueObjectFactory/ProcessResultFactory.php @@ -1,57 +1,41 @@ removedAndAddedFilesCollector = $removedAndAddedFilesCollector; $this->nodesToRemoveCollector = $nodesToRemoveCollector; } - /** * @param File[] $files */ - public function create(array $files): ProcessResult + public function create(array $files) : \Rector\Core\ValueObject\ProcessResult { $fileDiffs = []; $errors = []; - foreach ($files as $file) { if ($file->getFileDiff() === null) { continue; } - - $errors = array_merge($errors, $file->getErrors()); + $errors = \array_merge($errors, $file->getErrors()); $fileDiffs[] = $file->getFileDiff(); } - - return new ProcessResult( - $fileDiffs, - $errors, - $this->removedAndAddedFilesCollector->getAddedFileCount(), - $this->removedAndAddedFilesCollector->getRemovedFilesCount(), - $this->nodesToRemoveCollector->getCount(), - ); + return new \Rector\Core\ValueObject\ProcessResult($fileDiffs, $errors, $this->removedAndAddedFilesCollector->getAddedFileCount(), $this->removedAndAddedFilesCollector->getRemovedFilesCount(), $this->nodesToRemoveCollector->getCount()); } } diff --git a/src/constants.php b/src/constants.php index 4396afb5be2..cfca8a05693 100644 --- a/src/constants.php +++ b/src/constants.php @@ -1,13 +1,13 @@ $depth, - ]); -} - -/** - * @param Node|Node[] $node - */ -function print_node($node): void -{ - $standard = new Standard(); - - if (is_array($node)) { - foreach ($node as $singleNode) { - $printedContent = $standard->prettyPrint([$singleNode]); - Dumper::dump($printedContent); - } - } else { - $printedContent = $standard->prettyPrint([$node]); - Dumper::dump($printedContent); +use RectorPrefix20210509\Tracy\Dumper; +if (!\function_exists('dn')) { + function dn(\PhpParser\Node $node, int $depth = 2) : void + { + \RectorPrefix20210509\dump_node($node, $depth); + } +} +if (!\function_exists('dump_node')) { + /** + * @param Node|Node[] $node + */ + function dump_node($node, int $depth = 2) : void + { + $nodes = \is_array($node) ? $node : [$node]; + foreach ($nodes as $node) { + \RectorPrefix20210509\Tracy\Dumper::dump($node, [\RectorPrefix20210509\Tracy\Dumper::DEPTH => $depth]); + } + } +} +if (!\function_exists('print_node')) { + /** + * @param Node|Node[] $node + */ + function print_node($node) : void + { + $standard = new \PhpParser\PrettyPrinter\Standard(); + $nodes = \is_array($node) ? $node : [$node]; + foreach ($nodes as $node) { + $printedContent = $standard->prettyPrint([$node]); + \RectorPrefix20210509\Tracy\Dumper::dump($printedContent); + } } } diff --git a/stubs/Symfony/Component/Routing/Annotation/Route.php b/stubs/Symfony/Component/Routing/Annotation/Route.php new file mode 100644 index 00000000000..fd408704b50 --- /dev/null +++ b/stubs/Symfony/Component/Routing/Annotation/Route.php @@ -0,0 +1,177 @@ + $value) { + $method = 'set'.str_replace('_', '', $key); + if (!method_exists($this, $method)) { + throw new \BadMethodCallException(sprintf('Unknown property "%s" on annotation "%s".', $key, \get_class($this))); + } + $this->$method($value); + } + } + + public function setPath($path) + { + $this->path = $path; + } + + public function getPath() + { + return $this->path; + } + + public function setLocalizedPaths(array $localizedPaths) + { + $this->localizedPaths = $localizedPaths; + } + + public function getLocalizedPaths(): array + { + return $this->localizedPaths; + } + + public function setHost($pattern) + { + $this->host = $pattern; + } + + public function getHost() + { + return $this->host; + } + + public function setName($name) + { + $this->name = $name; + } + + public function getName() + { + return $this->name; + } + + public function setRequirements($requirements) + { + $this->requirements = $requirements; + } + + public function getRequirements() + { + return $this->requirements; + } + + public function setOptions($options) + { + $this->options = $options; + } + + public function getOptions() + { + return $this->options; + } + + public function setDefaults($defaults) + { + $this->defaults = $defaults; + } + + public function getDefaults() + { + return $this->defaults; + } + + public function setSchemes($schemes) + { + $this->schemes = \is_array($schemes) ? $schemes : [$schemes]; + } + + public function getSchemes() + { + return $this->schemes; + } + + public function setMethods($methods) + { + $this->methods = \is_array($methods) ? $methods : [$methods]; + } + + public function getMethods() + { + return $this->methods; + } + + public function setCondition($condition) + { + $this->condition = $condition; + } + + public function getCondition() + { + return $this->condition; + } +} diff --git a/tests/fixture-finalize/SkipSomeEntity.php b/tests/fixture-finalize/SkipSomeEntity.php new file mode 100644 index 00000000000..ee06f874e0e --- /dev/null +++ b/tests/fixture-finalize/SkipSomeEntity.php @@ -0,0 +1,14 @@ +services(); - $services->set(ValueObjectWrapArgRector::class) - ->call('configure', [[ - ValueObjectWrapArgRector::VALUE_OBJECT_WRAP_ARGS => ValueObjectInliner::inline([ - new ValueObjectWrapArg( - 'Rector\NodeTypeResolver\NodeTypeResolver', - 'isMethodStaticCallOrClassMethodObjectType', - 1, - 'PHPStan\Type\ObjectType' - ), - new ValueObjectWrapArg( - 'Rector\NodeTypeResolver\NodeTypeResolver', - 'isObjectType', - 1, - 'PHPStan\Type\ObjectType' - ), - new ValueObjectWrapArg( - 'Rector\NodeTypeResolver\NodeTypeResolver', - 'isObjectTypes', - 1, - 'PHPStan\Type\ObjectType' - ), - new ValueObjectWrapArg( - 'Rector\Core\Rector\AbstractRector', - 'isObjectType', - 1, - 'PHPStan\Type\ObjectType' - ), - ]) - ]]); - - $services->set(RenameClassRector::class) - ->call('configure', [[ - 'Rector\Core\Console\Command\AbstractCommand' => 'Symfony\Component\Console\Command\Command', - 'Rector\Testing\PHPUnit\AbstractCommunityRectorTestCase' => 'Rector\Testing\PHPUnit\AbstractRectorTestCase', - 'Rector\AttributeAwarePhpDoc\Ast\PhpDoc\AttributeAwareParamTagValueNode' => 'Rector\BetterPhpDocParser\ValueObject\PhpDoc\VariadicAwareParamTagValueNode', - // @see https://github.com/rectorphp/rector/pull/5841 - 'Rector\AttributeAwarePhpDoc\Ast\PhpDoc\AttributeAwarePhpDocTagNode' => 'PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode', - 'Rector\AttributeAwarePhpDoc\Ast\Type\AttributeAwareGenericTypeNode' => 'PHPStan\PhpDocParser\Ast\Type\GenericTypeNode', - // etc. - ]]); - - $services->set(RenameClassConstFetchRector::class) - ->call('configure', [[ - RenameClassConstFetchRector::CLASS_CONSTANT_RENAME => ValueObjectInliner::inline([ - new RenameClassAndConstFetch( - 'Rector\PHPStanStaticTypeMapper\PHPStanStaticTypeMapper', - 'KIND_PARAM', - 'Rector\PHPStanStaticTypeMapper\ValueObject\TypeKind', - 'KIND_PARAM', - ) - ]) - ]]); + $services->set(\Rector\Arguments\Rector\MethodCall\ValueObjectWrapArgRector::class)->call('configure', [[\Rector\Arguments\Rector\MethodCall\ValueObjectWrapArgRector::VALUE_OBJECT_WRAP_ARGS => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Arguments\ValueObject\ValueObjectWrapArg('Rector\\NodeTypeResolver\\NodeTypeResolver', 'isMethodStaticCallOrClassMethodObjectType', 1, 'PHPStan\\Type\\ObjectType'), new \Rector\Arguments\ValueObject\ValueObjectWrapArg('Rector\\NodeTypeResolver\\NodeTypeResolver', 'isObjectType', 1, 'PHPStan\\Type\\ObjectType'), new \Rector\Arguments\ValueObject\ValueObjectWrapArg('Rector\\NodeTypeResolver\\NodeTypeResolver', 'isObjectTypes', 1, 'PHPStan\\Type\\ObjectType'), new \Rector\Arguments\ValueObject\ValueObjectWrapArg('Rector\\Core\\Rector\\AbstractRector', 'isObjectType', 1, 'PHPStan\\Type\\ObjectType')])]]); + $services->set(\Rector\Renaming\Rector\Name\RenameClassRector::class)->call('configure', [[ + 'Rector\\Core\\Console\\Command\\AbstractCommand' => 'Symfony\\Component\\Console\\Command\\Command', + 'Rector\\Testing\\PHPUnit\\AbstractCommunityRectorTestCase' => 'Rector\\Testing\\PHPUnit\\AbstractRectorTestCase', + 'Rector\\AttributeAwarePhpDoc\\Ast\\PhpDoc\\AttributeAwareParamTagValueNode' => 'Rector\\BetterPhpDocParser\\ValueObject\\PhpDoc\\VariadicAwareParamTagValueNode', + // @see https://github.com/rectorphp/rector/pull/5841 + 'Rector\\AttributeAwarePhpDoc\\Ast\\PhpDoc\\AttributeAwarePhpDocTagNode' => 'PHPStan\\PhpDocParser\\Ast\\PhpDoc\\PhpDocTagNode', + 'Rector\\AttributeAwarePhpDoc\\Ast\\Type\\AttributeAwareGenericTypeNode' => 'PHPStan\\PhpDocParser\\Ast\\Type\\GenericTypeNode', + ]]); + $services->set(\Rector\Renaming\Rector\ClassConstFetch\RenameClassConstFetchRector::class)->call('configure', [[\Rector\Renaming\Rector\ClassConstFetch\RenameClassConstFetchRector::CLASS_CONSTANT_RENAME => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Renaming\ValueObject\RenameClassAndConstFetch('Rector\\PHPStanStaticTypeMapper\\PHPStanStaticTypeMapper', 'KIND_PARAM', 'Rector\\PHPStanStaticTypeMapper\\ValueObject\\TypeKind', 'KIND_PARAM')])]]); }; diff --git a/upgrade/rector_09.php b/upgrade/rector_09.php index 606aed0624d..4533973425d 100644 --- a/upgrade/rector_09.php +++ b/upgrade/rector_09.php @@ -1,6 +1,7 @@ services(); - $services->set(RenameClassConstFetchRector::class) - ->call('configure', [[ - RenameClassConstFetchRector::CLASS_CONSTANT_RENAME => ValueObjectInliner::inline([ - new RenameClassAndConstFetch( - 'Rector\Core\Configuration\Option', - 'EXCLUDE_RECTORS', - 'Rector\Core\Configuration\Option', - 'SKIP', - ) - ]) - ]]); - - $services->set(RenameMethodRector::class) - ->call('configure', [[ - RenameMethodRector::METHOD_CALL_RENAMES => ValueObjectInliner::inline([ - new MethodCallRename('Rector\Core\Rector\AbstractRector', 'getDefinition', 'getRuleDefinition') - ]) - ]]); - - $services->set(RenameClassRector::class) - ->call('configure', [[ - RenameClassRector::OLD_TO_NEW_CLASSES => [ - 'Rector\Core\RectorDefinition\CodeSample' => 'Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample', - 'Rector\Core\RectorDefinition\RectorDefinition' => 'Symplify\RuleDocGenerator\ValueObject\RuleDefinition', - ] - ]]); + $services->set(\Rector\Renaming\Rector\ClassConstFetch\RenameClassConstFetchRector::class)->call('configure', [[\Rector\Renaming\Rector\ClassConstFetch\RenameClassConstFetchRector::CLASS_CONSTANT_RENAME => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Renaming\ValueObject\RenameClassAndConstFetch('Rector\\Core\\Configuration\\Option', 'EXCLUDE_RECTORS', 'Rector\\Core\\Configuration\\Option', 'SKIP')])]]); + $services->set(\Rector\Renaming\Rector\MethodCall\RenameMethodRector::class)->call('configure', [[\Rector\Renaming\Rector\MethodCall\RenameMethodRector::METHOD_CALL_RENAMES => \Symplify\SymfonyPhpConfig\ValueObjectInliner::inline([new \Rector\Renaming\ValueObject\MethodCallRename('Rector\\Core\\Rector\\AbstractRector', 'getDefinition', 'getRuleDefinition')])]]); + $services->set(\Rector\Renaming\Rector\Name\RenameClassRector::class)->call('configure', [[\Rector\Renaming\Rector\Name\RenameClassRector::OLD_TO_NEW_CLASSES => ['Rector\\Core\\RectorDefinition\\CodeSample' => 'Symplify\\RuleDocGenerator\\ValueObject\\CodeSample\\CodeSample', 'Rector\\Core\\RectorDefinition\\RectorDefinition' => 'Symplify\\RuleDocGenerator\\ValueObject\\RuleDefinition']]]); };